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