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