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