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