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