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