]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
add dump_packet, don't log lcp echo request/reply messages once
[ppp.git] / pppd / main.c
1 /*
2  * main.c - Point-to-Point Protocol main module
3  *
4  * Copyright (c) 1989 Carnegie Mellon University.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms are permitted
8  * provided that the above copyright notice and this paragraph are
9  * duplicated in all such forms and that any documentation,
10  * advertising materials, and other materials related to such
11  * distribution and use acknowledge that the software was developed
12  * by Carnegie Mellon University.  The name of the
13  * University may not be used to endorse or promote products derived
14  * from this software without specific prior written permission.
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18  */
19
20 #define RCSID   "$Id: main.c,v 1.107 2001/05/23 03:39:13 paulus Exp $"
21
22 #include <stdio.h>
23 #include <ctype.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <signal.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <syslog.h>
31 #include <netdb.h>
32 #include <utmp.h>
33 #include <pwd.h>
34 #include <setjmp.h>
35 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <sys/time.h>
39 #include <sys/resource.h>
40 #include <sys/stat.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
44
45 #include "pppd.h"
46 #include "magic.h"
47 #include "fsm.h"
48 #include "lcp.h"
49 #include "ipcp.h"
50 #ifdef INET6
51 #include "ipv6cp.h"
52 #endif
53 #include "upap.h"
54 #include "chap.h"
55 #include "ccp.h"
56 #include "pathnames.h"
57 #include "tdb.h"
58
59 #ifdef CBCP_SUPPORT
60 #include "cbcp.h"
61 #endif
62
63 #ifdef IPX_CHANGE
64 #include "ipxcp.h"
65 #endif /* IPX_CHANGE */
66 #ifdef AT_CHANGE
67 #include "atcp.h"
68 #endif
69
70 static const char rcsid[] = RCSID;
71
72 /* interface vars */
73 char ifname[32];                /* Interface name */
74 int ifunit;                     /* Interface unit number */
75
76 struct channel *the_channel;
77
78 char *progname;                 /* Name of this program */
79 char hostname[MAXNAMELEN];      /* Our hostname */
80 static char pidfilename[MAXPATHLEN];    /* name of pid file */
81 static char linkpidfile[MAXPATHLEN];    /* name of linkname pid file */
82 char ppp_devnam[MAXPATHLEN];    /* name of PPP tty (maybe ttypx) */
83 uid_t uid;                      /* Our real user-id */
84 struct notifier *pidchange = NULL;
85 struct notifier *phasechange = NULL;
86 struct notifier *exitnotify = NULL;
87 struct notifier *sigreceived = NULL;
88
89 int hungup;                     /* terminal has been hung up */
90 int privileged;                 /* we're running as real uid root */
91 int need_holdoff;               /* need holdoff period before restarting */
92 int detached;                   /* have detached from terminal */
93 volatile int status;            /* exit status for pppd */
94 int unsuccess;                  /* # unsuccessful connection attempts */
95 int do_callback;                /* != 0 if we should do callback next */
96 int doing_callback;             /* != 0 if we are doing callback */
97 TDB_CONTEXT *pppdb;             /* database for storing status etc. */
98 char db_key[32];
99
100 int (*holdoff_hook) __P((void)) = NULL;
101 int (*new_phase_hook) __P((int)) = NULL;
102
103 static int conn_running;        /* we have a [dis]connector running */
104 static int devfd;               /* fd of underlying device */
105 static int fd_ppp = -1;         /* fd for talking PPP */
106 static int fd_loop;             /* fd for getting demand-dial packets */
107
108 int phase;                      /* where the link is at */
109 int kill_link;
110 int open_ccp_flag;
111 int listen_time;
112 int got_sigusr2;
113 int got_sigterm;
114 int got_sighup;
115
116 static int waiting;
117 static sigjmp_buf sigjmp;
118
119 char **script_env;              /* Env. variable values for scripts */
120 int s_env_nalloc;               /* # words avail at script_env */
121
122 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
123 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
124
125 static int n_children;          /* # child processes still running */
126 static int got_sigchld;         /* set if we have received a SIGCHLD */
127
128 int privopen;                   /* don't lock, open device as root */
129
130 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
131
132 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
133 int ngroups;                    /* How many groups valid in groups */
134
135 static struct timeval start_time;       /* Time when link was started. */
136
137 struct pppd_stats link_stats;
138 int link_connect_time;
139 int link_stats_valid;
140
141 /*
142  * We maintain a list of child process pids and
143  * functions to call when they exit.
144  */
145 struct subprocess {
146     pid_t       pid;
147     char        *prog;
148     void        (*done) __P((void *));
149     void        *arg;
150     struct subprocess *next;
151 };
152
153 static struct subprocess *children;
154
155 /* Prototypes for procedures local to this file. */
156
157 static void setup_signals __P((void));
158 static void create_pidfile __P((void));
159 static void create_linkpidfile __P((void));
160 static void cleanup __P((void));
161 static void get_input __P((void));
162 static void calltimeout __P((void));
163 static struct timeval *timeleft __P((struct timeval *));
164 static void kill_my_pg __P((int));
165 static void hup __P((int));
166 static void term __P((int));
167 static void chld __P((int));
168 static void toggle_debug __P((int));
169 static void open_ccp __P((int));
170 static void bad_signal __P((int));
171 static void holdoff_end __P((void *));
172 static int reap_kids __P((int waitfor));
173 static void update_db_entry __P((void));
174 static void add_db_key __P((const char *));
175 static void delete_db_key __P((const char *));
176 static void cleanup_db __P((void));
177 static void handle_events __P((void));
178
179 extern  char    *ttyname __P((int));
180 extern  char    *getlogin __P((void));
181 int main __P((int, char *[]));
182
183 #ifdef ultrix
184 #undef  O_NONBLOCK
185 #define O_NONBLOCK      O_NDELAY
186 #endif
187
188 #ifdef ULTRIX
189 #define setlogmask(x)
190 #endif
191
192 /*
193  * PPP Data Link Layer "protocol" table.
194  * One entry per supported protocol.
195  * The last entry must be NULL.
196  */
197 struct protent *protocols[] = {
198     &lcp_protent,
199     &pap_protent,
200     &chap_protent,
201 #ifdef CBCP_SUPPORT
202     &cbcp_protent,
203 #endif
204     &ipcp_protent,
205 #ifdef INET6
206     &ipv6cp_protent,
207 #endif
208     &ccp_protent,
209 #ifdef IPX_CHANGE
210     &ipxcp_protent,
211 #endif
212 #ifdef AT_CHANGE
213     &atcp_protent,
214 #endif
215     NULL
216 };
217
218 /*
219  * If PPP_DRV_NAME is not defined, use the default "ppp" as the device name.
220  */
221 #if !defined(PPP_DRV_NAME)
222 #define PPP_DRV_NAME    "ppp"
223 #endif /* !defined(PPP_DRV_NAME) */
224
225 int
226 main(argc, argv)
227     int argc;
228     char *argv[];
229 {
230     int i, t;
231     char *p;
232     struct passwd *pw;
233     struct protent *protp;
234     char numbuf[16];
235
236     new_phase(PHASE_INITIALIZE);
237
238     /*
239      * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
240      * This way we can close 0, 1, 2 in detach() without clobbering
241      * a fd that we are using.
242      */
243     if ((i = open("/dev/null", O_RDWR)) >= 0) {
244         while (0 <= i && i <= 2)
245             i = dup(i);
246         if (i >= 0)
247             close(i);
248     }
249
250     script_env = NULL;
251
252     /* Initialize syslog facilities */
253     reopen_log();
254
255     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
256         option_error("Couldn't get hostname: %m");
257         exit(1);
258     }
259     hostname[MAXNAMELEN-1] = 0;
260
261     /* make sure we don't create world or group writable files. */
262     umask(umask(0777) | 022);
263
264     uid = getuid();
265     privileged = uid == 0;
266     slprintf(numbuf, sizeof(numbuf), "%d", uid);
267     script_setenv("ORIG_UID", numbuf, 0);
268
269     ngroups = getgroups(NGROUPS_MAX, groups);
270
271     /*
272      * Initialize magic number generator now so that protocols may
273      * use magic numbers in initialization.
274      */
275     magic_init();
276
277     /*
278      * Initialize each protocol.
279      */
280     for (i = 0; (protp = protocols[i]) != NULL; ++i)
281         (*protp->init)(0);
282
283     /*
284      * Initialize the default channel.
285      */
286     tty_init();
287
288     progname = *argv;
289
290     /*
291      * Parse, in order, the system options file, the user's options file,
292      * and the command line arguments.
293      */
294     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
295         || !options_from_user()
296         || !parse_args(argc-1, argv+1))
297         exit(EXIT_OPTION_ERROR);
298     devnam_fixed = 1;           /* can no longer change device name */
299
300     /*
301      * Work out the device name, if it hasn't already been specified,
302      * and parse the tty's options file.
303      */
304     if (the_channel->process_extra_options)
305         (*the_channel->process_extra_options)();
306
307     if (debug)
308         setlogmask(LOG_UPTO(LOG_DEBUG));
309
310     /*
311      * Check that we are running as root.
312      */
313     if (geteuid() != 0) {
314         option_error("must be root to run %s, since it is not setuid-root",
315                      argv[0]);
316         exit(EXIT_NOT_ROOT);
317     }
318
319     if (!ppp_available()) {
320         option_error("%s", no_ppp_msg);
321         exit(EXIT_NO_KERNEL_SUPPORT);
322     }
323
324     /*
325      * Check that the options given are valid and consistent.
326      */
327     check_options();
328     if (!sys_check_options())
329         exit(EXIT_OPTION_ERROR);
330     auth_check_options();
331 #ifdef HAVE_MULTILINK
332     mp_check_options();
333 #endif
334     for (i = 0; (protp = protocols[i]) != NULL; ++i)
335         if (protp->check_options != NULL)
336             (*protp->check_options)();
337     if (the_channel->check_options)
338         (*the_channel->check_options)();
339
340
341     if (dump_options || dryrun) {
342         init_pr_log(NULL, LOG_INFO);
343         print_options(pr_log, NULL);
344         end_pr_log();
345         if (dryrun)
346             die(0);
347     }
348
349     /*
350      * Initialize system-dependent stuff.
351      */
352     sys_init();
353
354     pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
355     if (pppdb != NULL) {
356         slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
357         update_db_entry();
358     } else {
359         warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
360         if (multilink) {
361             warn("Warning: disabling multilink");
362             multilink = 0;
363         }
364     }
365
366     /*
367      * Detach ourselves from the terminal, if required,
368      * and identify who is running us.
369      */
370     if (!nodetach && !updetach)
371         detach();
372     p = getlogin();
373     if (p == NULL) {
374         pw = getpwuid(uid);
375         if (pw != NULL && pw->pw_name != NULL)
376             p = pw->pw_name;
377         else
378             p = "(unknown)";
379     }
380     syslog(LOG_NOTICE, "pppd %s started by %s, uid %d", VERSION, p, uid);
381     script_setenv("PPPLOGNAME", p, 0);
382
383     if (devnam[0])
384         script_setenv("DEVICE", devnam, 1);
385     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
386     script_setenv("PPPD_PID", numbuf, 1);
387
388     setup_signals();
389
390     waiting = 0;
391
392     create_linkpidfile();
393
394     /*
395      * If we're doing dial-on-demand, set up the interface now.
396      */
397     if (demand) {
398         /*
399          * Open the loopback channel and set it up to be the ppp interface.
400          */
401         tdb_writelock(pppdb);
402         fd_loop = open_ppp_loopback();
403         set_ifunit(1);
404         tdb_writeunlock(pppdb);
405
406         /*
407          * Configure the interface and mark it up, etc.
408          */
409         demand_conf();
410     }
411
412     do_callback = 0;
413     for (;;) {
414
415         listen_time = 0;
416         need_holdoff = 1;
417         devfd = -1;
418         status = EXIT_OK;
419         ++unsuccess;
420         doing_callback = do_callback;
421         do_callback = 0;
422
423         if (demand && !doing_callback) {
424             /*
425              * Don't do anything until we see some activity.
426              */
427             new_phase(PHASE_DORMANT);
428             demand_unblock();
429             add_fd(fd_loop);
430             for (;;) {
431                 handle_events();
432                 if (kill_link && !persist)
433                     break;
434                 if (get_loop_output())
435                     break;
436             }
437             remove_fd(fd_loop);
438             if (kill_link && !persist)
439                 break;
440
441             /*
442              * Now we want to bring up the link.
443              */
444             demand_block();
445             info("Starting link");
446         }
447
448         new_phase(PHASE_SERIALCONN);
449
450         devfd = the_channel->connect();
451         if (devfd < 0)
452             goto fail;
453
454         /* set up the serial device as a ppp interface */
455         tdb_writelock(pppdb);
456         fd_ppp = the_channel->establish_ppp(devfd);
457         if (fd_ppp < 0) {
458             tdb_writeunlock(pppdb);
459             status = EXIT_FATAL_ERROR;
460             goto disconnect;
461         }
462
463         if (!demand && ifunit >= 0)
464             set_ifunit(1);
465         tdb_writeunlock(pppdb);
466
467         /*
468          * Start opening the connection and wait for
469          * incoming events (reply, timeout, etc.).
470          */
471         if (ifunit >= 0)
472                 notice("Connect: %s <--> %s", ifname, ppp_devnam);
473         else
474                 notice("Starting negotiation on %s", ppp_devnam);
475         gettimeofday(&start_time, NULL);
476         link_stats_valid = 0;
477         script_unsetenv("CONNECT_TIME");
478         script_unsetenv("BYTES_SENT");
479         script_unsetenv("BYTES_RCVD");
480         lcp_lowerup(0);
481
482         add_fd(fd_ppp);
483         lcp_open(0);            /* Start protocol */
484         status = EXIT_NEGOTIATION_FAILED;
485         new_phase(PHASE_ESTABLISH);
486         while (phase != PHASE_DEAD) {
487             handle_events();
488             get_input();
489             if (kill_link)
490                 lcp_close(0, "User request");
491             if (open_ccp_flag) {
492                 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
493                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
494                     (*ccp_protent.open)(0);
495                 }
496             }
497         }
498
499         /*
500          * Print connect time and statistics.
501          */
502         if (link_stats_valid) {
503             int t = (link_connect_time + 5) / 6;    /* 1/10ths of minutes */
504             info("Connect time %d.%d minutes.", t/10, t%10);
505             info("Sent %u bytes, received %u bytes.",
506                  link_stats.bytes_out, link_stats.bytes_in);
507         }
508
509         /*
510          * Delete pid file before disestablishing ppp.  Otherwise it
511          * can happen that another pppd gets the same unit and then
512          * we delete its pid file.
513          */
514         if (!demand) {
515             if (pidfilename[0] != 0
516                 && unlink(pidfilename) < 0 && errno != ENOENT) 
517                 warn("unable to delete pid file %s: %m", pidfilename);
518             pidfilename[0] = 0;
519         }
520
521         /*
522          * If we may want to bring the link up again, transfer
523          * the ppp unit back to the loopback.  Set the
524          * real serial device back to its normal mode of operation.
525          */
526         remove_fd(fd_ppp);
527         clean_check();
528         the_channel->disestablish_ppp(devfd);
529         fd_ppp = -1;
530         if (!hungup)
531             lcp_lowerdown(0);
532         if (!demand)
533             script_unsetenv("IFNAME");
534
535         /*
536          * Run disconnector script, if requested.
537          * XXX we may not be able to do this if the line has hung up!
538          */
539     disconnect:
540         new_phase(PHASE_DISCONNECT);
541         the_channel->disconnect();
542
543     fail:
544         if (the_channel->cleanup)
545             (*the_channel->cleanup)();
546
547         if (!demand) {
548             if (pidfilename[0] != 0
549                 && unlink(pidfilename) < 0 && errno != ENOENT) 
550                 warn("unable to delete pid file %s: %m", pidfilename);
551             pidfilename[0] = 0;
552         }
553
554         if (!persist || (maxfail > 0 && unsuccess >= maxfail))
555             break;
556
557         if (demand)
558             demand_discard();
559         t = need_holdoff? holdoff: 0;
560         if (holdoff_hook)
561             t = (*holdoff_hook)();
562         if (t > 0) {
563             new_phase(PHASE_HOLDOFF);
564             TIMEOUT(holdoff_end, NULL, t);
565             do {
566                 handle_events();
567                 if (kill_link)
568                     new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
569             } while (phase == PHASE_HOLDOFF);
570             if (!persist)
571                 break;
572         }
573     }
574
575     /* Wait for scripts to finish */
576     /* XXX should have a timeout here */
577     while (n_children > 0) {
578         if (debug) {
579             struct subprocess *chp;
580             dbglog("Waiting for %d child processes...", n_children);
581             for (chp = children; chp != NULL; chp = chp->next)
582                 dbglog("  script %s, pid %d", chp->prog, chp->pid);
583         }
584         if (reap_kids(1) < 0)
585             break;
586     }
587
588     die(status);
589     return 0;
590 }
591
592 /*
593  * handle_events - wait for something to happen and respond to it.
594  */
595 static void
596 handle_events()
597 {
598     struct timeval timo;
599     sigset_t mask;
600
601     kill_link = open_ccp_flag = 0;
602     if (sigsetjmp(sigjmp, 1) == 0) {
603         sigprocmask(SIG_BLOCK, &mask, NULL);
604         if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
605             sigprocmask(SIG_UNBLOCK, &mask, NULL);
606         } else {
607             waiting = 1;
608             sigprocmask(SIG_UNBLOCK, &mask, NULL);
609             wait_input(timeleft(&timo));
610         }
611     }
612     waiting = 0;
613     calltimeout();
614     if (got_sighup) {
615         kill_link = 1;
616         got_sighup = 0;
617         if (status != EXIT_HANGUP)
618             status = EXIT_USER_REQUEST;
619     }
620     if (got_sigterm) {
621         kill_link = 1;
622         persist = 0;
623         status = EXIT_USER_REQUEST;
624         got_sigterm = 0;
625     }
626     if (got_sigchld) {
627         reap_kids(0);   /* Don't leave dead kids lying around */
628         got_sigchld = 0;
629     }
630     if (got_sigusr2) {
631         open_ccp_flag = 1;
632         got_sigusr2 = 0;
633     }
634 }
635
636 /*
637  * setup_signals - initialize signal handling.
638  */
639 static void
640 setup_signals()
641 {
642     struct sigaction sa;
643     sigset_t mask;
644
645     /*
646      * Compute mask of all interesting signals and install signal handlers
647      * for each.  Only one signal handler may be active at a time.  Therefore,
648      * all other signals should be masked when any handler is executing.
649      */
650     sigemptyset(&mask);
651     sigaddset(&mask, SIGHUP);
652     sigaddset(&mask, SIGINT);
653     sigaddset(&mask, SIGTERM);
654     sigaddset(&mask, SIGCHLD);
655     sigaddset(&mask, SIGUSR2);
656
657 #define SIGNAL(s, handler)      do { \
658         sa.sa_handler = handler; \
659         if (sigaction(s, &sa, NULL) < 0) \
660             fatal("Couldn't establish signal handler (%d): %m", s); \
661     } while (0)
662
663     sa.sa_mask = mask;
664     sa.sa_flags = 0;
665     SIGNAL(SIGHUP, hup);                /* Hangup */
666     SIGNAL(SIGINT, term);               /* Interrupt */
667     SIGNAL(SIGTERM, term);              /* Terminate */
668     SIGNAL(SIGCHLD, chld);
669
670     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
671     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
672
673     /*
674      * Install a handler for other signals which would otherwise
675      * cause pppd to exit without cleaning up.
676      */
677     SIGNAL(SIGABRT, bad_signal);
678     SIGNAL(SIGALRM, bad_signal);
679     SIGNAL(SIGFPE, bad_signal);
680     SIGNAL(SIGILL, bad_signal);
681     SIGNAL(SIGPIPE, bad_signal);
682     SIGNAL(SIGQUIT, bad_signal);
683     SIGNAL(SIGSEGV, bad_signal);
684 #ifdef SIGBUS
685     SIGNAL(SIGBUS, bad_signal);
686 #endif
687 #ifdef SIGEMT
688     SIGNAL(SIGEMT, bad_signal);
689 #endif
690 #ifdef SIGPOLL
691     SIGNAL(SIGPOLL, bad_signal);
692 #endif
693 #ifdef SIGPROF
694     SIGNAL(SIGPROF, bad_signal);
695 #endif
696 #ifdef SIGSYS
697     SIGNAL(SIGSYS, bad_signal);
698 #endif
699 #ifdef SIGTRAP
700     SIGNAL(SIGTRAP, bad_signal);
701 #endif
702 #ifdef SIGVTALRM
703     SIGNAL(SIGVTALRM, bad_signal);
704 #endif
705 #ifdef SIGXCPU
706     SIGNAL(SIGXCPU, bad_signal);
707 #endif
708 #ifdef SIGXFSZ
709     SIGNAL(SIGXFSZ, bad_signal);
710 #endif
711
712     /*
713      * Apparently we can get a SIGPIPE when we call syslog, if
714      * syslogd has died and been restarted.  Ignoring it seems
715      * be sufficient.
716      */
717     signal(SIGPIPE, SIG_IGN);
718 }
719
720 /*
721  * set_ifunit - do things we need to do once we know which ppp
722  * unit we are using.
723  */
724 void
725 set_ifunit(iskey)
726     int iskey;
727 {
728     info("Using interface %s%d", PPP_DRV_NAME, ifunit);
729     slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
730     script_setenv("IFNAME", ifname, iskey);
731     if (iskey) {
732         create_pidfile();       /* write pid to file */
733         create_linkpidfile();
734     }
735 }
736
737 /*
738  * detach - detach us from the controlling terminal.
739  */
740 void
741 detach()
742 {
743     int pid;
744     char numbuf[16];
745
746     if (detached)
747         return;
748     if ((pid = fork()) < 0) {
749         error("Couldn't detach (fork failed: %m)");
750         die(1);                 /* or just return? */
751     }
752     if (pid != 0) {
753         /* parent */
754         notify(pidchange, pid);
755         exit(0);                /* parent dies */
756     }
757     setsid();
758     chdir("/");
759     close(0);
760     close(1);
761     close(2);
762     detached = 1;
763     if (log_default)
764         log_to_fd = -1;
765     /* update pid files if they have been written already */
766     if (pidfilename[0])
767         create_pidfile();
768     if (linkpidfile[0])
769         create_linkpidfile();
770     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
771     script_setenv("PPPD_PID", numbuf, 1);
772 }
773
774 /*
775  * reopen_log - (re)open our connection to syslog.
776  */
777 void
778 reopen_log()
779 {
780 #ifdef ULTRIX
781     openlog("pppd", LOG_PID);
782 #else
783     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
784     setlogmask(LOG_UPTO(LOG_INFO));
785 #endif
786 }
787
788 /*
789  * Create a file containing our process ID.
790  */
791 static void
792 create_pidfile()
793 {
794     FILE *pidfile;
795
796     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
797              _PATH_VARRUN, ifname);
798     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
799         fprintf(pidfile, "%d\n", getpid());
800         (void) fclose(pidfile);
801     } else {
802         error("Failed to create pid file %s: %m", pidfilename);
803         pidfilename[0] = 0;
804     }
805 }
806
807 static void
808 create_linkpidfile()
809 {
810     FILE *pidfile;
811
812     if (linkname[0] == 0)
813         return;
814     script_setenv("LINKNAME", linkname, 1);
815     slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
816              _PATH_VARRUN, linkname);
817     if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
818         fprintf(pidfile, "%d\n", getpid());
819         if (ifname[0])
820             fprintf(pidfile, "%s\n", ifname);
821         (void) fclose(pidfile);
822     } else {
823         error("Failed to create pid file %s: %m", linkpidfile);
824         linkpidfile[0] = 0;
825     }
826 }
827
828 /*
829  * holdoff_end - called via a timeout when the holdoff period ends.
830  */
831 static void
832 holdoff_end(arg)
833     void *arg;
834 {
835     new_phase(PHASE_DORMANT);
836 }
837
838 /* List of protocol names, to make our messages a little more informative. */
839 struct protocol_list {
840     u_short     proto;
841     const char  *name;
842 } protocol_list[] = {
843     { 0x21,     "IP" },
844     { 0x23,     "OSI Network Layer" },
845     { 0x25,     "Xerox NS IDP" },
846     { 0x27,     "DECnet Phase IV" },
847     { 0x29,     "Appletalk" },
848     { 0x2b,     "Novell IPX" },
849     { 0x2d,     "VJ compressed TCP/IP" },
850     { 0x2f,     "VJ uncompressed TCP/IP" },
851     { 0x31,     "Bridging PDU" },
852     { 0x33,     "Stream Protocol ST-II" },
853     { 0x35,     "Banyan Vines" },
854     { 0x39,     "AppleTalk EDDP" },
855     { 0x3b,     "AppleTalk SmartBuffered" },
856     { 0x3d,     "Multi-Link" },
857     { 0x3f,     "NETBIOS Framing" },
858     { 0x41,     "Cisco Systems" },
859     { 0x43,     "Ascom Timeplex" },
860     { 0x45,     "Fujitsu Link Backup and Load Balancing (LBLB)" },
861     { 0x47,     "DCA Remote Lan" },
862     { 0x49,     "Serial Data Transport Protocol (PPP-SDTP)" },
863     { 0x4b,     "SNA over 802.2" },
864     { 0x4d,     "SNA" },
865     { 0x4f,     "IP6 Header Compression" },
866     { 0x6f,     "Stampede Bridging" },
867     { 0xfb,     "single-link compression" },
868     { 0xfd,     "1st choice compression" },
869     { 0x0201,   "802.1d Hello Packets" },
870     { 0x0203,   "IBM Source Routing BPDU" },
871     { 0x0205,   "DEC LANBridge100 Spanning Tree" },
872     { 0x0231,   "Luxcom" },
873     { 0x0233,   "Sigma Network Systems" },
874     { 0x8021,   "Internet Protocol Control Protocol" },
875     { 0x8023,   "OSI Network Layer Control Protocol" },
876     { 0x8025,   "Xerox NS IDP Control Protocol" },
877     { 0x8027,   "DECnet Phase IV Control Protocol" },
878     { 0x8029,   "Appletalk Control Protocol" },
879     { 0x802b,   "Novell IPX Control Protocol" },
880     { 0x8031,   "Bridging NCP" },
881     { 0x8033,   "Stream Protocol Control Protocol" },
882     { 0x8035,   "Banyan Vines Control Protocol" },
883     { 0x803d,   "Multi-Link Control Protocol" },
884     { 0x803f,   "NETBIOS Framing Control Protocol" },
885     { 0x8041,   "Cisco Systems Control Protocol" },
886     { 0x8043,   "Ascom Timeplex" },
887     { 0x8045,   "Fujitsu LBLB Control Protocol" },
888     { 0x8047,   "DCA Remote Lan Network Control Protocol (RLNCP)" },
889     { 0x8049,   "Serial Data Control Protocol (PPP-SDCP)" },
890     { 0x804b,   "SNA over 802.2 Control Protocol" },
891     { 0x804d,   "SNA Control Protocol" },
892     { 0x804f,   "IP6 Header Compression Control Protocol" },
893     { 0x006f,   "Stampede Bridging Control Protocol" },
894     { 0x80fb,   "Single Link Compression Control Protocol" },
895     { 0x80fd,   "Compression Control Protocol" },
896     { 0xc021,   "Link Control Protocol" },
897     { 0xc023,   "Password Authentication Protocol" },
898     { 0xc025,   "Link Quality Report" },
899     { 0xc027,   "Shiva Password Authentication Protocol" },
900     { 0xc029,   "CallBack Control Protocol (CBCP)" },
901     { 0xc081,   "Container Control Protocol" },
902     { 0xc223,   "Challenge Handshake Authentication Protocol" },
903     { 0xc281,   "Proprietary Authentication Protocol" },
904     { 0,        NULL },
905 };
906
907 /*
908  * protocol_name - find a name for a PPP protocol.
909  */
910 const char *
911 protocol_name(proto)
912     int proto;
913 {
914     struct protocol_list *lp;
915
916     for (lp = protocol_list; lp->proto != 0; ++lp)
917         if (proto == lp->proto)
918             return lp->name;
919     return NULL;
920 }
921
922 /*
923  * get_input - called when incoming data is available.
924  */
925 static void
926 get_input()
927 {
928     int len, i;
929     u_char *p;
930     u_short protocol;
931     struct protent *protp;
932
933     p = inpacket_buf;   /* point to beginning of packet buffer */
934
935     len = read_packet(inpacket_buf);
936     if (len < 0)
937         return;
938
939     if (len == 0) {
940         notice("Modem hangup");
941         hungup = 1;
942         status = EXIT_HANGUP;
943         lcp_lowerdown(0);       /* serial link is no longer available */
944         link_terminated(0);
945         return;
946     }
947
948     if (len < PPP_HDRLEN) {
949         dbglog("received short packet:%.*B", len, p);
950         return;
951     }
952
953     dump_packet("rcvd", p, len);
954
955     p += 2;                             /* Skip address and control */
956     GETSHORT(protocol, p);
957     len -= PPP_HDRLEN;
958
959     /*
960      * Toss all non-LCP packets unless LCP is OPEN.
961      */
962     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
963         MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
964         return;
965     }
966
967     /*
968      * Until we get past the authentication phase, toss all packets
969      * except LCP, LQR and authentication packets.
970      */
971     if (phase <= PHASE_AUTHENTICATE
972         && !(protocol == PPP_LCP || protocol == PPP_LQR
973              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
974         MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
975                    protocol, phase));
976         return;
977     }
978
979     /*
980      * Upcall the proper protocol input routine.
981      */
982     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
983         if (protp->protocol == protocol && protp->enabled_flag) {
984             (*protp->input)(0, p, len);
985             return;
986         }
987         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
988             && protp->datainput != NULL) {
989             (*protp->datainput)(0, p, len);
990             return;
991         }
992     }
993
994     if (debug) {
995         const char *pname = protocol_name(protocol);
996         if (pname != NULL)
997             warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
998         else
999             warn("Unsupported protocol 0x%x received", protocol);
1000     }
1001     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1002 }
1003
1004 /*
1005  * new_phase - signal the start of a new phase of pppd's operation.
1006  */
1007 void
1008 new_phase(p)
1009     int p;
1010 {
1011     phase = p;
1012     if (new_phase_hook)
1013         (*new_phase_hook)(p);
1014     notify(phasechange, p);
1015 }
1016
1017 /*
1018  * die - clean up state and exit with the specified status.
1019  */
1020 void
1021 die(status)
1022     int status;
1023 {
1024     cleanup();
1025     notify(exitnotify, status);
1026     syslog(LOG_INFO, "Exit.");
1027     exit(status);
1028 }
1029
1030 /*
1031  * cleanup - restore anything which needs to be restored before we exit
1032  */
1033 /* ARGSUSED */
1034 static void
1035 cleanup()
1036 {
1037     sys_cleanup();
1038
1039     if (fd_ppp >= 0)
1040         the_channel->disestablish_ppp(devfd);
1041     if (the_channel->cleanup)
1042         (*the_channel->cleanup)();
1043
1044     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
1045         warn("unable to delete pid file %s: %m", pidfilename);
1046     pidfilename[0] = 0;
1047     if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT) 
1048         warn("unable to delete pid file %s: %m", linkpidfile);
1049     linkpidfile[0] = 0;
1050
1051     if (pppdb != NULL)
1052         cleanup_db();
1053 }
1054
1055 /*
1056  * update_link_stats - get stats at link termination.
1057  */
1058 void
1059 update_link_stats(u)
1060     int u;
1061 {
1062     struct timeval now;
1063     char numbuf[32];
1064
1065     if (!get_ppp_stats(u, &link_stats)
1066         || gettimeofday(&now, NULL) < 0)
1067         return;
1068     link_connect_time = now.tv_sec - start_time.tv_sec;
1069     link_stats_valid = 1;
1070
1071     slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1072     script_setenv("CONNECT_TIME", numbuf, 0);
1073     slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1074     script_setenv("BYTES_SENT", numbuf, 0);
1075     slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1076     script_setenv("BYTES_RCVD", numbuf, 0);
1077 }
1078
1079
1080 struct  callout {
1081     struct timeval      c_time;         /* time at which to call routine */
1082     void                *c_arg;         /* argument to routine */
1083     void                (*c_func) __P((void *)); /* routine */
1084     struct              callout *c_next;
1085 };
1086
1087 static struct callout *callout = NULL;  /* Callout list */
1088 static struct timeval timenow;          /* Current time */
1089
1090 /*
1091  * timeout - Schedule a timeout.
1092  */
1093 void
1094 timeout(func, arg, secs, usecs)
1095     void (*func) __P((void *));
1096     void *arg;
1097     int secs, usecs;
1098 {
1099     struct callout *newp, *p, **pp;
1100
1101     MAINDEBUG(("Timeout %p:%p in %d.%03d seconds.", func, arg,
1102                secs, usecs/1000));
1103
1104     /*
1105      * Allocate timeout.
1106      */
1107     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1108         fatal("Out of memory in timeout()!");
1109     newp->c_arg = arg;
1110     newp->c_func = func;
1111     gettimeofday(&timenow, NULL);
1112     newp->c_time.tv_sec = timenow.tv_sec + secs;
1113     newp->c_time.tv_usec = timenow.tv_usec + usecs;
1114     if (newp->c_time.tv_usec >= 1000000) {
1115         newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
1116         newp->c_time.tv_usec %= 1000000;
1117     }
1118
1119     /*
1120      * Find correct place and link it in.
1121      */
1122     for (pp = &callout; (p = *pp); pp = &p->c_next)
1123         if (newp->c_time.tv_sec < p->c_time.tv_sec
1124             || (newp->c_time.tv_sec == p->c_time.tv_sec
1125                 && newp->c_time.tv_usec < p->c_time.tv_usec))
1126             break;
1127     newp->c_next = p;
1128     *pp = newp;
1129 }
1130
1131
1132 /*
1133  * untimeout - Unschedule a timeout.
1134  */
1135 void
1136 untimeout(func, arg)
1137     void (*func) __P((void *));
1138     void *arg;
1139 {
1140     struct callout **copp, *freep;
1141   
1142     MAINDEBUG(("Untimeout %p:%p.", func, arg));
1143   
1144     /*
1145      * Find first matching timeout and remove it from the list.
1146      */
1147     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1148         if (freep->c_func == func && freep->c_arg == arg) {
1149             *copp = freep->c_next;
1150             free((char *) freep);
1151             break;
1152         }
1153 }
1154
1155
1156 /*
1157  * calltimeout - Call any timeout routines which are now due.
1158  */
1159 static void
1160 calltimeout()
1161 {
1162     struct callout *p;
1163
1164     while (callout != NULL) {
1165         p = callout;
1166
1167         if (gettimeofday(&timenow, NULL) < 0)
1168             fatal("Failed to get time of day: %m");
1169         if (!(p->c_time.tv_sec < timenow.tv_sec
1170               || (p->c_time.tv_sec == timenow.tv_sec
1171                   && p->c_time.tv_usec <= timenow.tv_usec)))
1172             break;              /* no, it's not time yet */
1173
1174         callout = p->c_next;
1175         (*p->c_func)(p->c_arg);
1176
1177         free((char *) p);
1178     }
1179 }
1180
1181
1182 /*
1183  * timeleft - return the length of time until the next timeout is due.
1184  */
1185 static struct timeval *
1186 timeleft(tvp)
1187     struct timeval *tvp;
1188 {
1189     if (callout == NULL)
1190         return NULL;
1191
1192     gettimeofday(&timenow, NULL);
1193     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1194     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1195     if (tvp->tv_usec < 0) {
1196         tvp->tv_usec += 1000000;
1197         tvp->tv_sec -= 1;
1198     }
1199     if (tvp->tv_sec < 0)
1200         tvp->tv_sec = tvp->tv_usec = 0;
1201
1202     return tvp;
1203 }
1204
1205
1206 /*
1207  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1208  */
1209 static void
1210 kill_my_pg(sig)
1211     int sig;
1212 {
1213     struct sigaction act, oldact;
1214
1215     act.sa_handler = SIG_IGN;
1216     act.sa_flags = 0;
1217     kill(0, sig);
1218     sigaction(sig, &act, &oldact);
1219     sigaction(sig, &oldact, NULL);
1220 }
1221
1222
1223 /*
1224  * hup - Catch SIGHUP signal.
1225  *
1226  * Indicates that the physical layer has been disconnected.
1227  * We don't rely on this indication; if the user has sent this
1228  * signal, we just take the link down.
1229  */
1230 static void
1231 hup(sig)
1232     int sig;
1233 {
1234     info("Hangup (SIGHUP)");
1235     got_sighup = 1;
1236     if (conn_running)
1237         /* Send the signal to the [dis]connector process(es) also */
1238         kill_my_pg(sig);
1239     notify(sigreceived, sig);
1240     if (waiting)
1241         siglongjmp(sigjmp, 1);
1242 }
1243
1244
1245 /*
1246  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1247  *
1248  * Indicates that we should initiate a graceful disconnect and exit.
1249  */
1250 /*ARGSUSED*/
1251 static void
1252 term(sig)
1253     int sig;
1254 {
1255     info("Terminating on signal %d.", sig);
1256     got_sigterm = 1;
1257     if (conn_running)
1258         /* Send the signal to the [dis]connector process(es) also */
1259         kill_my_pg(sig);
1260     notify(sigreceived, sig);
1261     if (waiting)
1262         siglongjmp(sigjmp, 1);
1263 }
1264
1265
1266 /*
1267  * chld - Catch SIGCHLD signal.
1268  * Sets a flag so we will call reap_kids in the mainline.
1269  */
1270 static void
1271 chld(sig)
1272     int sig;
1273 {
1274     got_sigchld = 1;
1275     if (waiting)
1276         siglongjmp(sigjmp, 1);
1277 }
1278
1279
1280 /*
1281  * toggle_debug - Catch SIGUSR1 signal.
1282  *
1283  * Toggle debug flag.
1284  */
1285 /*ARGSUSED*/
1286 static void
1287 toggle_debug(sig)
1288     int sig;
1289 {
1290     debug = !debug;
1291     if (debug) {
1292         setlogmask(LOG_UPTO(LOG_DEBUG));
1293     } else {
1294         setlogmask(LOG_UPTO(LOG_WARNING));
1295     }
1296 }
1297
1298
1299 /*
1300  * open_ccp - Catch SIGUSR2 signal.
1301  *
1302  * Try to (re)negotiate compression.
1303  */
1304 /*ARGSUSED*/
1305 static void
1306 open_ccp(sig)
1307     int sig;
1308 {
1309     got_sigusr2 = 1;
1310     if (waiting)
1311         siglongjmp(sigjmp, 1);
1312 }
1313
1314
1315 /*
1316  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1317  */
1318 static void
1319 bad_signal(sig)
1320     int sig;
1321 {
1322     static int crashed = 0;
1323
1324     if (crashed)
1325         _exit(127);
1326     crashed = 1;
1327     error("Fatal signal %d", sig);
1328     if (conn_running)
1329         kill_my_pg(SIGTERM);
1330     notify(sigreceived, sig);
1331     die(127);
1332 }
1333
1334
1335 /*
1336  * device_script - run a program to talk to the specified fds
1337  * (e.g. to run the connector or disconnector script).
1338  * stderr gets connected to the log fd or to the _PATH_CONNERRS file.
1339  */
1340 int
1341 device_script(program, in, out, dont_wait)
1342     char *program;
1343     int in, out;
1344     int dont_wait;
1345 {
1346     int pid, fd;
1347     int status = -1;
1348     int errfd;
1349
1350     ++conn_running;
1351     pid = fork();
1352
1353     if (pid < 0) {
1354         --conn_running;
1355         error("Failed to create child process: %m");
1356         return -1;
1357     }
1358
1359     if (pid != 0) {
1360         if (dont_wait) {
1361             record_child(pid, program, NULL, NULL);
1362             status = 0;
1363         } else {
1364             while (waitpid(pid, &status, 0) < 0) {
1365                 if (errno == EINTR)
1366                     continue;
1367                 fatal("error waiting for (dis)connection process: %m");
1368             }
1369             --conn_running;
1370         }
1371         return (status == 0 ? 0 : -1);
1372     }
1373
1374     /* here we are executing in the child */
1375     /* make sure fds 0, 1, 2 are occupied */
1376     while ((fd = dup(in)) >= 0) {
1377         if (fd > 2) {
1378             close(fd);
1379             break;
1380         }
1381     }
1382
1383     /* dup in and out to fds > 2 */
1384     in = dup(in);
1385     out = dup(out);
1386     if (log_to_fd >= 0) {
1387         errfd = dup(log_to_fd);
1388     } else {
1389         errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1390     }
1391
1392     /* close fds 0 - 2 and any others we can think of */
1393     close(0);
1394     close(1);
1395     close(2);
1396     sys_close();
1397     if (the_channel->close)
1398         (*the_channel->close)();
1399     closelog();
1400
1401     /* dup the in, out, err fds to 0, 1, 2 */
1402     dup2(in, 0);
1403     close(in);
1404     dup2(out, 1);
1405     close(out);
1406     if (errfd >= 0) {
1407         dup2(errfd, 2);
1408         close(errfd);
1409     }
1410
1411     setuid(uid);
1412     if (getuid() != uid) {
1413         error("setuid failed");
1414         exit(1);
1415     }
1416     setgid(getgid());
1417     execl("/bin/sh", "sh", "-c", program, (char *)0);
1418     error("could not exec /bin/sh: %m");
1419     exit(99);
1420     /* NOTREACHED */
1421 }
1422
1423
1424 /*
1425  * run-program - execute a program with given arguments,
1426  * but don't wait for it.
1427  * If the program can't be executed, logs an error unless
1428  * must_exist is 0 and the program file doesn't exist.
1429  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1430  * or isn't an executable plain file, or the process ID of the child.
1431  * If done != NULL, (*done)(arg) will be called later (within
1432  * reap_kids) iff the return value is > 0.
1433  */
1434 pid_t
1435 run_program(prog, args, must_exist, done, arg)
1436     char *prog;
1437     char **args;
1438     int must_exist;
1439     void (*done) __P((void *));
1440     void *arg;
1441 {
1442     int pid;
1443     struct stat sbuf;
1444
1445     /*
1446      * First check if the file exists and is executable.
1447      * We don't use access() because that would use the
1448      * real user-id, which might not be root, and the script
1449      * might be accessible only to root.
1450      */
1451     errno = EINVAL;
1452     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1453         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1454         if (must_exist || errno != ENOENT)
1455             warn("Can't execute %s: %m", prog);
1456         return 0;
1457     }
1458
1459     pid = fork();
1460     if (pid == -1) {
1461         error("Failed to create child process for %s: %m", prog);
1462         return -1;
1463     }
1464     if (pid == 0) {
1465         int new_fd;
1466
1467         /* Leave the current location */
1468         (void) setsid();        /* No controlling tty. */
1469         (void) umask (S_IRWXG|S_IRWXO);
1470         (void) chdir ("/");     /* no current directory. */
1471         setuid(0);              /* set real UID = root */
1472         setgid(getegid());
1473
1474         /* Ensure that nothing of our device environment is inherited. */
1475         sys_close();
1476         closelog();
1477         close (0);
1478         close (1);
1479         close (2);
1480         if (the_channel->close)
1481             (*the_channel->close)();
1482
1483         /* Don't pass handles to the PPP device, even by accident. */
1484         new_fd = open (_PATH_DEVNULL, O_RDWR);
1485         if (new_fd >= 0) {
1486             if (new_fd != 0) {
1487                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1488                 close (new_fd);
1489             }
1490             dup2 (0, 1); /* stdout -> /dev/null */
1491             dup2 (0, 2); /* stderr -> /dev/null */
1492         }
1493
1494 #ifdef BSD
1495         /* Force the priority back to zero if pppd is running higher. */
1496         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1497             warn("can't reset priority to 0: %m"); 
1498 #endif
1499
1500         /* SysV recommends a second fork at this point. */
1501
1502         /* run the program */
1503         execve(prog, args, script_env);
1504         if (must_exist || errno != ENOENT) {
1505             /* have to reopen the log, there's nowhere else
1506                for the message to go. */
1507             reopen_log();
1508             syslog(LOG_ERR, "Can't execute %s: %m", prog);
1509             closelog();
1510         }
1511         _exit(-1);
1512     }
1513
1514     if (debug)
1515         dbglog("Script %s started (pid %d)", prog, pid);
1516     record_child(pid, prog, done, arg);
1517
1518     return pid;
1519 }
1520
1521
1522 /*
1523  * record_child - add a child process to the list for reap_kids
1524  * to use.
1525  */
1526 void
1527 record_child(pid, prog, done, arg)
1528     int pid;
1529     char *prog;
1530     void (*done) __P((void *));
1531     void *arg;
1532 {
1533     struct subprocess *chp;
1534
1535     ++n_children;
1536
1537     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1538     if (chp == NULL) {
1539         warn("losing track of %s process", prog);
1540     } else {
1541         chp->pid = pid;
1542         chp->prog = prog;
1543         chp->done = done;
1544         chp->arg = arg;
1545         chp->next = children;
1546         children = chp;
1547     }
1548 }
1549
1550
1551 /*
1552  * reap_kids - get status from any dead child processes,
1553  * and log a message for abnormal terminations.
1554  */
1555 static int
1556 reap_kids(waitfor)
1557     int waitfor;
1558 {
1559     int pid, status;
1560     struct subprocess *chp, **prevp;
1561
1562     if (n_children == 0)
1563         return 0;
1564     while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1565            && pid != 0) {
1566         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1567             if (chp->pid == pid) {
1568                 --n_children;
1569                 *prevp = chp->next;
1570                 break;
1571             }
1572         }
1573         if (WIFSIGNALED(status)) {
1574             warn("Child process %s (pid %d) terminated with signal %d",
1575                  (chp? chp->prog: "??"), pid, WTERMSIG(status));
1576         } else if (debug)
1577             dbglog("Script %s finished (pid %d), status = 0x%x",
1578                    (chp? chp->prog: "??"), pid, status);
1579         if (chp && chp->done)
1580             (*chp->done)(chp->arg);
1581         if (chp)
1582             free(chp);
1583     }
1584     if (pid == -1) {
1585         if (errno == ECHILD)
1586             return -1;
1587         if (errno != EINTR)
1588             error("Error waiting for child process: %m");
1589     }
1590     return 0;
1591 }
1592
1593 /*
1594  * add_notifier - add a new function to be called when something happens.
1595  */
1596 void
1597 add_notifier(notif, func, arg)
1598     struct notifier **notif;
1599     notify_func func;
1600     void *arg;
1601 {
1602     struct notifier *np;
1603
1604     np = malloc(sizeof(struct notifier));
1605     if (np == 0)
1606         novm("notifier struct");
1607     np->next = *notif;
1608     np->func = func;
1609     np->arg = arg;
1610     *notif = np;
1611 }
1612
1613 /*
1614  * remove_notifier - remove a function from the list of things to
1615  * be called when something happens.
1616  */
1617 void
1618 remove_notifier(notif, func, arg)
1619     struct notifier **notif;
1620     notify_func func;
1621     void *arg;
1622 {
1623     struct notifier *np;
1624
1625     for (; (np = *notif) != 0; notif = &np->next) {
1626         if (np->func == func && np->arg == arg) {
1627             *notif = np->next;
1628             free(np);
1629             break;
1630         }
1631     }
1632 }
1633
1634 /*
1635  * notify - call a set of functions registered with add_notify.
1636  */
1637 void
1638 notify(notif, val)
1639     struct notifier *notif;
1640     int val;
1641 {
1642     struct notifier *np;
1643
1644     while ((np = notif) != 0) {
1645         notif = np->next;
1646         (*np->func)(np->arg, val);
1647     }
1648 }
1649
1650 /*
1651  * novm - log an error message saying we ran out of memory, and die.
1652  */
1653 void
1654 novm(msg)
1655     char *msg;
1656 {
1657     fatal("Virtual memory exhausted allocating %s\n", msg);
1658 }
1659
1660 /*
1661  * script_setenv - set an environment variable value to be used
1662  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1663  */
1664 void
1665 script_setenv(var, value, iskey)
1666     char *var, *value;
1667     int iskey;
1668 {
1669     size_t varl = strlen(var);
1670     size_t vl = varl + strlen(value) + 2;
1671     int i;
1672     char *p, *newstring;
1673
1674     newstring = (char *) malloc(vl+1);
1675     if (newstring == 0)
1676         return;
1677     *newstring++ = iskey;
1678     slprintf(newstring, vl, "%s=%s", var, value);
1679
1680     /* check if this variable is already set */
1681     if (script_env != 0) {
1682         for (i = 0; (p = script_env[i]) != 0; ++i) {
1683             if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1684                 if (p[-1] && pppdb != NULL)
1685                     delete_db_key(p);
1686                 free(p-1);
1687                 script_env[i] = newstring;
1688                 if (iskey && pppdb != NULL)
1689                     add_db_key(newstring);
1690                 update_db_entry();
1691                 return;
1692             }
1693         }
1694     } else {
1695         /* no space allocated for script env. ptrs. yet */
1696         i = 0;
1697         script_env = (char **) malloc(16 * sizeof(char *));
1698         if (script_env == 0)
1699             return;
1700         s_env_nalloc = 16;
1701     }
1702
1703     /* reallocate script_env with more space if needed */
1704     if (i + 1 >= s_env_nalloc) {
1705         int new_n = i + 17;
1706         char **newenv = (char **) realloc((void *)script_env,
1707                                           new_n * sizeof(char *));
1708         if (newenv == 0)
1709             return;
1710         script_env = newenv;
1711         s_env_nalloc = new_n;
1712     }
1713
1714     script_env[i] = newstring;
1715     script_env[i+1] = 0;
1716
1717     if (pppdb != NULL) {
1718         if (iskey)
1719             add_db_key(newstring);
1720         update_db_entry();
1721     }
1722 }
1723
1724 /*
1725  * script_unsetenv - remove a variable from the environment
1726  * for scripts.
1727  */
1728 void
1729 script_unsetenv(var)
1730     char *var;
1731 {
1732     int vl = strlen(var);
1733     int i;
1734     char *p;
1735
1736     if (script_env == 0)
1737         return;
1738     for (i = 0; (p = script_env[i]) != 0; ++i) {
1739         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1740             if (p[-1] && pppdb != NULL)
1741                 delete_db_key(p);
1742             free(p-1);
1743             while ((script_env[i] = script_env[i+1]) != 0)
1744                 ++i;
1745             break;
1746         }
1747     }
1748     if (pppdb != NULL)
1749         update_db_entry();
1750 }
1751
1752 /*
1753  * update_db_entry - update our entry in the database.
1754  */
1755 static void
1756 update_db_entry()
1757 {
1758     TDB_DATA key, dbuf;
1759     int vlen, i;
1760     char *p, *q, *vbuf;
1761
1762     if (script_env == NULL)
1763         return;
1764     vlen = 0;
1765     for (i = 0; (p = script_env[i]) != 0; ++i)
1766         vlen += strlen(p) + 1;
1767     vbuf = malloc(vlen);
1768     if (vbuf == 0)
1769         novm("database entry");
1770     q = vbuf;
1771     for (i = 0; (p = script_env[i]) != 0; ++i)
1772         q += slprintf(q, vbuf + vlen - q, "%s;", p);
1773
1774     key.dptr = db_key;
1775     key.dsize = strlen(db_key);
1776     dbuf.dptr = vbuf;
1777     dbuf.dsize = vlen;
1778     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
1779         error("tdb_store failed: %s", tdb_error(pppdb));
1780
1781 }
1782
1783 /*
1784  * add_db_key - add a key that we can use to look up our database entry.
1785  */
1786 static void
1787 add_db_key(str)
1788     const char *str;
1789 {
1790     TDB_DATA key, dbuf;
1791
1792     key.dptr = (char *) str;
1793     key.dsize = strlen(str);
1794     dbuf.dptr = db_key;
1795     dbuf.dsize = strlen(db_key);
1796     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
1797         error("tdb_store key failed: %s", tdb_error(pppdb));
1798 }
1799
1800 /*
1801  * delete_db_key - delete a key for looking up our database entry.
1802  */
1803 static void
1804 delete_db_key(str)
1805     const char *str;
1806 {
1807     TDB_DATA key;
1808
1809     key.dptr = (char *) str;
1810     key.dsize = strlen(str);
1811     tdb_delete(pppdb, key);
1812 }
1813
1814 /*
1815  * cleanup_db - delete all the entries we put in the database.
1816  */
1817 static void
1818 cleanup_db()
1819 {
1820     TDB_DATA key;
1821     int i;
1822     char *p;
1823
1824     key.dptr = db_key;
1825     key.dsize = strlen(db_key);
1826     tdb_delete(pppdb, key);
1827     for (i = 0; (p = script_env[i]) != 0; ++i)
1828         if (p[-1])
1829             delete_db_key(p);
1830 }