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