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