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