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