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