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