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