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