]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
Fix snafu in run_program(). Patch from Robert Vogelgesang.
[ppp.git] / pppd / main.c
1 /*
2  * main.c - Point-to-Point Protocol main module
3  *
4  * Copyright (c) 1984-2000 Carnegie Mellon University. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in
15  *    the documentation and/or other materials provided with the
16  *    distribution.
17  *
18  * 3. The name "Carnegie Mellon University" must not be used to
19  *    endorse or promote products derived from this software without
20  *    prior written permission. For permission or any legal
21  *    details, please contact
22  *      Office of Technology Transfer
23  *      Carnegie Mellon University
24  *      5000 Forbes Avenue
25  *      Pittsburgh, PA  15213-3890
26  *      (412) 268-4387, fax: (412) 268-7395
27  *      tech-transfer@andrew.cmu.edu
28  *
29  * 4. Redistributions of any form whatsoever must retain the following
30  *    acknowledgment:
31  *    "This product includes software developed by Computing Services
32  *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
33  *
34  * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
35  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
36  * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
37  * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
38  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
39  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
40  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
41  *
42  * Copyright (c) 1999-2004 Paul Mackerras. All rights reserved.
43  *
44  * Redistribution and use in source and binary forms, with or without
45  * modification, are permitted provided that the following conditions
46  * are met:
47  *
48  * 1. Redistributions of source code must retain the above copyright
49  *    notice, this list of conditions and the following disclaimer.
50  *
51  * 2. The name(s) of the authors of this software must not be used to
52  *    endorse or promote products derived from this software without
53  *    prior written permission.
54  *
55  * 3. Redistributions of any form whatsoever must retain the following
56  *    acknowledgment:
57  *    "This product includes software developed by Paul Mackerras
58  *     <paulus@samba.org>".
59  *
60  * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
61  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
62  * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
63  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
64  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
65  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
66  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
67  */
68
69 #define RCSID   "$Id: main.c,v 1.153 2006/06/04 03:52:50 paulus Exp $"
70
71 #include <stdio.h>
72 #include <ctype.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <unistd.h>
76 #include <signal.h>
77 #include <errno.h>
78 #include <fcntl.h>
79 #include <syslog.h>
80 #include <netdb.h>
81 #include <utmp.h>
82 #include <pwd.h>
83 #include <setjmp.h>
84 #include <sys/param.h>
85 #include <sys/types.h>
86 #include <sys/wait.h>
87 #include <sys/time.h>
88 #include <sys/resource.h>
89 #include <sys/stat.h>
90 #include <sys/socket.h>
91 #include <netinet/in.h>
92 #include <arpa/inet.h>
93
94 #include "pppd.h"
95 #include "magic.h"
96 #include "fsm.h"
97 #include "lcp.h"
98 #include "ipcp.h"
99 #ifdef INET6
100 #include "ipv6cp.h"
101 #endif
102 #include "upap.h"
103 #include "chap-new.h"
104 #include "eap.h"
105 #include "ccp.h"
106 #include "ecp.h"
107 #include "pathnames.h"
108
109 #ifdef USE_TDB
110 #include "tdb.h"
111 #endif
112
113 #ifdef CBCP_SUPPORT
114 #include "cbcp.h"
115 #endif
116
117 #ifdef IPX_CHANGE
118 #include "ipxcp.h"
119 #endif /* IPX_CHANGE */
120 #ifdef AT_CHANGE
121 #include "atcp.h"
122 #endif
123
124 static const char rcsid[] = RCSID;
125
126 /* interface vars */
127 char ifname[32];                /* Interface name */
128 int ifunit;                     /* Interface unit number */
129
130 struct channel *the_channel;
131
132 char *progname;                 /* Name of this program */
133 char hostname[MAXNAMELEN];      /* Our hostname */
134 static char pidfilename[MAXPATHLEN];    /* name of pid file */
135 static char linkpidfile[MAXPATHLEN];    /* name of linkname pid file */
136 char ppp_devnam[MAXPATHLEN];    /* name of PPP tty (maybe ttypx) */
137 uid_t uid;                      /* Our real user-id */
138 struct notifier *pidchange = NULL;
139 struct notifier *phasechange = NULL;
140 struct notifier *exitnotify = NULL;
141 struct notifier *sigreceived = NULL;
142 struct notifier *fork_notifier = NULL;
143
144 int hungup;                     /* terminal has been hung up */
145 int privileged;                 /* we're running as real uid root */
146 int need_holdoff;               /* need holdoff period before restarting */
147 int detached;                   /* have detached from terminal */
148 volatile int status;            /* exit status for pppd */
149 int unsuccess;                  /* # unsuccessful connection attempts */
150 int do_callback;                /* != 0 if we should do callback next */
151 int doing_callback;             /* != 0 if we are doing callback */
152 int ppp_session_number;         /* Session number, for channels with such a
153                                    concept (eg PPPoE) */
154 int childwait_done;             /* have timed out waiting for children */
155
156 #ifdef USE_TDB
157 TDB_CONTEXT *pppdb;             /* database for storing status etc. */
158 #endif
159
160 char db_key[32];
161
162 int (*holdoff_hook) __P((void)) = NULL;
163 int (*new_phase_hook) __P((int)) = NULL;
164 void (*snoop_recv_hook) __P((unsigned char *p, int len)) = NULL;
165 void (*snoop_send_hook) __P((unsigned char *p, int len)) = NULL;
166
167 static int conn_running;        /* we have a [dis]connector running */
168 static int fd_loop;             /* fd for getting demand-dial packets */
169
170 int fd_devnull;                 /* fd for /dev/null */
171 int devfd = -1;                 /* fd of underlying device */
172 int fd_ppp = -1;                /* fd for talking PPP */
173 int phase;                      /* where the link is at */
174 int kill_link;
175 int asked_to_quit;
176 int open_ccp_flag;
177 int listen_time;
178 int got_sigusr2;
179 int got_sigterm;
180 int got_sighup;
181
182 static sigset_t signals_handled;
183 static int waiting;
184 static sigjmp_buf sigjmp;
185
186 char **script_env;              /* Env. variable values for scripts */
187 int s_env_nalloc;               /* # words avail at script_env */
188
189 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
190 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
191
192 static int n_children;          /* # child processes still running */
193 static int got_sigchld;         /* set if we have received a SIGCHLD */
194
195 int privopen;                   /* don't lock, open device as root */
196
197 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
198
199 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
200 int ngroups;                    /* How many groups valid in groups */
201
202 static struct timeval start_time;       /* Time when link was started. */
203
204 static struct pppd_stats old_link_stats;
205 struct pppd_stats link_stats;
206 unsigned link_connect_time;
207 int link_stats_valid;
208
209 int error_count;
210
211 bool bundle_eof;
212 bool bundle_terminating;
213
214 /*
215  * We maintain a list of child process pids and
216  * functions to call when they exit.
217  */
218 struct subprocess {
219     pid_t       pid;
220     char        *prog;
221     void        (*done) __P((void *));
222     void        *arg;
223     struct subprocess *next;
224 };
225
226 static struct subprocess *children;
227
228 /* Prototypes for procedures local to this file. */
229
230 static void setup_signals __P((void));
231 static void create_pidfile __P((int pid));
232 static void create_linkpidfile __P((int pid));
233 static void cleanup __P((void));
234 static void get_input __P((void));
235 static void calltimeout __P((void));
236 static struct timeval *timeleft __P((struct timeval *));
237 static void kill_my_pg __P((int));
238 static void hup __P((int));
239 static void term __P((int));
240 static void chld __P((int));
241 static void toggle_debug __P((int));
242 static void open_ccp __P((int));
243 static void bad_signal __P((int));
244 static void holdoff_end __P((void *));
245 static void forget_child __P((int pid, int status));
246 static int reap_kids __P((void));
247 static void childwait_end __P((void *));
248
249 #ifdef USE_TDB
250 static void update_db_entry __P((void));
251 static void add_db_key __P((const char *));
252 static void delete_db_key __P((const char *));
253 static void cleanup_db __P((void));
254 #endif
255
256 static void handle_events __P((void));
257 void print_link_stats __P((void));
258
259 extern  char    *ttyname __P((int));
260 extern  char    *getlogin __P((void));
261 int main __P((int, char *[]));
262
263 #ifdef ultrix
264 #undef  O_NONBLOCK
265 #define O_NONBLOCK      O_NDELAY
266 #endif
267
268 #ifdef ULTRIX
269 #define setlogmask(x)
270 #endif
271
272 /*
273  * PPP Data Link Layer "protocol" table.
274  * One entry per supported protocol.
275  * The last entry must be NULL.
276  */
277 struct protent *protocols[] = {
278     &lcp_protent,
279     &pap_protent,
280     &chap_protent,
281 #ifdef CBCP_SUPPORT
282     &cbcp_protent,
283 #endif
284     &ipcp_protent,
285 #ifdef INET6
286     &ipv6cp_protent,
287 #endif
288     &ccp_protent,
289     &ecp_protent,
290 #ifdef IPX_CHANGE
291     &ipxcp_protent,
292 #endif
293 #ifdef AT_CHANGE
294     &atcp_protent,
295 #endif
296     &eap_protent,
297     NULL
298 };
299
300 /*
301  * If PPP_DRV_NAME is not defined, use the default "ppp" as the device name.
302  */
303 #if !defined(PPP_DRV_NAME)
304 #define PPP_DRV_NAME    "ppp"
305 #endif /* !defined(PPP_DRV_NAME) */
306
307 int
308 main(argc, argv)
309     int argc;
310     char *argv[];
311 {
312     int i, t;
313     char *p;
314     struct passwd *pw;
315     struct protent *protp;
316     char numbuf[16];
317
318     link_stats_valid = 0;
319     new_phase(PHASE_INITIALIZE);
320
321     script_env = NULL;
322
323     /* Initialize syslog facilities */
324     reopen_log();
325
326     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
327         option_error("Couldn't get hostname: %m");
328         exit(1);
329     }
330     hostname[MAXNAMELEN-1] = 0;
331
332     /* make sure we don't create world or group writable files. */
333     umask(umask(0777) | 022);
334
335     uid = getuid();
336     privileged = uid == 0;
337     slprintf(numbuf, sizeof(numbuf), "%d", uid);
338     script_setenv("ORIG_UID", numbuf, 0);
339
340     ngroups = getgroups(NGROUPS_MAX, groups);
341
342     /*
343      * Initialize magic number generator now so that protocols may
344      * use magic numbers in initialization.
345      */
346     magic_init();
347
348     /*
349      * Initialize each protocol.
350      */
351     for (i = 0; (protp = protocols[i]) != NULL; ++i)
352         (*protp->init)(0);
353
354     /*
355      * Initialize the default channel.
356      */
357     tty_init();
358
359     progname = *argv;
360
361     /*
362      * Parse, in order, the system options file, the user's options file,
363      * and the command line arguments.
364      */
365     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
366         || !options_from_user()
367         || !parse_args(argc-1, argv+1))
368         exit(EXIT_OPTION_ERROR);
369     devnam_fixed = 1;           /* can no longer change device name */
370
371     /*
372      * Work out the device name, if it hasn't already been specified,
373      * and parse the tty's options file.
374      */
375     if (the_channel->process_extra_options)
376         (*the_channel->process_extra_options)();
377
378     if (debug)
379         setlogmask(LOG_UPTO(LOG_DEBUG));
380
381     /*
382      * Check that we are running as root.
383      */
384     if (geteuid() != 0) {
385         option_error("must be root to run %s, since it is not setuid-root",
386                      argv[0]);
387         exit(EXIT_NOT_ROOT);
388     }
389
390     if (!ppp_available()) {
391         option_error("%s", no_ppp_msg);
392         exit(EXIT_NO_KERNEL_SUPPORT);
393     }
394
395     /*
396      * Check that the options given are valid and consistent.
397      */
398     check_options();
399     if (!sys_check_options())
400         exit(EXIT_OPTION_ERROR);
401     auth_check_options();
402 #ifdef HAVE_MULTILINK
403     mp_check_options();
404 #endif
405     for (i = 0; (protp = protocols[i]) != NULL; ++i)
406         if (protp->check_options != NULL)
407             (*protp->check_options)();
408     if (the_channel->check_options)
409         (*the_channel->check_options)();
410
411
412     if (dump_options || dryrun) {
413         init_pr_log(NULL, LOG_INFO);
414         print_options(pr_log, NULL);
415         end_pr_log();
416     }
417
418     if (dryrun)
419         die(0);
420
421     /* Make sure fds 0, 1, 2 are open to somewhere. */
422     fd_devnull = open(_PATH_DEVNULL, O_RDWR);
423     if (fd_devnull < 0)
424         fatal("Couldn't open %s: %m", _PATH_DEVNULL);
425     while (fd_devnull <= 2) {
426         i = dup(fd_devnull);
427         if (i < 0)
428             fatal("Critical shortage of file descriptors: dup failed: %m");
429         fd_devnull = i;
430     }
431
432     /*
433      * Initialize system-dependent stuff.
434      */
435     sys_init();
436
437 #ifdef USE_TDB
438     pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
439     if (pppdb != NULL) {
440         slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
441         update_db_entry();
442     } else {
443         warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
444         if (multilink) {
445             warn("Warning: disabling multilink");
446             multilink = 0;
447         }
448     }
449 #endif
450
451     /*
452      * Detach ourselves from the terminal, if required,
453      * and identify who is running us.
454      */
455     if (!nodetach && !updetach)
456         detach();
457     p = getlogin();
458     if (p == NULL) {
459         pw = getpwuid(uid);
460         if (pw != NULL && pw->pw_name != NULL)
461             p = pw->pw_name;
462         else
463             p = "(unknown)";
464     }
465     syslog(LOG_NOTICE, "pppd %s started by %s, uid %d", VERSION, p, uid);
466     script_setenv("PPPLOGNAME", p, 0);
467
468     if (devnam[0])
469         script_setenv("DEVICE", devnam, 1);
470     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
471     script_setenv("PPPD_PID", numbuf, 1);
472
473     setup_signals();
474
475     create_linkpidfile(getpid());
476
477     waiting = 0;
478
479     /*
480      * If we're doing dial-on-demand, set up the interface now.
481      */
482     if (demand) {
483         /*
484          * Open the loopback channel and set it up to be the ppp interface.
485          */
486         fd_loop = open_ppp_loopback();
487         set_ifunit(1);
488         /*
489          * Configure the interface and mark it up, etc.
490          */
491         demand_conf();
492     }
493
494     do_callback = 0;
495     for (;;) {
496
497         bundle_eof = 0;
498         bundle_terminating = 0;
499         listen_time = 0;
500         need_holdoff = 1;
501         devfd = -1;
502         status = EXIT_OK;
503         ++unsuccess;
504         doing_callback = do_callback;
505         do_callback = 0;
506
507         if (demand && !doing_callback) {
508             /*
509              * Don't do anything until we see some activity.
510              */
511             new_phase(PHASE_DORMANT);
512             demand_unblock();
513             add_fd(fd_loop);
514             for (;;) {
515                 handle_events();
516                 if (asked_to_quit)
517                     break;
518                 if (get_loop_output())
519                     break;
520             }
521             remove_fd(fd_loop);
522             if (asked_to_quit)
523                 break;
524
525             /*
526              * Now we want to bring up the link.
527              */
528             demand_block();
529             info("Starting link");
530         }
531
532         gettimeofday(&start_time, NULL);
533         script_unsetenv("CONNECT_TIME");
534         script_unsetenv("BYTES_SENT");
535         script_unsetenv("BYTES_RCVD");
536
537         lcp_open(0);            /* Start protocol */
538         start_link(0);
539         while (phase != PHASE_DEAD) {
540             handle_events();
541             get_input();
542             if (kill_link)
543                 lcp_close(0, "User request");
544             if (asked_to_quit) {
545                 bundle_terminating = 1;
546                 if (phase == PHASE_MASTER)
547                     mp_bundle_terminated();
548             }
549             if (open_ccp_flag) {
550                 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
551                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
552                     (*ccp_protent.open)(0);
553                 }
554             }
555         }
556         /* restore FSMs to original state */
557         lcp_close(0, "");
558
559         if (!persist || asked_to_quit || (maxfail > 0 && unsuccess >= maxfail))
560             break;
561
562         if (demand)
563             demand_discard();
564         t = need_holdoff? holdoff: 0;
565         if (holdoff_hook)
566             t = (*holdoff_hook)();
567         if (t > 0) {
568             new_phase(PHASE_HOLDOFF);
569             TIMEOUT(holdoff_end, NULL, t);
570             do {
571                 handle_events();
572                 if (kill_link)
573                     new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
574             } while (phase == PHASE_HOLDOFF);
575             if (!persist)
576                 break;
577         }
578     }
579
580     /* Wait for scripts to finish */
581     reap_kids();
582     if (n_children > 0) {
583         if (child_wait > 0)
584             TIMEOUT(childwait_end, NULL, child_wait);
585         if (debug) {
586             struct subprocess *chp;
587             dbglog("Waiting for %d child processes...", n_children);
588             for (chp = children; chp != NULL; chp = chp->next)
589                 dbglog("  script %s, pid %d", chp->prog, chp->pid);
590         }
591         while (n_children > 0 && !childwait_done) {
592             handle_events();
593             if (kill_link && !childwait_done)
594                 childwait_end(NULL);
595         }
596     }
597
598     die(status);
599     return 0;
600 }
601
602 /*
603  * handle_events - wait for something to happen and respond to it.
604  */
605 static void
606 handle_events()
607 {
608     struct timeval timo;
609
610     kill_link = open_ccp_flag = 0;
611     if (sigsetjmp(sigjmp, 1) == 0) {
612         sigprocmask(SIG_BLOCK, &signals_handled, NULL);
613         if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
614             sigprocmask(SIG_UNBLOCK, &signals_handled, NULL);
615         } else {
616             waiting = 1;
617             sigprocmask(SIG_UNBLOCK, &signals_handled, NULL);
618             wait_input(timeleft(&timo));
619         }
620     }
621     waiting = 0;
622     calltimeout();
623     if (got_sighup) {
624         info("Hangup (SIGHUP)");
625         kill_link = 1;
626         got_sighup = 0;
627         if (status != EXIT_HANGUP)
628             status = EXIT_USER_REQUEST;
629     }
630     if (got_sigterm) {
631         info("Terminating on signal %d", got_sigterm);
632         kill_link = 1;
633         asked_to_quit = 1;
634         persist = 0;
635         status = EXIT_USER_REQUEST;
636         got_sigterm = 0;
637     }
638     if (got_sigchld) {
639         got_sigchld = 0;
640         reap_kids();    /* Don't leave dead kids lying around */
641     }
642     if (got_sigusr2) {
643         open_ccp_flag = 1;
644         got_sigusr2 = 0;
645     }
646 }
647
648 /*
649  * setup_signals - initialize signal handling.
650  */
651 static void
652 setup_signals()
653 {
654     struct sigaction sa;
655
656     /*
657      * Compute mask of all interesting signals and install signal handlers
658      * for each.  Only one signal handler may be active at a time.  Therefore,
659      * all other signals should be masked when any handler is executing.
660      */
661     sigemptyset(&signals_handled);
662     sigaddset(&signals_handled, SIGHUP);
663     sigaddset(&signals_handled, SIGINT);
664     sigaddset(&signals_handled, SIGTERM);
665     sigaddset(&signals_handled, SIGCHLD);
666     sigaddset(&signals_handled, SIGUSR2);
667
668 #define SIGNAL(s, handler)      do { \
669         sa.sa_handler = handler; \
670         if (sigaction(s, &sa, NULL) < 0) \
671             fatal("Couldn't establish signal handler (%d): %m", s); \
672     } while (0)
673
674     sa.sa_mask = signals_handled;
675     sa.sa_flags = 0;
676     SIGNAL(SIGHUP, hup);                /* Hangup */
677     SIGNAL(SIGINT, term);               /* Interrupt */
678     SIGNAL(SIGTERM, term);              /* Terminate */
679     SIGNAL(SIGCHLD, chld);
680
681     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
682     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
683
684     /*
685      * Install a handler for other signals which would otherwise
686      * cause pppd to exit without cleaning up.
687      */
688     SIGNAL(SIGABRT, bad_signal);
689     SIGNAL(SIGALRM, bad_signal);
690     SIGNAL(SIGFPE, bad_signal);
691     SIGNAL(SIGILL, bad_signal);
692     SIGNAL(SIGPIPE, bad_signal);
693     SIGNAL(SIGQUIT, bad_signal);
694     SIGNAL(SIGSEGV, bad_signal);
695 #ifdef SIGBUS
696     SIGNAL(SIGBUS, bad_signal);
697 #endif
698 #ifdef SIGEMT
699     SIGNAL(SIGEMT, bad_signal);
700 #endif
701 #ifdef SIGPOLL
702     SIGNAL(SIGPOLL, bad_signal);
703 #endif
704 #ifdef SIGPROF
705     SIGNAL(SIGPROF, bad_signal);
706 #endif
707 #ifdef SIGSYS
708     SIGNAL(SIGSYS, bad_signal);
709 #endif
710 #ifdef SIGTRAP
711     SIGNAL(SIGTRAP, bad_signal);
712 #endif
713 #ifdef SIGVTALRM
714     SIGNAL(SIGVTALRM, bad_signal);
715 #endif
716 #ifdef SIGXCPU
717     SIGNAL(SIGXCPU, bad_signal);
718 #endif
719 #ifdef SIGXFSZ
720     SIGNAL(SIGXFSZ, bad_signal);
721 #endif
722
723     /*
724      * Apparently we can get a SIGPIPE when we call syslog, if
725      * syslogd has died and been restarted.  Ignoring it seems
726      * be sufficient.
727      */
728     signal(SIGPIPE, SIG_IGN);
729 }
730
731 /*
732  * set_ifunit - do things we need to do once we know which ppp
733  * unit we are using.
734  */
735 void
736 set_ifunit(iskey)
737     int iskey;
738 {
739     info("Using interface %s%d", PPP_DRV_NAME, ifunit);
740     slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
741     script_setenv("IFNAME", ifname, iskey);
742     if (iskey) {
743         create_pidfile(getpid());       /* write pid to file */
744         create_linkpidfile(getpid());
745     }
746 }
747
748 /*
749  * detach - detach us from the controlling terminal.
750  */
751 void
752 detach()
753 {
754     int pid;
755     char numbuf[16];
756     int pipefd[2];
757
758     if (detached)
759         return;
760     if (pipe(pipefd) == -1)
761         pipefd[0] = pipefd[1] = -1;
762     if ((pid = fork()) < 0) {
763         error("Couldn't detach (fork failed: %m)");
764         die(1);                 /* or just return? */
765     }
766     if (pid != 0) {
767         /* parent */
768         notify(pidchange, pid);
769         /* update pid files if they have been written already */
770         if (pidfilename[0])
771             create_pidfile(pid);
772         if (linkpidfile[0])
773             create_linkpidfile(pid);
774         exit(0);                /* parent dies */
775     }
776     setsid();
777     chdir("/");
778     dup2(fd_devnull, 0);
779     dup2(fd_devnull, 1);
780     dup2(fd_devnull, 2);
781     detached = 1;
782     if (log_default)
783         log_to_fd = -1;
784     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
785     script_setenv("PPPD_PID", numbuf, 1);
786
787     /* wait for parent to finish updating pid & lock files and die */
788     close(pipefd[1]);
789     complete_read(pipefd[0], numbuf, 1);
790     close(pipefd[0]);
791 }
792
793 /*
794  * reopen_log - (re)open our connection to syslog.
795  */
796 void
797 reopen_log()
798 {
799     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
800     setlogmask(LOG_UPTO(LOG_INFO));
801 }
802
803 /*
804  * Create a file containing our process ID.
805  */
806 static void
807 create_pidfile(pid)
808     int pid;
809 {
810     FILE *pidfile;
811
812     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
813              _PATH_VARRUN, ifname);
814     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
815         fprintf(pidfile, "%d\n", pid);
816         (void) fclose(pidfile);
817     } else {
818         error("Failed to create pid file %s: %m", pidfilename);
819         pidfilename[0] = 0;
820     }
821 }
822
823 void
824 create_linkpidfile(pid)
825     int pid;
826 {
827     FILE *pidfile;
828
829     if (linkname[0] == 0)
830         return;
831     script_setenv("LINKNAME", linkname, 1);
832     slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
833              _PATH_VARRUN, linkname);
834     if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
835         fprintf(pidfile, "%d\n", pid);
836         if (ifname[0])
837             fprintf(pidfile, "%s\n", ifname);
838         (void) fclose(pidfile);
839     } else {
840         error("Failed to create pid file %s: %m", linkpidfile);
841         linkpidfile[0] = 0;
842     }
843 }
844
845 /*
846  * remove_pidfile - remove our pid files
847  */
848 void remove_pidfiles()
849 {
850     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
851         warn("unable to delete pid file %s: %m", pidfilename);
852     pidfilename[0] = 0;
853     if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
854         warn("unable to delete pid file %s: %m", linkpidfile);
855     linkpidfile[0] = 0;
856 }
857
858 /*
859  * holdoff_end - called via a timeout when the holdoff period ends.
860  */
861 static void
862 holdoff_end(arg)
863     void *arg;
864 {
865     new_phase(PHASE_DORMANT);
866 }
867
868 /* List of protocol names, to make our messages a little more informative. */
869 struct protocol_list {
870     u_short     proto;
871     const char  *name;
872 } protocol_list[] = {
873     { 0x21,     "IP" },
874     { 0x23,     "OSI Network Layer" },
875     { 0x25,     "Xerox NS IDP" },
876     { 0x27,     "DECnet Phase IV" },
877     { 0x29,     "Appletalk" },
878     { 0x2b,     "Novell IPX" },
879     { 0x2d,     "VJ compressed TCP/IP" },
880     { 0x2f,     "VJ uncompressed TCP/IP" },
881     { 0x31,     "Bridging PDU" },
882     { 0x33,     "Stream Protocol ST-II" },
883     { 0x35,     "Banyan Vines" },
884     { 0x39,     "AppleTalk EDDP" },
885     { 0x3b,     "AppleTalk SmartBuffered" },
886     { 0x3d,     "Multi-Link" },
887     { 0x3f,     "NETBIOS Framing" },
888     { 0x41,     "Cisco Systems" },
889     { 0x43,     "Ascom Timeplex" },
890     { 0x45,     "Fujitsu Link Backup and Load Balancing (LBLB)" },
891     { 0x47,     "DCA Remote Lan" },
892     { 0x49,     "Serial Data Transport Protocol (PPP-SDTP)" },
893     { 0x4b,     "SNA over 802.2" },
894     { 0x4d,     "SNA" },
895     { 0x4f,     "IP6 Header Compression" },
896     { 0x51,     "KNX Bridging Data" },
897     { 0x53,     "Encryption" },
898     { 0x55,     "Individual Link Encryption" },
899     { 0x57,     "IPv6" },
900     { 0x59,     "PPP Muxing" },
901     { 0x5b,     "Vendor-Specific Network Protocol" },
902     { 0x61,     "RTP IPHC Full Header" },
903     { 0x63,     "RTP IPHC Compressed TCP" },
904     { 0x65,     "RTP IPHC Compressed non-TCP" },
905     { 0x67,     "RTP IPHC Compressed UDP 8" },
906     { 0x69,     "RTP IPHC Compressed RTP 8" },
907     { 0x6f,     "Stampede Bridging" },
908     { 0x73,     "MP+" },
909     { 0xc1,     "NTCITS IPI" },
910     { 0xfb,     "single-link compression" },
911     { 0xfd,     "Compressed Datagram" },
912     { 0x0201,   "802.1d Hello Packets" },
913     { 0x0203,   "IBM Source Routing BPDU" },
914     { 0x0205,   "DEC LANBridge100 Spanning Tree" },
915     { 0x0207,   "Cisco Discovery Protocol" },
916     { 0x0209,   "Netcs Twin Routing" },
917     { 0x020b,   "STP - Scheduled Transfer Protocol" },
918     { 0x020d,   "EDP - Extreme Discovery Protocol" },
919     { 0x0211,   "Optical Supervisory Channel Protocol" },
920     { 0x0213,   "Optical Supervisory Channel Protocol" },
921     { 0x0231,   "Luxcom" },
922     { 0x0233,   "Sigma Network Systems" },
923     { 0x0235,   "Apple Client Server Protocol" },
924     { 0x0281,   "MPLS Unicast" },
925     { 0x0283,   "MPLS Multicast" },
926     { 0x0285,   "IEEE p1284.4 standard - data packets" },
927     { 0x0287,   "ETSI TETRA Network Protocol Type 1" },
928     { 0x0289,   "Multichannel Flow Treatment Protocol" },
929     { 0x2063,   "RTP IPHC Compressed TCP No Delta" },
930     { 0x2065,   "RTP IPHC Context State" },
931     { 0x2067,   "RTP IPHC Compressed UDP 16" },
932     { 0x2069,   "RTP IPHC Compressed RTP 16" },
933     { 0x4001,   "Cray Communications Control Protocol" },
934     { 0x4003,   "CDPD Mobile Network Registration Protocol" },
935     { 0x4005,   "Expand accelerator protocol" },
936     { 0x4007,   "ODSICP NCP" },
937     { 0x4009,   "DOCSIS DLL" },
938     { 0x400B,   "Cetacean Network Detection Protocol" },
939     { 0x4021,   "Stacker LZS" },
940     { 0x4023,   "RefTek Protocol" },
941     { 0x4025,   "Fibre Channel" },
942     { 0x4027,   "EMIT Protocols" },
943     { 0x405b,   "Vendor-Specific Protocol (VSP)" },
944     { 0x8021,   "Internet Protocol Control Protocol" },
945     { 0x8023,   "OSI Network Layer Control Protocol" },
946     { 0x8025,   "Xerox NS IDP Control Protocol" },
947     { 0x8027,   "DECnet Phase IV Control Protocol" },
948     { 0x8029,   "Appletalk Control Protocol" },
949     { 0x802b,   "Novell IPX Control Protocol" },
950     { 0x8031,   "Bridging NCP" },
951     { 0x8033,   "Stream Protocol Control Protocol" },
952     { 0x8035,   "Banyan Vines Control Protocol" },
953     { 0x803d,   "Multi-Link Control Protocol" },
954     { 0x803f,   "NETBIOS Framing Control Protocol" },
955     { 0x8041,   "Cisco Systems Control Protocol" },
956     { 0x8043,   "Ascom Timeplex" },
957     { 0x8045,   "Fujitsu LBLB Control Protocol" },
958     { 0x8047,   "DCA Remote Lan Network Control Protocol (RLNCP)" },
959     { 0x8049,   "Serial Data Control Protocol (PPP-SDCP)" },
960     { 0x804b,   "SNA over 802.2 Control Protocol" },
961     { 0x804d,   "SNA Control Protocol" },
962     { 0x804f,   "IP6 Header Compression Control Protocol" },
963     { 0x8051,   "KNX Bridging Control Protocol" },
964     { 0x8053,   "Encryption Control Protocol" },
965     { 0x8055,   "Individual Link Encryption Control Protocol" },
966     { 0x8057,   "IPv6 Control Protovol" },
967     { 0x8059,   "PPP Muxing Control Protocol" },
968     { 0x805b,   "Vendor-Specific Network Control Protocol (VSNCP)" },
969     { 0x806f,   "Stampede Bridging Control Protocol" },
970     { 0x8073,   "MP+ Control Protocol" },
971     { 0x80c1,   "NTCITS IPI Control Protocol" },
972     { 0x80fb,   "Single Link Compression Control Protocol" },
973     { 0x80fd,   "Compression Control Protocol" },
974     { 0x8207,   "Cisco Discovery Protocol Control" },
975     { 0x8209,   "Netcs Twin Routing" },
976     { 0x820b,   "STP - Control Protocol" },
977     { 0x820d,   "EDPCP - Extreme Discovery Protocol Ctrl Prtcl" },
978     { 0x8235,   "Apple Client Server Protocol Control" },
979     { 0x8281,   "MPLSCP" },
980     { 0x8285,   "IEEE p1284.4 standard - Protocol Control" },
981     { 0x8287,   "ETSI TETRA TNP1 Control Protocol" },
982     { 0x8289,   "Multichannel Flow Treatment Protocol" },
983     { 0xc021,   "Link Control Protocol" },
984     { 0xc023,   "Password Authentication Protocol" },
985     { 0xc025,   "Link Quality Report" },
986     { 0xc027,   "Shiva Password Authentication Protocol" },
987     { 0xc029,   "CallBack Control Protocol (CBCP)" },
988     { 0xc02b,   "BACP Bandwidth Allocation Control Protocol" },
989     { 0xc02d,   "BAP" },
990     { 0xc05b,   "Vendor-Specific Authentication Protocol (VSAP)" },
991     { 0xc081,   "Container Control Protocol" },
992     { 0xc223,   "Challenge Handshake Authentication Protocol" },
993     { 0xc225,   "RSA Authentication Protocol" },
994     { 0xc227,   "Extensible Authentication Protocol" },
995     { 0xc229,   "Mitsubishi Security Info Exch Ptcl (SIEP)" },
996     { 0xc26f,   "Stampede Bridging Authorization Protocol" },
997     { 0xc281,   "Proprietary Authentication Protocol" },
998     { 0xc283,   "Proprietary Authentication Protocol" },
999     { 0xc481,   "Proprietary Node ID Authentication Protocol" },
1000     { 0,        NULL },
1001 };
1002
1003 /*
1004  * protocol_name - find a name for a PPP protocol.
1005  */
1006 const char *
1007 protocol_name(proto)
1008     int proto;
1009 {
1010     struct protocol_list *lp;
1011
1012     for (lp = protocol_list; lp->proto != 0; ++lp)
1013         if (proto == lp->proto)
1014             return lp->name;
1015     return NULL;
1016 }
1017
1018 /*
1019  * get_input - called when incoming data is available.
1020  */
1021 static void
1022 get_input()
1023 {
1024     int len, i;
1025     u_char *p;
1026     u_short protocol;
1027     struct protent *protp;
1028
1029     p = inpacket_buf;   /* point to beginning of packet buffer */
1030
1031     len = read_packet(inpacket_buf);
1032     if (len < 0)
1033         return;
1034
1035     if (len == 0) {
1036         if (bundle_eof && multilink_master) {
1037             notice("Last channel has disconnected");
1038             mp_bundle_terminated();
1039             return;
1040         }
1041         notice("Modem hangup");
1042         hungup = 1;
1043         status = EXIT_HANGUP;
1044         lcp_lowerdown(0);       /* serial link is no longer available */
1045         link_terminated(0);
1046         return;
1047     }
1048
1049     if (len < PPP_HDRLEN) {
1050         dbglog("received short packet:%.*B", len, p);
1051         return;
1052     }
1053
1054     dump_packet("rcvd", p, len);
1055     if (snoop_recv_hook) snoop_recv_hook(p, len);
1056
1057     p += 2;                             /* Skip address and control */
1058     GETSHORT(protocol, p);
1059     len -= PPP_HDRLEN;
1060
1061     /*
1062      * Toss all non-LCP packets unless LCP is OPEN.
1063      */
1064     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1065         dbglog("Discarded non-LCP packet when LCP not open");
1066         return;
1067     }
1068
1069     /*
1070      * Until we get past the authentication phase, toss all packets
1071      * except LCP, LQR and authentication packets.
1072      */
1073     if (phase <= PHASE_AUTHENTICATE
1074         && !(protocol == PPP_LCP || protocol == PPP_LQR
1075              || protocol == PPP_PAP || protocol == PPP_CHAP ||
1076                 protocol == PPP_EAP)) {
1077         dbglog("discarding proto 0x%x in phase %d",
1078                    protocol, phase);
1079         return;
1080     }
1081
1082     /*
1083      * Upcall the proper protocol input routine.
1084      */
1085     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1086         if (protp->protocol == protocol && protp->enabled_flag) {
1087             (*protp->input)(0, p, len);
1088             return;
1089         }
1090         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1091             && protp->datainput != NULL) {
1092             (*protp->datainput)(0, p, len);
1093             return;
1094         }
1095     }
1096
1097     if (debug) {
1098         const char *pname = protocol_name(protocol);
1099         if (pname != NULL)
1100             warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1101         else
1102             warn("Unsupported protocol 0x%x received", protocol);
1103     }
1104     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1105 }
1106
1107 /*
1108  * ppp_send_config - configure the transmit-side characteristics of
1109  * the ppp interface.  Returns -1, indicating an error, if the channel
1110  * send_config procedure called error() (or incremented error_count
1111  * itself), otherwise 0.
1112  */
1113 int
1114 ppp_send_config(unit, mtu, accm, pcomp, accomp)
1115     int unit, mtu;
1116     u_int32_t accm;
1117     int pcomp, accomp;
1118 {
1119         int errs;
1120
1121         if (the_channel->send_config == NULL)
1122                 return 0;
1123         errs = error_count;
1124         (*the_channel->send_config)(mtu, accm, pcomp, accomp);
1125         return (error_count != errs)? -1: 0;
1126 }
1127
1128 /*
1129  * ppp_recv_config - configure the receive-side characteristics of
1130  * the ppp interface.  Returns -1, indicating an error, if the channel
1131  * recv_config procedure called error() (or incremented error_count
1132  * itself), otherwise 0.
1133  */
1134 int
1135 ppp_recv_config(unit, mru, accm, pcomp, accomp)
1136     int unit, mru;
1137     u_int32_t accm;
1138     int pcomp, accomp;
1139 {
1140         int errs;
1141
1142         if (the_channel->recv_config == NULL)
1143                 return 0;
1144         errs = error_count;
1145         (*the_channel->recv_config)(mru, accm, pcomp, accomp);
1146         return (error_count != errs)? -1: 0;
1147 }
1148
1149 /*
1150  * new_phase - signal the start of a new phase of pppd's operation.
1151  */
1152 void
1153 new_phase(p)
1154     int p;
1155 {
1156     phase = p;
1157     if (new_phase_hook)
1158         (*new_phase_hook)(p);
1159     notify(phasechange, p);
1160 }
1161
1162 /*
1163  * die - clean up state and exit with the specified status.
1164  */
1165 void
1166 die(status)
1167     int status;
1168 {
1169     if (!doing_multilink || multilink_master)
1170         print_link_stats();
1171     cleanup();
1172     notify(exitnotify, status);
1173     syslog(LOG_INFO, "Exit.");
1174     exit(status);
1175 }
1176
1177 /*
1178  * cleanup - restore anything which needs to be restored before we exit
1179  */
1180 /* ARGSUSED */
1181 static void
1182 cleanup()
1183 {
1184     sys_cleanup();
1185
1186     if (fd_ppp >= 0)
1187         the_channel->disestablish_ppp(devfd);
1188     if (the_channel->cleanup)
1189         (*the_channel->cleanup)();
1190     remove_pidfiles();
1191
1192 #ifdef USE_TDB
1193     if (pppdb != NULL)
1194         cleanup_db();
1195 #endif
1196
1197 }
1198
1199 void
1200 print_link_stats()
1201 {
1202     /*
1203      * Print connect time and statistics.
1204      */
1205     if (link_stats_valid) {
1206        int t = (link_connect_time + 5) / 6;    /* 1/10ths of minutes */
1207        info("Connect time %d.%d minutes.", t/10, t%10);
1208        info("Sent %u bytes, received %u bytes.",
1209             link_stats.bytes_out, link_stats.bytes_in);
1210        link_stats_valid = 0;
1211     }
1212 }
1213
1214 /*
1215  * reset_link_stats - "reset" stats when link goes up.
1216  */
1217 void
1218 reset_link_stats(u)
1219     int u;
1220 {
1221     if (!get_ppp_stats(u, &old_link_stats))
1222         return;
1223     gettimeofday(&start_time, NULL);
1224 }
1225
1226 /*
1227  * update_link_stats - get stats at link termination.
1228  */
1229 void
1230 update_link_stats(u)
1231     int u;
1232 {
1233     struct timeval now;
1234     char numbuf[32];
1235
1236     if (!get_ppp_stats(u, &link_stats)
1237         || gettimeofday(&now, NULL) < 0)
1238         return;
1239     link_connect_time = now.tv_sec - start_time.tv_sec;
1240     link_stats_valid = 1;
1241
1242     link_stats.bytes_in  -= old_link_stats.bytes_in;
1243     link_stats.bytes_out -= old_link_stats.bytes_out;
1244     link_stats.pkts_in   -= old_link_stats.pkts_in;
1245     link_stats.pkts_out  -= old_link_stats.pkts_out;
1246
1247     slprintf(numbuf, sizeof(numbuf), "%u", link_connect_time);
1248     script_setenv("CONNECT_TIME", numbuf, 0);
1249     slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_out);
1250     script_setenv("BYTES_SENT", numbuf, 0);
1251     slprintf(numbuf, sizeof(numbuf), "%u", link_stats.bytes_in);
1252     script_setenv("BYTES_RCVD", numbuf, 0);
1253 }
1254
1255
1256 struct  callout {
1257     struct timeval      c_time;         /* time at which to call routine */
1258     void                *c_arg;         /* argument to routine */
1259     void                (*c_func) __P((void *)); /* routine */
1260     struct              callout *c_next;
1261 };
1262
1263 static struct callout *callout = NULL;  /* Callout list */
1264 static struct timeval timenow;          /* Current time */
1265
1266 /*
1267  * timeout - Schedule a timeout.
1268  */
1269 void
1270 timeout(func, arg, secs, usecs)
1271     void (*func) __P((void *));
1272     void *arg;
1273     int secs, usecs;
1274 {
1275     struct callout *newp, *p, **pp;
1276
1277     /*
1278      * Allocate timeout.
1279      */
1280     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1281         fatal("Out of memory in timeout()!");
1282     newp->c_arg = arg;
1283     newp->c_func = func;
1284     gettimeofday(&timenow, NULL);
1285     newp->c_time.tv_sec = timenow.tv_sec + secs;
1286     newp->c_time.tv_usec = timenow.tv_usec + usecs;
1287     if (newp->c_time.tv_usec >= 1000000) {
1288         newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
1289         newp->c_time.tv_usec %= 1000000;
1290     }
1291
1292     /*
1293      * Find correct place and link it in.
1294      */
1295     for (pp = &callout; (p = *pp); pp = &p->c_next)
1296         if (newp->c_time.tv_sec < p->c_time.tv_sec
1297             || (newp->c_time.tv_sec == p->c_time.tv_sec
1298                 && newp->c_time.tv_usec < p->c_time.tv_usec))
1299             break;
1300     newp->c_next = p;
1301     *pp = newp;
1302 }
1303
1304
1305 /*
1306  * untimeout - Unschedule a timeout.
1307  */
1308 void
1309 untimeout(func, arg)
1310     void (*func) __P((void *));
1311     void *arg;
1312 {
1313     struct callout **copp, *freep;
1314
1315     /*
1316      * Find first matching timeout and remove it from the list.
1317      */
1318     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1319         if (freep->c_func == func && freep->c_arg == arg) {
1320             *copp = freep->c_next;
1321             free((char *) freep);
1322             break;
1323         }
1324 }
1325
1326
1327 /*
1328  * calltimeout - Call any timeout routines which are now due.
1329  */
1330 static void
1331 calltimeout()
1332 {
1333     struct callout *p;
1334
1335     while (callout != NULL) {
1336         p = callout;
1337
1338         if (gettimeofday(&timenow, NULL) < 0)
1339             fatal("Failed to get time of day: %m");
1340         if (!(p->c_time.tv_sec < timenow.tv_sec
1341               || (p->c_time.tv_sec == timenow.tv_sec
1342                   && p->c_time.tv_usec <= timenow.tv_usec)))
1343             break;              /* no, it's not time yet */
1344
1345         callout = p->c_next;
1346         (*p->c_func)(p->c_arg);
1347
1348         free((char *) p);
1349     }
1350 }
1351
1352
1353 /*
1354  * timeleft - return the length of time until the next timeout is due.
1355  */
1356 static struct timeval *
1357 timeleft(tvp)
1358     struct timeval *tvp;
1359 {
1360     if (callout == NULL)
1361         return NULL;
1362
1363     gettimeofday(&timenow, NULL);
1364     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1365     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1366     if (tvp->tv_usec < 0) {
1367         tvp->tv_usec += 1000000;
1368         tvp->tv_sec -= 1;
1369     }
1370     if (tvp->tv_sec < 0)
1371         tvp->tv_sec = tvp->tv_usec = 0;
1372
1373     return tvp;
1374 }
1375
1376
1377 /*
1378  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1379  * We assume that sig is currently blocked.
1380  */
1381 static void
1382 kill_my_pg(sig)
1383     int sig;
1384 {
1385     struct sigaction act, oldact;
1386
1387     sigemptyset(&act.sa_mask);          /* unnecessary in fact */
1388     act.sa_handler = SIG_IGN;
1389     act.sa_flags = 0;
1390     kill(0, sig);
1391     /*
1392      * The kill() above made the signal pending for us, as well as
1393      * the rest of our process group, but we don't want it delivered
1394      * to us.  It is blocked at the moment.  Setting it to be ignored
1395      * will cause the pending signal to be discarded.  If we did the
1396      * kill() after setting the signal to be ignored, it is unspecified
1397      * (by POSIX) whether the signal is immediately discarded or left
1398      * pending, and in fact Linux would leave it pending, and so it
1399      * would be delivered after the current signal handler exits,
1400      * leading to an infinite loop.
1401      */
1402     sigaction(sig, &act, &oldact);
1403     sigaction(sig, &oldact, NULL);
1404 }
1405
1406
1407 /*
1408  * hup - Catch SIGHUP signal.
1409  *
1410  * Indicates that the physical layer has been disconnected.
1411  * We don't rely on this indication; if the user has sent this
1412  * signal, we just take the link down.
1413  */
1414 static void
1415 hup(sig)
1416     int sig;
1417 {
1418     /* can't log a message here, it can deadlock */
1419     got_sighup = 1;
1420     if (conn_running)
1421         /* Send the signal to the [dis]connector process(es) also */
1422         kill_my_pg(sig);
1423     notify(sigreceived, sig);
1424     if (waiting)
1425         siglongjmp(sigjmp, 1);
1426 }
1427
1428
1429 /*
1430  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1431  *
1432  * Indicates that we should initiate a graceful disconnect and exit.
1433  */
1434 /*ARGSUSED*/
1435 static void
1436 term(sig)
1437     int sig;
1438 {
1439     /* can't log a message here, it can deadlock */
1440     got_sigterm = sig;
1441     if (conn_running)
1442         /* Send the signal to the [dis]connector process(es) also */
1443         kill_my_pg(sig);
1444     notify(sigreceived, sig);
1445     if (waiting)
1446         siglongjmp(sigjmp, 1);
1447 }
1448
1449
1450 /*
1451  * chld - Catch SIGCHLD signal.
1452  * Sets a flag so we will call reap_kids in the mainline.
1453  */
1454 static void
1455 chld(sig)
1456     int sig;
1457 {
1458     got_sigchld = 1;
1459     if (waiting)
1460         siglongjmp(sigjmp, 1);
1461 }
1462
1463
1464 /*
1465  * toggle_debug - Catch SIGUSR1 signal.
1466  *
1467  * Toggle debug flag.
1468  */
1469 /*ARGSUSED*/
1470 static void
1471 toggle_debug(sig)
1472     int sig;
1473 {
1474     debug = !debug;
1475     if (debug) {
1476         setlogmask(LOG_UPTO(LOG_DEBUG));
1477     } else {
1478         setlogmask(LOG_UPTO(LOG_WARNING));
1479     }
1480 }
1481
1482
1483 /*
1484  * open_ccp - Catch SIGUSR2 signal.
1485  *
1486  * Try to (re)negotiate compression.
1487  */
1488 /*ARGSUSED*/
1489 static void
1490 open_ccp(sig)
1491     int sig;
1492 {
1493     got_sigusr2 = 1;
1494     if (waiting)
1495         siglongjmp(sigjmp, 1);
1496 }
1497
1498
1499 /*
1500  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1501  */
1502 static void
1503 bad_signal(sig)
1504     int sig;
1505 {
1506     static int crashed = 0;
1507
1508     if (crashed)
1509         _exit(127);
1510     crashed = 1;
1511     error("Fatal signal %d", sig);
1512     if (conn_running)
1513         kill_my_pg(SIGTERM);
1514     notify(sigreceived, sig);
1515     die(127);
1516 }
1517
1518 /*
1519  * safe_fork - Create a child process.  The child closes all the
1520  * file descriptors that we don't want to leak to a script.
1521  * The parent waits for the child to do this before returning.
1522  * This also arranges for the specified fds to be dup'd to
1523  * fds 0, 1, 2 in the child.
1524  */
1525 pid_t
1526 safe_fork(int infd, int outfd, int errfd)
1527 {
1528         pid_t pid;
1529         int fd, pipefd[2];
1530         char buf[1];
1531
1532         /* make sure fds 0, 1, 2 are occupied (probably not necessary) */
1533         while ((fd = dup(fd_devnull)) >= 0) {
1534                 if (fd > 2) {
1535                         close(fd);
1536                         break;
1537                 }
1538         }
1539
1540         if (pipe(pipefd) == -1)
1541                 pipefd[0] = pipefd[1] = -1;
1542         pid = fork();
1543         if (pid < 0) {
1544                 error("fork failed: %m");
1545                 return -1;
1546         }
1547         if (pid > 0) {
1548                 /* parent */
1549                 close(pipefd[1]);
1550                 /* this read() blocks until the close(pipefd[1]) below */
1551                 complete_read(pipefd[0], buf, 1);
1552                 close(pipefd[0]);
1553                 return pid;
1554         }
1555
1556         /* Executing in the child */
1557         sys_close();
1558 #ifdef USE_TDB
1559         tdb_close(pppdb);
1560 #endif
1561
1562         /* make sure infd, outfd and errfd won't get tromped on below */
1563         if (infd == 1 || infd == 2)
1564                 infd = dup(infd);
1565         if (outfd == 0 || outfd == 2)
1566                 outfd = dup(outfd);
1567         if (errfd == 0 || errfd == 1)
1568                 errfd = dup(errfd);
1569
1570         /* dup the in, out, err fds to 0, 1, 2 */
1571         if (infd != 0)
1572                 dup2(infd, 0);
1573         if (outfd != 1)
1574                 dup2(outfd, 1);
1575         if (errfd != 2)
1576                 dup2(errfd, 2);
1577
1578         closelog();
1579         if (log_to_fd > 2)
1580                 close(log_to_fd);
1581         if (the_channel->close)
1582                 (*the_channel->close)();
1583         else
1584                 close(devfd);   /* some plugins don't have a close function */
1585         close(fd_ppp);
1586         close(fd_devnull);
1587         if (infd != 0)
1588                 close(infd);
1589         if (outfd != 1)
1590                 close(outfd);
1591         if (errfd != 2)
1592                 close(errfd);
1593
1594         notify(fork_notifier, 0);
1595         close(pipefd[0]);
1596         /* this close unblocks the read() call above in the parent */
1597         close(pipefd[1]);
1598
1599         return 0;
1600 }
1601
1602 /*
1603  * device_script - run a program to talk to the specified fds
1604  * (e.g. to run the connector or disconnector script).
1605  * stderr gets connected to the log fd or to the _PATH_CONNERRS file.
1606  */
1607 int
1608 device_script(program, in, out, dont_wait)
1609     char *program;
1610     int in, out;
1611     int dont_wait;
1612 {
1613     int pid;
1614     int status = -1;
1615     int errfd;
1616
1617     if (log_to_fd >= 0)
1618         errfd = log_to_fd;
1619     else
1620         errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1621
1622     ++conn_running;
1623     pid = safe_fork(in, out, errfd);
1624
1625     if (pid != 0 && log_to_fd < 0)
1626         close(errfd);
1627
1628     if (pid < 0) {
1629         --conn_running;
1630         error("Failed to create child process: %m");
1631         return -1;
1632     }
1633
1634     if (pid != 0) {
1635         if (dont_wait) {
1636             record_child(pid, program, NULL, NULL);
1637             status = 0;
1638         } else {
1639             while (waitpid(pid, &status, 0) < 0) {
1640                 if (errno == EINTR)
1641                     continue;
1642                 fatal("error waiting for (dis)connection process: %m");
1643             }
1644             --conn_running;
1645         }
1646         return (status == 0 ? 0 : -1);
1647     }
1648
1649     /* here we are executing in the child */
1650
1651     setgid(getgid());
1652     setuid(uid);
1653     if (getuid() != uid) {
1654         fprintf(stderr, "pppd: setuid failed\n");
1655         exit(1);
1656     }
1657     execl("/bin/sh", "sh", "-c", program, (char *)0);
1658     perror("pppd: could not exec /bin/sh");
1659     exit(99);
1660     /* NOTREACHED */
1661 }
1662
1663
1664 /*
1665  * run-program - execute a program with given arguments,
1666  * but don't wait for it unless wait is non-zero.
1667  * If the program can't be executed, logs an error unless
1668  * must_exist is 0 and the program file doesn't exist.
1669  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1670  * or isn't an executable plain file, or the process ID of the child.
1671  * If done != NULL, (*done)(arg) will be called later (within
1672  * reap_kids) iff the return value is > 0.
1673  */
1674 pid_t
1675 run_program(prog, args, must_exist, done, arg, wait)
1676     char *prog;
1677     char **args;
1678     int must_exist;
1679     void (*done) __P((void *));
1680     void *arg;
1681     int wait;
1682 {
1683     int pid, status;
1684     struct stat sbuf;
1685
1686     /*
1687      * First check if the file exists and is executable.
1688      * We don't use access() because that would use the
1689      * real user-id, which might not be root, and the script
1690      * might be accessible only to root.
1691      */
1692     errno = EINVAL;
1693     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1694         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1695         if (must_exist || errno != ENOENT)
1696             warn("Can't execute %s: %m", prog);
1697         return 0;
1698     }
1699
1700     pid = safe_fork(fd_devnull, fd_devnull, fd_devnull);
1701     if (pid == -1) {
1702         error("Failed to create child process for %s: %m", prog);
1703         return -1;
1704     }
1705     if (pid != 0) {
1706         if (debug)
1707             dbglog("Script %s started (pid %d)", prog, pid);
1708         record_child(pid, prog, done, arg);
1709         if (wait) {
1710             while (waitpid(pid, &status, 0) < 0) {
1711                 if (errno == EINTR)
1712                     continue;
1713                 fatal("error waiting for script %s: %m", prog);
1714             }
1715             forget_child(pid, status);
1716         }
1717         return pid;
1718     }
1719
1720     /* Leave the current location */
1721     (void) setsid();    /* No controlling tty. */
1722     (void) umask (S_IRWXG|S_IRWXO);
1723     (void) chdir ("/"); /* no current directory. */
1724     setuid(0);          /* set real UID = root */
1725     setgid(getegid());
1726
1727 #ifdef BSD
1728     /* Force the priority back to zero if pppd is running higher. */
1729     if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1730         warn("can't reset priority to 0: %m");
1731 #endif
1732
1733     /* run the program */
1734     execve(prog, args, script_env);
1735     if (must_exist || errno != ENOENT) {
1736         /* have to reopen the log, there's nowhere else
1737            for the message to go. */
1738         reopen_log();
1739         syslog(LOG_ERR, "Can't execute %s: %m", prog);
1740         closelog();
1741     }
1742     _exit(-1);
1743 }
1744
1745
1746 /*
1747  * record_child - add a child process to the list for reap_kids
1748  * to use.
1749  */
1750 void
1751 record_child(pid, prog, done, arg)
1752     int pid;
1753     char *prog;
1754     void (*done) __P((void *));
1755     void *arg;
1756 {
1757     struct subprocess *chp;
1758
1759     ++n_children;
1760
1761     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1762     if (chp == NULL) {
1763         warn("losing track of %s process", prog);
1764     } else {
1765         chp->pid = pid;
1766         chp->prog = prog;
1767         chp->done = done;
1768         chp->arg = arg;
1769         chp->next = children;
1770         children = chp;
1771     }
1772 }
1773
1774 /*
1775  * childwait_end - we got fed up waiting for the child processes to
1776  * exit, send them all a SIGTERM.
1777  */
1778 static void
1779 childwait_end(arg)
1780     void *arg;
1781 {
1782     struct subprocess *chp;
1783
1784     for (chp = children; chp != NULL; chp = chp->next) {
1785         if (debug)
1786             dbglog("sending SIGTERM to process %d", chp->pid);
1787         kill(chp->pid, SIGTERM);
1788     }
1789     childwait_done = 1;
1790 }
1791
1792 /*
1793  * forget_child - clean up after a dead child
1794  */
1795 static void
1796 forget_child(pid, status)
1797     int pid, status;
1798 {
1799     struct subprocess *chp, **prevp;
1800
1801     for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1802         if (chp->pid == pid) {
1803             --n_children;
1804             *prevp = chp->next;
1805             break;
1806         }
1807     }
1808     if (WIFSIGNALED(status)) {
1809         warn("Child process %s (pid %d) terminated with signal %d",
1810              (chp? chp->prog: "??"), pid, WTERMSIG(status));
1811     } else if (debug)
1812         dbglog("Script %s finished (pid %d), status = 0x%x",
1813                (chp? chp->prog: "??"), pid,
1814                WIFEXITED(status) ? WEXITSTATUS(status) : status);
1815     if (chp && chp->done)
1816         (*chp->done)(chp->arg);
1817     if (chp)
1818         free(chp);
1819 }
1820
1821 /*
1822  * reap_kids - get status from any dead child processes,
1823  * and log a message for abnormal terminations.
1824  */
1825 static int
1826 reap_kids()
1827 {
1828     int pid, status;
1829
1830     if (n_children == 0)
1831         return 0;
1832     while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1833         forget_child(pid, status);
1834     }
1835     if (pid == -1) {
1836         if (errno == ECHILD)
1837             return -1;
1838         if (errno != EINTR)
1839             error("Error waiting for child process: %m");
1840     }
1841     return 0;
1842 }
1843
1844 /*
1845  * add_notifier - add a new function to be called when something happens.
1846  */
1847 void
1848 add_notifier(notif, func, arg)
1849     struct notifier **notif;
1850     notify_func func;
1851     void *arg;
1852 {
1853     struct notifier *np;
1854
1855     np = malloc(sizeof(struct notifier));
1856     if (np == 0)
1857         novm("notifier struct");
1858     np->next = *notif;
1859     np->func = func;
1860     np->arg = arg;
1861     *notif = np;
1862 }
1863
1864 /*
1865  * remove_notifier - remove a function from the list of things to
1866  * be called when something happens.
1867  */
1868 void
1869 remove_notifier(notif, func, arg)
1870     struct notifier **notif;
1871     notify_func func;
1872     void *arg;
1873 {
1874     struct notifier *np;
1875
1876     for (; (np = *notif) != 0; notif = &np->next) {
1877         if (np->func == func && np->arg == arg) {
1878             *notif = np->next;
1879             free(np);
1880             break;
1881         }
1882     }
1883 }
1884
1885 /*
1886  * notify - call a set of functions registered with add_notifier.
1887  */
1888 void
1889 notify(notif, val)
1890     struct notifier *notif;
1891     int val;
1892 {
1893     struct notifier *np;
1894
1895     while ((np = notif) != 0) {
1896         notif = np->next;
1897         (*np->func)(np->arg, val);
1898     }
1899 }
1900
1901 /*
1902  * novm - log an error message saying we ran out of memory, and die.
1903  */
1904 void
1905 novm(msg)
1906     char *msg;
1907 {
1908     fatal("Virtual memory exhausted allocating %s\n", msg);
1909 }
1910
1911 /*
1912  * script_setenv - set an environment variable value to be used
1913  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1914  */
1915 void
1916 script_setenv(var, value, iskey)
1917     char *var, *value;
1918     int iskey;
1919 {
1920     size_t varl = strlen(var);
1921     size_t vl = varl + strlen(value) + 2;
1922     int i;
1923     char *p, *newstring;
1924
1925     newstring = (char *) malloc(vl+1);
1926     if (newstring == 0)
1927         return;
1928     *newstring++ = iskey;
1929     slprintf(newstring, vl, "%s=%s", var, value);
1930
1931     /* check if this variable is already set */
1932     if (script_env != 0) {
1933         for (i = 0; (p = script_env[i]) != 0; ++i) {
1934             if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1935 #ifdef USE_TDB
1936                 if (p[-1] && pppdb != NULL)
1937                     delete_db_key(p);
1938 #endif
1939                 free(p-1);
1940                 script_env[i] = newstring;
1941 #ifdef USE_TDB
1942                 if (iskey && pppdb != NULL)
1943                     add_db_key(newstring);
1944                 update_db_entry();
1945 #endif
1946                 return;
1947             }
1948         }
1949     } else {
1950         /* no space allocated for script env. ptrs. yet */
1951         i = 0;
1952         script_env = (char **) malloc(16 * sizeof(char *));
1953         if (script_env == 0)
1954             return;
1955         s_env_nalloc = 16;
1956     }
1957
1958     /* reallocate script_env with more space if needed */
1959     if (i + 1 >= s_env_nalloc) {
1960         int new_n = i + 17;
1961         char **newenv = (char **) realloc((void *)script_env,
1962                                           new_n * sizeof(char *));
1963         if (newenv == 0)
1964             return;
1965         script_env = newenv;
1966         s_env_nalloc = new_n;
1967     }
1968
1969     script_env[i] = newstring;
1970     script_env[i+1] = 0;
1971
1972 #ifdef USE_TDB
1973     if (pppdb != NULL) {
1974         if (iskey)
1975             add_db_key(newstring);
1976         update_db_entry();
1977     }
1978 #endif
1979 }
1980
1981 /*
1982  * script_unsetenv - remove a variable from the environment
1983  * for scripts.
1984  */
1985 void
1986 script_unsetenv(var)
1987     char *var;
1988 {
1989     int vl = strlen(var);
1990     int i;
1991     char *p;
1992
1993     if (script_env == 0)
1994         return;
1995     for (i = 0; (p = script_env[i]) != 0; ++i) {
1996         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1997 #ifdef USE_TDB
1998             if (p[-1] && pppdb != NULL)
1999                 delete_db_key(p);
2000 #endif
2001             free(p-1);
2002             while ((script_env[i] = script_env[i+1]) != 0)
2003                 ++i;
2004             break;
2005         }
2006     }
2007 #ifdef USE_TDB
2008     if (pppdb != NULL)
2009         update_db_entry();
2010 #endif
2011 }
2012
2013 /*
2014  * Any arbitrary string used as a key for locking the database.
2015  * It doesn't matter what it is as long as all pppds use the same string.
2016  */
2017 #define PPPD_LOCK_KEY   "pppd lock"
2018
2019 /*
2020  * lock_db - get an exclusive lock on the TDB database.
2021  * Used to ensure atomicity of various lookup/modify operations.
2022  */
2023 void lock_db()
2024 {
2025 #ifdef USE_TDB
2026         TDB_DATA key;
2027
2028         key.dptr = PPPD_LOCK_KEY;
2029         key.dsize = strlen(key.dptr);
2030         tdb_chainlock(pppdb, key);
2031 #endif
2032 }
2033
2034 /*
2035  * unlock_db - remove the exclusive lock obtained by lock_db.
2036  */
2037 void unlock_db()
2038 {
2039 #ifdef USE_TDB
2040         TDB_DATA key;
2041
2042         key.dptr = PPPD_LOCK_KEY;
2043         key.dsize = strlen(key.dptr);
2044         tdb_chainunlock(pppdb, key);
2045 #endif
2046 }
2047
2048 #ifdef USE_TDB
2049 /*
2050  * update_db_entry - update our entry in the database.
2051  */
2052 static void
2053 update_db_entry()
2054 {
2055     TDB_DATA key, dbuf;
2056     int vlen, i;
2057     char *p, *q, *vbuf;
2058
2059     if (script_env == NULL)
2060         return;
2061     vlen = 0;
2062     for (i = 0; (p = script_env[i]) != 0; ++i)
2063         vlen += strlen(p) + 1;
2064     vbuf = malloc(vlen + 1);
2065     if (vbuf == 0)
2066         novm("database entry");
2067     q = vbuf;
2068     for (i = 0; (p = script_env[i]) != 0; ++i)
2069         q += slprintf(q, vbuf + vlen - q, "%s;", p);
2070
2071     key.dptr = db_key;
2072     key.dsize = strlen(db_key);
2073     dbuf.dptr = vbuf;
2074     dbuf.dsize = vlen;
2075     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2076         error("tdb_store failed: %s", tdb_error(pppdb));
2077
2078     if (vbuf)
2079         free(vbuf);
2080
2081 }
2082
2083 /*
2084  * add_db_key - add a key that we can use to look up our database entry.
2085  */
2086 static void
2087 add_db_key(str)
2088     const char *str;
2089 {
2090     TDB_DATA key, dbuf;
2091
2092     key.dptr = (char *) str;
2093     key.dsize = strlen(str);
2094     dbuf.dptr = db_key;
2095     dbuf.dsize = strlen(db_key);
2096     if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2097         error("tdb_store key failed: %s", tdb_error(pppdb));
2098 }
2099
2100 /*
2101  * delete_db_key - delete a key for looking up our database entry.
2102  */
2103 static void
2104 delete_db_key(str)
2105     const char *str;
2106 {
2107     TDB_DATA key;
2108
2109     key.dptr = (char *) str;
2110     key.dsize = strlen(str);
2111     tdb_delete(pppdb, key);
2112 }
2113
2114 /*
2115  * cleanup_db - delete all the entries we put in the database.
2116  */
2117 static void
2118 cleanup_db()
2119 {
2120     TDB_DATA key;
2121     int i;
2122     char *p;
2123
2124     key.dptr = db_key;
2125     key.dsize = strlen(db_key);
2126     tdb_delete(pppdb, key);
2127     for (i = 0; (p = script_env[i]) != 0; ++i)
2128         if (p[-1])
2129             delete_db_key(p);
2130 }
2131 #endif /* USE_TDB */