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