]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
added support for kdebug, extended accm, detecting 7-bit links;
[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.7 1994/04/18 04:06:26 paulus Exp $";
22 #endif
23
24 #define SETSID
25
26 #include <stdio.h>
27 #include <signal.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <syslog.h>
31 #include <netdb.h>
32 #include <utmp.h>
33 #include <sys/wait.h>
34
35 /*
36  * If REQ_SYSOPTIONS is defined to 1, pppd will not run unless
37  * /etc/ppp/options exists.
38  */
39 #ifndef REQ_SYSOPTIONS
40 #define REQ_SYSOPTIONS  0
41 #endif
42
43 #ifdef STREAMS
44 #undef SGTTY
45 #endif
46
47 #ifdef SGTTY
48 #include <sgtty.h>
49 #else
50 #ifndef sun
51 #include <sys/ioctl.h>
52 #endif
53 #include <termios.h>
54 #endif
55
56 #include <sys/param.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include <sys/socket.h>
60 #include <sys/time.h>
61
62 #include "callout.h"
63
64 #include <net/if.h>
65 #include <net/if_ppp.h>
66
67 #include <string.h>
68
69 #ifndef BSD
70 #define BSD 43
71 #endif /*BSD*/
72
73 #include "ppp.h"
74 #include "magic.h"
75 #include "fsm.h"
76 #include "lcp.h"
77 #include "ipcp.h"
78 #include "upap.h"
79 #include "chap.h"
80
81 #include "pppd.h"
82 #include "pathnames.h"
83 #include "patchlevel.h"
84
85
86 #ifndef TRUE
87 #define TRUE (1)
88 #endif /*TRUE*/
89
90 #ifndef FALSE
91 #define FALSE (0)
92 #endif /*FALSE*/
93
94 #ifdef PIDPATH
95 static char *pidpath = PIDPATH; /* filename in which pid will be stored */
96 #else
97 static char *pidpath = _PATH_PIDFILE;
98 #endif /* PIDFILE */
99
100 /* interface vars */
101 char ifname[IFNAMSIZ];          /* Interface name */
102 int ifunit;                     /* Interface unit number */
103
104 char *progname;                 /* Name of this program */
105 char hostname[MAXNAMELEN];      /* Our hostname */
106 char our_name[MAXNAMELEN];
107 char remote_name[MAXNAMELEN];
108
109 static pid_t    pid;            /* Our pid */
110 static pid_t    pgrpid;         /* Process Group ID */
111 static char pidfilename[MAXPATHLEN];
112
113 char devname[MAXPATHLEN] = "/dev/tty";  /* Device name */
114 int default_device = TRUE;      /* use default device (stdin/out) */
115
116 int fd;                         /* Device file descriptor */
117 int s;                          /* Socket file descriptor */
118
119 int phase;                      /* where the link is at */
120
121 #ifdef SGTTY
122 static struct sgttyb initsgttyb;        /* Initial TTY sgttyb */
123 #else
124 static struct termios inittermios;      /* Initial TTY termios */
125 #endif
126
127 static int initfdflags = -1;    /* Initial file descriptor flags */
128
129 static int restore_term;        /* 1 => we've munged the terminal */
130
131 u_char outpacket_buf[MTU+DLLHEADERLEN]; /* buffer for outgoing packet */
132 static u_char inpacket_buf[MTU+DLLHEADERLEN]; /* buffer for incoming packet */
133
134 int hungup;                     /* terminal has been hung up */
135 static int n_children;          /* # child processes still running */
136
137 /* configured variables */
138
139 int debug = 0;                  /* Debug flag */
140 int kdebugflag = 0;             /* Kernel debugging flag */
141 char user[MAXNAMELEN];          /* username for PAP */
142 char passwd[MAXSECRETLEN];      /* password for PAP */
143 char *connector = NULL;         /* "connect" command */
144 char *disconnector = NULL;      /* "disconnect" command */
145 int inspeed = 0;                /* Input/Output speed requested */
146 int baud_rate;                  /* bits/sec currently used */
147 u_long netmask = 0;             /* netmask to use on ppp interface */
148 int crtscts = 0;                /* use h/w flow control */
149 int nodetach = 0;               /* don't fork */
150 int modem = 0;                  /* use modem control lines */
151 int auth_required = 0;          /* require peer to authenticate */
152 int defaultroute = 0;           /* assign default route through interface */
153 int proxyarp = 0;               /* set entry in arp table */
154 int persist = 0;                /* re-initiate on termination */
155 int answer = 0;                 /* wait for incoming call */
156 int uselogin = 0;               /* check PAP info against /etc/passwd */
157 int lockflag = 0;               /* lock the serial device */
158
159
160 /* prototypes */
161 static void hup __ARGS((int, int, struct sigcontext *, char *));
162 static void intr __ARGS((int, int, struct sigcontext *, char *));
163 static void term __ARGS((int, int, struct sigcontext *, char *));
164 static void alrm __ARGS((int, int, struct sigcontext *, char *));
165 static void io __ARGS((int, int, struct sigcontext *, char *));
166 static void incdebug __ARGS((int));
167 static void nodebug __ARGS((int));
168 void establish_ppp __ARGS((void));
169
170 void reap_kids __ARGS((void));
171 void cleanup __ARGS((int, caddr_t));
172 void die __ARGS((int));
173 void novm __ARGS((char *));
174
175 void log_packet __ARGS((u_char *, int, char *));
176 void format_packet __ARGS((u_char *, int,
177                            void (*) (void *, char *, ...), void *));
178 void pr_log __ARGS((void *, char *, ...));
179
180 #ifdef  STREAMS
181 extern  char    *ttyname __ARGS((int));
182 #endif
183 extern  char    *getlogin __ARGS((void));
184
185 /*
186  * PPP Data Link Layer "protocol" table.
187  * One entry per supported protocol.
188  */
189 static struct protent {
190     u_short protocol;
191     void (*init)();
192     void (*input)();
193     void (*protrej)();
194     int  (*printpkt)();
195     char *name;
196 } prottbl[] = {
197     { LCP, lcp_init, lcp_input, lcp_protrej, lcp_printpkt, "LCP" },
198     { IPCP, ipcp_init, ipcp_input, ipcp_protrej, ipcp_printpkt, "IPCP" },
199     { UPAP, upap_init, upap_input, upap_protrej, upap_printpkt, "PAP" },
200     { CHAP, ChapInit, ChapInput, ChapProtocolReject, ChapPrintPkt, "CHAP" },
201 };
202
203 #define N_PROTO         (sizeof(prottbl) / sizeof(prottbl[0]))
204
205 main(argc, argv)
206     int argc;
207     char *argv[];
208 {
209     int mask, i;
210     struct sigvec sv;
211     struct cmd *cmdp;
212     FILE *pidfile;
213     char *p;
214
215 #ifdef STREAMS
216     p = ttyname(fileno(stdin));
217     if (p)
218         strcpy(devname, p);
219 #endif
220   
221     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
222         perror("couldn't get hostname");
223         die(1);
224     }
225     hostname[MAXNAMELEN-1] = 0;
226
227     pid = getpid();
228
229     if (!ppp_available()) {
230         fprintf(stderr, "Sorry - PPP is not available on this system\n");
231         exit(1);
232     }
233
234     /*
235      * Initialize to the standard option set, then parse, in order,
236      * the system options file, the user's options file, and the command
237      * line arguments.
238      */
239     for (i = 0; i < N_PROTO; i++)
240         (*prottbl[i].init)(0);
241   
242     progname = *argv;
243
244     if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS) ||
245         !options_from_user() ||
246         !parse_args(argc-1, argv+1))
247         die(1);
248     check_auth_options();
249     setipdefault();
250
251     if (lockflag && !default_device)
252         if (lock(devname) < 0)
253             die(1);
254
255     /*
256      * Initialize syslog system and magic number package.
257      */
258 #if (BSD >= 43 || defined(sun)) && !defined(ultrix)
259     openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
260     setlogmask(LOG_UPTO(LOG_INFO));
261 #else
262     openlog("pppd", LOG_PID);
263 #define LOG_UPTO(x) (x)
264 #define setlogmask(x) (x)
265 #endif
266     if (debug)
267         setlogmask(LOG_UPTO(LOG_DEBUG));
268
269     magic_init();
270
271     p = getlogin();
272     if (p == NULL)
273         p = "(unknown)";
274     syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
275            VERSION, PATCHLEVEL, p, getuid());
276
277 #ifdef SETSID
278     /*
279      * Make sure we can set the serial device to be our controlling terminal.
280      */
281     if (default_device) {
282         /*
283          * No device name was specified:
284          * we are in the device's session already.
285          */
286         if ((pgrpid = getpgrp(0)) < 0) {
287             syslog(LOG_ERR, "getpgrp(0): %m");
288             die(1);
289         }
290
291     } else {
292         /*
293          * Not default device: make sure we're not a process group leader,
294          * then become session leader of a new session (so we can make
295          * our device its controlling terminal and thus get SIGHUPs).
296          */
297         if (!nodetach) {
298             /* fork so we're not a process group leader */
299             if (pid = fork()) {
300                 exit(0);        /* parent is finished */
301             }
302             if (pid < 0) {
303                 syslog(LOG_ERR, "fork: %m");
304                 die(1);
305             }
306             pid = getpid();     /* otherwise pid is 0 in child */
307         } else {
308             /*
309              * try to put ourself into our parent's process group,
310              * so we're not a process group leader
311              */
312             if (setpgrp(pid, getppid()) < 0)
313                 syslog(LOG_WARNING, "setpgrp: %m");
314         }
315
316         /* create new session */
317         if ((pgrpid = setsid()) < 0) {
318             syslog(LOG_ERR, "setsid(): %m");
319             die(1);
320         }
321     }
322 #endif
323
324     /* Get an internet socket for doing socket ioctl's on. */
325     if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
326         syslog(LOG_ERR, "socket : %m");
327         die(1);
328     }
329   
330     /*
331      * Compute mask of all interesting signals and install signal handlers
332      * for each.  Only one signal handler may be active at a time.  Therefore,
333      * all other signals should be masked when any handler is executing.
334      */
335     sigemptyset(&mask);
336     sigaddset(&mask, SIGHUP);
337     sigaddset(&mask, SIGINT);
338     sigaddset(&mask, SIGALRM);
339     sigaddset(&mask, SIGIO);
340 #ifdef  STREAMS
341     sigaddset(&mask, SIGPOLL);
342 #endif
343
344 #define SIGNAL(s, handler)      { \
345         sv.sv_handler = handler; \
346         if (sigvec(s, &sv, NULL) < 0) { \
347             syslog(LOG_ERR, "sigvec(%d): %m", s); \
348             die(1); \
349         } \
350     }
351
352     sv.sv_mask = mask;
353     sv.sv_flags = 0;
354     SIGNAL(SIGHUP, hup);                /* Hangup */
355     SIGNAL(SIGINT, intr);               /* Interrupt */
356     SIGNAL(SIGTERM, term);              /* Terminate */
357     SIGNAL(SIGALRM, alrm);              /* Timeout */
358     SIGNAL(SIGIO, io);                  /* Input available */
359 #ifdef  STREAMS
360     SIGNAL(SIGPOLL, io);                /* Input available */
361 #endif
362
363     signal(SIGUSR1, incdebug);          /* Increment debug flag */
364     signal(SIGUSR2, nodebug);           /* Reset debug flag */
365
366     /*
367      * Block SIGIOs and SIGPOLLs for now
368      */
369     sigemptyset(&mask);
370     sigaddset(&mask, SIGIO);
371 #ifdef  STREAMS
372     sigaddset(&mask, SIGPOLL);
373 #endif
374     sigprocmask(SIG_BLOCK, &mask, NULL);
375
376     /*
377      * Open the serial device and set it up to be the ppp interface.
378      */
379     if ((fd = open(devname, O_RDWR /*| O_NDELAY*/)) < 0) {
380         syslog(LOG_ERR, "open(%s): %m", devname);
381         die(1);
382     }
383     hungup = 0;
384
385 #ifdef TIOCSCTTY
386     /* set device to be controlling tty */
387     if (!default_device && ioctl(fd, TIOCSCTTY) < 0) {
388         syslog(LOG_ERR, "ioctl(TIOCSCTTY): %m");
389         die(1);
390     }
391 #endif /* TIOCSCTTY */
392
393     /* set line speed, flow control, etc. */
394     set_up_tty(fd);
395
396     /* run connection script */
397     if (connector) {
398         MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
399
400         /* drop dtr to hang up in case modem is off hook */
401         if (!default_device && modem) {
402             setdtr(fd, FALSE);
403             sleep(1);
404             setdtr(fd, TRUE);
405         }
406
407         if (device_script(connector, fd, fd) < 0) {
408             syslog(LOG_ERR, "could not set up connection");
409             setdtr(fd, FALSE);
410             die(1);
411         }
412
413         syslog(LOG_INFO, "Connected...");
414         sleep(1);               /* give it time to set up its terminal */
415     }
416   
417     /* set up the serial device as a ppp interface */
418     establish_ppp();
419
420     syslog(LOG_INFO, "Using interface ppp%d", ifunit);
421     (void) sprintf(ifname, "ppp%d", ifunit);
422
423     /* write pid to file */
424     (void) sprintf(pidfilename, "%s/%s.pid", pidpath, ifname);
425     if ((pidfile = fopen(pidfilename, "w")) != NULL) {
426         fprintf(pidfile, "%d\n", pid);
427         (void) fclose(pidfile);
428     } else {
429         syslog(LOG_ERR, "unable to create pid file: %m");
430         pidfilename[0] = 0;
431     }
432
433     /*
434      * Set process group of device to our process group so we can get
435      * SIGIOs and SIGHUPs.
436      */
437 #ifdef SETSID
438     if (default_device) {
439         int id = tcgetpgrp(fd);
440         if (id != pgrpid) {
441             syslog(LOG_WARNING, "warning: not in tty's process group");
442         }
443     } else {
444         if (tcsetpgrp(fd, pgrpid) < 0) {
445             syslog(LOG_ERR, "tcsetpgrp(): %m");
446             die(1);
447         }
448     }
449 #else
450     /* set process group on tty so we get SIGIO's */
451     if (ioctl(fd, TIOCSPGRP, &pgrpid) < 0) {
452         syslog(LOG_ERR, "ioctl(TIOCSPGRP): %m");
453         die(1);
454     }
455 #endif
456
457     /*
458      * Record initial device flags, then set device to cause SIGIO
459      * signals to be generated.
460      */
461     if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
462         syslog(LOG_ERR, "fcntl(F_GETFL): %m");
463         die(1);
464     }
465     if (fcntl(fd, F_SETFL, FNDELAY | FASYNC) == -1) {
466         syslog(LOG_ERR, "fcntl(F_SETFL, FNDELAY | FASYNC): %m");
467         die(1);
468     }
469   
470     /*
471      * Block all signals, start opening the connection, and  wait for
472      * incoming signals (reply, timeout, etc.).
473      */
474     syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devname);
475     sigprocmask(SIG_BLOCK, &mask, NULL); /* Block signals now */
476     lcp_lowerup(0);             /* XXX Well, sort of... */
477     lcp_open(0);                /* Start protocol */
478     for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
479         sigpause(0);            /* Wait for next signal */
480         reap_kids();            /* Don't leave dead kids lying around */
481     }
482
483     /*
484      * Run disconnector script, if requested
485      */
486     if (disconnector) {
487         if (device_script(disconnector, fd, fd) < 0) {
488             syslog(LOG_WARNING, "disconnect script failed");
489             die(1);
490         }
491
492         syslog(LOG_INFO, "Disconnected...");
493     }
494
495     quit();
496 }
497
498 #if B9600 == 9600
499 /*
500  * XXX assume speed_t values numerically equal bits per second
501  * (so we can ask for any speed).
502  */
503 #define translate_speed(bps)    (bps)
504 #define baud_rate_of(speed)     (speed)
505
506 #else
507 /*
508  * List of valid speeds.
509  */
510 struct speed {
511     int speed_int, speed_val;
512 } speeds[] = {
513 #ifdef B50
514     { 50, B50 },
515 #endif
516 #ifdef B75
517     { 75, B75 },
518 #endif
519 #ifdef B110
520     { 110, B110 },
521 #endif
522 #ifdef B134
523     { 134, B134 },
524 #endif
525 #ifdef B150
526     { 150, B150 },
527 #endif
528 #ifdef B200
529     { 200, B200 },
530 #endif
531 #ifdef B300
532     { 300, B300 },
533 #endif
534 #ifdef B600
535     { 600, B600 },
536 #endif
537 #ifdef B1200
538     { 1200, B1200 },
539 #endif
540 #ifdef B1800
541     { 1800, B1800 },
542 #endif
543 #ifdef B2000
544     { 2000, B2000 },
545 #endif
546 #ifdef B2400
547     { 2400, B2400 },
548 #endif
549 #ifdef B3600
550     { 3600, B3600 },
551 #endif
552 #ifdef B4800
553     { 4800, B4800 },
554 #endif
555 #ifdef B7200
556     { 7200, B7200 },
557 #endif
558 #ifdef B9600
559     { 9600, B9600 },
560 #endif
561 #ifdef B19200
562     { 19200, B19200 },
563 #endif
564 #ifdef B38400
565     { 38400, B38400 },
566 #endif
567 #ifdef EXTA
568     { 19200, EXTA },
569 #endif
570 #ifdef EXTB
571     { 38400, EXTB },
572 #endif
573 #ifdef B57600
574     { 57600, B57600 },
575 #endif
576 #ifdef B115200
577     { 115200, B115200 },
578 #endif
579     { 0, 0 }
580 };
581
582 /*
583  * Translate from bits/second to a speed_t.
584  */
585 int
586 translate_speed(bps)
587     int bps;
588 {
589     struct speed *speedp;
590
591     if (bps == 0)
592         return 0;
593     for (speedp = speeds; speedp->speed_int; speedp++)
594         if (bps == speedp->speed_int)
595             return speedp->speed_val;
596     syslog(LOG_WARNING, "speed %d not supported", bps);
597     return 0;
598 }
599
600 /*
601  * Translate from a speed_t to bits/second.
602  */
603 int
604 baud_rate_of(speed)
605     int speed;
606 {
607     struct speed *speedp;
608
609     if (speed == 0)
610         return 0;
611     for (speedp = speeds; speedp->speed_int; speedp++)
612         if (speed == speedp->speed_val)
613             return speedp->speed_int;
614     return 0;
615 }
616 #endif
617
618 /*
619  * set_up_tty: Set up the serial port on `fd' for 8 bits, no parity,
620  * at the requested speed, etc.
621  */
622 set_up_tty(fd)
623     int fd;
624 {
625 #ifndef SGTTY
626     int speed;
627     struct termios tios;
628
629     if (tcgetattr(fd, &tios) < 0) {
630         syslog(LOG_ERR, "tcgetattr: %m");
631         die(1);
632     }
633
634     if (!restore_term)
635         inittermios = tios;
636
637 #ifdef CRTSCTS
638     tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL | CRTSCTS);
639     if (crtscts)
640         tios.c_cflag |= CRTSCTS;
641 #else
642     tios.c_cflag &= ~(CSIZE | CSTOPB | PARENB | CLOCAL);
643 #endif  /* CRTSCTS */
644
645     tios.c_cflag |= CS8 | CREAD | HUPCL;
646     if (!modem)
647         tios.c_cflag |= CLOCAL;
648     tios.c_iflag = IGNBRK | IGNPAR;
649     tios.c_oflag = 0;
650     tios.c_lflag = 0;
651     tios.c_cc[VMIN] = 1;
652     tios.c_cc[VTIME] = 0;
653     speed = translate_speed(inspeed);
654     if (speed) {
655         cfsetospeed(&tios, speed);
656         cfsetispeed(&tios, speed);
657     } else {
658         speed = cfgetospeed(&tios);
659     }
660
661     if (tcsetattr(fd, TCSAFLUSH, &tios) < 0) {
662         syslog(LOG_ERR, "tcsetattr: %m");
663         die(1);
664     }
665
666 #else   /* SGTTY */
667     int speed;
668     struct sgttyb sgttyb;
669
670     /*
671      * Put the tty in raw mode.
672      */
673     if (ioctl(fd, TIOCGETP, &sgttyb) < 0) {
674         syslog(LOG_ERR, "ioctl(TIOCGETP): %m");
675         die(1);
676     }
677
678     if (!restore_term)
679         initsgttyb = sgttyb;
680
681     sgttyb.sg_flags = RAW | ANYP;
682     speed = translate_speed(inspeed);
683     if (speed)
684         sgttyb.sg_ispeed = speed;
685     else
686         speed = sgttyb.sg_ispeed;
687
688     if (ioctl(fd, TIOCSETP, &sgttyb) < 0) {
689         syslog(LOG_ERR, "ioctl(TIOCSETP): %m");
690         die(1);
691     }
692 #endif
693
694     baud_rate = baud_rate_of(speed);
695     restore_term = TRUE;
696 }
697
698 /*
699  * setdtr - control the DTR line on the serial port.
700  * This is called from die(), so it shouldn't call die().
701  */
702 setdtr(fd, on)
703 int fd, on;
704 {
705     int modembits = TIOCM_DTR;
706
707     ioctl(fd, (on? TIOCMBIS: TIOCMBIC), &modembits);
708 }
709
710
711 /*
712  * quit - Clean up state and exit.
713  */
714 void 
715 quit()
716 {
717     die(0);
718 }
719
720 /*
721  * die - like quit, except we can specify an exit status.
722  */
723 void
724 die(status)
725     int status;
726 {
727     cleanup(0, NULL);
728     syslog(LOG_INFO, "Exit.");
729     exit(status);
730 }
731
732 /*
733  * cleanup - restore anything which needs to be restored before we exit
734  */
735 /* ARGSUSED */
736 void
737 cleanup(status, arg)
738     int status;
739     caddr_t arg;
740 {
741     if (fd >= 0) {
742         /* drop dtr to hang up */
743         if (modem)
744             setdtr(fd, FALSE);
745
746         if (fcntl(fd, F_SETFL, initfdflags) < 0)
747             syslog(LOG_WARNING, "fcntl(F_SETFL, fdflags): %m");
748
749         disestablish_ppp();
750
751         if (restore_term) {
752 #ifndef SGTTY
753             if (tcsetattr(fd, TCSAFLUSH, &inittermios) < 0)
754                 syslog(LOG_WARNING, "tcsetattr: %m");
755 #else
756             if (ioctl(fd, TIOCSETP, &initsgttyb) < 0)
757                 syslog(LOG_WARNING, "ioctl(TIOCSETP): %m");
758 #endif
759         }
760
761         close(fd);
762         fd = 0;
763     }
764
765     if (pidfilename[0] != 0 && unlink(pidfilename) < 0) 
766         syslog(LOG_WARNING, "unable to unlink pid file: %m");
767     pidfilename[0] = 0;
768
769     if (lockflag && !default_device)
770         unlock();
771 }
772
773
774 static struct callout *callout = NULL;          /* Callout list */
775 static struct timeval schedtime;                /* Time last timeout was set */
776
777 /*
778  * timeout - Schedule a timeout.
779  *
780  * Note that this timeout takes the number of seconds, NOT hz (as in
781  * the kernel).
782  */
783 void
784 timeout(func, arg, time)
785     void (*func)();
786     caddr_t arg;
787     int time;
788 {
789     struct itimerval itv;
790     struct callout *newp, **oldpp;
791   
792     MAINDEBUG((LOG_DEBUG, "Timeout %x:%x in %d seconds.",
793                (int) func, (int) arg, time));
794   
795     /*
796      * Allocate timeout.
797      */
798     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
799         syslog(LOG_ERR, "Out of memory in timeout()!");
800         die(1);
801     }
802     newp->c_arg = arg;
803     newp->c_func = func;
804   
805     /*
806      * Find correct place to link it in and decrement its time by the
807      * amount of time used by preceding timeouts.
808      */
809     for (oldpp = &callout;
810          *oldpp && (*oldpp)->c_time <= time;
811          oldpp = &(*oldpp)->c_next)
812         time -= (*oldpp)->c_time;
813     newp->c_time = time;
814     newp->c_next = *oldpp;
815     if (*oldpp)
816         (*oldpp)->c_time -= time;
817     *oldpp = newp;
818   
819     /*
820      * If this is now the first callout then we have to set a new
821      * itimer.
822      */
823     if (callout == newp) {
824         itv.it_interval.tv_sec = itv.it_interval.tv_usec =
825             itv.it_value.tv_usec = 0;
826         itv.it_value.tv_sec = callout->c_time;
827         MAINDEBUG((LOG_DEBUG, "Setting itimer for %d seconds in timeout.",
828                    itv.it_value.tv_sec));
829         if (setitimer(ITIMER_REAL, &itv, NULL)) {
830             syslog(LOG_ERR, "setitimer(ITIMER_REAL): %m");
831             die(1);
832         }
833         if (gettimeofday(&schedtime, NULL)) {
834             syslog(LOG_ERR, "gettimeofday: %m");
835             die(1);
836         }
837     }
838 }
839
840
841 /*
842  * untimeout - Unschedule a timeout.
843  */
844 void
845 untimeout(func, arg)
846     void (*func)();
847     caddr_t arg;
848 {
849     struct itimerval itv;
850     struct callout **copp, *freep;
851     int reschedule = 0;
852   
853     MAINDEBUG((LOG_DEBUG, "Untimeout %x:%x.", (int) func, (int) arg));
854   
855     /*
856      * If the first callout is unscheduled then we have to set a new
857      * itimer.
858      */
859     if (callout &&
860         callout->c_func == func &&
861         callout->c_arg == arg)
862         reschedule = 1;
863   
864     /*
865      * Find first matching timeout.  Add its time to the next timeouts
866      * time.
867      */
868     for (copp = &callout; *copp; copp = &(*copp)->c_next)
869         if ((*copp)->c_func == func &&
870             (*copp)->c_arg == arg) {
871             freep = *copp;
872             *copp = freep->c_next;
873             if (*copp)
874                 (*copp)->c_time += freep->c_time;
875             (void) free((char *) freep);
876             break;
877         }
878   
879     if (reschedule) {
880         itv.it_interval.tv_sec = itv.it_interval.tv_usec =
881             itv.it_value.tv_usec = 0;
882         itv.it_value.tv_sec = callout ? callout->c_time : 0;
883         MAINDEBUG((LOG_DEBUG, "Setting itimer for %d seconds in untimeout.",
884                    itv.it_value.tv_sec));
885         if (setitimer(ITIMER_REAL, &itv, NULL)) {
886             syslog(LOG_ERR, "setitimer(ITIMER_REAL): %m");
887             die(1);
888         }
889         if (gettimeofday(&schedtime, NULL)) {
890             syslog(LOG_ERR, "gettimeofday: %m");
891             die(1);
892         }
893     }
894 }
895
896
897 /*
898  * adjtimeout - Decrement the first timeout by the amount of time since
899  * it was scheduled.
900  */
901 void
902 adjtimeout()
903 {
904     struct timeval tv;
905     int timediff;
906   
907     if (callout == NULL)
908         return;
909     /*
910      * Make sure that the clock hasn't been warped dramatically.
911      * Account for recently expired, but blocked timer by adding
912      * small fudge factor.
913      */
914     if (gettimeofday(&tv, NULL)) {
915         syslog(LOG_ERR, "gettimeofday: %m");
916         die(1);
917     }
918     timediff = tv.tv_sec - schedtime.tv_sec;
919     if (timediff < 0 ||
920         timediff > callout->c_time + 1)
921         return;
922   
923     callout->c_time -= timediff;        /* OK, Adjust time */
924 }
925
926
927 /*
928  * hup - Catch SIGHUP signal.
929  *
930  * Indicates that the physical layer has been disconnected.
931  */
932 /*ARGSUSED*/
933 static void
934 hup(sig, code, scp, addr)
935     int sig, code;
936     struct sigcontext *scp;
937     char *addr;
938 {
939     syslog(LOG_INFO, "Hangup (SIGHUP)");
940
941     hungup = 1;                 /* they hung up on us! */
942     persist = 0;                /* don't try to restart */
943     adjtimeout();               /* Adjust timeouts */
944     lcp_lowerdown(0);           /* Reset connection */
945     quit();                     /* and die */
946 }
947
948
949 /*
950  * term - Catch SIGTERM signal.
951  *
952  * Indicates that we should initiate a graceful disconnect and exit.
953  */
954 /*ARGSUSED*/
955 static void
956 term(sig, code, scp, addr)
957     int sig, code;
958     struct sigcontext *scp;
959     char *addr;
960 {
961     syslog(LOG_INFO, "Terminating link.");
962     persist = 0;                /* don't try to restart */
963     adjtimeout();               /* Adjust timeouts */
964     lcp_close(0);               /* Close connection */
965 }
966
967
968 /*
969  * intr - Catch SIGINT signal (DEL/^C).
970  *
971  * Indicates that we should initiate a graceful disconnect and exit.
972  */
973 /*ARGSUSED*/
974 static void
975 intr(sig, code, scp, addr)
976     int sig, code;
977     struct sigcontext *scp;
978     char *addr;
979 {
980     syslog(LOG_INFO, "Interrupt received: terminating link");
981     persist = 0;                /* don't try to restart */
982     adjtimeout();               /* Adjust timeouts */
983     lcp_close(0);               /* Close connection */
984 }
985
986
987 /*
988  * alrm - Catch SIGALRM signal.
989  *
990  * Indicates a timeout.
991  */
992 /*ARGSUSED*/
993 static void
994 alrm(sig, code, scp, addr)
995     int sig, code;
996     struct sigcontext *scp;
997     char *addr;
998 {
999     struct itimerval itv;
1000     struct callout *freep, *list, *last;
1001
1002     MAINDEBUG((LOG_DEBUG, "Alarm"));
1003
1004     /*
1005      * Get the first scheduled timeout and any that were scheduled
1006      * for the same time as a list, and remove them all from callout
1007      * list.
1008      */
1009     list = last = callout;
1010     while (last->c_next != NULL && last->c_next->c_time == 0)
1011         last = last->c_next;
1012     callout = last->c_next;
1013     last->c_next = NULL;
1014
1015     /*
1016      * Set a new itimer if there are more timeouts scheduled.
1017      */
1018     if (callout) {
1019         itv.it_interval.tv_sec = itv.it_interval.tv_usec = 0;
1020         itv.it_value.tv_usec = 0;
1021         itv.it_value.tv_sec = callout->c_time;
1022         MAINDEBUG((LOG_DEBUG, "Setting itimer for %d seconds in alrm.",
1023                    itv.it_value.tv_sec));
1024         if (setitimer(ITIMER_REAL, &itv, NULL)) {
1025             syslog(LOG_ERR, "setitimer(ITIMER_REAL): %m");
1026             die(1);
1027         }
1028         if (gettimeofday(&schedtime, NULL)) {
1029             syslog(LOG_ERR, "gettimeofday: %m");
1030             die(1);
1031         }
1032     }
1033
1034     /*
1035      * Now call all the timeout routines scheduled for this time.
1036      */
1037     while (list) {
1038         (*list->c_func)(list->c_arg);
1039         freep = list;
1040         list = list->c_next;
1041         (void) free((char *) freep);
1042     }
1043   
1044 }
1045
1046
1047 /*
1048  * io - Catch SIGIO signal.
1049  *
1050  * Indicates that incoming data is available.
1051  */
1052 /*ARGSUSED*/
1053 static void
1054 io(sig, code, scp, addr)
1055     int sig, code;
1056     struct sigcontext *scp;
1057     char *addr;
1058 {
1059     int len, i;
1060     u_char *p;
1061     u_short protocol;
1062     fd_set fdset;
1063     struct timeval notime;
1064     int ready;
1065
1066     MAINDEBUG((LOG_DEBUG, "IO signal received"));
1067     adjtimeout();               /* Adjust timeouts */
1068
1069     /* we do this to see if the SIGIO handler is being invoked for input */
1070     /* ready, or for the socket buffer hitting the low-water mark. */
1071
1072     notime.tv_sec = 0;
1073     notime.tv_usec = 0;
1074     FD_ZERO(&fdset);
1075     FD_SET(fd, &fdset);
1076   
1077     if ((ready = select(32, &fdset, (fd_set *) NULL, (fd_set *) NULL,
1078                       &notime)) == -1) {
1079         syslog(LOG_ERR, "Error in io() select: %m");
1080         die(1);
1081     }
1082     
1083     if (ready == 0) {
1084         MAINDEBUG((LOG_DEBUG, "IO non-input ready SIGIO occured."));
1085         return;
1086     }
1087
1088     /* Yup, this is for real */
1089     for (;;) {                  /* Read all available packets */
1090         p = inpacket_buf;       /* point to beginning of packet buffer */
1091
1092         len = read_packet(inpacket_buf);
1093         if (len < 0)
1094             return;
1095
1096         if (len == 0) {
1097             syslog(LOG_WARNING, "End of file on fd!");
1098             die(1);
1099         }
1100
1101         if (debug /*&& (debugflags & DBG_INPACKET)*/)
1102             log_packet(p, len, "rcvd ");
1103
1104         if (len < DLLHEADERLEN) {
1105             MAINDEBUG((LOG_INFO, "io(): Received short packet."));
1106             return;
1107         }
1108
1109         p += 2;                         /* Skip address and control */
1110         GETSHORT(protocol, p);
1111         len -= DLLHEADERLEN;
1112
1113         /*
1114          * Toss all non-LCP packets unless LCP is OPEN.
1115          */
1116         if (protocol != LCP && lcp_fsm[0].state != OPENED) {
1117             MAINDEBUG((LOG_INFO,
1118                        "io(): Received non-LCP packet when LCP not open."));
1119             return;
1120         }
1121
1122         /*
1123          * Upcall the proper protocol input routine.
1124          */
1125         for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
1126             if (prottbl[i].protocol == protocol) {
1127                 (*prottbl[i].input)(0, p, len);
1128                 break;
1129             }
1130
1131         if (i == sizeof (prottbl) / sizeof (struct protent)) {
1132             syslog(LOG_WARNING, "input: Unknown protocol (%x) received!",
1133                    protocol);
1134             lcp_sprotrej(0, p - DLLHEADERLEN, len + DLLHEADERLEN);
1135         }
1136     }
1137 }
1138
1139 /*
1140  * demuxprotrej - Demultiplex a Protocol-Reject.
1141  */
1142 void
1143 demuxprotrej(unit, protocol)
1144     int unit;
1145     u_short protocol;
1146 {
1147     int i;
1148
1149     /*
1150      * Upcall the proper Protocol-Reject routine.
1151      */
1152     for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
1153         if (prottbl[i].protocol == protocol) {
1154             (*prottbl[i].protrej)(unit);
1155             return;
1156         }
1157
1158     syslog(LOG_WARNING,
1159            "demuxprotrej: Unrecognized Protocol-Reject for protocol %d!",
1160            protocol);
1161 }
1162
1163
1164 /*
1165  * incdebug - Catch SIGUSR1 signal.
1166  *
1167  * Increment debug flag.
1168  */
1169 /*ARGSUSED*/
1170 static void
1171 incdebug(sig)
1172     int sig;
1173 {
1174     syslog(LOG_INFO, "Debug turned ON, Level %d", debug);
1175     setlogmask(LOG_UPTO(LOG_DEBUG));
1176     debug++;
1177 }
1178
1179
1180 /*
1181  * nodebug - Catch SIGUSR2 signal.
1182  *
1183  * Turn off debugging.
1184  */
1185 /*ARGSUSED*/
1186 static void
1187 nodebug(sig)
1188     int sig;
1189 {
1190     setlogmask(LOG_UPTO(LOG_WARNING));
1191     debug = 0;
1192 }
1193
1194
1195 /*
1196  * device_script - run a program to connect or disconnect the
1197  * serial device.
1198  */
1199 int
1200 device_script(program, in, out)
1201     char *program;
1202     int in, out;
1203 {
1204     int pid;
1205     int status;
1206     sigset_t mask;
1207
1208     sigemptyset(&mask);
1209     sigaddset(&mask, SIGINT);
1210     sigaddset(&mask, SIGHUP);
1211     sigprocmask(SIG_BLOCK, &mask, &mask);
1212
1213     pid = fork();
1214
1215     if (pid < 0) {
1216         syslog(LOG_ERR, "fork: %m");
1217         die(1);
1218     }
1219
1220     if (pid == 0) {
1221         setreuid(getuid(), getuid());
1222         setregid(getgid(), getgid());
1223         sigprocmask(SIG_SETMASK, &mask, NULL);
1224         dup2(in, 0);
1225         dup2(out, 1);
1226         execl("/bin/sh", "sh", "-c", program, (char *)0);
1227         syslog(LOG_ERR, "could not exec /bin/sh: %m");
1228         _exit(99);
1229         /* NOTREACHED */
1230     }
1231
1232     while (waitpid(pid, &status, 0) < 0) {
1233         if (errno == EINTR)
1234             continue;
1235         syslog(LOG_ERR, "waiting for (dis)connection process: %m");
1236         die(1);
1237     }
1238     sigprocmask(SIG_SETMASK, &mask, NULL);
1239
1240     return (status == 0 ? 0 : -1);
1241 }
1242
1243
1244 /*
1245  * run-program - execute a program with given arguments,
1246  * but don't wait for it.
1247  * If the program can't be executed, logs an error unless
1248  * must_exist is 0 and the program file doesn't exist.
1249  */
1250 int
1251 run_program(prog, args, must_exist)
1252     char *prog;
1253     char **args;
1254     int must_exist;
1255 {
1256     int pid;
1257
1258     pid = fork();
1259     if (pid == -1) {
1260         syslog(LOG_ERR, "can't fork to run %s: %m", prog);
1261         return -1;
1262     }
1263     if (pid == 0) {
1264         execv(prog, args);
1265         if (must_exist || errno != ENOENT)
1266             syslog(LOG_WARNING, "can't execute %s: %m", prog);
1267         _exit(-1);
1268     }
1269     MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1270     ++n_children;
1271     return 0;
1272 }
1273
1274
1275 /*
1276  * reap_kids - get status from any dead child processes,
1277  * and log a message for abnormal terminations.
1278  */
1279 void
1280 reap_kids()
1281 {
1282     int pid, status;
1283
1284     if (n_children == 0)
1285         return;
1286     if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1287         if (errno != ECHILD)
1288             syslog(LOG_ERR, "waitpid: %m");
1289         return;
1290     }
1291     if (pid > 0) {
1292         --n_children;
1293         if (WIFSIGNALED(status)) {
1294             syslog(LOG_WARNING, "child process %d terminated with signal %d",
1295                    pid, WTERMSIG(status));
1296         }
1297     }
1298 }
1299
1300
1301 /*
1302  * log_packet - format a packet and log it.
1303  */
1304
1305 char line[256];                 /* line to be logged accumulated here */
1306 char *linep;
1307
1308 void
1309 log_packet(p, len, prefix)
1310     u_char *p;
1311     int len;
1312     char *prefix;
1313 {
1314     strcpy(line, prefix);
1315     linep = line + strlen(line);
1316     format_packet(p, len, pr_log, NULL);
1317     if (linep != line)
1318         syslog(LOG_DEBUG, "%s", line);
1319 }
1320
1321 /*
1322  * format_packet - make a readable representation of a packet,
1323  * calling `printer(arg, format, ...)' to output it.
1324  */
1325 void
1326 format_packet(p, len, printer, arg)
1327     u_char *p;
1328     int len;
1329     void (*printer) __ARGS((void *, char *, ...));
1330     void *arg;
1331 {
1332     int i, n;
1333     u_short proto;
1334     u_char x;
1335
1336     if (len >= DLLHEADERLEN && p[0] == ALLSTATIONS && p[1] == UI) {
1337         p += 2;
1338         GETSHORT(proto, p);
1339         len -= DLLHEADERLEN;
1340         for (i = 0; i < N_PROTO; ++i)
1341             if (proto == prottbl[i].protocol)
1342                 break;
1343         if (i < N_PROTO) {
1344             printer(arg, "[%s", prottbl[i].name);
1345             n = (*prottbl[i].printpkt)(p, len, printer, arg);
1346             printer(arg, "]");
1347             p += n;
1348             len -= n;
1349         } else {
1350             printer(arg, "[proto=0x%x]", proto);
1351         }
1352     }
1353
1354     for (; len > 0; --len) {
1355         GETCHAR(x, p);
1356         printer(arg, " %.2x", x);
1357     }
1358 }
1359
1360 #ifdef __STDC__
1361 #include <stdarg.h>
1362
1363 void
1364 pr_log(void *arg, char *fmt, ...)
1365 {
1366     int n;
1367     va_list pvar;
1368     char buf[256];
1369
1370     va_start(pvar, fmt);
1371     vsprintf(buf, fmt, pvar);
1372     va_end(pvar);
1373
1374     n = strlen(buf);
1375     if (linep + n + 1 > line + sizeof(line)) {
1376         syslog(LOG_DEBUG, "%s", line);
1377         linep = line;
1378     }
1379     strcpy(linep, buf);
1380     linep += n;
1381 }
1382
1383 #else /* __STDC__ */
1384 #include <varargs.h>
1385
1386 void
1387 pr_log(arg, fmt, va_alist)
1388 void *arg;
1389 char *fmt;
1390 va_dcl
1391 {
1392     int n;
1393     va_list pvar;
1394     char buf[256];
1395
1396     va_start(pvar);
1397     vsprintf(buf, fmt, pvar);
1398     va_end(pvar);
1399
1400     n = strlen(buf);
1401     if (linep + n + 1 > line + sizeof(line)) {
1402         syslog(LOG_DEBUG, "%s", line);
1403         linep = line;
1404     }
1405     strcpy(linep, buf);
1406     linep += n;
1407 }
1408 #endif
1409
1410 /*
1411  * print_string - print a readable representation of a string using
1412  * printer.
1413  */
1414 void
1415 print_string(p, len, printer, arg)
1416     char *p;
1417     int len;
1418     void (*printer) __ARGS((void *, char *, ...));
1419     void *arg;
1420 {
1421     int c;
1422
1423     printer(arg, "\"");
1424     for (; len > 0; --len) {
1425         c = *p++;
1426         if (' ' <= c && c <= '~')
1427             printer(arg, "%c", c);
1428         else
1429             printer(arg, "\\%.3o", c);
1430     }
1431     printer(arg, "\"");
1432 }
1433
1434 /*
1435  * novm - log an error message saying we ran out of memory, and die.
1436  */
1437 void
1438 novm(msg)
1439     char *msg;
1440 {
1441     syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1442     die(1);
1443 }