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