1/*
2 * main.c - Point-to-Point Protocol main module
3 *
4 * Copyright (c) 1984-2000 Carnegie Mellon University. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in
15 *    the documentation and/or other materials provided with the
16 *    distribution.
17 *
18 * 3. The name "Carnegie Mellon University" must not be used to
19 *    endorse or promote products derived from this software without
20 *    prior written permission. For permission or any legal
21 *    details, please contact
22 *      Office of Technology Transfer
23 *      Carnegie Mellon University
24 *      5000 Forbes Avenue
25 *      Pittsburgh, PA  15213-3890
26 *      (412) 268-4387, fax: (412) 268-7395
27 *      tech-transfer@andrew.cmu.edu
28 *
29 * 4. Redistributions of any form whatsoever must retain the following
30 *    acknowledgment:
31 *    "This product includes software developed by Computing Services
32 *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
33 *
34 * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
35 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
36 * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
37 * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
38 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
39 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
40 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41 *
42 * Copyright (c) 1999-2004 Paul Mackerras. All rights reserved.
43 *
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
46 * are met:
47 *
48 * 1. Redistributions of source code must retain the above copyright
49 *    notice, this list of conditions and the following disclaimer.
50 *
51 * 2. The name(s) of the authors of this software must not be used to
52 *    endorse or promote products derived from this software without
53 *    prior written permission.
54 *
55 * 3. Redistributions of any form whatsoever must retain the following
56 *    acknowledgment:
57 *    "This product includes software developed by Paul Mackerras
58 *     <paulus@samba.org>".
59 *
60 * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
61 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
62 * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
63 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
64 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
65 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
66 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
67 */
68
69#define RCSID	"$Id: main.c,v 1.153 2006/06/04 03:52:50 paulus Exp $"
70
71#include <stdio.h>
72#include <ctype.h>
73#include <stdlib.h>
74#include <string.h>
75#include <unistd.h>
76#include <signal.h>
77#include <errno.h>
78#include <fcntl.h>
79#include <syslog.h>
80#include <netdb.h>
81#include <utmp.h>
82#include <pwd.h>
83#include <setjmp.h>
84#include <sys/param.h>
85#include <sys/types.h>
86#include <sys/wait.h>
87#include <sys/time.h>
88#include <sys/resource.h>
89#include <sys/stat.h>
90#include <sys/socket.h>
91#include <netinet/in.h>
92#include <arpa/inet.h>
93
94#include "pppd.h"
95#include "magic.h"
96#include "fsm.h"
97#include "lcp.h"
98#include "ipcp.h"
99#ifdef INET6
100#include "ipv6cp.h"
101#endif
102#include "upap.h"
103#include "chap-new.h"
104#include "eap.h"
105#include "ccp.h"
106#include "ecp.h"
107#include "pathnames.h"
108
109#ifdef USE_TDB
110#include "tdb.h"
111#endif
112
113#ifdef CBCP_SUPPORT
114#include "cbcp.h"
115#endif
116
117#ifdef IPX_CHANGE
118#include "ipxcp.h"
119#endif /* IPX_CHANGE */
120#ifdef AT_CHANGE
121#include "atcp.h"
122#endif
123
124static const char rcsid[] = RCSID;
125
126/* interface vars */
127char ifname[32];		/* Interface name */
128int ifunit;			/* Interface unit number */
129
130struct channel *the_channel;
131
132char *progname;			/* Name of this program */
133char hostname[MAXNAMELEN];	/* Our hostname */
134static char pidfilename[MAXPATHLEN];	/* name of pid file */
135static char linkpidfile[MAXPATHLEN];	/* name of linkname pid file */
136char ppp_devnam[MAXPATHLEN];	/* name of PPP tty (maybe ttypx) */
137uid_t uid;			/* Our real user-id */
138struct notifier *pidchange = NULL;
139struct notifier *phasechange = NULL;
140struct notifier *exitnotify = NULL;
141struct notifier *sigreceived = NULL;
142struct notifier *fork_notifier = NULL;
143
144int hungup;			/* terminal has been hung up */
145int privileged;			/* we're running as real uid root */
146int need_holdoff;		/* need holdoff period before restarting */
147int detached;			/* have detached from terminal */
148volatile int status;		/* exit status for pppd */
149int unsuccess;			/* # unsuccessful connection attempts */
150int do_callback;		/* != 0 if we should do callback next */
151int doing_callback;		/* != 0 if we are doing callback */
152int ppp_session_number;		/* Session number, for channels with such a
153				   concept (eg PPPoE) */
154int childwait_done;		/* have timed out waiting for children */
155
156#ifdef USE_TDB
157TDB_CONTEXT *pppdb;		/* database for storing status etc. */
158#endif
159
160char db_key[32];
161
162int (*holdoff_hook) __P((void)) = NULL;
163int (*new_phase_hook) __P((int)) = NULL;
164void (*snoop_recv_hook) __P((unsigned char *p, int len)) = NULL;
165void (*snoop_send_hook) __P((unsigned char *p, int len)) = NULL;
166
167static int conn_running;	/* we have a [dis]connector running */
168static int fd_loop;		/* fd for getting demand-dial packets */
169
170int fd_devnull;			/* fd for /dev/null */
171int devfd = -1;			/* fd of underlying device */
172int fd_ppp = -1;		/* fd for talking PPP */
173int phase;			/* where the link is at */
174int kill_link;
175int asked_to_quit;
176int open_ccp_flag;
177int listen_time;
178int got_sigusr2;
179int got_sigterm;
180int got_sighup;
181/* Foxconn added start Winster Chan 12/23/2005 */
182int got_sigusr1;    /* Add signal SIGUSR1 */
183int conn_link = 1;
184/* Foxconn added end Winster Chan 12/23/2005 */
185
186static sigset_t signals_handled;
187static int waiting;
188static sigjmp_buf sigjmp;
189
190char **script_env;		/* Env. variable values for scripts */
191int s_env_nalloc;		/* # words avail at script_env */
192
193u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
194u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
195
196static int n_children;		/* # child processes still running */
197static int got_sigchld;		/* set if we have received a SIGCHLD */
198
199int privopen;			/* don't lock, open device as root */
200
201char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
202
203GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
204int ngroups;			/* How many groups valid in groups */
205
206static struct timeval start_time;	/* Time when link was started. */
207
208static struct pppd_stats old_link_stats;
209struct pppd_stats link_stats;
210unsigned link_connect_time;
211int link_stats_valid;
212
213int error_count;
214
215bool bundle_eof;
216bool bundle_terminating;
217
218/*
219 * We maintain a list of child process pids and
220 * functions to call when they exit.
221 */
222struct subprocess {
223    pid_t	pid;
224    char	*prog;
225    void	(*done) __P((void *));
226    void	*arg;
227    struct subprocess *next;
228};
229
230static struct subprocess *children;
231
232/* Prototypes for procedures local to this file. */
233
234static void setup_signals __P((void));
235static void create_pidfile __P((int pid));
236static void create_linkpidfile __P((int pid));
237static void cleanup __P((void));
238static void get_input __P((void));
239static void calltimeout __P((void));
240static struct timeval *timeleft __P((struct timeval *));
241static void kill_my_pg __P((int));
242static void hup __P((int));
243static void term __P((int));
244static void chld __P((int));
245static void toggle_debug __P((int));
246static void open_ccp __P((int));
247static void bad_signal __P((int));
248static void holdoff_end __P((void *));
249static void forget_child __P((int pid, int status));
250static int reap_kids __P((void));
251static void childwait_end __P((void *));
252
253#ifdef USE_TDB
254static void update_db_entry __P((void));
255static void add_db_key __P((const char *));
256static void delete_db_key __P((const char *));
257static void cleanup_db __P((void));
258#endif
259
260static void handle_events __P((void));
261void print_link_stats __P((void));
262
263extern	char	*ttyname __P((int));
264extern	char	*getlogin __P((void));
265int main __P((int, char *[]));
266
267#ifdef ultrix
268#undef	O_NONBLOCK
269#define	O_NONBLOCK	O_NDELAY
270#endif
271
272#ifdef ULTRIX
273#define setlogmask(x)
274#endif
275
276/*
277 * PPP Data Link Layer "protocol" table.
278 * One entry per supported protocol.
279 * The last entry must be NULL.
280 */
281struct protent *protocols[] = {
282    &lcp_protent,
283    &pap_protent,
284    &chap_protent,
285#ifdef CBCP_SUPPORT
286    &cbcp_protent,
287#endif
288    &ipcp_protent,
289#ifdef INET6
290    &ipv6cp_protent,
291#endif
292    &ccp_protent,
293    &ecp_protent,
294#ifdef IPX_CHANGE
295    &ipxcp_protent,
296#endif
297#ifdef AT_CHANGE
298    &atcp_protent,
299#endif
300    &eap_protent,
301    NULL
302};
303
304/*
305 * If PPP_DRV_NAME is not defined, use the default "ppp" as the device name.
306 */
307#if !defined(PPP_DRV_NAME)
308#define PPP_DRV_NAME	"ppp"
309#endif /* !defined(PPP_DRV_NAME) */
310
311int
312main(argc, argv)
313    int argc;
314    char *argv[];
315{
316    int i, t;
317    char *p;
318    struct passwd *pw;
319    struct protent *protp;
320    char numbuf[16];
321
322    link_stats_valid = 0;
323    new_phase(PHASE_INITIALIZE);
324
325    script_env = NULL;
326
327    /* Initialize syslog facilities */
328    reopen_log();
329
330    if (gethostname(hostname, MAXNAMELEN) < 0 ) {
331	option_error("Couldn't get hostname: %m");
332	exit(1);
333    }
334    hostname[MAXNAMELEN-1] = 0;
335
336    /* make sure we don't create world or group writable files. */
337    umask(umask(0777) | 022);
338
339    uid = getuid();
340    privileged = uid == 0;
341    slprintf(numbuf, sizeof(numbuf), "%d", uid);
342    script_setenv("ORIG_UID", numbuf, 0);
343
344    ngroups = getgroups(NGROUPS_MAX, groups);
345
346    /*
347     * Initialize magic number generator now so that protocols may
348     * use magic numbers in initialization.
349     */
350    magic_init();
351
352    /*
353     * Initialize each protocol.
354     */
355    for (i = 0; (protp = protocols[i]) != NULL; ++i)
356        (*protp->init)(0);
357
358    /*
359     * Initialize the default channel.
360     */
361    tty_init();
362
363    progname = *argv;
364
365    /* foxconn added start, zacker, 04/20/2011 */
366    if (strstr(progname, "pppdv6"))
367    {
368        path_upapfile = _PATH_UPAPFILE_IPV6;
369        path_chapfile = _PATH_CHAPFILE_IPV6;
370        path_srpfile = _PATH_SRPFILE_IPV6;
371    }
372    /* foxconn added end, zacker, 04/20/2011 */
373
374    /*
375     * Parse, in order, the system options file, the user's options file,
376     * and the command line arguments.
377     */
378    if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
379	|| !options_from_user()
380	|| !parse_args(argc-1, argv+1))
381	exit(EXIT_OPTION_ERROR);
382    devnam_fixed = 1;		/* can no longer change device name */
383
384    /*
385     * Work out the device name, if it hasn't already been specified,
386     * and parse the tty's options file.
387     */
388    if (the_channel->process_extra_options)
389	(*the_channel->process_extra_options)();
390  /* Foxconn add start by Adams 12/20/2007 */
391#ifdef SUPPORT_PPP_DEBUG
392   if( debug_level >0 && debug_level < 8)
393   {
394     switch(debug_level){
395        case 1:
396                 setlogmask(LOG_UPTO(LOG_EMERG));
397                 break;
398        case 2:
399                   setlogmask(LOG_UPTO(LOG_ALERT));
400                 break;
401        case 3:
402                   setlogmask(LOG_UPTO(LOG_CRIT));
403                 break;
404        case 4:
405                   setlogmask(LOG_UPTO(LOG_ERR));
406                 break;
407        case 5:
408                   setlogmask(LOG_UPTO(LOG_WARNING));
409                 break;
410        case 6:
411                   setlogmask(LOG_UPTO(LOG_NOTICE));
412                 break;
413        case 7:
414                   setlogmask(LOG_UPTO(LOG_INFO));
415                 break;
416        case 8:
417                 setlogmask(LOG_UPTO(LOG_DEBUG));
418                 break;
419    }
420  }
421#else
422    if (debug)
423	setlogmask(LOG_UPTO(LOG_DEBUG));
424#endif
425    /*
426     * Check that we are running as root.
427     */
428    if (geteuid() != 0) {
429	option_error("must be root to run %s, since it is not setuid-root",
430		     argv[0]);
431	exit(EXIT_NOT_ROOT);
432    }
433
434    if (!ppp_available()) {
435	option_error("%s", no_ppp_msg);
436	exit(EXIT_NO_KERNEL_SUPPORT);
437    }
438
439    /*
440     * Check that the options given are valid and consistent.
441     */
442    check_options();
443    if (!sys_check_options())
444	exit(EXIT_OPTION_ERROR);
445    auth_check_options();
446#ifdef HAVE_MULTILINK
447    mp_check_options();
448#endif
449    for (i = 0; (protp = protocols[i]) != NULL; ++i)
450	if (protp->check_options != NULL)
451	    (*protp->check_options)();
452    if (the_channel->check_options)
453	(*the_channel->check_options)();
454
455
456    if (dump_options || dryrun) {
457	init_pr_log(NULL, LOG_INFO);
458	print_options(pr_log, NULL);
459	end_pr_log();
460    }
461
462    if (dryrun)
463	die(0);
464
465    /* Make sure fds 0, 1, 2 are open to somewhere. */
466    fd_devnull = open(_PATH_DEVNULL, O_RDWR);
467    if (fd_devnull < 0)
468	fatal("Couldn't open %s: %m", _PATH_DEVNULL);
469    while (fd_devnull <= 2) {
470	i = dup(fd_devnull);
471	if (i < 0)
472	    fatal("Critical shortage of file descriptors: dup failed: %m");
473	fd_devnull = i;
474    }
475
476    /*
477     * Initialize system-dependent stuff.
478     */
479    sys_init();
480
481#ifdef USE_TDB
482    pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
483    if (pppdb != NULL) {
484	slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
485	update_db_entry();
486    } else {
487	warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
488	if (multilink) {
489	    warn("Warning: disabling multilink");
490	    multilink = 0;
491	}
492    }
493#endif
494
495    /*
496     * Detach ourselves from the terminal, if required,
497     * and identify who is running us.
498     */
499    if (!nodetach && !updetach)
500	detach();
501    p = getlogin();
502    if (p == NULL) {
503	pw = getpwuid(uid);
504	if (pw != NULL && pw->pw_name != NULL)
505	    p = pw->pw_name;
506	else
507	    p = "(unknown)";
508    }
509#if defined(USE_SYSLOG) /* foxconn wklin added, 08/13/2007 */
510    syslog(LOG_NOTICE, "pppd %s started by %s, uid %d", VERSION, p, uid);
511#endif
512    script_setenv("PPPLOGNAME", p, 0);
513
514    if (devnam[0])
515	script_setenv("DEVICE", devnam, 1);
516    slprintf(numbuf, sizeof(numbuf), "%d", getpid());
517    script_setenv("PPPD_PID", numbuf, 1);
518
519    setup_signals();
520
521    create_linkpidfile(getpid());
522
523    waiting = 0;
524
525    /*
526     * If we're doing dial-on-demand, set up the interface now.
527     */
528    if (demand) {
529	/*
530	 * Open the loopback channel and set it up to be the ppp interface.
531	 */
532	fd_loop = open_ppp_loopback();
533	set_ifunit(1);
534	/*
535	 * Configure the interface and mark it up, etc.
536	 */
537	demand_conf();
538    }
539
540    do_callback = 0;
541    for (;;) {
542
543	bundle_eof = 0;
544	bundle_terminating = 0;
545	listen_time = 0;
546	need_holdoff = 1;
547	devfd = -1;
548	status = EXIT_OK;
549	++unsuccess;
550	doing_callback = do_callback;
551	do_callback = 0;
552
553	if (demand && !doing_callback) {
554	    /*
555	     * Don't do anything until we see some activity.
556	     */
557	    new_phase(PHASE_DORMANT);
558	    demand_unblock();
559	    add_fd(fd_loop);
560	    for (;;) {
561		handle_events();
562		if (asked_to_quit)
563		    break;
564        /* Foxconn modified start Winster Chan 12/23/2005 */
565#if 0
566		if (get_loop_output())
567		    break;
568#else
569        if (conn_link) {
570            if (get_loop_output())
571                break;
572        }
573        else {
574            demand_discard2();
575        }
576#endif
577        /* Foxconn modified end Winster Chan 12/23/2005 */
578	    }
579	    remove_fd(fd_loop);
580	    if (asked_to_quit)
581		break;
582
583	    /*
584	     * Now we want to bring up the link.
585	     */
586	    demand_block();
587	    info("Starting link");
588	}
589
590	gettimeofday(&start_time, NULL);
591	script_unsetenv("CONNECT_TIME");
592	script_unsetenv("BYTES_SENT");
593	script_unsetenv("BYTES_RCVD");
594
595	lcp_open(0);		/* Start protocol */
596	start_link(0);
597	while (phase != PHASE_DEAD) {
598	    handle_events();
599	    get_input();
600	    if (kill_link)
601		lcp_close(0, "User request");
602	    if (asked_to_quit) {
603		bundle_terminating = 1;
604		if (phase == PHASE_MASTER)
605		    mp_bundle_terminated();
606	    }
607	    if (open_ccp_flag) {
608		if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
609		    ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
610		    (*ccp_protent.open)(0);
611		}
612	    }
613	}
614	/* restore FSMs to original state */
615	lcp_close(0, "");
616
617	if (!persist || asked_to_quit || (maxfail > 0 && unsuccess >= maxfail))
618	    break;
619
620	if (demand)
621	    demand_discard();
622	t = need_holdoff? holdoff: 0;
623	if (holdoff_hook)
624	    t = (*holdoff_hook)();
625	if (t > 0) {
626	    new_phase(PHASE_HOLDOFF);
627	    TIMEOUT(holdoff_end, NULL, t);
628	    do {
629		handle_events();
630		if (kill_link)
631		    new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
632	    } while (phase == PHASE_HOLDOFF);
633	    if (!persist)
634		break;
635	}
636    }
637
638    /* Wait for scripts to finish */
639    reap_kids();
640    if (n_children > 0) {
641	if (child_wait > 0)
642	    TIMEOUT(childwait_end, NULL, child_wait);
643	if (debug) {
644	    struct subprocess *chp;
645	    dbglog("Waiting for %d child processes...", n_children);
646	    for (chp = children; chp != NULL; chp = chp->next)
647		dbglog("  script %s, pid %d", chp->prog, chp->pid);
648	}
649	while (n_children > 0 && !childwait_done) {
650	    handle_events();
651	    if (kill_link && !childwait_done)
652		childwait_end(NULL);
653	}
654    }
655
656    die(status);
657    return 0;
658}
659
660/*
661 * handle_events - wait for something to happen and respond to it.
662 */
663static void
664handle_events()
665{
666    struct timeval timo;
667
668    kill_link = open_ccp_flag = 0;
669    if (sigsetjmp(sigjmp, 1) == 0) {
670	sigprocmask(SIG_BLOCK, &signals_handled, NULL);
671        /* Foxconn modified start Winster Chan 12/23/2005 */
672#if 0
673	if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
674#else
675        if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld || got_sigusr1) {
676#endif
677        /* Foxconn modified end Winster Chan 12/23/2005 */
678	    sigprocmask(SIG_UNBLOCK, &signals_handled, NULL);
679	} else {
680	    waiting = 1;
681	    sigprocmask(SIG_UNBLOCK, &signals_handled, NULL);
682	    wait_input(timeleft(&timo));
683	}
684    }
685    waiting = 0;
686    calltimeout();
687    if (got_sighup) {
688	info("Hangup (SIGHUP)");
689	kill_link = 1;
690	got_sighup = 0;
691	if (status != EXIT_HANGUP)
692	    status = EXIT_USER_REQUEST;
693    }
694    if (got_sigterm) {
695	info("Terminating on signal %d", got_sigterm);
696	kill_link = 1;
697	asked_to_quit = 1;
698	persist = 0;
699	status = EXIT_USER_REQUEST;
700	got_sigterm = 0;
701    }
702    if (got_sigchld) {
703	got_sigchld = 0;
704	reap_kids();	/* Don't leave dead kids lying around */
705    }
706    if (got_sigusr2) {
707        /* Foxconn modified start Winster Chan 12/23/2005 */
708#if 0
709	open_ccp_flag = 1;
710	got_sigusr2 = 0;
711#else
712        kill_link = 0;
713        conn_link = 1;
714        got_sigusr2 = 0;
715#endif
716        /* Foxconn modified end Winster Chan 12/23/2005 */
717    }
718    /* Foxconn added start Winster Chan 12/23/2005 */
719    if (got_sigusr1) {
720        kill_link = 1;
721        conn_link = 0;
722        need_holdoff = 0;
723        status = EXIT_USER_REQUEST;
724        got_sigusr1 = 0;
725    }
726    /* Foxconn added end Winster Chan 12/23/2005 */
727}
728
729/*
730 * setup_signals - initialize signal handling.
731 */
732static void
733setup_signals()
734{
735    struct sigaction sa;
736
737    /*
738     * Compute mask of all interesting signals and install signal handlers
739     * for each.  Only one signal handler may be active at a time.  Therefore,
740     * all other signals should be masked when any handler is executing.
741     */
742    sigemptyset(&signals_handled);
743    sigaddset(&signals_handled, SIGHUP);
744    sigaddset(&signals_handled, SIGINT);
745    sigaddset(&signals_handled, SIGTERM);
746    sigaddset(&signals_handled, SIGCHLD);
747    sigaddset(&signals_handled, SIGUSR2);
748
749#define SIGNAL(s, handler)	do { \
750	sa.sa_handler = handler; \
751	if (sigaction(s, &sa, NULL) < 0) \
752	    fatal("Couldn't establish signal handler (%d): %m", s); \
753    } while (0)
754
755    sa.sa_mask = signals_handled;
756    sa.sa_flags = 0;
757    SIGNAL(SIGHUP, hup);		/* Hangup */
758    SIGNAL(SIGINT, term);		/* Interrupt */
759    SIGNAL(SIGTERM, term);		/* Terminate */
760    SIGNAL(SIGCHLD, chld);
761
762    SIGNAL(SIGUSR1, toggle_debug);	/* Toggle debug flag */
763    SIGNAL(SIGUSR2, open_ccp);		/* Reopen CCP */
764
765    /*
766     * Install a handler for other signals which would otherwise
767     * cause pppd to exit without cleaning up.
768     */
769    SIGNAL(SIGABRT, bad_signal);
770    SIGNAL(SIGALRM, bad_signal);
771    SIGNAL(SIGFPE, bad_signal);
772    SIGNAL(SIGILL, bad_signal);
773    SIGNAL(SIGPIPE, bad_signal);
774    SIGNAL(SIGQUIT, bad_signal);
775    SIGNAL(SIGSEGV, bad_signal);
776#ifdef SIGBUS
777    SIGNAL(SIGBUS, bad_signal);
778#endif
779#ifdef SIGEMT
780    SIGNAL(SIGEMT, bad_signal);
781#endif
782#ifdef SIGPOLL
783    SIGNAL(SIGPOLL, bad_signal);
784#endif
785#ifdef SIGPROF
786    SIGNAL(SIGPROF, bad_signal);
787#endif
788#ifdef SIGSYS
789    SIGNAL(SIGSYS, bad_signal);
790#endif
791#ifdef SIGTRAP
792    SIGNAL(SIGTRAP, bad_signal);
793#endif
794#ifdef SIGVTALRM
795    SIGNAL(SIGVTALRM, bad_signal);
796#endif
797#ifdef SIGXCPU
798    SIGNAL(SIGXCPU, bad_signal);
799#endif
800#ifdef SIGXFSZ
801    SIGNAL(SIGXFSZ, bad_signal);
802#endif
803
804    /*
805     * Apparently we can get a SIGPIPE when we call syslog, if
806     * syslogd has died and been restarted.  Ignoring it seems
807     * be sufficient.
808     */
809    signal(SIGPIPE, SIG_IGN);
810}
811
812/*
813 * set_ifunit - do things we need to do once we know which ppp
814 * unit we are using.
815 */
816void
817set_ifunit(iskey)
818    int iskey;
819{
820    info("Using interface %s%d", PPP_DRV_NAME, ifunit);
821    slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
822    script_setenv("IFNAME", ifname, iskey);
823    if (iskey) {
824	create_pidfile(getpid());	/* write pid to file */
825	create_linkpidfile(getpid());
826    }
827}
828
829/*
830 * detach - detach us from the controlling terminal.
831 */
832void
833detach()
834{
835    int pid;
836    char numbuf[16];
837    int pipefd[2];
838
839    if (detached)
840	return;
841    if (pipe(pipefd) == -1)
842	pipefd[0] = pipefd[1] = -1;
843    if ((pid = fork()) < 0) {
844	error("Couldn't detach (fork failed: %m)");
845	die(1);			/* or just return? */
846    }
847    if (pid != 0) {
848	/* parent */
849	notify(pidchange, pid);
850	/* update pid files if they have been written already */
851	if (pidfilename[0])
852	    create_pidfile(pid);
853	if (linkpidfile[0])
854	    create_linkpidfile(pid);
855	exit(0);		/* parent dies */
856    }
857    setsid();
858    chdir("/");
859    dup2(fd_devnull, 0);
860    dup2(fd_devnull, 1);
861    dup2(fd_devnull, 2);
862    detached = 1;
863    if (log_default)
864	log_to_fd = -1;
865    slprintf(numbuf, sizeof(numbuf), "%d", getpid());
866    script_setenv("PPPD_PID", numbuf, 1);
867
868    /* wait for parent to finish updating pid & lock files and die */
869    close(pipefd[1]);
870    complete_read(pipefd[0], numbuf, 1);
871    close(pipefd[0]);
872}
873
874/*
875 * reopen_log - (re)open our connection to syslog.
876 */
877void
878reopen_log()
879{
880#if defined(USE_SYSLOG) /* foxconn wklin added, 08/13/2007 */
881    openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
882    setlogmask(LOG_UPTO(LOG_INFO));
883#endif
884}
885
886/*
887 * Create a file containing our process ID.
888 */
889static void
890create_pidfile(pid)
891    int pid;
892{
893    FILE *pidfile;
894
895    slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
896	     _PATH_VARRUN, ifname);
897    if ((pidfile = fopen(pidfilename, "w")) != NULL) {
898	fprintf(pidfile, "%d\n", pid);
899	(void) fclose(pidfile);
900    } else {
901	error("Failed to create pid file %s: %m", pidfilename);
902	pidfilename[0] = 0;
903    }
904}
905
906void
907create_linkpidfile(pid)
908    int pid;
909{
910    FILE *pidfile;
911
912    if (linkname[0] == 0)
913	return;
914    script_setenv("LINKNAME", linkname, 1);
915    slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
916	     _PATH_VARRUN, linkname);
917    if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
918	fprintf(pidfile, "%d\n", pid);
919	if (ifname[0])
920	    fprintf(pidfile, "%s\n", ifname);
921	(void) fclose(pidfile);
922    } else {
923	error("Failed to create pid file %s: %m", linkpidfile);
924	linkpidfile[0] = 0;
925    }
926}
927
928/*
929 * remove_pidfile - remove our pid files
930 */
931void remove_pidfiles()
932{
933    if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
934	warn("unable to delete pid file %s: %m", pidfilename);
935    pidfilename[0] = 0;
936    if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
937	warn("unable to delete pid file %s: %m", linkpidfile);
938    linkpidfile[0] = 0;
939}
940
941/*
942 * holdoff_end - called via a timeout when the holdoff period ends.
943 */
944static void
945holdoff_end(arg)
946    void *arg;
947{
948    new_phase(PHASE_DORMANT);
949}
950
951/* List of protocol names, to make our messages a little more informative. */
952struct protocol_list {
953    u_short	proto;
954    const char	*name;
955} protocol_list[] = {
956    { 0x21,	"IP" },
957    { 0x23,	"OSI Network Layer" },
958    { 0x25,	"Xerox NS IDP" },
959    { 0x27,	"DECnet Phase IV" },
960    { 0x29,	"Appletalk" },
961    { 0x2b,	"Novell IPX" },
962    { 0x2d,	"VJ compressed TCP/IP" },
963    { 0x2f,	"VJ uncompressed TCP/IP" },
964    { 0x31,	"Bridging PDU" },
965    { 0x33,	"Stream Protocol ST-II" },
966    { 0x35,	"Banyan Vines" },
967    { 0x39,	"AppleTalk EDDP" },
968    { 0x3b,	"AppleTalk SmartBuffered" },
969    { 0x3d,	"Multi-Link" },
970    { 0x3f,	"NETBIOS Framing" },
971    { 0x41,	"Cisco Systems" },
972    { 0x43,	"Ascom Timeplex" },
973    { 0x45,	"Fujitsu Link Backup and Load Balancing (LBLB)" },
974    { 0x47,	"DCA Remote Lan" },
975    { 0x49,	"Serial Data Transport Protocol (PPP-SDTP)" },
976    { 0x4b,	"SNA over 802.2" },
977    { 0x4d,	"SNA" },
978    { 0x4f,	"IP6 Header Compression" },
979    { 0x51,	"KNX Bridging Data" },
980    { 0x53,	"Encryption" },
981    { 0x55,	"Individual Link Encryption" },
982    { 0x57,	"IPv6" },
983    { 0x59,	"PPP Muxing" },
984    { 0x5b,	"Vendor-Specific Network Protocol" },
985    { 0x61,	"RTP IPHC Full Header" },
986    { 0x63,	"RTP IPHC Compressed TCP" },
987    { 0x65,	"RTP IPHC Compressed non-TCP" },
988    { 0x67,	"RTP IPHC Compressed UDP 8" },
989    { 0x69,	"RTP IPHC Compressed RTP 8" },
990    { 0x6f,	"Stampede Bridging" },
991    { 0x73,	"MP+" },
992    { 0xc1,	"NTCITS IPI" },
993    { 0xfb,	"single-link compression" },
994    { 0xfd,	"Compressed Datagram" },
995    { 0x0201,	"802.1d Hello Packets" },
996    { 0x0203,	"IBM Source Routing BPDU" },
997    { 0x0205,	"DEC LANBridge100 Spanning Tree" },
998    { 0x0207,	"Cisco Discovery Protocol" },
999    { 0x0209,	"Netcs Twin Routing" },
1000    { 0x020b,	"STP - Scheduled Transfer Protocol" },
1001    { 0x020d,	"EDP - Extreme Discovery Protocol" },
1002    { 0x0211,	"Optical Supervisory Channel Protocol" },
1003    { 0x0213,	"Optical Supervisory Channel Protocol" },
1004    { 0x0231,	"Luxcom" },
1005    { 0x0233,	"Sigma Network Systems" },
1006    { 0x0235,	"Apple Client Server Protocol" },
1007    { 0x0281,	"MPLS Unicast" },
1008    { 0x0283,	"MPLS Multicast" },
1009    { 0x0285,	"IEEE p1284.4 standard - data packets" },
1010    { 0x0287,	"ETSI TETRA Network Protocol Type 1" },
1011    { 0x0289,	"Multichannel Flow Treatment Protocol" },
1012    { 0x2063,	"RTP IPHC Compressed TCP No Delta" },
1013    { 0x2065,	"RTP IPHC Context State" },
1014    { 0x2067,	"RTP IPHC Compressed UDP 16" },
1015    { 0x2069,	"RTP IPHC Compressed RTP 16" },
1016    { 0x4001,	"Cray Communications Control Protocol" },
1017    { 0x4003,	"CDPD Mobile Network Registration Protocol" },
1018    { 0x4005,	"Expand accelerator protocol" },
1019    { 0x4007,	"ODSICP NCP" },
1020    { 0x4009,	"DOCSIS DLL" },
1021    { 0x400B,	"Cetacean Network Detection Protocol" },
1022    { 0x4021,	"Stacker LZS" },
1023    { 0x4023,	"RefTek Protocol" },
1024    { 0x4025,	"Fibre Channel" },
1025    { 0x4027,	"EMIT Protocols" },
1026    { 0x405b,	"Vendor-Specific Protocol (VSP)" },
1027    { 0x8021,	"Internet Protocol Control Protocol" },
1028    { 0x8023,	"OSI Network Layer Control Protocol" },
1029    { 0x8025,	"Xerox NS IDP Control Protocol" },
1030    { 0x8027,	"DECnet Phase IV Control Protocol" },
1031    { 0x8029,	"Appletalk Control Protocol" },
1032    { 0x802b,	"Novell IPX Control Protocol" },
1033    { 0x8031,	"Bridging NCP" },
1034    { 0x8033,	"Stream Protocol Control Protocol" },
1035    { 0x8035,	"Banyan Vines Control Protocol" },
1036    { 0x803d,	"Multi-Link Control Protocol" },
1037    { 0x803f,	"NETBIOS Framing Control Protocol" },
1038    { 0x8041,	"Cisco Systems Control Protocol" },
1039    { 0x8043,	"Ascom Timeplex" },
1040    { 0x8045,	"Fujitsu LBLB Control Protocol" },
1041    { 0x8047,	"DCA Remote Lan Network Control Protocol (RLNCP)" },
1042    { 0x8049,	"Serial Data Control Protocol (PPP-SDCP)" },
1043    { 0x804b,	"SNA over 802.2 Control Protocol" },
1044    { 0x804d,	"SNA Control Protocol" },
1045    { 0x804f,	"IP6 Header Compression Control Protocol" },
1046    { 0x8051,	"KNX Bridging Control Protocol" },
1047    { 0x8053,	"Encryption Control Protocol" },
1048    { 0x8055,	"Individual Link Encryption Control Protocol" },
1049    { 0x8057,	"IPv6 Control Protovol" },
1050    { 0x8059,	"PPP Muxing Control Protocol" },
1051    { 0x805b,	"Vendor-Specific Network Control Protocol (VSNCP)" },
1052    { 0x806f,	"Stampede Bridging Control Protocol" },
1053    { 0x8073,	"MP+ Control Protocol" },
1054    { 0x80c1,	"NTCITS IPI Control Protocol" },
1055    { 0x80fb,	"Single Link Compression Control Protocol" },
1056    { 0x80fd,	"Compression Control Protocol" },
1057    { 0x8207,	"Cisco Discovery Protocol Control" },
1058    { 0x8209,	"Netcs Twin Routing" },
1059    { 0x820b,	"STP - Control Protocol" },
1060    { 0x820d,	"EDPCP - Extreme Discovery Protocol Ctrl Prtcl" },
1061    { 0x8235,	"Apple Client Server Protocol Control" },
1062    { 0x8281,	"MPLSCP" },
1063    { 0x8285,	"IEEE p1284.4 standard - Protocol Control" },
1064    { 0x8287,	"ETSI TETRA TNP1 Control Protocol" },
1065    { 0x8289,	"Multichannel Flow Treatment Protocol" },
1066    { 0xc021,	"Link Control Protocol" },
1067    { 0xc023,	"Password Authentication Protocol" },
1068    { 0xc025,	"Link Quality Report" },
1069    { 0xc027,	"Shiva Password Authentication Protocol" },
1070    { 0xc029,	"CallBack Control Protocol (CBCP)" },
1071    { 0xc02b,	"BACP Bandwidth Allocation Control Protocol" },
1072    { 0xc02d,	"BAP" },
1073    { 0xc05b,	"Vendor-Specific Authentication Protocol (VSAP)" },
1074    { 0xc081,	"Container Control Protocol" },
1075    { 0xc223,	"Challenge Handshake Authentication Protocol" },
1076    { 0xc225,	"RSA Authentication Protocol" },
1077    { 0xc227,	"Extensible Authentication Protocol" },
1078    { 0xc229,	"Mitsubishi Security Info Exch Ptcl (SIEP)" },
1079    { 0xc26f,	"Stampede Bridging Authorization Protocol" },
1080    { 0xc281,	"Proprietary Authentication Protocol" },
1081    { 0xc283,	"Proprietary Authentication Protocol" },
1082    { 0xc481,	"Proprietary Node ID Authentication Protocol" },
1083    { 0,	NULL },
1084};
1085
1086/*
1087 * protocol_name - find a name for a PPP protocol.
1088 */
1089const char *
1090protocol_name(proto)
1091    int proto;
1092{
1093    struct protocol_list *lp;
1094
1095    for (lp = protocol_list; lp->proto != 0; ++lp)
1096	if (proto == lp->proto)
1097	    return lp->name;
1098    return NULL;
1099}
1100
1101/*
1102 * get_input - called when incoming data is available.
1103 */
1104static void
1105get_input()
1106{
1107    int len, i;
1108    u_char *p;
1109    u_short protocol;
1110    struct protent *protp;
1111
1112    p = inpacket_buf;	/* point to beginning of packet buffer */
1113
1114    len = read_packet(inpacket_buf);
1115    if (len < 0)
1116	return;
1117
1118    if (len == 0) {
1119	if (bundle_eof && multilink_master) {
1120	    notice("Last channel has disconnected");
1121	    mp_bundle_terminated();
1122	    return;
1123	}
1124	notice("Modem hangup");
1125	hungup = 1;
1126	status = EXIT_HANGUP;
1127	lcp_lowerdown(0);	/* serial link is no longer available */
1128	link_terminated(0);
1129	return;
1130    }
1131
1132    if (len < PPP_HDRLEN) {
1133	dbglog("received short packet:%.*B", len, p);
1134	return;
1135    }
1136
1137    dump_packet("rcvd", p, len);
1138    if (snoop_recv_hook) snoop_recv_hook(p, len);
1139
1140    p += 2;				/* Skip address and control */
1141    GETSHORT(protocol, p);
1142    len -= PPP_HDRLEN;
1143
1144    /*
1145     * Toss all non-LCP packets unless LCP is OPEN.
1146     */
1147    if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1148	dbglog("Discarded non-LCP packet when LCP not open");
1149	return;
1150    }
1151
1152    /*
1153     * Until we get past the authentication phase, toss all packets
1154     * except LCP, LQR and authentication packets.
1155     */
1156    if (phase <= PHASE_AUTHENTICATE
1157	&& !(protocol == PPP_LCP || protocol == PPP_LQR
1158	     || protocol == PPP_PAP || protocol == PPP_CHAP ||
1159		protocol == PPP_EAP)) {
1160	dbglog("discarding proto 0x%x in phase %d",
1161		   protocol, phase);
1162	return;
1163    }
1164
1165    /*
1166     * Upcall the proper protocol input routine.
1167     */
1168    for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1169	if (protp->protocol == protocol && protp->enabled_flag) {
1170	    (*protp->input)(0, p, len);
1171	    return;
1172	}
1173        if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1174	    && protp->datainput != NULL) {
1175	    (*protp->datainput)(0, p, len);
1176	    return;
1177	}
1178    }
1179
1180    if (debug) {
1181	const char *pname = protocol_name(protocol);
1182	if (pname != NULL)
1183	    warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1184	else
1185	    warn("Unsupported protocol 0x%x received", protocol);
1186    }
1187    lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1188}
1189
1190/*
1191 * ppp_send_config - configure the transmit-side characteristics of
1192 * the ppp interface.  Returns -1, indicating an error, if the channel
1193 * send_config procedure called error() (or incremented error_count
1194 * itself), otherwise 0.
1195 */
1196int
1197ppp_send_config(unit, mtu, accm, pcomp, accomp)
1198    int unit, mtu;
1199    u_int32_t accm;
1200    int pcomp, accomp;
1201{
1202	int errs;
1203
1204	if (the_channel->send_config == NULL)
1205		return 0;
1206	errs = error_count;
1207	(*the_channel->send_config)(mtu, accm, pcomp, accomp);
1208	return (error_count != errs)? -1: 0;
1209}
1210
1211/*
1212 * ppp_recv_config - configure the receive-side characteristics of
1213 * the ppp interface.  Returns -1, indicating an error, if the channel
1214 * recv_config procedure called error() (or incremented error_count
1215 * itself), otherwise 0.
1216 */
1217int
1218ppp_recv_config(unit, mru, accm, pcomp, accomp)
1219    int unit, mru;
1220    u_int32_t accm;
1221    int pcomp, accomp;
1222{
1223	int errs;
1224
1225	if (the_channel->recv_config == NULL)
1226		return 0;
1227	errs = error_count;
1228	(*the_channel->recv_config)(mru, accm, pcomp, accomp);
1229	return (error_count != errs)? -1: 0;
1230}
1231
1232/*
1233 * new_phase - signal the start of a new phase of pppd's operation.
1234 */
1235void
1236new_phase(p)
1237    int p;
1238{
1239    phase = p;
1240    if (new_phase_hook)
1241	(*new_phase_hook)(p);
1242    notify(phasechange, p);
1243}
1244
1245/*
1246 * die - clean up state and exit with the specified status.
1247 */
1248void
1249die(status)
1250    int status;
1251{
1252    if (!doing_multilink || multilink_master)
1253	print_link_stats();
1254    cleanup();
1255    notify(exitnotify, status);
1256#if defined(USE_SYSLOG) /* foxconn wklin added, 08/13/2007 */
1257    syslog(LOG_INFO, "Exit.");
1258#endif
1259    exit(status);
1260}
1261
1262/*
1263 * cleanup - restore anything which needs to be restored before we exit
1264 */
1265/* ARGSUSED */
1266static void
1267cleanup()
1268{
1269    sys_cleanup();
1270
1271    if (fd_ppp >= 0)
1272	the_channel->disestablish_ppp(devfd);
1273    if (the_channel->cleanup)
1274	(*the_channel->cleanup)();
1275    remove_pidfiles();
1276
1277#ifdef USE_TDB
1278    if (pppdb != NULL)
1279	cleanup_db();
1280#endif
1281
1282}
1283
1284void
1285print_link_stats()
1286{
1287    /*
1288     * Print connect time and statistics.
1289     */
1290    if (link_stats_valid) {
1291       int t = (link_connect_time + 5) / 6;    /* 1/10ths of minutes */
1292       info("Connect time %d.%d minutes.", t/10, t%10);
1293       info("Sent %u bytes, received %u bytes.",
1294	    link_stats.bytes_out, link_stats.bytes_in);
1295       link_stats_valid = 0;
1296    }
1297}
1298
1299/*
1300 * reset_link_stats - "reset" stats when link goes up.
1301 */
1302void
1303reset_link_stats(u)
1304    int u;
1305{
1306    if (!get_ppp_stats(u, &old_link_stats))
1307	return;
1308    gettimeofday(&start_time, NULL);
1309}
1310
1311/*
1312 * update_link_stats - get stats at link termination.
1313 */
1314void
1315update_link_stats(u)
1316    int u;
1317{
1318    struct timeval now;
1319    char numbuf[32];
1320
1321    if (!get_ppp_stats(u, &link_stats)
1322	|| gettimeofday(&now, NULL) < 0)
1323	return;
1324    link_connect_time = now.tv_sec - start_time.tv_sec;
1325    link_stats_valid = 1;
1326
1327    link_stats.bytes_in  -= old_link_stats.bytes_in;
1328    link_stats.bytes_out -= old_link_stats.bytes_out;
1329    link_stats.pkts_in   -= old_link_stats.pkts_in;
1330    link_stats.pkts_out  -= old_link_stats.pkts_out;
1331
1332    slprintf(numbuf, sizeof(numbuf), "%u", link_connect_time);
1333    script_setenv("CONNECT_TIME", numbuf, 0);
1334    slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_out);
1335    script_setenv("BYTES_SENT", numbuf, 0);
1336    slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_in);
1337    script_setenv("BYTES_RCVD", numbuf, 0);
1338}
1339
1340
1341struct	callout {
1342    struct timeval	c_time;		/* time at which to call routine */
1343    void		*c_arg;		/* argument to routine */
1344    void		(*c_func) __P((void *)); /* routine */
1345    struct		callout *c_next;
1346};
1347
1348static struct callout *callout = NULL;	/* Callout list */
1349static struct timeval timenow;		/* Current time */
1350
1351/*
1352 * timeout - Schedule a timeout.
1353 */
1354void
1355timeout(func, arg, secs, usecs)
1356    void (*func) __P((void *));
1357    void *arg;
1358    int secs, usecs;
1359{
1360    struct callout *newp, *p, **pp;
1361
1362    /*
1363     * Allocate timeout.
1364     */
1365    if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1366	fatal("Out of memory in timeout()!");
1367    newp->c_arg = arg;
1368    newp->c_func = func;
1369    gettimeofday(&timenow, NULL);
1370    newp->c_time.tv_sec = timenow.tv_sec + secs;
1371    newp->c_time.tv_usec = timenow.tv_usec + usecs;
1372    if (newp->c_time.tv_usec >= 1000000) {
1373	newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
1374	newp->c_time.tv_usec %= 1000000;
1375    }
1376
1377    /*
1378     * Find correct place and link it in.
1379     */
1380    for (pp = &callout; (p = *pp); pp = &p->c_next)
1381	if (newp->c_time.tv_sec < p->c_time.tv_sec
1382	    || (newp->c_time.tv_sec == p->c_time.tv_sec
1383		&& newp->c_time.tv_usec < p->c_time.tv_usec))
1384	    break;
1385    newp->c_next = p;
1386    *pp = newp;
1387}
1388
1389
1390/*
1391 * untimeout - Unschedule a timeout.
1392 */
1393void
1394untimeout(func, arg)
1395    void (*func) __P((void *));
1396    void *arg;
1397{
1398    struct callout **copp, *freep;
1399
1400    /*
1401     * Find first matching timeout and remove it from the list.
1402     */
1403    for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1404	if (freep->c_func == func && freep->c_arg == arg) {
1405	    *copp = freep->c_next;
1406	    free((char *) freep);
1407	    break;
1408	}
1409}
1410
1411
1412/*
1413 * calltimeout - Call any timeout routines which are now due.
1414 */
1415static void
1416calltimeout()
1417{
1418    struct callout *p;
1419
1420    while (callout != NULL) {
1421	p = callout;
1422
1423	if (gettimeofday(&timenow, NULL) < 0)
1424	    fatal("Failed to get time of day: %m");
1425	if (!(p->c_time.tv_sec < timenow.tv_sec
1426	      || (p->c_time.tv_sec == timenow.tv_sec
1427		  && p->c_time.tv_usec <= timenow.tv_usec)))
1428	    break;		/* no, it's not time yet */
1429
1430	callout = p->c_next;
1431	(*p->c_func)(p->c_arg);
1432
1433	free((char *) p);
1434    }
1435}
1436
1437
1438/*
1439 * timeleft - return the length of time until the next timeout is due.
1440 */
1441static struct timeval *
1442timeleft(tvp)
1443    struct timeval *tvp;
1444{
1445    if (callout == NULL)
1446	return NULL;
1447
1448    gettimeofday(&timenow, NULL);
1449    tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1450    tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1451    if (tvp->tv_usec < 0) {
1452	tvp->tv_usec += 1000000;
1453	tvp->tv_sec -= 1;
1454    }
1455    if (tvp->tv_sec < 0)
1456	tvp->tv_sec = tvp->tv_usec = 0;
1457
1458    return tvp;
1459}
1460
1461
1462/*
1463 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1464 * We assume that sig is currently blocked.
1465 */
1466static void
1467kill_my_pg(sig)
1468    int sig;
1469{
1470    struct sigaction act, oldact;
1471
1472    sigemptyset(&act.sa_mask);		/* unnecessary in fact */
1473    act.sa_handler = SIG_IGN;
1474    act.sa_flags = 0;
1475    kill(0, sig);
1476    /*
1477     * The kill() above made the signal pending for us, as well as
1478     * the rest of our process group, but we don't want it delivered
1479     * to us.  It is blocked at the moment.  Setting it to be ignored
1480     * will cause the pending signal to be discarded.  If we did the
1481     * kill() after setting the signal to be ignored, it is unspecified
1482     * (by POSIX) whether the signal is immediately discarded or left
1483     * pending, and in fact Linux would leave it pending, and so it
1484     * would be delivered after the current signal handler exits,
1485     * leading to an infinite loop.
1486     */
1487    sigaction(sig, &act, &oldact);
1488    sigaction(sig, &oldact, NULL);
1489}
1490
1491
1492/*
1493 * hup - Catch SIGHUP signal.
1494 *
1495 * Indicates that the physical layer has been disconnected.
1496 * We don't rely on this indication; if the user has sent this
1497 * signal, we just take the link down.
1498 */
1499static void
1500hup(sig)
1501    int sig;
1502{
1503    /* can't log a message here, it can deadlock */
1504    got_sighup = 1;
1505    /* Foxconn removed start Winster Chan 12/23/2005 */
1506#if 0
1507    if (conn_running)
1508	/* Send the signal to the [dis]connector process(es) also */
1509	kill_my_pg(sig);
1510#endif
1511    /* Foxconn removed end Winster Chan 12/23/2005 */
1512    notify(sigreceived, sig);
1513    if (waiting)
1514	siglongjmp(sigjmp, 1);
1515}
1516
1517
1518/*
1519 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1520 *
1521 * Indicates that we should initiate a graceful disconnect and exit.
1522 */
1523/*ARGSUSED*/
1524static void
1525term(sig)
1526    int sig;
1527{
1528    /* can't log a message here, it can deadlock */
1529    got_sigterm = sig;
1530    /* Foxconn removed start Winster Chan 12/23/2005 */
1531#if 0
1532    if (conn_running)
1533	/* Send the signal to the [dis]connector process(es) also */
1534	kill_my_pg(sig);
1535#endif
1536    /* Foxconn removed end Winster Chan 12/23/2005 */
1537    notify(sigreceived, sig);
1538    if (waiting)
1539	siglongjmp(sigjmp, 1);
1540}
1541
1542
1543/*
1544 * chld - Catch SIGCHLD signal.
1545 * Sets a flag so we will call reap_kids in the mainline.
1546 */
1547static void
1548chld(sig)
1549    int sig;
1550{
1551    got_sigchld = 1;
1552    if (waiting)
1553	siglongjmp(sigjmp, 1);
1554}
1555
1556
1557/*
1558 * toggle_debug - Catch SIGUSR1 signal.
1559 *
1560 * Toggle debug flag.
1561 */
1562/*ARGSUSED*/
1563static void
1564toggle_debug(sig)
1565    int sig;
1566{
1567    /* Foxconn modified start Winster Chan 12/23/2005 */
1568#if 0
1569    debug = !debug;
1570    if (debug) {
1571	setlogmask(LOG_UPTO(LOG_DEBUG));
1572    } else {
1573	setlogmask(LOG_UPTO(LOG_WARNING));
1574    }
1575#else
1576    info("Disconnect on signal %d.", sig);
1577    got_sigusr1 = 1;
1578    notify(sigreceived, sig);
1579    if (waiting)
1580	siglongjmp(sigjmp, 1);
1581#endif
1582    /* Foxconn modified end Winster Chan 12/23/2005 */
1583}
1584
1585
1586/*
1587 * open_ccp - Catch SIGUSR2 signal.
1588 *
1589 * Try to (re)negotiate compression.
1590 */
1591/*ARGSUSED*/
1592static void
1593open_ccp(sig)
1594    int sig;
1595{
1596    /* Foxconn modified start Winster Chan 12/23/2005 */
1597#if 0
1598    got_sigusr2 = 1;
1599    if (waiting)
1600	siglongjmp(sigjmp, 1);
1601#else
1602    info("Connect on signal %d.", sig);
1603    got_sigusr2 = 1;
1604    notify(sigreceived, sig);
1605    if (waiting)
1606	siglongjmp(sigjmp, 1);
1607#endif
1608    /* Foxconn modified end Winster Chan 12/23/2005 */
1609}
1610
1611
1612/*
1613 * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1614 */
1615static void
1616bad_signal(sig)
1617    int sig;
1618{
1619    static int crashed = 0;
1620
1621    if (crashed)
1622	_exit(127);
1623    crashed = 1;
1624    error("Fatal signal %d", sig);
1625    if (conn_running)
1626	kill_my_pg(SIGTERM);
1627    notify(sigreceived, sig);
1628    die(127);
1629}
1630
1631/*
1632 * safe_fork - Create a child process.  The child closes all the
1633 * file descriptors that we don't want to leak to a script.
1634 * The parent waits for the child to do this before returning.
1635 * This also arranges for the specified fds to be dup'd to
1636 * fds 0, 1, 2 in the child.
1637 */
1638pid_t
1639safe_fork(int infd, int outfd, int errfd)
1640{
1641	pid_t pid;
1642	int fd, pipefd[2];
1643	char buf[1];
1644
1645	/* make sure fds 0, 1, 2 are occupied (probably not necessary) */
1646	while ((fd = dup(fd_devnull)) >= 0) {
1647		if (fd > 2) {
1648			close(fd);
1649			break;
1650		}
1651	}
1652
1653	if (pipe(pipefd) == -1)
1654		pipefd[0] = pipefd[1] = -1;
1655	pid = fork();
1656	if (pid < 0) {
1657		error("fork failed: %m");
1658		return -1;
1659	}
1660	if (pid > 0) {
1661		/* parent */
1662		close(pipefd[1]);
1663		/* this read() blocks until the close(pipefd[1]) below */
1664		complete_read(pipefd[0], buf, 1);
1665		close(pipefd[0]);
1666		return pid;
1667	}
1668
1669	/* Executing in the child */
1670	sys_close();
1671#ifdef USE_TDB
1672	tdb_close(pppdb);
1673#endif
1674
1675	/* make sure infd, outfd and errfd won't get tromped on below */
1676	if (infd == 1 || infd == 2)
1677		infd = dup(infd);
1678	if (outfd == 0 || outfd == 2)
1679		outfd = dup(outfd);
1680	if (errfd == 0 || errfd == 1)
1681		errfd = dup(errfd);
1682
1683	/* dup the in, out, err fds to 0, 1, 2 */
1684	if (infd != 0)
1685		dup2(infd, 0);
1686	if (outfd != 1)
1687		dup2(outfd, 1);
1688	if (errfd != 2)
1689		dup2(errfd, 2);
1690
1691	closelog();
1692	if (log_to_fd > 2)
1693		close(log_to_fd);
1694	if (the_channel->close)
1695		(*the_channel->close)();
1696	else
1697		close(devfd);	/* some plugins don't have a close function */
1698	close(fd_ppp);
1699	close(fd_devnull);
1700	if (infd != 0)
1701		close(infd);
1702	if (outfd != 1)
1703		close(outfd);
1704	if (errfd != 2)
1705		close(errfd);
1706
1707	notify(fork_notifier, 0);
1708	close(pipefd[0]);
1709	/* this close unblocks the read() call above in the parent */
1710	close(pipefd[1]);
1711
1712	return 0;
1713}
1714
1715/*
1716 * device_script - run a program to talk to the specified fds
1717 * (e.g. to run the connector or disconnector script).
1718 * stderr gets connected to the log fd or to the _PATH_CONNERRS file.
1719 */
1720int
1721device_script(program, in, out, dont_wait)
1722    char *program;
1723    int in, out;
1724    int dont_wait;
1725{
1726    int pid;
1727    int status = -1;
1728    int errfd;
1729
1730    if (log_to_fd >= 0)
1731	errfd = log_to_fd;
1732    else
1733	errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1734
1735    ++conn_running;
1736    pid = safe_fork(in, out, errfd);
1737
1738    if (pid != 0 && log_to_fd < 0)
1739	close(errfd);
1740
1741    if (pid < 0) {
1742	--conn_running;
1743	error("Failed to create child process: %m");
1744	return -1;
1745    }
1746
1747    if (pid != 0) {
1748	if (dont_wait) {
1749	    record_child(pid, program, NULL, NULL);
1750	    status = 0;
1751	} else {
1752	    while (waitpid(pid, &status, 0) < 0) {
1753		if (errno == EINTR)
1754		    continue;
1755		fatal("error waiting for (dis)connection process: %m");
1756	    }
1757	    --conn_running;
1758	}
1759	return (status == 0 ? 0 : -1);
1760    }
1761
1762    /* here we are executing in the child */
1763
1764    setgid(getgid());
1765    setuid(uid);
1766    if (getuid() != uid) {
1767	fprintf(stderr, "pppd: setuid failed\n");
1768	exit(1);
1769    }
1770    execl("/bin/sh", "sh", "-c", program, (char *)0);
1771    perror("pppd: could not exec /bin/sh");
1772    exit(99);
1773    /* NOTREACHED */
1774}
1775
1776
1777/*
1778 * run-program - execute a program with given arguments,
1779 * but don't wait for it unless wait is non-zero.
1780 * If the program can't be executed, logs an error unless
1781 * must_exist is 0 and the program file doesn't exist.
1782 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1783 * or isn't an executable plain file, or the process ID of the child.
1784 * If done != NULL, (*done)(arg) will be called later (within
1785 * reap_kids) iff the return value is > 0.
1786 */
1787pid_t
1788run_program(prog, args, must_exist, done, arg, wait)
1789    char *prog;
1790    char **args;
1791    int must_exist;
1792    void (*done) __P((void *));
1793    void *arg;
1794    int wait;
1795{
1796    int pid, status;
1797    struct stat sbuf;
1798
1799    /*
1800     * First check if the file exists and is executable.
1801     * We don't use access() because that would use the
1802     * real user-id, which might not be root, and the script
1803     * might be accessible only to root.
1804     */
1805    errno = EINVAL;
1806    if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1807	|| (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1808	if (must_exist || errno != ENOENT)
1809	    warn("Can't execute %s: %m", prog);
1810	return 0;
1811    }
1812
1813    pid = safe_fork(fd_devnull, fd_devnull, fd_devnull);
1814    if (pid == -1) {
1815	error("Failed to create child process for %s: %m", prog);
1816	return -1;
1817    }
1818    if (pid != 0) {
1819	if (debug)
1820	    dbglog("Script %s started (pid %d)", prog, pid);
1821	record_child(pid, prog, done, arg);
1822	if (wait) {
1823	    while (waitpid(pid, &status, 0) < 0) {
1824		if (errno == EINTR)
1825		    continue;
1826		fatal("error waiting for script %s: %m", prog);
1827	    }
1828	    forget_child(pid, status);
1829	}
1830	return pid;
1831    }
1832
1833    /* Leave the current location */
1834    (void) setsid();	/* No controlling tty. */
1835    (void) umask (S_IRWXG|S_IRWXO);
1836    (void) chdir ("/");	/* no current directory. */
1837    setuid(0);		/* set real UID = root */
1838    setgid(getegid());
1839
1840#ifdef BSD
1841    /* Force the priority back to zero if pppd is running higher. */
1842    if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1843	warn("can't reset priority to 0: %m");
1844#endif
1845
1846    /* run the program */
1847    execve(prog, args, script_env);
1848    if (must_exist || errno != ENOENT) {
1849	/* have to reopen the log, there's nowhere else
1850	   for the message to go. */
1851	reopen_log();
1852#if defined(USE_SYSLOG) /* foxconn wklin added, 08/13/2007 */
1853	syslog(LOG_ERR, "Can't execute %s: %m", prog);
1854#endif
1855	closelog();
1856    }
1857    _exit(-1);
1858}
1859
1860
1861/*
1862 * record_child - add a child process to the list for reap_kids
1863 * to use.
1864 */
1865void
1866record_child(pid, prog, done, arg)
1867    int pid;
1868    char *prog;
1869    void (*done) __P((void *));
1870    void *arg;
1871{
1872    struct subprocess *chp;
1873
1874    ++n_children;
1875
1876    chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1877    if (chp == NULL) {
1878	warn("losing track of %s process", prog);
1879    } else {
1880	chp->pid = pid;
1881	chp->prog = prog;
1882	chp->done = done;
1883	chp->arg = arg;
1884	chp->next = children;
1885	children = chp;
1886    }
1887}
1888
1889/*
1890 * childwait_end - we got fed up waiting for the child processes to
1891 * exit, send them all a SIGTERM.
1892 */
1893static void
1894childwait_end(arg)
1895    void *arg;
1896{
1897    struct subprocess *chp;
1898
1899    for (chp = children; chp != NULL; chp = chp->next) {
1900	if (debug)
1901	    dbglog("sending SIGTERM to process %d", chp->pid);
1902	kill(chp->pid, SIGTERM);
1903    }
1904    childwait_done = 1;
1905}
1906
1907/*
1908 * forget_child - clean up after a dead child
1909 */
1910static void
1911forget_child(pid, status)
1912    int pid, status;
1913{
1914    struct subprocess *chp, **prevp;
1915
1916    for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1917        if (chp->pid == pid) {
1918	    --n_children;
1919	    *prevp = chp->next;
1920	    break;
1921	}
1922    }
1923    if (WIFSIGNALED(status)) {
1924        warn("Child process %s (pid %d) terminated with signal %d",
1925	     (chp? chp->prog: "??"), pid, WTERMSIG(status));
1926    } else if (debug)
1927        dbglog("Script %s finished (pid %d), status = 0x%x",
1928	       (chp? chp->prog: "??"), pid,
1929	       WIFEXITED(status) ? WEXITSTATUS(status) : status);
1930    if (chp && chp->done)
1931        (*chp->done)(chp->arg);
1932    if (chp)
1933        free(chp);
1934}
1935
1936/*
1937 * reap_kids - get status from any dead child processes,
1938 * and log a message for abnormal terminations.
1939 */
1940static int
1941reap_kids()
1942{
1943    int pid, status;
1944
1945    if (n_children == 0)
1946	return 0;
1947    while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1948        forget_child(pid, status);
1949    }
1950    if (pid == -1) {
1951	if (errno == ECHILD)
1952	    return -1;
1953	if (errno != EINTR)
1954	    error("Error waiting for child process: %m");
1955    }
1956    return 0;
1957}
1958
1959/*
1960 * add_notifier - add a new function to be called when something happens.
1961 */
1962void
1963add_notifier(notif, func, arg)
1964    struct notifier **notif;
1965    notify_func func;
1966    void *arg;
1967{
1968    struct notifier *np;
1969
1970    np = malloc(sizeof(struct notifier));
1971    if (np == 0)
1972	novm("notifier struct");
1973    np->next = *notif;
1974    np->func = func;
1975    np->arg = arg;
1976    *notif = np;
1977}
1978
1979/*
1980 * remove_notifier - remove a function from the list of things to
1981 * be called when something happens.
1982 */
1983void
1984remove_notifier(notif, func, arg)
1985    struct notifier **notif;
1986    notify_func func;
1987    void *arg;
1988{
1989    struct notifier *np;
1990
1991    for (; (np = *notif) != 0; notif = &np->next) {
1992	if (np->func == func && np->arg == arg) {
1993	    *notif = np->next;
1994	    free(np);
1995	    break;
1996	}
1997    }
1998}
1999
2000/*
2001 * notify - call a set of functions registered with add_notifier.
2002 */
2003void
2004notify(notif, val)
2005    struct notifier *notif;
2006    int val;
2007{
2008    struct notifier *np;
2009
2010    while ((np = notif) != 0) {
2011	notif = np->next;
2012	(*np->func)(np->arg, val);
2013    }
2014}
2015
2016/*
2017 * novm - log an error message saying we ran out of memory, and die.
2018 */
2019void
2020novm(msg)
2021    char *msg;
2022{
2023    fatal("Virtual memory exhausted allocating %s\n", msg);
2024}
2025
2026/*
2027 * script_setenv - set an environment variable value to be used
2028 * for scripts that we run (e.g. ip-up, auth-up, etc.)
2029 */
2030void
2031script_setenv(var, value, iskey)
2032    char *var, *value;
2033    int iskey;
2034{
2035    size_t varl = strlen(var);
2036    size_t vl = varl + strlen(value) + 2;
2037    int i;
2038    char *p, *newstring;
2039
2040    newstring = (char *) malloc(vl+1);
2041    if (newstring == 0)
2042	return;
2043    *newstring++ = iskey;
2044    slprintf(newstring, vl, "%s=%s", var, value);
2045
2046    /* check if this variable is already set */
2047    if (script_env != 0) {
2048	for (i = 0; (p = script_env[i]) != 0; ++i) {
2049	    if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
2050#ifdef USE_TDB
2051		if (p[-1] && pppdb != NULL)
2052		    delete_db_key(p);
2053#endif
2054		free(p-1);
2055		script_env[i] = newstring;
2056#ifdef USE_TDB
2057		if (iskey && pppdb != NULL)
2058		    add_db_key(newstring);
2059		update_db_entry();
2060#endif
2061		return;
2062	    }
2063	}
2064    } else {
2065	/* no space allocated for script env. ptrs. yet */
2066	i = 0;
2067	script_env = (char **) malloc(16 * sizeof(char *));
2068	if (script_env == 0)
2069	    return;
2070	s_env_nalloc = 16;
2071    }
2072
2073    /* reallocate script_env with more space if needed */
2074    if (i + 1 >= s_env_nalloc) {
2075	int new_n = i + 17;
2076	char **newenv = (char **) realloc((void *)script_env,
2077					  new_n * sizeof(char *));
2078	if (newenv == 0)
2079	    return;
2080	script_env = newenv;
2081	s_env_nalloc = new_n;
2082    }
2083
2084    script_env[i] = newstring;
2085    script_env[i+1] = 0;
2086
2087#ifdef USE_TDB
2088    if (pppdb != NULL) {
2089	if (iskey)
2090	    add_db_key(newstring);
2091	update_db_entry();
2092    }
2093#endif
2094}
2095
2096/*
2097 * script_unsetenv - remove a variable from the environment
2098 * for scripts.
2099 */
2100void
2101script_unsetenv(var)
2102    char *var;
2103{
2104    int vl = strlen(var);
2105    int i;
2106    char *p;
2107
2108    if (script_env == 0)
2109	return;
2110    for (i = 0; (p = script_env[i]) != 0; ++i) {
2111	if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2112#ifdef USE_TDB
2113	    if (p[-1] && pppdb != NULL)
2114		delete_db_key(p);
2115#endif
2116	    free(p-1);
2117	    while ((script_env[i] = script_env[i+1]) != 0)
2118		++i;
2119	    break;
2120	}
2121    }
2122#ifdef USE_TDB
2123    if (pppdb != NULL)
2124	update_db_entry();
2125#endif
2126}
2127
2128/*
2129 * Any arbitrary string used as a key for locking the database.
2130 * It doesn't matter what it is as long as all pppds use the same string.
2131 */
2132#define PPPD_LOCK_KEY	"pppd lock"
2133
2134/*
2135 * lock_db - get an exclusive lock on the TDB database.
2136 * Used to ensure atomicity of various lookup/modify operations.
2137 */
2138void lock_db()
2139{
2140#ifdef USE_TDB
2141	TDB_DATA key;
2142
2143	key.dptr = PPPD_LOCK_KEY;
2144	key.dsize = strlen(key.dptr);
2145	tdb_chainlock(pppdb, key);
2146#endif
2147}
2148
2149/*
2150 * unlock_db - remove the exclusive lock obtained by lock_db.
2151 */
2152void unlock_db()
2153{
2154#ifdef USE_TDB
2155	TDB_DATA key;
2156
2157	key.dptr = PPPD_LOCK_KEY;
2158	key.dsize = strlen(key.dptr);
2159	tdb_chainunlock(pppdb, key);
2160#endif
2161}
2162
2163#ifdef USE_TDB
2164/*
2165 * update_db_entry - update our entry in the database.
2166 */
2167static void
2168update_db_entry()
2169{
2170    TDB_DATA key, dbuf;
2171    int vlen, i;
2172    char *p, *q, *vbuf;
2173
2174    if (script_env == NULL)
2175	return;
2176    vlen = 0;
2177    for (i = 0; (p = script_env[i]) != 0; ++i)
2178	vlen += strlen(p) + 1;
2179    vbuf = malloc(vlen + 1);
2180    if (vbuf == 0)
2181	novm("database entry");
2182    q = vbuf;
2183    for (i = 0; (p = script_env[i]) != 0; ++i)
2184	q += slprintf(q, vbuf + vlen - q, "%s;", p);
2185
2186    key.dptr = db_key;
2187    key.dsize = strlen(db_key);
2188    dbuf.dptr = vbuf;
2189    dbuf.dsize = vlen;
2190    if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2191	error("tdb_store failed: %s", tdb_error(pppdb));
2192
2193    if (vbuf)
2194        free(vbuf);
2195
2196}
2197
2198/*
2199 * add_db_key - add a key that we can use to look up our database entry.
2200 */
2201static void
2202add_db_key(str)
2203    const char *str;
2204{
2205    TDB_DATA key, dbuf;
2206
2207    key.dptr = (char *) str;
2208    key.dsize = strlen(str);
2209    dbuf.dptr = db_key;
2210    dbuf.dsize = strlen(db_key);
2211    if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2212	error("tdb_store key failed: %s", tdb_error(pppdb));
2213}
2214
2215/*
2216 * delete_db_key - delete a key for looking up our database entry.
2217 */
2218static void
2219delete_db_key(str)
2220    const char *str;
2221{
2222    TDB_DATA key;
2223
2224    key.dptr = (char *) str;
2225    key.dsize = strlen(str);
2226    tdb_delete(pppdb, key);
2227}
2228
2229/*
2230 * cleanup_db - delete all the entries we put in the database.
2231 */
2232static void
2233cleanup_db()
2234{
2235    TDB_DATA key;
2236    int i;
2237    char *p;
2238
2239    key.dptr = db_key;
2240    key.dsize = strlen(db_key);
2241    tdb_delete(pppdb, key);
2242    for (i = 0; (p = script_env[i]) != 0; ++i)
2243	if (p[-1])
2244	    delete_db_key(p);
2245}
2246#endif /* USE_TDB */
2247