]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
this is really still back at 2.3.0 (or 2.2)
[ppp.git] / pppd / main.c
1 /*
2  * main.c - Point-to-Point Protocol main module
3  *
4  * Copyright (c) 1989 Carnegie Mellon University.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms are permitted
8  * provided that the above copyright notice and this paragraph are
9  * duplicated in all such forms and that any documentation,
10  * advertising materials, and other materials related to such
11  * distribution and use acknowledge that the software was developed
12  * by Carnegie Mellon University.  The name of the
13  * University may not be used to endorse or promote products derived
14  * from this software without specific prior written permission.
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18  */
19
20 #ifndef lint
21 static char rcsid[] = "$Id: main.c,v 1.42 1997/07/14 03:53:25 paulus Exp $";
22 #endif
23
24 #include <stdio.h>
25 #include <ctype.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <signal.h>
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <syslog.h>
33 #include <netdb.h>
34 #include <utmp.h>
35 #include <pwd.h>
36 #include <sys/param.h>
37 #include <sys/types.h>
38 #include <sys/wait.h>
39 #include <sys/time.h>
40 #include <sys/resource.h>
41 #include <sys/stat.h>
42 #include <sys/socket.h>
43 #include <net/if.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 #include "patchlevel.h"
55
56 #ifdef CBCP_SUPPORT
57 #include "cbcp.h"
58 #endif
59
60 #if defined(SUNOS4)
61 extern char *strerror();
62 #endif
63
64 #ifdef IPX_CHANGE
65 #include "ipxcp.h"
66 #endif /* IPX_CHANGE */
67 #ifdef AT_CHANGE
68 #include "atcp.h"
69 #endif
70
71 /* interface vars */
72 char ifname[IFNAMSIZ];          /* Interface name */
73 int ifunit;                     /* Interface unit number */
74
75 char *progname;                 /* Name of this program */
76 char hostname[MAXNAMELEN];      /* Our hostname */
77 static char pidfilename[MAXPATHLEN];    /* name of pid file */
78 static char default_devnam[MAXPATHLEN]; /* name of default device */
79 static pid_t pid;               /* Our pid */
80 static uid_t uid;               /* Our real user-id */
81 static int conn_running;        /* we have a [dis]connector running */
82
83 int ttyfd = -1;                 /* Serial port file descriptor */
84 mode_t tty_mode = -1;           /* Original access permissions to tty */
85 int baud_rate;                  /* Actual bits/second for serial device */
86 int hungup;                     /* terminal has been hung up */
87 int privileged;                 /* we're running as real uid root */
88 int need_holdoff;               /* need holdoff period before restarting */
89
90 int phase;                      /* where the link is at */
91 int kill_link;
92 int open_ccp_flag;
93 int redirect_stderr;            /* Connector's stderr should go to file */
94
95 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
96 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
97
98 static int n_children;          /* # child processes still running */
99
100 static int locked;              /* lock() has succeeded */
101
102 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
103
104 /* Prototypes for procedures local to this file. */
105
106 static void cleanup __P((void));
107 static void close_tty __P((void));
108 static void get_input __P((void));
109 static void calltimeout __P((void));
110 static struct timeval *timeleft __P((struct timeval *));
111 static void kill_my_pg __P((int));
112 static void hup __P((int));
113 static void term __P((int));
114 static void chld __P((int));
115 static void toggle_debug __P((int));
116 static void open_ccp __P((int));
117 static void bad_signal __P((int));
118 static void holdoff_end __P((void *));
119 static int device_script __P((char *, int, int));
120 static void reap_kids __P((void));
121 static void pr_log __P((void *, char *, ...));
122
123 extern  char    *ttyname __P((int));
124 extern  char    *getlogin __P((void));
125 int main __P((int, char *[]));
126
127 #ifdef ultrix
128 #undef  O_NONBLOCK
129 #define O_NONBLOCK      O_NDELAY
130 #endif
131
132 #ifdef ULTRIX
133 #define setlogmask(x)
134 #endif
135
136 /*
137  * PPP Data Link Layer "protocol" table.
138  * One entry per supported protocol.
139  * The last entry must be NULL.
140  */
141 struct protent *protocols[] = {
142     &lcp_protent,
143     &pap_protent,
144     &chap_protent,
145 #ifdef CBCP_SUPPORT
146     &cbcp_protent,
147 #endif
148     &ipcp_protent,
149     &ccp_protent,
150 #ifdef IPX_CHANGE
151     &ipxcp_protent,
152 #endif
153 #ifdef AT_CHANGE
154     &atcp_protent,
155 #endif
156     NULL
157 };
158
159 int
160 main(argc, argv)
161     int argc;
162     char *argv[];
163 {
164     int i, nonblock, fdflags;
165     struct sigaction sa;
166     FILE *pidfile;
167     char *p;
168     struct passwd *pw;
169     struct timeval timo;
170     sigset_t mask;
171     struct protent *protp;
172     struct stat statbuf;
173
174     phase = PHASE_INITIALIZE;
175     p = ttyname(0);
176     if (p)
177         strcpy(devnam, p);
178     strcpy(default_devnam, devnam);
179
180     /* Initialize syslog facilities */
181 #ifdef ULTRIX
182     openlog("pppd", LOG_PID);
183 #else
184     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
185     setlogmask(LOG_UPTO(LOG_INFO));
186 #endif
187
188     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
189         option_error("Couldn't get hostname: %m");
190         die(1);
191     }
192     hostname[MAXNAMELEN-1] = 0;
193
194     uid = getuid();
195     privileged = uid == 0;
196
197     /*
198      * Initialize to the standard option set, then parse, in order,
199      * the system options file, the user's options file,
200      * the tty's options file, and the command line arguments.
201      */
202     for (i = 0; (protp = protocols[i]) != NULL; ++i)
203         (*protp->init)(0);
204   
205     progname = *argv;
206
207     if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
208         || !options_from_user())
209         exit(1);
210     scan_args(argc-1, argv+1);  /* look for tty name on command line */
211     if (!options_for_tty()
212         || !parse_args(argc-1, argv+1))
213         exit(1);
214
215     /*
216      * Check that we are running as root.
217      */
218     if (geteuid() != 0) {
219         option_error("must be root to run %s, since it is not setuid-root",
220                      argv[0]);
221         die(1);
222     }
223
224     if (!ppp_available()) {
225         option_error(no_ppp_msg);
226         exit(1);
227     }
228
229     /*
230      * Check that the options given are valid and consistent.
231      */
232     sys_check_options();
233     auth_check_options();
234     for (i = 0; (protp = protocols[i]) != NULL; ++i)
235         if (protp->check_options != NULL)
236             (*protp->check_options)();
237     if (demand && connector == 0) {
238         option_error("connect script required for demand-dialling\n");
239         exit(1);
240     }
241
242     /*
243      * If the user has specified the default device name explicitly,
244      * pretend they hadn't.
245      */
246     if (!default_device && strcmp(devnam, default_devnam) == 0)
247         default_device = 1;
248     redirect_stderr = !nodetach || default_device;
249
250     /*
251      * Initialize system-dependent stuff and magic number package.
252      */
253     sys_init();
254     magic_init();
255     if (debug)
256         setlogmask(LOG_UPTO(LOG_DEBUG));
257
258     /*
259      * Detach ourselves from the terminal, if required,
260      * and identify who is running us.
261      */
262     if (!default_device && !nodetach && daemon(0, 0) < 0) {
263         perror("Couldn't detach from controlling terminal");
264         exit(1);
265     }
266     pid = getpid();
267     p = getlogin();
268     if (p == NULL) {
269         pw = getpwuid(uid);
270         if (pw != NULL && pw->pw_name != NULL)
271             p = pw->pw_name;
272         else
273             p = "(unknown)";
274     }
275     syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
276            VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
277   
278     /*
279      * Compute mask of all interesting signals and install signal handlers
280      * for each.  Only one signal handler may be active at a time.  Therefore,
281      * all other signals should be masked when any handler is executing.
282      */
283     sigemptyset(&mask);
284     sigaddset(&mask, SIGHUP);
285     sigaddset(&mask, SIGINT);
286     sigaddset(&mask, SIGTERM);
287     sigaddset(&mask, SIGCHLD);
288
289 #define SIGNAL(s, handler)      { \
290         sa.sa_handler = handler; \
291         if (sigaction(s, &sa, NULL) < 0) { \
292             syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
293             die(1); \
294         } \
295     }
296
297     sa.sa_mask = mask;
298     sa.sa_flags = 0;
299     SIGNAL(SIGHUP, hup);                /* Hangup */
300     SIGNAL(SIGINT, term);               /* Interrupt */
301     SIGNAL(SIGTERM, term);              /* Terminate */
302     SIGNAL(SIGCHLD, chld);
303
304     SIGNAL(SIGUSR1, toggle_debug);      /* Toggle debug flag */
305     SIGNAL(SIGUSR2, open_ccp);          /* Reopen CCP */
306
307     /*
308      * Install a handler for other signals which would otherwise
309      * cause pppd to exit without cleaning up.
310      */
311     SIGNAL(SIGABRT, bad_signal);
312     SIGNAL(SIGALRM, bad_signal);
313     SIGNAL(SIGFPE, bad_signal);
314     SIGNAL(SIGILL, bad_signal);
315     SIGNAL(SIGPIPE, bad_signal);
316     SIGNAL(SIGQUIT, bad_signal);
317     SIGNAL(SIGSEGV, bad_signal);
318 #ifdef SIGBUS
319     SIGNAL(SIGBUS, bad_signal);
320 #endif
321 #ifdef SIGEMT
322     SIGNAL(SIGEMT, bad_signal);
323 #endif
324 #ifdef SIGPOLL
325     SIGNAL(SIGPOLL, bad_signal);
326 #endif
327 #ifdef SIGPROF
328     SIGNAL(SIGPROF, bad_signal);
329 #endif
330 #ifdef SIGSYS
331     SIGNAL(SIGSYS, bad_signal);
332 #endif
333 #ifdef SIGTRAP
334     SIGNAL(SIGTRAP, bad_signal);
335 #endif
336 #ifdef SIGVTALRM
337     SIGNAL(SIGVTALRM, bad_signal);
338 #endif
339 #ifdef SIGXCPU
340     SIGNAL(SIGXCPU, bad_signal);
341 #endif
342 #ifdef SIGXFSZ
343     SIGNAL(SIGXFSZ, bad_signal);
344 #endif
345
346     /*
347      * Apparently we can get a SIGPIPE when we call syslog, if
348      * syslogd has died and been restarted.  Ignoring it seems
349      * be sufficient.
350      */
351     signal(SIGPIPE, SIG_IGN);
352
353     /*
354      * If we're doing dial-on-demand, set up the interface now.
355      */
356     if (demand) {
357         /*
358          * Open the loopback channel and set it up to be the ppp interface.
359          */
360         open_ppp_loopback();
361
362         syslog(LOG_INFO, "Using interface ppp%d", ifunit);
363         (void) sprintf(ifname, "ppp%d", ifunit);
364
365         /* write pid to file */
366         (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
367         if ((pidfile = fopen(pidfilename, "w")) != NULL) {
368             fprintf(pidfile, "%d\n", pid);
369             (void) fclose(pidfile);
370         } else {
371             syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
372             pidfilename[0] = 0;
373         }
374
375         /*
376          * Configure the interface and mark it up, etc.
377          */
378         demand_conf();
379     }
380
381     for (;;) {
382
383         need_holdoff = 1;
384
385         if (demand) {
386             /*
387              * Don't do anything until we see some activity.
388              */
389             phase = PHASE_DORMANT;
390             kill_link = 0;
391             demand_unblock();
392             for (;;) {
393                 wait_loop_output(timeleft(&timo));
394                 calltimeout();
395                 if (kill_link) {
396                     if (!persist)
397                         die(0);
398                     kill_link = 0;
399                 }
400                 if (get_loop_output())
401                     break;
402                 reap_kids();
403             }
404
405             /*
406              * Now we want to bring up the link.
407              */
408             demand_block();
409             syslog(LOG_INFO, "Starting link");
410         }
411
412         /*
413          * Lock the device if we've been asked to.
414          */
415         if (lockflag && !default_device) {
416             if (lock(devnam) < 0)
417                 goto fail;
418             locked = 1;
419         }
420
421         /*
422          * Open the serial device and set it up to be the ppp interface.
423          * First we open it in non-blocking mode so we can set the
424          * various termios flags appropriately.  If we aren't dialling
425          * out and we want to use the modem lines, we reopen it later
426          * in order to wait for the carrier detect signal from the modem.
427          */
428         while ((ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0)) < 0) {
429             if (errno != EINTR)
430                 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
431             if (!persist || errno != EINTR)
432                 goto fail;
433         }
434         if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
435             || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
436             syslog(LOG_WARNING,
437                    "Couldn't reset non-blocking mode on device: %m");
438
439         hungup = 0;
440         kill_link = 0;
441
442         /*
443          * Do the equivalent of `mesg n' to stop broadcast messages.
444          */
445         if (fstat(ttyfd, &statbuf) < 0
446             || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
447             syslog(LOG_WARNING,
448                    "Couldn't restrict write permissions to %s: %m", devnam);
449         } else
450             tty_mode = statbuf.st_mode;
451
452         /*
453          * Set line speed, flow control, etc.
454          * Previously, if we had a connection script, we would set CLOCAL
455          * while the script was running.  But then, if CD was negated
456          * before the script finished, we would miss it.
457          */
458         set_up_tty(ttyfd, 0);
459
460         /* run connection script */
461         if (connector && connector[0]) {
462             MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
463
464             /* drop dtr to hang up in case modem is off hook */
465             if (!default_device && modem) {
466                 setdtr(ttyfd, FALSE);
467                 sleep(1);
468                 setdtr(ttyfd, TRUE);
469             }
470
471             if (device_script(connector, ttyfd, ttyfd) < 0) {
472                 syslog(LOG_ERR, "Connect script failed");
473                 setdtr(ttyfd, FALSE);
474                 goto fail;
475             }
476
477             syslog(LOG_INFO, "Serial connection established.");
478             sleep(1);           /* give it time to set up its terminal */
479         }
480
481         /* reopen tty if necessary to wait for carrier */
482         if (connector == NULL && modem) {
483             while ((i = open(devnam, O_RDWR)) < 0) {
484                 if (errno != EINTR)
485                     syslog(LOG_ERR, "Failed to reopen %s: %m", devnam);
486                 if (!persist || errno != EINTR || hungup || kill_link)
487                     goto fail;
488             }
489             close(i);
490         }
491
492         /* run welcome script, if any */
493         if (welcomer && welcomer[0]) {
494             if (device_script(welcomer, ttyfd, ttyfd) < 0)
495                 syslog(LOG_WARNING, "Welcome script failed");
496         }
497
498         /* set up the serial device as a ppp interface */
499         establish_ppp(ttyfd);
500
501         if (!demand) {
502             
503             syslog(LOG_INFO, "Using interface ppp%d", ifunit);
504             (void) sprintf(ifname, "ppp%d", ifunit);
505             
506             /* write pid to file */
507             (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
508             if ((pidfile = fopen(pidfilename, "w")) != NULL) {
509                 fprintf(pidfile, "%d\n", pid);
510                 (void) fclose(pidfile);
511             } else {
512                 syslog(LOG_ERR, "Failed to create pid file %s: %m",
513                        pidfilename);
514                 pidfilename[0] = 0;
515             }
516         }
517
518         /*
519          * Start opening the connection and wait for
520          * incoming events (reply, timeout, etc.).
521          */
522         syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
523         lcp_lowerup(0);
524         lcp_open(0);            /* Start protocol */
525         for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
526             wait_input(timeleft(&timo));
527             calltimeout();
528             get_input();
529             if (kill_link) {
530                 lcp_close(0, "User request");
531                 kill_link = 0;
532             }
533             if (open_ccp_flag) {
534                 if (phase == PHASE_NETWORK) {
535                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
536                     (*ccp_protent.open)(0);
537                 }
538                 open_ccp_flag = 0;
539             }
540             reap_kids();        /* Don't leave dead kids lying around */
541         }
542
543         /*
544          * If we may want to bring the link up again, transfer
545          * the ppp unit back to the loopback.  Set the
546          * real serial device back to its normal mode of operation.
547          */
548         clean_check();
549         if (demand)
550             restore_loop();
551         disestablish_ppp(ttyfd);
552
553         /*
554          * Run disconnector script, if requested.
555          * XXX we may not be able to do this if the line has hung up!
556          */
557         if (disconnector && !hungup) {
558             set_up_tty(ttyfd, 1);
559             if (device_script(disconnector, ttyfd, ttyfd) < 0) {
560                 syslog(LOG_WARNING, "disconnect script failed");
561             } else {
562                 syslog(LOG_INFO, "Serial link disconnected.");
563             }
564         }
565
566     fail:
567         if (ttyfd >= 0)
568             close_tty();
569         if (locked) {
570             unlock();
571             locked = 0;
572         }
573
574         if (!demand) {
575             if (pidfilename[0] != 0
576                 && unlink(pidfilename) < 0 && errno != ENOENT) 
577                 syslog(LOG_WARNING, "unable to delete pid file: %m");
578             pidfilename[0] = 0;
579         }
580
581         if (!persist)
582             break;
583
584         if (demand)
585             demand_discard();
586         if (holdoff > 0 && need_holdoff) {
587             phase = PHASE_HOLDOFF;
588             TIMEOUT(holdoff_end, NULL, holdoff);
589             do {
590                 wait_time(timeleft(&timo));
591                 calltimeout();
592                 if (kill_link) {
593                     if (!persist)
594                         die(0);
595                     kill_link = 0;
596                     phase = PHASE_DORMANT; /* allow signal to end holdoff */
597                 }
598                 reap_kids();
599             } while (phase == PHASE_HOLDOFF);
600         }
601     }
602
603     die(0);
604     return 0;
605 }
606
607 /*
608  * holdoff_end - called via a timeout when the holdoff period ends.
609  */
610 static void
611 holdoff_end(arg)
612     void *arg;
613 {
614     phase = PHASE_DORMANT;
615 }
616
617 /*
618  * get_input - called when incoming data is available.
619  */
620 static void
621 get_input()
622 {
623     int len, i;
624     u_char *p;
625     u_short protocol;
626     struct protent *protp;
627
628     p = inpacket_buf;   /* point to beginning of packet buffer */
629
630     len = read_packet(inpacket_buf);
631     if (len < 0)
632         return;
633
634     if (len == 0) {
635         syslog(LOG_NOTICE, "Modem hangup");
636         hungup = 1;
637         lcp_lowerdown(0);       /* serial link is no longer available */
638         link_terminated(0);
639         return;
640     }
641
642     if (debug /*&& (debugflags & DBG_INPACKET)*/)
643         log_packet(p, len, "rcvd ", LOG_DEBUG);
644
645     if (len < PPP_HDRLEN) {
646         MAINDEBUG((LOG_INFO, "io(): Received short packet."));
647         return;
648     }
649
650     p += 2;                             /* Skip address and control */
651     GETSHORT(protocol, p);
652     len -= PPP_HDRLEN;
653
654     /*
655      * Toss all non-LCP packets unless LCP is OPEN.
656      */
657     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
658         MAINDEBUG((LOG_INFO,
659                    "get_input: Received non-LCP packet when LCP not open."));
660         return;
661     }
662
663     /*
664      * Until we get past the authentication phase, toss all packets
665      * except LCP, LQR and authentication packets.
666      */
667     if (phase <= PHASE_AUTHENTICATE
668         && !(protocol == PPP_LCP || protocol == PPP_LQR
669              || protocol == PPP_PAP || protocol == PPP_CHAP)) {
670         MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
671                    protocol, phase));
672         return;
673     }
674
675     /*
676      * Upcall the proper protocol input routine.
677      */
678     for (i = 0; (protp = protocols[i]) != NULL; ++i) {
679         if (protp->protocol == protocol && protp->enabled_flag) {
680             (*protp->input)(0, p, len);
681             return;
682         }
683         if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
684             && protp->datainput != NULL) {
685             (*protp->datainput)(0, p, len);
686             return;
687         }
688     }
689
690     if (debug)
691         syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
692     lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
693 }
694
695
696 /*
697  * quit - Clean up state and exit (with an error indication).
698  */
699 void 
700 quit()
701 {
702     die(1);
703 }
704
705 /*
706  * die - like quit, except we can specify an exit status.
707  */
708 void
709 die(status)
710     int status;
711 {
712     cleanup();
713     syslog(LOG_INFO, "Exit.");
714     exit(status);
715 }
716
717 /*
718  * cleanup - restore anything which needs to be restored before we exit
719  */
720 /* ARGSUSED */
721 static void
722 cleanup()
723 {
724     sys_cleanup();
725
726     if (ttyfd >= 0)
727         close_tty();
728
729     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
730         syslog(LOG_WARNING, "unable to delete pid file: %m");
731     pidfilename[0] = 0;
732
733     if (locked)
734         unlock();
735 }
736
737 /*
738  * close_tty - restore the terminal device and close it.
739  */
740 static void
741 close_tty()
742 {
743     disestablish_ppp(ttyfd);
744
745     /* drop dtr to hang up */
746     if (modem) {
747         setdtr(ttyfd, FALSE);
748         /*
749          * This sleep is in case the serial port has CLOCAL set by default,
750          * and consequently will reassert DTR when we close the device.
751          */
752         sleep(1);
753     }
754
755     restore_tty(ttyfd);
756
757     if (tty_mode != (mode_t) -1)
758         chmod(devnam, tty_mode);
759
760     close(ttyfd);
761     ttyfd = -1;
762 }
763
764
765 struct  callout {
766     struct timeval      c_time;         /* time at which to call routine */
767     void                *c_arg;         /* argument to routine */
768     void                (*c_func) __P((void *)); /* routine */
769     struct              callout *c_next;
770 };
771
772 static struct callout *callout = NULL;  /* Callout list */
773 static struct timeval timenow;          /* Current time */
774
775 /*
776  * timeout - Schedule a timeout.
777  *
778  * Note that this timeout takes the number of seconds, NOT hz (as in
779  * the kernel).
780  */
781 void
782 timeout(func, arg, time)
783     void (*func) __P((void *));
784     void *arg;
785     int time;
786 {
787     struct callout *newp, *p, **pp;
788   
789     MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
790                (long) func, (long) arg, time));
791   
792     /*
793      * Allocate timeout.
794      */
795     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
796         syslog(LOG_ERR, "Out of memory in timeout()!");
797         die(1);
798     }
799     newp->c_arg = arg;
800     newp->c_func = func;
801     gettimeofday(&timenow, NULL);
802     newp->c_time.tv_sec = timenow.tv_sec + time;
803     newp->c_time.tv_usec = timenow.tv_usec;
804   
805     /*
806      * Find correct place and link it in.
807      */
808     for (pp = &callout; (p = *pp); pp = &p->c_next)
809         if (newp->c_time.tv_sec < p->c_time.tv_sec
810             || (newp->c_time.tv_sec == p->c_time.tv_sec
811                 && newp->c_time.tv_usec < p->c_time.tv_sec))
812             break;
813     newp->c_next = p;
814     *pp = newp;
815 }
816
817
818 /*
819  * untimeout - Unschedule a timeout.
820  */
821 void
822 untimeout(func, arg)
823     void (*func) __P((void *));
824     void *arg;
825 {
826     struct callout **copp, *freep;
827   
828     MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
829   
830     /*
831      * Find first matching timeout and remove it from the list.
832      */
833     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
834         if (freep->c_func == func && freep->c_arg == arg) {
835             *copp = freep->c_next;
836             (void) free((char *) freep);
837             break;
838         }
839 }
840
841
842 /*
843  * calltimeout - Call any timeout routines which are now due.
844  */
845 static void
846 calltimeout()
847 {
848     struct callout *p;
849
850     while (callout != NULL) {
851         p = callout;
852
853         if (gettimeofday(&timenow, NULL) < 0) {
854             syslog(LOG_ERR, "Failed to get time of day: %m");
855             die(1);
856         }
857         if (!(p->c_time.tv_sec < timenow.tv_sec
858               || (p->c_time.tv_sec == timenow.tv_sec
859                   && p->c_time.tv_usec <= timenow.tv_usec)))
860             break;              /* no, it's not time yet */
861
862         callout = p->c_next;
863         (*p->c_func)(p->c_arg);
864
865         free((char *) p);
866     }
867 }
868
869
870 /*
871  * timeleft - return the length of time until the next timeout is due.
872  */
873 static struct timeval *
874 timeleft(tvp)
875     struct timeval *tvp;
876 {
877     if (callout == NULL)
878         return NULL;
879
880     gettimeofday(&timenow, NULL);
881     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
882     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
883     if (tvp->tv_usec < 0) {
884         tvp->tv_usec += 1000000;
885         tvp->tv_sec -= 1;
886     }
887     if (tvp->tv_sec < 0)
888         tvp->tv_sec = tvp->tv_usec = 0;
889
890     return tvp;
891 }
892
893
894 /*
895  * kill_my_pg - send a signal to our process group, and ignore it ourselves.
896  */
897 static void
898 kill_my_pg(sig)
899     int sig;
900 {
901     struct sigaction act, oldact;
902
903     act.sa_handler = SIG_IGN;
904     act.sa_flags = 0;
905     kill(0, sig);
906     sigaction(sig, &act, &oldact);
907     sigaction(sig, &oldact, NULL);
908 }
909
910
911 /*
912  * hup - Catch SIGHUP signal.
913  *
914  * Indicates that the physical layer has been disconnected.
915  * We don't rely on this indication; if the user has sent this
916  * signal, we just take the link down.
917  */
918 static void
919 hup(sig)
920     int sig;
921 {
922     syslog(LOG_INFO, "Hangup (SIGHUP)");
923     kill_link = 1;
924     if (conn_running)
925         /* Send the signal to the [dis]connector process(es) also */
926         kill_my_pg(sig);
927 }
928
929
930 /*
931  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
932  *
933  * Indicates that we should initiate a graceful disconnect and exit.
934  */
935 /*ARGSUSED*/
936 static void
937 term(sig)
938     int sig;
939 {
940     syslog(LOG_INFO, "Terminating on signal %d.", sig);
941     persist = 0;                /* don't try to restart */
942     kill_link = 1;
943     if (conn_running)
944         /* Send the signal to the [dis]connector process(es) also */
945         kill_my_pg(sig);
946 }
947
948
949 /*
950  * chld - Catch SIGCHLD signal.
951  * Calls reap_kids to get status for any dead kids.
952  */
953 static void
954 chld(sig)
955     int sig;
956 {
957     reap_kids();
958 }
959
960
961 /*
962  * toggle_debug - Catch SIGUSR1 signal.
963  *
964  * Toggle debug flag.
965  */
966 /*ARGSUSED*/
967 static void
968 toggle_debug(sig)
969     int sig;
970 {
971     debug = !debug;
972     if (debug) {
973         setlogmask(LOG_UPTO(LOG_DEBUG));
974     } else {
975         setlogmask(LOG_UPTO(LOG_WARNING));
976     }
977 }
978
979
980 /*
981  * open_ccp - Catch SIGUSR2 signal.
982  *
983  * Try to (re)negotiate compression.
984  */
985 /*ARGSUSED*/
986 static void
987 open_ccp(sig)
988     int sig;
989 {
990     open_ccp_flag = 1;
991 }
992
993
994 /*
995  * bad_signal - We've caught a fatal signal.  Clean up state and exit.
996  */
997 static void
998 bad_signal(sig)
999     int sig;
1000 {
1001     syslog(LOG_ERR, "Fatal signal %d", sig);
1002     if (conn_running)
1003         kill_my_pg(SIGTERM);
1004     die(1);
1005 }
1006
1007
1008 /*
1009  * device_script - run a program to connect or disconnect the
1010  * serial device.
1011  */
1012 static int
1013 device_script(program, in, out)
1014     char *program;
1015     int in, out;
1016 {
1017     int pid;
1018     int status;
1019     int errfd;
1020
1021     conn_running = 1;
1022     pid = fork();
1023
1024     if (pid < 0) {
1025         conn_running = 0;
1026         syslog(LOG_ERR, "Failed to create child process: %m");
1027         die(1);
1028     }
1029
1030     if (pid == 0) {
1031         sys_close();
1032         closelog();
1033         if (in == out) {
1034             if (in != 0) {
1035                 dup2(in, 0);
1036                 close(in);
1037             }
1038             dup2(0, 1);
1039         } else {
1040             if (out == 0)
1041                 out = dup(out);
1042             if (in != 0) {
1043                 dup2(in, 0);
1044                 close(in);
1045             }
1046             if (out != 1) {
1047                 dup2(out, 1);
1048                 close(out);
1049             }
1050         }
1051         if (redirect_stderr) {
1052             close(2);
1053             errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
1054             if (errfd >= 0 && errfd != 2) {
1055                 dup2(errfd, 2);
1056                 close(errfd);
1057             }
1058         }
1059         setuid(getuid());
1060         setgid(getgid());
1061         execl("/bin/sh", "sh", "-c", program, (char *)0);
1062         syslog(LOG_ERR, "could not exec /bin/sh: %m");
1063         _exit(99);
1064         /* NOTREACHED */
1065     }
1066
1067     while (waitpid(pid, &status, 0) < 0) {
1068         if (errno == EINTR)
1069             continue;
1070         syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1071         die(1);
1072     }
1073     conn_running = 0;
1074
1075     return (status == 0 ? 0 : -1);
1076 }
1077
1078
1079 /*
1080  * run-program - execute a program with given arguments,
1081  * but don't wait for it.
1082  * If the program can't be executed, logs an error unless
1083  * must_exist is 0 and the program file doesn't exist.
1084  */
1085 int
1086 run_program(prog, args, must_exist)
1087     char *prog;
1088     char **args;
1089     int must_exist;
1090 {
1091     int pid;
1092     char *nullenv[1];
1093
1094     pid = fork();
1095     if (pid == -1) {
1096         syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1097         return -1;
1098     }
1099     if (pid == 0) {
1100         int new_fd;
1101
1102         /* Leave the current location */
1103         (void) setsid();    /* No controlling tty. */
1104         (void) umask (S_IRWXG|S_IRWXO);
1105         (void) chdir ("/"); /* no current directory. */
1106         setuid(geteuid());
1107         setgid(getegid());
1108
1109         /* Ensure that nothing of our device environment is inherited. */
1110         sys_close();
1111         closelog();
1112         close (0);
1113         close (1);
1114         close (2);
1115         close (ttyfd);  /* tty interface to the ppp device */
1116
1117         /* Don't pass handles to the PPP device, even by accident. */
1118         new_fd = open (_PATH_DEVNULL, O_RDWR);
1119         if (new_fd >= 0) {
1120             if (new_fd != 0) {
1121                 dup2  (new_fd, 0); /* stdin <- /dev/null */
1122                 close (new_fd);
1123             }
1124             dup2 (0, 1); /* stdout -> /dev/null */
1125             dup2 (0, 2); /* stderr -> /dev/null */
1126         }
1127
1128 #ifdef BSD
1129         /* Force the priority back to zero if pppd is running higher. */
1130         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1131             syslog (LOG_WARNING, "can't reset priority to 0: %m"); 
1132 #endif
1133
1134         /* SysV recommends a second fork at this point. */
1135
1136         /* run the program; give it a null environment */
1137         nullenv[0] = NULL;
1138         execve(prog, args, nullenv);
1139         if (must_exist || errno != ENOENT)
1140             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1141         _exit(-1);
1142     }
1143     MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1144     ++n_children;
1145     return 0;
1146 }
1147
1148
1149 /*
1150  * reap_kids - get status from any dead child processes,
1151  * and log a message for abnormal terminations.
1152  */
1153 static void
1154 reap_kids()
1155 {
1156     int pid, status;
1157
1158     if (n_children == 0)
1159         return;
1160     if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1161         if (errno != ECHILD)
1162             syslog(LOG_ERR, "Error waiting for child process: %m");
1163         return;
1164     }
1165     if (pid > 0) {
1166         --n_children;
1167         if (WIFSIGNALED(status)) {
1168             syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1169                    pid, WTERMSIG(status));
1170         }
1171     }
1172 }
1173
1174
1175 /*
1176  * log_packet - format a packet and log it.
1177  */
1178
1179 char line[256];                 /* line to be logged accumulated here */
1180 char *linep;
1181
1182 void
1183 log_packet(p, len, prefix, level)
1184     u_char *p;
1185     int len;
1186     char *prefix;
1187     int level;
1188 {
1189     strcpy(line, prefix);
1190     linep = line + strlen(line);
1191     format_packet(p, len, pr_log, NULL);
1192     if (linep != line)
1193         syslog(level, "%s", line);
1194 }
1195
1196 /*
1197  * format_packet - make a readable representation of a packet,
1198  * calling `printer(arg, format, ...)' to output it.
1199  */
1200 void
1201 format_packet(p, len, printer, arg)
1202     u_char *p;
1203     int len;
1204     void (*printer) __P((void *, char *, ...));
1205     void *arg;
1206 {
1207     int i, n;
1208     u_short proto;
1209     u_char x;
1210     struct protent *protp;
1211
1212     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1213         p += 2;
1214         GETSHORT(proto, p);
1215         len -= PPP_HDRLEN;
1216         for (i = 0; (protp = protocols[i]) != NULL; ++i)
1217             if (proto == protp->protocol)
1218                 break;
1219         if (protp != NULL) {
1220             printer(arg, "[%s", protp->name);
1221             n = (*protp->printpkt)(p, len, printer, arg);
1222             printer(arg, "]");
1223             p += n;
1224             len -= n;
1225         } else {
1226             printer(arg, "[proto=0x%x]", proto);
1227         }
1228     }
1229
1230     for (; len > 0; --len) {
1231         GETCHAR(x, p);
1232         printer(arg, " %.2x", x);
1233     }
1234 }
1235
1236 static void
1237 pr_log __V((void *arg, char *fmt, ...))
1238 {
1239     int n;
1240     va_list pvar;
1241     char buf[256];
1242
1243 #if __STDC__
1244     va_start(pvar, fmt);
1245 #else
1246     void *arg;
1247     char *fmt;
1248     va_start(pvar);
1249     arg = va_arg(pvar, void *);
1250     fmt = va_arg(pvar, char *);
1251 #endif
1252
1253     vsprintf(buf, fmt, pvar);
1254     va_end(pvar);
1255
1256     n = strlen(buf);
1257     if (linep + n + 1 > line + sizeof(line)) {
1258         syslog(LOG_DEBUG, "%s", line);
1259         linep = line;
1260     }
1261     strcpy(linep, buf);
1262     linep += n;
1263 }
1264
1265 /*
1266  * print_string - print a readable representation of a string using
1267  * printer.
1268  */
1269 void
1270 print_string(p, len, printer, arg)
1271     char *p;
1272     int len;
1273     void (*printer) __P((void *, char *, ...));
1274     void *arg;
1275 {
1276     int c;
1277
1278     printer(arg, "\"");
1279     for (; len > 0; --len) {
1280         c = *p++;
1281         if (' ' <= c && c <= '~') {
1282             if (c == '\\' || c == '"')
1283                 printer(arg, "\\");
1284             printer(arg, "%c", c);
1285         } else {
1286             switch (c) {
1287             case '\n':
1288                 printer(arg, "\\n");
1289                 break;
1290             case '\r':
1291                 printer(arg, "\\r");
1292                 break;
1293             case '\t':
1294                 printer(arg, "\\t");
1295                 break;
1296             default:
1297                 printer(arg, "\\%.3o", c);
1298             }
1299         }
1300     }
1301     printer(arg, "\"");
1302 }
1303
1304 /*
1305  * novm - log an error message saying we ran out of memory, and die.
1306  */
1307 void
1308 novm(msg)
1309     char *msg;
1310 {
1311     syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1312     die(1);
1313 }
1314
1315 /*
1316  * fmtmsg - format a message into a buffer.  Like sprintf except we
1317  * also specify the length of the output buffer, and we handle
1318  * %r (recursive format), %m (error message) and %I (IP address) formats.
1319  * Doesn't do floating-point formats.
1320  * Returns the number of chars put into buf.
1321  */
1322 int
1323 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1324 {
1325     va_list args;
1326     int n;
1327
1328 #if __STDC__
1329     va_start(args, fmt);
1330 #else
1331     char *buf;
1332     int buflen;
1333     char *fmt;
1334     va_start(args);
1335     buf = va_arg(args, char *);
1336     buflen = va_arg(args, int);
1337     fmt = va_arg(args, char *);
1338 #endif
1339     n = vfmtmsg(buf, buflen, fmt, args);
1340     va_end(args);
1341     return n;
1342 }
1343
1344 /*
1345  * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1346  */
1347 #define OUTCHAR(c)      (buflen > 0? (--buflen, *buf++ = (c)): 0)
1348
1349 int
1350 vfmtmsg(buf, buflen, fmt, args)
1351     char *buf;
1352     int buflen;
1353     char *fmt;
1354     va_list args;
1355 {
1356     int c, i, n;
1357     int width, prec, fillch;
1358     int base, len, neg, quoted;
1359     unsigned long val = 0;
1360     char *str, *f, *buf0;
1361     unsigned char *p;
1362     char num[32];
1363     time_t t;
1364     static char hexchars[] = "0123456789abcdef";
1365
1366     buf0 = buf;
1367     --buflen;
1368     while (buflen > 0) {
1369         for (f = fmt; *f != '%' && *f != 0; ++f)
1370             ;
1371         if (f > fmt) {
1372             len = f - fmt;
1373             if (len > buflen)
1374                 len = buflen;
1375             memcpy(buf, fmt, len);
1376             buf += len;
1377             buflen -= len;
1378             fmt = f;
1379         }
1380         if (*fmt == 0)
1381             break;
1382         c = *++fmt;
1383         width = prec = 0;
1384         fillch = ' ';
1385         if (c == '0') {
1386             fillch = '0';
1387             c = *++fmt;
1388         }
1389         if (c == '*') {
1390             width = va_arg(args, int);
1391             c = *++fmt;
1392         } else {
1393             while (isdigit(c)) {
1394                 width = width * 10 + c - '0';
1395                 c = *++fmt;
1396             }
1397         }
1398         if (c == '.') {
1399             c = *++fmt;
1400             if (c == '*') {
1401                 prec = va_arg(args, int);
1402                 c = *++fmt;
1403             } else {
1404                 while (isdigit(c)) {
1405                     prec = prec * 10 + c - '0';
1406                     c = *++fmt;
1407                 }
1408             }
1409         }
1410         str = 0;
1411         base = 0;
1412         neg = 0;
1413         ++fmt;
1414         switch (c) {
1415         case 'd':
1416             i = va_arg(args, int);
1417             if (i < 0) {
1418                 neg = 1;
1419                 val = -i;
1420             } else
1421                 val = i;
1422             base = 10;
1423             break;
1424         case 'o':
1425             val = va_arg(args, unsigned int);
1426             base = 8;
1427             break;
1428         case 'x':
1429             val = va_arg(args, unsigned int);
1430             base = 16;
1431             break;
1432         case 'p':
1433             val = (unsigned long) va_arg(args, void *);
1434             base = 16;
1435             neg = 2;
1436             break;
1437         case 's':
1438             str = va_arg(args, char *);
1439             break;
1440         case 'c':
1441             num[0] = va_arg(args, int);
1442             num[1] = 0;
1443             str = num;
1444             break;
1445         case 'm':
1446             str = strerror(errno);
1447             break;
1448         case 'I':
1449             str = ip_ntoa(va_arg(args, u_int32_t));
1450             break;
1451         case 'r':
1452             f = va_arg(args, char *);
1453 #ifndef __powerpc__
1454             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1455 #else
1456             /* On the powerpc, a va_list is an array of 1 structure */
1457             n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1458 #endif
1459             buf += n;
1460             buflen -= n;
1461             continue;
1462         case 't':
1463             time(&t);
1464             str = ctime(&t);
1465             str += 4;           /* chop off the day name */
1466             str[15] = 0;        /* chop off year and newline */
1467             break;
1468         case 'v':               /* "visible" string */
1469         case 'q':               /* quoted string */
1470             quoted = c == 'q';
1471             p = va_arg(args, unsigned char *);
1472             if (fillch == '0' && prec > 0) {
1473                 n = prec;
1474             } else {
1475                 n = strlen((char *)p);
1476                 if (prec > 0 && prec < n)
1477                     n = prec;
1478             }
1479             while (n > 0 && buflen > 0) {
1480                 c = *p++;
1481                 --n;
1482                 if (!quoted && c >= 0x80) {
1483                     OUTCHAR('M');
1484                     OUTCHAR('-');
1485                     c -= 0x80;
1486                 }
1487                 if (quoted && (c == '"' || c == '\\'))
1488                     OUTCHAR('\\');
1489                 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1490                     if (quoted) {
1491                         OUTCHAR('\\');
1492                         switch (c) {
1493                         case '\t':      OUTCHAR('t');   break;
1494                         case '\n':      OUTCHAR('n');   break;
1495                         case '\b':      OUTCHAR('b');   break;
1496                         case '\f':      OUTCHAR('f');   break;
1497                         default:
1498                             OUTCHAR('x');
1499                             OUTCHAR(hexchars[c >> 4]);
1500                             OUTCHAR(hexchars[c & 0xf]);
1501                         }
1502                     } else {
1503                         if (c == '\t')
1504                             OUTCHAR(c);
1505                         else {
1506                             OUTCHAR('^');
1507                             OUTCHAR(c ^ 0x40);
1508                         }
1509                     }
1510                 } else
1511                     OUTCHAR(c);
1512             }
1513             continue;
1514         default:
1515             *buf++ = '%';
1516             if (c != '%')
1517                 --fmt;          /* so %z outputs %z etc. */
1518             --buflen;
1519             continue;
1520         }
1521         if (base != 0) {
1522             str = num + sizeof(num);
1523             *--str = 0;
1524             while (str > num + neg) {
1525                 *--str = hexchars[val % base];
1526                 val = val / base;
1527                 if (--prec <= 0 && val == 0)
1528                     break;
1529             }
1530             switch (neg) {
1531             case 1:
1532                 *--str = '-';
1533                 break;
1534             case 2:
1535                 *--str = 'x';
1536                 *--str = '0';
1537                 break;
1538             }
1539             len = num + sizeof(num) - 1 - str;
1540         } else {
1541             len = strlen(str);
1542             if (prec > 0 && len > prec)
1543                 len = prec;
1544         }
1545         if (width > 0) {
1546             if (width > buflen)
1547                 width = buflen;
1548             if ((n = width - len) > 0) {
1549                 buflen -= n;
1550                 for (; n > 0; --n)
1551                     *buf++ = fillch;
1552             }
1553         }
1554         if (len > buflen)
1555             len = buflen;
1556         memcpy(buf, str, len);
1557         buf += len;
1558         buflen -= len;
1559     }
1560     *buf = 0;
1561     return buf - buf0;
1562 }