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