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