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