www.usr.com/support/gpl/USR9107_release.1.4.tar.gz
[bcm963xx.git] / userapps / opensource / ppp / pppoecd / main.c
1 /*
2  * main.c - Point-to-Point Protocol main module
3  *
4  * Copyright (c) 1989 Carnegie Mellon University.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms are permitted
8  * provided that the above copyright notice and this paragraph are
9  * duplicated in all such forms and that any documentation,
10  * advertising materials, and other materials related to such
11  * distribution and use acknowledge that the software was developed
12  * by Carnegie Mellon University.  The name of the
13  * University may not be used to endorse or promote products derived
14  * from this software without specific prior written permission.
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18  */
19
20 #define RCSID   "$Id: main.c,v 1.2 2001/08/08 22:47:15 mhuang Exp $"
21
22 #include <stdio.h>
23 #include <ctype.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <unistd.h>
27 #include <signal.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <syslog.h>
31 #include <netdb.h>
32 #include <utmp.h>
33 #include <pwd.h>
34 #include <setjmp.h>
35 #include <sys/param.h>
36 #include <sys/types.h>
37 #include <sys/wait.h>
38 #include <sys/time.h>
39 #include <sys/resource.h>
40 #include <sys/stat.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #include <arpa/inet.h>
44
45 #include "pppd.h"
46 #include "magic.h"
47 #include "fsm.h"
48 #include "lcp.h"
49 #include "ipcp.h"
50 #include "upap.h"
51 #include "chap.h"
52 #include "ccp.h"
53 #include "pathnames.h"
54
55 #ifdef CBCP_SUPPORT
56 #include "cbcp.h"
57 #endif
58
59 #ifdef IPX_CHANGE
60 #include "ipxcp.h"
61 #endif /* IPX_CHANGE */
62 #ifdef AT_CHANGE
63 #include "atcp.h"
64 #endif
65
66 static const char rcsid[] = RCSID;
67
68 /* interface vars */
69 char ifname[32];                /* Interface name */
70 int ifunit;                     /* Interface unit number */
71
72 struct channel *the_channel;
73
74 char *progname;                 /* Name of this program */
75 char hostname[MAXNAMELEN];      /* Our hostname */
76 static char pidfilename[MAXPATHLEN];    /* name of pid file */
77 static char linkpidfile[MAXPATHLEN];    /* name of linkname pid file */
78 char ppp_devnam[MAXPATHLEN];    /* name of PPP tty (maybe ttypx) */
79 uid_t uid;                      /* Our real user-id */
80
81 int hungup;                     /* terminal has been hung up */
82 int privileged;                 /* we're running as real uid root */
83 int need_holdoff;               /* need holdoff period before restarting */
84 int detached;                   /* have detached from terminal */
85 volatile int status;            /* exit status for pppd */
86 int unsuccess;                  /* # unsuccessful connection attempts */
87 int do_callback;                /* != 0 if we should do callback next */
88 int doing_callback;             /* != 0 if we are doing callback */
89 #define pppdb NULL
90
91 int (*holdoff_hook) __P((void)) = NULL;
92 int (*new_phase_hook) __P((int)) = NULL;
93
94 static int conn_running;        /* we have a [dis]connector running */
95 static int devfd;               /* fd of underlying device */
96 static int fd_ppp = -1;         /* fd for talking PPP */
97
98 int phase;                      /* where the link is at */
99 int kill_link;
100 int open_ccp_flag;
101 int listen_time;
102 int got_sigusr2;
103 int got_sigterm;
104 int got_sighup;
105
106 static int waiting;
107 static sigjmp_buf sigjmp;
108
109 char **script_env;              /* Env. variable values for scripts */
110 int s_env_nalloc;               /* # words avail at script_env */
111
112 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
113 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
114
115 static int n_children;          /* # child processes still running */
116 static int got_sigchld;         /* set if we have received a SIGCHLD */
117
118 int privopen;                   /* don't lock, open device as root */
119
120 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
121
122 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
123 int ngroups;                    /* How many groups valid in groups */
124
125 static struct timeval start_time;       /* Time when link was started. */
126
127 struct pppd_stats link_stats;
128 int link_connect_time;
129 int link_stats_valid;
130
131 /*
132  * We maintain a list of child process pids and
133  * functions to call when they exit.
134  */
135 struct subprocess {
136     pid_t       pid;
137     char        *prog;
138     void        (*done) __P((void *));
139     void        *arg;
140     struct subprocess *next;
141 };
142
143 static struct subprocess *children;
144
145 /* Prototypes for procedures local to this file. */
146
147 static void setup_signals __P((void));
148 static void create_pidfile __P((void));
149 static void create_linkpidfile __P((void));
150 static void cleanup __P((void));
151 static void get_input __P((void));
152 static void calltimeout __P((void));
153 static struct timeval *timeleft __P((struct timeval *));
154 static void kill_my_pg __P((int));
155 static void hup __P((int));
156 static void term __P((int));
157 static void chld __P((int));
158 static void toggle_debug __P((int));
159 static void open_ccp __P((int));
160 static void bad_signal __P((int));
161 static void holdoff_end __P((void *));
162 static int reap_kids __P((int waitfor));
163 #define update_db_entry()
164 #define add_db_key(a)
165 #define delete_db_key(a)
166 #define cleanup_db()
167 static void handle_events __P((void));
168
169 extern  char    *ttyname __P((int));
170 extern  char    *getlogin __P((void));
171 int main __P((int, char *[]));
172
173 #ifdef ultrix
174 #undef  O_NONBLOCK
175 #define O_NONBLOCK      O_NDELAY
176 #endif
177
178 #ifdef ULTRIX
179 #define setlogmask(x)
180 #endif
181
182 /*
183  * PPP Data Link Layer "protocol" table.
184  * One entry per supported protocol.
185  * The last entry must be NULL.
186  */
187 struct protent *protocols[] = {
188     &lcp_protent,
189     &pap_protent,
190 #ifdef CHAP_SUPPORT
191     &chap_protent,
192 #endif
193     &ipcp_protent,
194 #ifdef CCP_SUPPORT
195     &ccp_protent,
196 #endif
197     NULL
198 };
199
200 /*
201  * If PPP_DRV_NAME is not defined, use the default "ppp" as the device name.
202  */
203 #if !defined(PPP_DRV_NAME)
204 #define PPP_DRV_NAME    "ppp"
205 #endif /* !defined(PPP_DRV_NAME) */
206
207 /* BRCM begin */
208 int
209 pppd_main(argc, argv)
210 /* BRCM end */
211     int argc;
212     char *argv[];
213 {
214     int i, t;
215     char *p;
216     struct passwd *pw;
217     struct protent *protp;
218     char numbuf[16];
219
220     new_phase(PHASE_INITIALIZE);
221
222     /*
223      * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
224      * This way we can close 0, 1, 2 in detach() without clobbering
225      * a fd that we are using.
226      */
227     if ((i = open("/dev/null", O_RDWR)) >= 0) {
228         while (0 <= i && i <= 2)
229             i = dup(i);
230         if (i >= 0)
231             close(i);
232     }
233
234     script_env = NULL;
235
236     /* Initialize syslog facilities */
237     reopen_log();
238
239     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
240         option_error("Couldn't get hostname: %m");
241         exit(1);
242     }
243     hostname[MAXNAMELEN-1] = 0;
244
245     /* make sure we don't create world or group writable files. */
246     umask(umask(0777) | 022);
247
248     uid = getuid();
249     privileged = uid == 0;
250     slprintf(numbuf, sizeof(numbuf), "%d", uid);
251     script_setenv("ORIG_UID", numbuf, 0);
252
253     ngroups = getgroups(NGROUPS_MAX, groups);
254
255     /*
256      * Initialize magic number generator now so that protocols may
257      * use magic numbers in initialization.
258      */
259     magic_init();
260
261     /*
262      * Initialize each protocol.
263      */
264     for (i = 0; (protp = protocols[i]) != NULL; ++i)
265         (*protp->init)(0);
266
267     progname = *argv;
268
269     /*
270      * Parse, in order, the system options file, the user's options file,
271      * and the command line arguments.
272      */
273
274     if (!parse_args(argc, argv))
275         exit(EXIT_OPTION_ERROR);
276     devnam_fixed = 1;           /* can no longer change device name */
277
278     /*
279      * Work out the device name, if it hasn't already been specified,
280      * and parse the tty's options file.
281      */
282     if (the_channel->process_extra_options)
283         (*the_channel->process_extra_options)();
284
285     if (debug)
286         setlogmask(LOG_UPTO(LOG_DEBUG));
287
288     /*
289      * Check that we are running as root.
290      */
291     if (geteuid() != 0) {
292         option_error("must be root to run %s, since it is not setuid-root",
293                      argv[0]);
294         exit(EXIT_NOT_ROOT);
295     }
296
297     if (!ppp_available()) {
298         option_error("%s", no_ppp_msg);
299         exit(EXIT_NO_KERNEL_SUPPORT);
300     }
301
302     /*
303      * Check that the options given are valid and consistent.
304      */
305     check_options();
306     if (!sys_check_options())
307         exit(EXIT_OPTION_ERROR);
308     auth_check_options();
309     for (i = 0; (protp = protocols[i]) != NULL; ++i)
310         if (protp->check_options != NULL)
311             (*protp->check_options)();
312     if (the_channel->check_options)
313         (*the_channel->check_options)();
314
315
316     if (dump_options || dryrun) {
317         init_pr_log(NULL, LOG_INFO);
318         print_options(pr_log, NULL);
319         end_pr_log();
320         if (dryrun)
321             die(0);
322     }
323
324     /*
325      * Initialize system-dependent stuff.
326      */
327     sys_init();
328
329     /*
330      * Detach ourselves from the terminal, if required,
331      * and identify who is running us.
332      */
333     if (!nodetach && !updetach)
334         detach();
335     p = getlogin();
336     if (p == NULL) {
337         pw = getpwuid(uid);
338         if (pw != NULL && pw->pw_name != NULL)
339             p = pw->pw_name;
340         else
341             p = "(unknown)";
342     }
343     syslog(LOG_NOTICE, "pppd %s started by %s, uid %d", VERSION, p, uid);
344     script_setenv("PPPLOGNAME", p, 0);
345
346     if (devnam[0])
347         script_setenv("DEVICE", devnam, 1);
348     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
349     script_setenv("PPPD_PID", numbuf, 1);
350
351     setup_signals();
352
353     waiting = 0;
354
355     create_linkpidfile();
356
357     do_callback = 0;
358     for (;;) {
359
360         listen_time = 0;
361         need_holdoff = 1;
362         devfd = -1;
363         status = EXIT_OK;
364         ++unsuccess;
365         doing_callback = do_callback;
366         do_callback = 0;
367
368         new_phase(PHASE_SERIALCONN);
369
370         devfd = the_channel->connect();
371         if (devfd < 0)
372             goto fail;
373
374         /* set up the serial device as a ppp interface */
375         fd_ppp = the_channel->establish_ppp(devfd);
376         if (fd_ppp < 0) {
377             status = EXIT_FATAL_ERROR;
378             goto disconnect;
379         }
380
381         if (!demand && ifunit >= 0)
382             set_ifunit(1);
383
384         /*
385          * Start opening the connection and wait for
386          * incoming events (reply, timeout, etc.).
387          */
388         notice("Connect: %s <--> %s", ifname, ppp_devnam);
389         gettimeofday(&start_time, NULL);
390         link_stats_valid = 0;
391         script_unsetenv("CONNECT_TIME");
392         script_unsetenv("BYTES_SENT");
393         script_unsetenv("BYTES_RCVD");
394         lcp_lowerup(0);
395
396         add_fd(fd_ppp);
397         lcp_open(0);            /* Start protocol */
398         status = EXIT_NEGOTIATION_FAILED;
399         new_phase(PHASE_ESTABLISH);
400         while (phase != PHASE_DEAD) {
401             handle_events();
402             get_input();
403             if (kill_link)
404                 lcp_close(0, "User request");
405 #ifdef CCP_SUPPORT
406             if (open_ccp_flag) {
407                 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
408                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
409                     (*ccp_protent.open)(0);
410                 }
411             }
412 #endif
413         }
414
415         /*
416          * Print connect time and statistics.
417          */
418         if (link_stats_valid) {
419             int t = (link_connect_time + 5) / 6;    /* 1/10ths of minutes */
420             info("Connect time %d.%d minutes.", t/10, t%10);
421             info("Sent %u bytes, received %u bytes.",
422                  link_stats.bytes_out, link_stats.bytes_in);
423         }
424
425         /*
426          * Delete pid file before disestablishing ppp.  Otherwise it
427          * can happen that another pppd gets the same unit and then
428          * we delete its pid file.
429          */
430         if (!demand) {
431             if (pidfilename[0] != 0
432                 && unlink(pidfilename) < 0 && errno != ENOENT)
433                 warn("unable to delete pid file %s: %m", pidfilename);
434             pidfilename[0] = 0;
435         }
436
437         /*
438          * If we may want to bring the link up again, transfer
439          * the ppp unit back to the loopback.  Set the
440          * real serial device back to its normal mode of operation.
441          */
442         remove_fd(fd_ppp);
443         clean_check();
444         the_channel->disestablish_ppp(devfd);
445         fd_ppp = -1;
446         if (!hungup)
447             lcp_lowerdown(0);
448         if (!demand)
449             script_unsetenv("IFNAME");
450
451         /*
452          * Run disconnector script, if requested.
453          * XXX we may not be able to do this if the line has hung up!
454          */
455     disconnect:
456         new_phase(PHASE_DISCONNECT);
457         the_channel->disconnect();
458
459     fail:
460         if (the_channel->cleanup)
461             (*the_channel->cleanup)();
462
463         if (!demand) {
464             if (pidfilename[0] != 0
465                 && unlink(pidfilename) < 0 && errno != ENOENT)
466                 warn("unable to delete pid file %s: %m", pidfilename);
467             pidfilename[0] = 0;
468         }
469
470         if (!persist || (maxfail > 0 && unsuccess >= maxfail))
471             break;
472
473         t = need_holdoff? holdoff: 0;
474         if (holdoff_hook)
475             t = (*holdoff_hook)();
476         if (t > 0) {
477             new_phase(PHASE_HOLDOFF);
478             TIMEOUT(holdoff_end, NULL, t);
479             do {
480                 handle_events();
481                 if (kill_link)
482                     new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
483             } while (phase == PHASE_HOLDOFF);
484             if (!persist)
485                 break;
486         }
487     }
488
489     /* Wait for scripts to finish */
490     /* XXX should have a timeout here */
491     while (n_children > 0) {
492         if (debug) {
493             struct subprocess *chp;
494             dbglog("Waiting for %d child processes...", n_children);
495             for (chp = children; chp != NULL; chp = chp->next)
496                 dbglog("  script %s, pid %d", chp->prog, chp->pid);
497         }
498         if (reap_kids(1) < 0)
499             break;
500     }
501
502     die(status);
503     return 0;
504 }
505
506 /*
507  * handle_events - wait for something to happen and respond to it.
508  */
509 static void
510 handle_events()
511 {
512     struct timeval timo;
513     sigset_t mask;
514
515     kill_link = open_ccp_flag = 0;
516     if (sigsetjmp(sigjmp, 1) == 0) {
517         sigprocmask(SIG_BLOCK, &mask, NULL);
518         if (got_sighup || got_sigterm || got_sigusr2 || got_sigchld) {
519             sigprocmask(SIG_UNBLOCK, &mask, NULL);
520         } else {
521             waiting = 1;
522             sigprocmask(SIG_UNBLOCK, &mask, NULL);
523             wait_input(timeleft(&timo));
524         }
525     }
526     waiting = 0;
527     calltimeout();
528     if (got_sighup) {
529         kill_link = 1;
530         got_sighup = 0;
531         if (status != EXIT_HANGUP)
532             status = EXIT_USER_REQUEST;
533     }
534     if (got_sigterm) {
535         kill_link = 1;
536         persist = 0;
537         status = EXIT_USER_REQUEST;
538         got_sigterm = 0;
539     }
540     if (got_sigchld) {
541         reap_kids(0);   /* Don't leave dead kids lying around */
542         got_sigchld = 0;
543     }
544     if (got_sigusr2) {
545         open_ccp_flag = 1;
546         got_sigusr2 = 0;
547     }
548 }
549
550 /*
551  * setup_signals - initialize signal handling.
552  */
553 static void
554 setup_signals()
555 {
556     struct sigaction sa;
557     sigset_t mask;
558
559     /*
560      * Compute mask of all interesting signals and install signal handlers
561      * for each.  Only one signal handler may be active at a time.  Therefore,
562      * all other signals should be masked when any handler is executing.
563      */
564     sigemptyset(&mask);
565     sigaddset(&mask, SIGHUP);
566     sigaddset(&mask, SIGINT);
567     sigaddset(&mask, SIGTERM);
568     sigaddset(&mask, SIGCHLD);
569     sigaddset(&mask, SIGUSR2);
570
571 #define SIGNAL(s, handler)      do { \
572         sa.sa_handler = handler; \
573         if (sigaction(s, &sa, NULL) < 0) \
574             fatal("Couldn't establish signal handler (%d): %m", s); \
575     } while (0)
576
577     sa.sa_mask = mask;
578     sa.sa_flags = 0;
579     SIGNAL(SIGHUP, hup);                /* Hangup */
580     SIGNAL(SIGINT, term);               /* Interrupt */
581     SIGNAL(SIGTERM, term);              /* Terminate */
582     SIGNAL(SIGCHLD, chld);
583
584     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
585     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
586
587     /*
588      * Install a handler for other signals which would otherwise
589      * cause pppd to exit without cleaning up.
590      */
591     SIGNAL(SIGABRT, bad_signal);
592     SIGNAL(SIGALRM, bad_signal);
593     SIGNAL(SIGFPE, bad_signal);
594     SIGNAL(SIGILL, bad_signal);
595     SIGNAL(SIGPIPE, bad_signal);
596     SIGNAL(SIGQUIT, bad_signal);
597     SIGNAL(SIGSEGV, bad_signal);
598 #ifdef SIGBUS
599     SIGNAL(SIGBUS, bad_signal);
600 #endif
601 #ifdef SIGEMT
602     SIGNAL(SIGEMT, bad_signal);
603 #endif
604 #ifdef SIGPOLL
605     SIGNAL(SIGPOLL, bad_signal);
606 #endif
607 #ifdef SIGPROF
608     SIGNAL(SIGPROF, bad_signal);
609 #endif
610 #ifdef SIGSYS
611     SIGNAL(SIGSYS, bad_signal);
612 #endif
613 #ifdef SIGTRAP
614     SIGNAL(SIGTRAP, bad_signal);
615 #endif
616 #ifdef SIGVTALRM
617     SIGNAL(SIGVTALRM, bad_signal);
618 #endif
619 #ifdef SIGXCPU
620     SIGNAL(SIGXCPU, bad_signal);
621 #endif
622 #ifdef SIGXFSZ
623     SIGNAL(SIGXFSZ, bad_signal);
624 #endif
625
626     /*
627      * Apparently we can get a SIGPIPE when we call syslog, if
628      * syslogd has died and been restarted.  Ignoring it seems
629      * be sufficient.
630      */
631     signal(SIGPIPE, SIG_IGN);
632 }
633
634 /*
635  * set_ifunit - do things we need to do once we know which ppp
636  * unit we are using.
637  */
638 void
639 set_ifunit(iskey)
640     int iskey;
641 {
642     info("Using interface %s%d", PPP_DRV_NAME, ifunit);
643     slprintf(ifname, sizeof(ifname), "%s%d", PPP_DRV_NAME, ifunit);
644     script_setenv("IFNAME", ifname, iskey);
645     if (iskey) {
646         create_pidfile();       /* write pid to file */
647         create_linkpidfile();
648     }
649 }
650
651 /*
652  * detach - detach us from the controlling terminal.
653  */
654 void
655 detach()
656 {
657     int pid;
658     char numbuf[16];
659
660     if (detached)
661         return;
662     if ((pid = fork()) < 0) {
663         error("Couldn't detach (fork failed: %m)");
664         die(1);                 /* or just return? */
665     }
666     if (pid != 0) {
667         /* parent */
668         exit(0);                /* parent dies */
669     }
670     setsid();
671     chdir("/");
672     close(0);
673     close(1);
674     close(2);
675     detached = 1;
676     if (log_default)
677         log_to_fd = -1;
678     /* update pid files if they have been written already */
679     if (pidfilename[0])
680         create_pidfile();
681     if (linkpidfile[0])
682         create_linkpidfile();
683     slprintf(numbuf, sizeof(numbuf), "%d", getpid());
684     script_setenv("PPPD_PID", numbuf, 1);
685 }
686
687 /*
688  * reopen_log - (re)open our connection to syslog.
689  */
690 void
691 reopen_log()
692 {
693 #ifdef ULTRIX
694     openlog("pppd", LOG_PID);
695 #else
696     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
697     setlogmask(LOG_UPTO(LOG_INFO));
698 #endif
699 }
700
701 /*
702  * Create a file containing our process ID.
703  */
704 static void
705 create_pidfile()
706 {
707     FILE *pidfile;
708
709     slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
710              _PATH_VARRUN, ifname);
711     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
712         fprintf(pidfile, "%d\n", getpid());
713         (void) fclose(pidfile);
714     } else {
715         error("Failed to create pid file %s: %m", pidfilename);
716         pidfilename[0] = 0;
717     }
718 }
719
720 static void
721 create_linkpidfile()
722 {
723     FILE *pidfile;
724
725     if (linkname[0] == 0)
726         return;
727     script_setenv("LINKNAME", linkname, 1);
728     slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
729              _PATH_VARRUN, linkname);
730     if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
731         fprintf(pidfile, "%d\n", getpid());
732         if (ifname[0])
733             fprintf(pidfile, "%s\n", ifname);
734         (void) fclose(pidfile);
735     } else {
736         error("Failed to create pid file %s: %m", linkpidfile);
737         linkpidfile[0] = 0;
738     }
739 }
740
741 /*
742  * holdoff_end - called via a timeout when the holdoff period ends.
743  */
744 static void
745 holdoff_end(arg)
746     void *arg;
747 {
748     new_phase(PHASE_DORMANT);
749 }
750
751 /*
752  * get_input - called when incoming data is available.
753  */
754 static void
755 get_input()
756 {
757     int len, i;
758     u_char *p;
759     u_short protocol;
760     struct protent *protp;
761
762     p = inpacket_buf;   /* point to beginning of packet buffer */
763
764     len = read_packet(inpacket_buf);
765     if (len < 0)
766         return;
767
768     if (len == 0) {
769         notice("Modem hangup");
770         hungup = 1;
771         status = EXIT_HANGUP;
772         lcp_lowerdown(0);       /* serial link is no longer available */
773         link_terminated(0);
774         return;
775     }
776
777     if (debug /*&& (debugflags & DBG_INPACKET)*/)
778         dbglog("rcvd %P", p, len);
779
780     if (len < PPP_HDRLEN) {
781         MAINDEBUG(("io(): Received short packet."));
782         return;
783     }
784
785     p += 2;                             /* Skip address and control */
786     GETSHORT(protocol, p);
787     len -= PPP_HDRLEN;
788
789     /*
790      * Toss all non-LCP packets unless LCP is OPEN.
791      */
792     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
793         MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
794         return;
795     }
796
797     /*
798      * Until we get past the authentication phase, toss all packets
799      * except LCP, LQR and authentication packets.
800      */
801     if (phase <= PHASE_AUTHENTICATE
802         && !(protocol == PPP_LCP || protocol == PPP_LQR
803              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
804         MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
805                    protocol, phase));
806         return;
807     }
808
809     /*
810      * Upcall the proper protocol input routine.
811      */
812     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
813         if (protp->protocol == protocol && protp->enabled_flag) {
814             (*protp->input)(0, p, len);
815             return;
816         }
817         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
818             && protp->datainput != NULL) {
819             (*protp->datainput)(0, p, len);
820             return;
821         }
822     }
823
824     if (debug) {
825         warn("Unsupported protocol 0x%x received", protocol);
826     }
827     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
828 }
829
830 /*
831  * new_phase - signal the start of a new phase of pppd's operation.
832  */
833 void
834 new_phase(p)
835     int p;
836 {
837     phase = p;
838     if (new_phase_hook)
839         (*new_phase_hook)(p);
840 }
841
842 /*
843  * die - clean up state and exit with the specified status.
844  */
845 void
846 die(status)
847     int status;
848 {
849     cleanup();
850     syslog(LOG_INFO, "Exit.");
851     exit(status);
852 }
853
854 /*
855  * cleanup - restore anything which needs to be restored before we exit
856  */
857 /* ARGSUSED */
858 static void
859 cleanup()
860 {
861     sys_cleanup();
862
863     if (fd_ppp >= 0)
864         the_channel->disestablish_ppp(devfd);
865     if (the_channel->cleanup)
866         (*the_channel->cleanup)();
867
868     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
869         warn("unable to delete pid file %s: %m", pidfilename);
870     pidfilename[0] = 0;
871     if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
872         warn("unable to delete pid file %s: %m", linkpidfile);
873     linkpidfile[0] = 0;
874 }
875
876 /*
877  * update_link_stats - get stats at link termination.
878  */
879 void
880 update_link_stats(u)
881     int u;
882 {
883     struct timeval now;
884     char numbuf[32];
885
886     if (!get_ppp_stats(u, &link_stats)
887         || gettimeofday(&now, NULL) < 0)
888         return;
889     link_connect_time = now.tv_sec - start_time.tv_sec;
890     link_stats_valid = 1;
891
892     slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
893     script_setenv("CONNECT_TIME", numbuf, 0);
894     slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
895     script_setenv("BYTES_SENT", numbuf, 0);
896     slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
897     script_setenv("BYTES_RCVD", numbuf, 0);
898 }
899
900
901 struct  callout {
902     struct timeval      c_time;         /* time at which to call routine */
903     void                *c_arg;         /* argument to routine */
904     void                (*c_func) __P((void *)); /* routine */
905     struct              callout *c_next;
906 };
907
908 static struct callout *callout = NULL;  /* Callout list */
909 static struct timeval timenow;          /* Current time */
910
911 /*
912  * timeout - Schedule a timeout.
913  *
914  * Note that this timeout takes the number of milliseconds, NOT hz (as in
915  * the kernel).
916  */
917 void
918 timeout(func, arg, secs, usecs)
919     void (*func) __P((void *));
920     void *arg;
921     int secs, usecs;
922 {
923     struct callout *newp, *p, **pp;
924
925     MAINDEBUG(("Timeout %p:%p in %d.%03d seconds.", func, arg,
926                time / 1000, time % 1000));
927
928     /*
929      * Allocate timeout.
930      */
931     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
932         fatal("Out of memory in timeout()!");
933     newp->c_arg = arg;
934     newp->c_func = func;
935     gettimeofday(&timenow, NULL);
936     newp->c_time.tv_sec = timenow.tv_sec + secs;
937     newp->c_time.tv_usec = timenow.tv_usec + usecs;
938     if (newp->c_time.tv_usec >= 1000000) {
939         newp->c_time.tv_sec += newp->c_time.tv_usec / 1000000;
940         newp->c_time.tv_usec %= 1000000;
941     }
942
943     /*
944      * Find correct place and link it in.
945      */
946     for (pp = &callout; (p = *pp); pp = &p->c_next)
947         if (newp->c_time.tv_sec < p->c_time.tv_sec
948             || (newp->c_time.tv_sec == p->c_time.tv_sec
949                 && newp->c_time.tv_usec < p->c_time.tv_usec))
950             break;
951     newp->c_next = p;
952     *pp = newp;
953 }
954
955
956 /*
957  * untimeout - Unschedule a timeout.
958  */
959 void
960 untimeout(func, arg)
961     void (*func) __P((void *));
962     void *arg;
963 {
964     struct callout **copp, *freep;
965
966     MAINDEBUG(("Untimeout %p:%p.", func, arg));
967
968     /*
969      * Find first matching timeout and remove it from the list.
970      */
971     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
972         if (freep->c_func == func && freep->c_arg == arg) {
973             *copp = freep->c_next;
974             free((char *) freep);
975             break;
976         }
977 }
978
979
980 /*
981  * calltimeout - Call any timeout routines which are now due.
982  */
983 static void
984 calltimeout()
985 {
986     struct callout *p;
987
988     while (callout != NULL) {
989         p = callout;
990
991         if (gettimeofday(&timenow, NULL) < 0)
992             fatal("Failed to get time of day: %m");
993         if (!(p->c_time.tv_sec < timenow.tv_sec
994               || (p->c_time.tv_sec == timenow.tv_sec
995                   && p->c_time.tv_usec <= timenow.tv_usec)))
996             break;              /* no, it's not time yet */
997
998         callout = p->c_next;
999         (*p->c_func)(p->c_arg);
1000
1001         free((char *) p);
1002     }
1003 }
1004
1005
1006 /*
1007  * timeleft - return the length of time until the next timeout is due.
1008  */
1009 static struct timeval *
1010 timeleft(tvp)
1011     struct timeval *tvp;
1012 {
1013     if (callout == NULL)
1014         return NULL;
1015
1016     gettimeofday(&timenow, NULL);
1017     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1018     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1019     if (tvp->tv_usec < 0) {
1020         tvp->tv_usec += 1000000;
1021         tvp->tv_sec -= 1;
1022     }
1023     if (tvp->tv_sec < 0)
1024         tvp->tv_sec = tvp->tv_usec = 0;
1025
1026     return tvp;
1027 }
1028
1029
1030 /*
1031  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1032  */
1033 static void
1034 kill_my_pg(sig)
1035     int sig;
1036 {
1037     struct sigaction act, oldact;
1038
1039     act.sa_handler = SIG_IGN;
1040     act.sa_flags = 0;
1041     kill(0, sig);
1042     sigaction(sig, &act, &oldact);
1043     sigaction(sig, &oldact, NULL);
1044 }
1045
1046
1047 /*
1048  * hup - Catch SIGHUP signal.
1049  *
1050  * Indicates that the physical layer has been disconnected.
1051  * We don't rely on this indication; if the user has sent this
1052  * signal, we just take the link down.
1053  */
1054 static void
1055 hup(sig)
1056     int sig;
1057 {
1058     info("Hangup (SIGHUP)");
1059     got_sighup = 1;
1060     if (conn_running)
1061         /* Send the signal to the [dis]connector process(es) also */
1062         kill_my_pg(sig);
1063     if (waiting)
1064         siglongjmp(sigjmp, 1);
1065 }
1066
1067
1068 /*
1069  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1070  *
1071  * Indicates that we should initiate a graceful disconnect and exit.
1072  */
1073 /*ARGSUSED*/
1074 static void
1075 term(sig)
1076     int sig;
1077 {
1078     info("Terminating on signal %d.", sig);
1079     got_sigterm = 1;
1080     if (conn_running)
1081         /* Send the signal to the [dis]connector process(es) also */
1082         kill_my_pg(sig);
1083     if (waiting)
1084         siglongjmp(sigjmp, 1);
1085 }
1086
1087
1088 /*
1089  * chld - Catch SIGCHLD signal.
1090  * Sets a flag so we will call reap_kids in the mainline.
1091  */
1092 static void
1093 chld(sig)
1094     int sig;
1095 {
1096     got_sigchld = 1;
1097     if (waiting)
1098         siglongjmp(sigjmp, 1);
1099 }
1100
1101
1102 /*
1103  * toggle_debug - Catch SIGUSR1 signal.
1104  *
1105  * Toggle debug flag.
1106  */
1107 /*ARGSUSED*/
1108 static void
1109 toggle_debug(sig)
1110     int sig;
1111 {
1112     debug = !debug;
1113     if (debug) {
1114         setlogmask(LOG_UPTO(LOG_DEBUG));
1115     } else {
1116         setlogmask(LOG_UPTO(LOG_WARNING));
1117     }
1118 }
1119
1120
1121 /*
1122  * open_ccp - Catch SIGUSR2 signal.
1123  *
1124  * Try to (re)negotiate compression.
1125  */
1126 /*ARGSUSED*/
1127 static void
1128 open_ccp(sig)
1129     int sig;
1130 {
1131     got_sigusr2 = 1;
1132     if (waiting)
1133         siglongjmp(sigjmp, 1);
1134 }
1135
1136
1137 /*
1138  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
1139  */
1140 static void
1141 bad_signal(sig)
1142     int sig;
1143 {
1144     static int crashed = 0;
1145
1146     if (crashed)
1147         _exit(127);
1148     crashed = 1;
1149     error("Fatal signal %d", sig);
1150     if (conn_running)
1151         kill_my_pg(SIGTERM);
1152     die(127);
1153 }
1154
1155 /*
1156  * run-program - execute a program with given arguments,
1157  * but don't wait for it.
1158  * If the program can't be executed, logs an error unless
1159  * must_exist is 0 and the program file doesn't exist.
1160  * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1161  * or isn't an executable plain file, or the process ID of the child.
1162  * If done != NULL, (*done)(arg) will be called later (within
1163  * reap_kids) iff the return value is > 0.
1164  */
1165 pid_t
1166 run_program(prog, args, must_exist, done, arg)
1167     char *prog;
1168     char **args;
1169     int must_exist;
1170     void (*done) __P((void *));
1171     void *arg;
1172 {
1173     int pid;
1174     struct stat sbuf;
1175
1176     /*
1177      * First check if the file exists and is executable.
1178      * We don't use access() because that would use the
1179      * real user-id, which might not be root, and the script
1180      * might be accessible only to root.
1181      */
1182     errno = EINVAL;
1183     if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1184         || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1185         if (must_exist || errno != ENOENT)
1186             warn("Can't execute %s: %m", prog);
1187         return 0;
1188     }
1189
1190     pid = fork();
1191     if (pid == -1) {
1192         error("Failed to create child process for %s: %m", prog);
1193         return -1;
1194     }
1195     if (pid == 0) {
1196         int new_fd;
1197
1198         /* Leave the current location */
1199         (void) setsid();        /* No controlling tty. */
1200         (void) umask (S_IRWXG|S_IRWXO);
1201         (void) chdir ("/");     /* no current directory. */
1202         setuid(0);              /* set real UID = root */
1203         setgid(getegid());
1204
1205         /* Ensure that nothing of our device environment is inherited. */
1206         sys_close();
1207         closelog();
1208         close (0);
1209         close (1);
1210         close (2);
1211         if (the_channel->close)
1212             (*the_channel->close)();
1213
1214         /* Don't pass handles to the PPP device, even by accident. */
1215         new_fd = open (_PATH_DEVNULL, O_RDWR);
1216         if (new_fd >= 0) {
1217             if (new_fd != 0) {
1218                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1219                 close (new_fd);
1220             }
1221             dup2 (0, 1); /* stdout -> /dev/null */
1222             dup2 (0, 2); /* stderr -> /dev/null */
1223         }
1224
1225 #ifdef BSD
1226         /* Force the priority back to zero if pppd is running higher. */
1227         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1228             warn("can't reset priority to 0: %m");
1229 #endif
1230
1231         /* SysV recommends a second fork at this point. */
1232
1233         /* run the program */
1234         execve(prog, args, script_env);
1235         if (must_exist || errno != ENOENT) {
1236             /* have to reopen the log, there's nowhere else
1237                for the message to go. */
1238             reopen_log();
1239             syslog(LOG_ERR, "Can't execute %s: %m", prog);
1240             closelog();
1241         }
1242         _exit(-1);
1243     }
1244
1245     if (debug)
1246         dbglog("Script %s started (pid %d)", prog, pid);
1247     record_child(pid, prog, done, arg);
1248
1249     return pid;
1250 }
1251
1252
1253 /*
1254  * record_child - add a child process to the list for reap_kids
1255  * to use.
1256  */
1257 void
1258 record_child(pid, prog, done, arg)
1259     int pid;
1260     char *prog;
1261     void (*done) __P((void *));
1262     void *arg;
1263 {
1264     struct subprocess *chp;
1265
1266     ++n_children;
1267
1268     chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1269     if (chp == NULL) {
1270         warn("losing track of %s process", prog);
1271     } else {
1272         chp->pid = pid;
1273         chp->prog = prog;
1274         chp->done = done;
1275         chp->arg = arg;
1276         chp->next = children;
1277         children = chp;
1278     }
1279 }
1280
1281
1282 /*
1283  * reap_kids - get status from any dead child processes,
1284  * and log a message for abnormal terminations.
1285  */
1286 static int
1287 reap_kids(waitfor)
1288     int waitfor;
1289 {
1290     int pid, status;
1291     struct subprocess *chp, **prevp;
1292
1293     if (n_children == 0)
1294         return 0;
1295     while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1296            && pid != 0) {
1297         for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1298             if (chp->pid == pid) {
1299                 --n_children;
1300                 *prevp = chp->next;
1301                 break;
1302             }
1303         }
1304         if (WIFSIGNALED(status)) {
1305             warn("Child process %s (pid %d) terminated with signal %d",
1306                  (chp? chp->prog: "??"), pid, WTERMSIG(status));
1307         } else if (debug)
1308             dbglog("Script %s finished (pid %d), status = 0x%x",
1309                    (chp? chp->prog: "??"), pid, status);
1310         if (chp && chp->done)
1311             (*chp->done)(chp->arg);
1312         if (chp)
1313             free(chp);
1314     }
1315     if (pid == -1) {
1316         if (errno == ECHILD)
1317             return -1;
1318         if (errno != EINTR)
1319             error("Error waiting for child process: %m");
1320     }
1321     return 0;
1322 }
1323
1324 /*
1325  * script_setenv - set an environment variable value to be used
1326  * for scripts that we run (e.g. ip-up, auth-up, etc.)
1327  */
1328 void
1329 script_setenv(var, value, iskey)
1330     char *var, *value;
1331     int iskey;
1332 {
1333     size_t varl = strlen(var);
1334     size_t vl = varl + strlen(value) + 2;
1335     int i;
1336     char *p, *newstring;
1337
1338     newstring = (char *) malloc(vl+1);
1339     if (newstring == 0)
1340         return;
1341     *newstring++ = iskey;
1342     slprintf(newstring, vl, "%s=%s", var, value);
1343
1344     /* check if this variable is already set */
1345     if (script_env != 0) {
1346         for (i = 0; (p = script_env[i]) != 0; ++i) {
1347             if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1348                 if (p[-1] && pppdb != NULL)
1349                     delete_db_key(p);
1350                 free(p-1);
1351                 script_env[i] = newstring;
1352                 if (iskey && pppdb != NULL)
1353                     add_db_key(newstring);
1354                 update_db_entry();
1355                 return;
1356             }
1357         }
1358     } else {
1359         /* no space allocated for script env. ptrs. yet */
1360         i = 0;
1361         script_env = (char **) malloc(16 * sizeof(char *));
1362         if (script_env == 0)
1363             return;
1364         s_env_nalloc = 16;
1365     }
1366
1367     /* reallocate script_env with more space if needed */
1368     if (i + 1 >= s_env_nalloc) {
1369         int new_n = i + 17;
1370         char **newenv = (char **) realloc((void *)script_env,
1371                                           new_n * sizeof(char *));
1372         if (newenv == 0)
1373             return;
1374         script_env = newenv;
1375         s_env_nalloc = new_n;
1376     }
1377
1378     script_env[i] = newstring;
1379     script_env[i+1] = 0;
1380
1381     if (pppdb != NULL) {
1382         if (iskey)
1383             add_db_key(newstring);
1384         update_db_entry();
1385     }
1386 }
1387
1388 /*
1389  * script_unsetenv - remove a variable from the environment
1390  * for scripts.
1391  */
1392 void
1393 script_unsetenv(var)
1394     char *var;
1395 {
1396     int vl = strlen(var);
1397     int i;
1398     char *p;
1399
1400     if (script_env == 0)
1401         return;
1402     for (i = 0; (p = script_env[i]) != 0; ++i) {
1403         if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1404             if (p[-1] && pppdb != NULL)
1405                 delete_db_key(p);
1406             free(p-1);
1407             while ((script_env[i] = script_env[i+1]) != 0)
1408                 ++i;
1409             break;
1410         }
1411     }
1412     if (pppdb != NULL)
1413         update_db_entry();
1414 }