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