]> git.ozlabs.org Git - ppp.git/blob - pppd/main.c
Minor fixes from the NetBSD port: fd -> ppp_fd in sys-bsd.c, etc.
[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.23.2.2 1995/06/06 12:11:43 paulus Exp $";
22 #endif
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.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 <pwd.h>
34 #include <sys/param.h>
35 #include <sys/types.h>
36 #include <sys/wait.h>
37 #include <sys/time.h>
38 #include <sys/resource.h>
39 #include <sys/stat.h>
40 #include <sys/socket.h>
41 #include <net/if.h>
42
43 #include "pppd.h"
44 #include "magic.h"
45 #include "fsm.h"
46 #include "lcp.h"
47 #include "ipcp.h"
48 #include "upap.h"
49 #include "chap.h"
50 #include "ccp.h"
51 #include "pathnames.h"
52 #include "patchlevel.h"
53
54 /*
55  * If REQ_SYSOPTIONS is defined to 1, pppd will not run unless
56  * /etc/ppp/options exists.
57  */
58 #ifndef REQ_SYSOPTIONS
59 #define REQ_SYSOPTIONS  1
60 #endif
61
62 /* interface vars */
63 char ifname[IFNAMSIZ];          /* Interface name */
64 int ifunit;                     /* Interface unit number */
65
66 char *progname;                 /* Name of this program */
67 char hostname[MAXNAMELEN];      /* Our hostname */
68 static char pidfilename[MAXPATHLEN];    /* name of pid file */
69 static char default_devnam[MAXPATHLEN]; /* name of default device */
70 static pid_t    pid;            /* Our pid */
71 static pid_t    pgrpid;         /* Process Group ID */
72 static uid_t uid;               /* Our real user-id */
73
74 int fd = -1;                    /* Device file descriptor */
75
76 int phase;                      /* where the link is at */
77 int kill_link;
78 int open_ccp_flag;
79
80 static int initfdflags = -1;    /* Initial file descriptor flags */
81 static int loop_fd = -1;        /* fd for loopback device */
82
83 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
84 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
85
86 int hungup;                     /* terminal has been hung up */
87 static int n_children;          /* # child processes still running */
88
89 int baud_rate;
90
91 static int locked;
92
93 /* prototypes */
94 static void hup __P((int));
95 static void term __P((int));
96 static void chld __P((int));
97 static void toggle_debug __P((int));
98 static void open_ccp __P((int));
99 static void holdoff_end __P((void *));
100
101 static void get_input __P((void));
102 void establish_ppp __P((int));
103 void calltimeout __P((void));
104 struct timeval *timeleft __P((struct timeval *));
105 void reap_kids __P((void));
106 void cleanup __P((int, caddr_t));
107 void close_fd __P((void));
108 void die __P((int));
109 void novm __P((char *));
110
111 void log_packet __P((u_char *, int, char *));
112 void format_packet __P((u_char *, int,
113                            void (*) (void *, char *, ...), void *));
114 void pr_log __P((void *, char *, ...));
115
116 extern  char    *ttyname __P((int));
117 extern  char    *getlogin __P((void));
118
119 #ifdef ultrix
120 #undef  O_NONBLOCK
121 #define O_NONBLOCK      O_NDELAY
122 #endif
123
124 /*
125  * PPP Data Link Layer "protocol" table.
126  * One entry per supported protocol.
127  */
128 static struct protent {
129     u_short protocol;
130     void (*init)();
131     void (*input)();
132     void (*protrej)();
133     int  (*printpkt)();
134     void (*datainput)();
135     char *name;
136 } prottbl[] = {
137     { PPP_LCP, lcp_init, lcp_input, lcp_protrej,
138           lcp_printpkt, NULL, "LCP" },
139     { PPP_IPCP, ipcp_init, ipcp_input, ipcp_protrej,
140           ipcp_printpkt, NULL, "IPCP" },
141     { PPP_PAP, upap_init, upap_input, upap_protrej,
142           upap_printpkt, NULL, "PAP" },
143     { PPP_CHAP, ChapInit, ChapInput, ChapProtocolReject,
144           ChapPrintPkt, NULL, "CHAP" },
145     { PPP_CCP, ccp_init, ccp_input, ccp_protrej,
146           ccp_printpkt, ccp_datainput, "CCP" },
147 };
148
149 #define N_PROTO         (sizeof(prottbl) / sizeof(prottbl[0]))
150
151 main(argc, argv)
152     int argc;
153     char *argv[];
154 {
155     int i, nonblock;
156     struct sigaction sa;
157     struct cmd *cmdp;
158     FILE *pidfile;
159     char *p;
160     struct passwd *pw;
161     struct timeval timo;
162     sigset_t mask;
163
164     p = ttyname(0);
165     if (p)
166         strcpy(devnam, p);
167     strcpy(default_devnam, devnam);
168
169     if (gethostname(hostname, MAXNAMELEN) < 0 ) {
170         perror("couldn't get hostname");
171         die(1);
172     }
173     hostname[MAXNAMELEN-1] = 0;
174
175     uid = getuid();
176
177     if (!ppp_available()) {
178         fprintf(stderr, "Sorry - PPP is not available on this system\n");
179         exit(1);
180     }
181
182     /*
183      * Initialize to the standard option set, then parse, in order,
184      * the system options file, the user's options file, and the command
185      * line arguments.
186      */
187     for (i = 0; i < N_PROTO; i++)
188         (*prottbl[i].init)(0);
189   
190     progname = *argv;
191
192     if (!options_from_file(_PATH_SYSOPTIONS, REQ_SYSOPTIONS, 0) ||
193         !options_from_user() ||
194         !parse_args(argc-1, argv+1) ||
195         !options_for_tty())
196         die(1);
197     check_auth_options();
198     setipdefault();
199
200     /*
201      * If the user has specified the default device name explicitly,
202      * pretend they hadn't.
203      */
204     if (!default_device && strcmp(devnam, default_devnam) == 0)
205         default_device = 1;
206
207     /*
208      * Initialize system-dependent stuff and magic number package.
209      */
210     sys_init();
211     magic_init();
212
213     /*
214      * For dial-on-demand, we need to know the remote address.
215      */
216     if (demand && ipcp_wantoptions[0].hisaddr == 0) {
217         fprintf(stderr, "Remote IP address must be specified for dial-on-demand\n");
218         exit(1);
219     }
220
221     /*
222      * Detach ourselves from the terminal, if required,
223      * and identify who is running us.
224      */
225     if (!default_device && !nodetach && daemon(0, 0) < 0) {
226         perror("Couldn't detach from controlling terminal");
227         exit(1);
228     }
229     pid = getpid();
230     p = getlogin();
231     if (p == NULL) {
232         pw = getpwuid(uid);
233         if (pw != NULL && pw->pw_name != NULL)
234             p = pw->pw_name;
235         else
236             p = "(unknown)";
237     }
238     syslog(LOG_NOTICE, "pppd %s.%d started by %s, uid %d",
239            VERSION, PATCHLEVEL, p, uid);
240   
241     /*
242      * Compute mask of all interesting signals and install signal handlers
243      * for each.  Only one signal handler may be active at a time.  Therefore,
244      * all other signals should be masked when any handler is executing.
245      */
246     sigemptyset(&mask);
247     sigaddset(&mask, SIGHUP);
248     sigaddset(&mask, SIGINT);
249     sigaddset(&mask, SIGTERM);
250     sigaddset(&mask, SIGCHLD);
251
252 #define SIGNAL(s, handler)      { \
253         sa.sa_handler = handler; \
254         if (sigaction(s, &sa, NULL) < 0) { \
255             syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
256             die(1); \
257         } \
258     }
259
260     sa.sa_mask = mask;
261     sa.sa_flags = 0;
262     SIGNAL(SIGHUP, hup);                /* Hangup */
263     SIGNAL(SIGINT, term);               /* Interrupt */
264     SIGNAL(SIGTERM, term);              /* Terminate */
265     SIGNAL(SIGCHLD, chld);
266
267     signal(SIGUSR1, toggle_debug);      /* Toggle debug flag */
268     signal(SIGUSR2, open_ccp);          /* Reopen CCP */
269
270     /*
271      * If we're doing dial-on-demand, set up the interface now.
272      */
273     if (demand) {
274         /*
275          * Open the loopback channel and set it up to be the ppp interface.
276          */
277         loop_fd = open_loopback();
278         establish_ppp(loop_fd);
279
280         syslog(LOG_INFO, "Using interface ppp%d", ifunit);
281         (void) sprintf(ifname, "ppp%d", ifunit);
282
283         /* write pid to file */
284         (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
285         if ((pidfile = fopen(pidfilename, "w")) != NULL) {
286             fprintf(pidfile, "%d\n", pid);
287             (void) fclose(pidfile);
288         } else {
289             syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
290             pidfilename[0] = 0;
291         }
292
293         /*
294          * Configure the interface and mark it up, etc.
295          */
296         fd = loop_fd;
297         demand_conf();
298     }
299
300     for (;;) {
301
302         if (demand) {
303             /*
304              * Don't do anything until we see some activity.
305              */
306             phase = PHASE_DORMANT;
307             fd = loop_fd;
308             kill_link = 0;
309             demand_unblock();
310             for (;;) {
311                 wait_loop_output(timeleft(&timo));
312                 calltimeout();
313                 if (kill_link) {
314                     if (!persist)
315                         die(0);
316                     kill_link = 0;
317                 }
318                 if (get_loop_output())
319                     break;
320                 reap_kids();
321             }
322
323             /*
324              * Now we want to bring up the link.
325              */
326             demand_block();
327             syslog(LOG_INFO, "Starting link");
328         }
329
330         /*
331          * Lock the device if we've been asked to.
332          */
333         if (lockflag && !default_device) {
334             if (lock(devnam) < 0)
335                 goto fail;
336             locked = 1;
337         }
338
339         /*
340          * Open the serial device and set it up to be the ppp interface.
341          * If we're dialling out, or we don't want to use the modem lines,
342          * we open it in non-blocking mode, but then we need to clear
343          * the non-blocking I/O bit.
344          */
345         nonblock = (connector || !modem)? O_NONBLOCK: 0;
346         if ((fd = open(devnam, nonblock | O_RDWR, 0)) < 0) {
347             syslog(LOG_ERR, "Failed to open %s: %m", devnam);
348             goto fail;
349         }
350         if ((initfdflags = fcntl(fd, F_GETFL)) == -1) {
351             syslog(LOG_ERR, "Couldn't get device fd flags: %m");
352             die(1);
353         }
354         if (nonblock) {
355             initfdflags &= ~O_NONBLOCK;
356             fcntl(fd, F_SETFL, initfdflags);
357         }
358         hungup = 0;
359         kill_link = 0;
360
361         /* run connection script */
362         if (connector && connector[0]) {
363             MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
364
365             /* set line speed, flow control, etc.; set CLOCAL for now */
366             set_up_tty(fd, 1);
367
368             /* drop dtr to hang up in case modem is off hook */
369             if (!default_device && modem) {
370                 setdtr(fd, FALSE);
371                 sleep(1);
372                 setdtr(fd, TRUE);
373             }
374
375             if (device_script(connector, fd, fd) < 0) {
376                 syslog(LOG_ERR, "Connect script failed");
377                 setdtr(fd, FALSE);
378                 goto fail;
379             }
380
381             syslog(LOG_INFO, "Serial connection established.");
382             sleep(1);           /* give it time to set up its terminal */
383         }
384   
385         /* set line speed, flow control, etc.; clear CLOCAL if modem option */
386         set_up_tty(fd, 0);
387
388         /*
389          * Set device for non-blocking reads.
390          */
391         if (fcntl(fd, F_SETFL, initfdflags | O_NONBLOCK) == -1) {
392             syslog(LOG_ERR, "Couldn't set device to non-blocking mode: %m");
393             die(1);
394         }
395   
396         if (!demand) {
397             /* set up the serial device as a ppp interface */
398             establish_ppp(fd);
399             
400             syslog(LOG_INFO, "Using interface ppp%d", ifunit);
401             (void) sprintf(ifname, "ppp%d", ifunit);
402             
403             /* write pid to file */
404             (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
405             if ((pidfile = fopen(pidfilename, "w")) != NULL) {
406                 fprintf(pidfile, "%d\n", pid);
407                 (void) fclose(pidfile);
408             } else {
409                 syslog(LOG_ERR, "Failed to create pid file %s: %m",
410                        pidfilename);
411                 pidfilename[0] = 0;
412             }
413
414         } else {
415             /*
416              * Transfer the PPP unit over to the real serial device.
417              */
418             transfer_ppp(fd);
419         }
420
421         /*
422          * Start opening the connection and wait for
423          * incoming events (reply, timeout, etc.).
424          */
425         syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
426         lcp_lowerup(0);
427         lcp_open(0);            /* Start protocol */
428         for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
429             wait_input(timeleft(&timo));
430             calltimeout();
431             if (kill_link) {
432                 lcp_close(0);
433                 kill_link = 0;
434             }
435             if (open_ccp_flag) {
436                 if (phase == PHASE_NETWORK) {
437                     ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
438                     ccp_open(0);
439                 }
440                 open_ccp_flag = 0;
441             }
442             get_input();
443             reap_kids();        /* Don't leave dead kids lying around */
444         }
445
446         /*
447          * If we may want to bring the link up again, transfer
448          * the ppp unit back to the loopback.  Set the
449          * real serial device back to its normal mode of operation.
450          */
451         clean_check();
452         if (demand) {
453             transfer_ppp(loop_fd);
454         } else {
455             disestablish_ppp(fd);
456         }
457
458         /*
459          * Run disconnector script, if requested.
460          * First we need to reset non-blocking mode.
461          * XXX we may not be able to do this if the line has hung up!
462          */
463         if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) >= 0)
464             initfdflags = -1;
465         if (disconnector && !hungup) {
466             set_up_tty(fd, 1);
467             if (device_script(disconnector, fd, fd) < 0) {
468                 syslog(LOG_WARNING, "disconnect script failed");
469             } else {
470                 syslog(LOG_INFO, "Serial link disconnected.");
471             }
472         }
473
474     fail:
475         close_fd();
476         if (locked) {
477             unlock();
478             locked = 0;
479         }
480
481         if (!demand) {
482             if (unlink(pidfilename) < 0 && errno != ENOENT) 
483                 syslog(LOG_WARNING, "unable to delete pid file: %m");
484             pidfilename[0] = 0;
485         }
486
487         if (!persist)
488             break;
489
490         demand_discard();
491         if (holdoff > 0) {
492             phase = PHASE_HOLDOFF;
493             TIMEOUT(holdoff_end, NULL, holdoff);
494             do {
495                 wait_time(timeleft(&timo));
496                 calltimeout();
497                 if (kill_link) {
498                     if (!persist)
499                         die(0);
500                     kill_link = 0;
501                     phase = PHASE_DORMANT; /* allow signal to end holdoff */
502                 }
503                 reap_kids();
504             } while (phase == PHASE_HOLDOFF);
505         }
506     }
507
508     die(0);
509 }
510
511 /*
512  * holdoff_end - called via a timeout when the holdoff period ends.
513  */
514 static void
515 holdoff_end(arg)
516     void *arg;
517 {
518     phase = PHASE_DORMANT;
519 }
520
521 /*
522  * get_input - called when incoming data is available.
523  */
524 static void
525 get_input()
526 {
527     int len, i;
528     u_char *p;
529     u_short protocol;
530
531     p = inpacket_buf;   /* point to beginning of packet buffer */
532
533     len = read_packet(inpacket_buf);
534     if (len < 0)
535         return;
536
537     if (len == 0) {
538         syslog(LOG_NOTICE, "Modem hangup");
539         hungup = 1;
540         lcp_lowerdown(0);       /* serial link is no longer available */
541         phase = PHASE_DEAD;
542         return;
543     }
544
545     if (debug /*&& (debugflags & DBG_INPACKET)*/)
546         log_packet(p, len, "rcvd ");
547
548     if (len < PPP_HDRLEN) {
549         MAINDEBUG((LOG_INFO, "io(): Received short packet."));
550         return;
551     }
552
553     p += 2;                             /* Skip address and control */
554     GETSHORT(protocol, p);
555     len -= PPP_HDRLEN;
556
557     /*
558      * Toss all non-LCP packets unless LCP is OPEN.
559      */
560     if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
561         MAINDEBUG((LOG_INFO,
562                    "io(): Received non-LCP packet when LCP not open."));
563         return;
564     }
565
566     /*
567      * Upcall the proper protocol input routine.
568      */
569     for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
570         if (prottbl[i].protocol == protocol) {
571             (*prottbl[i].input)(0, p, len);
572             break;
573         } else if (protocol == (prottbl[i].protocol & ~0x8000)
574                    && prottbl[i].datainput != NULL) {
575             (*prottbl[i].datainput)(0, p, len);
576             break;
577         }
578
579     if (i == sizeof (prottbl) / sizeof (struct protent)) {
580         if (debug)
581             syslog(LOG_WARNING, "Unknown protocol (0x%x) received", protocol);
582         lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
583     }
584 }
585
586
587 /*
588  * demuxprotrej - Demultiplex a Protocol-Reject.
589  */
590 void
591 demuxprotrej(unit, protocol)
592     int unit;
593     u_short protocol;
594 {
595     int i;
596
597     /*
598      * Upcall the proper Protocol-Reject routine.
599      */
600     for (i = 0; i < sizeof (prottbl) / sizeof (struct protent); i++)
601         if (prottbl[i].protocol == protocol) {
602             (*prottbl[i].protrej)(unit);
603             return;
604         }
605
606     syslog(LOG_WARNING,
607            "demuxprotrej: Unrecognized Protocol-Reject for protocol 0x%x",
608            protocol);
609 }
610
611
612 /*
613  * quit - Clean up state and exit.
614  */
615 void 
616 quit()
617 {
618     die(0);
619 }
620
621 /*
622  * die - like quit, except we can specify an exit status.
623  */
624 void
625 die(status)
626     int status;
627 {
628     cleanup(0, NULL);
629     syslog(LOG_INFO, "Exit.");
630     exit(status);
631 }
632
633 /*
634  * cleanup - restore anything which needs to be restored before we exit
635  */
636 /* ARGSUSED */
637 void
638 cleanup(status, arg)
639     int status;
640     caddr_t arg;
641 {
642     if (fd >= 0)
643         close_fd();
644
645     if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT) 
646         syslog(LOG_WARNING, "unable to delete pid file: %m");
647     pidfilename[0] = 0;
648
649     if (locked)
650         unlock();
651
652     if (demand)
653         demand_reset();
654 }
655
656 /*
657  * close_fd - restore the terminal device and close it.
658  */
659 void
660 close_fd()
661 {
662     /* drop dtr to hang up */
663     if (modem)
664         setdtr(fd, FALSE);
665
666     if (initfdflags != -1 && fcntl(fd, F_SETFL, initfdflags) < 0)
667         syslog(LOG_WARNING, "Couldn't restore device fd flags: %m");
668     initfdflags = -1;
669
670     disestablish_ppp(fd);
671
672     restore_tty();
673
674     close(fd);
675     fd = -1;
676 }
677
678
679 struct  callout {
680     struct timeval      c_time;         /* time at which to call routine */
681     caddr_t             c_arg;          /* argument to routine */
682     void                (*c_func)();    /* routine */
683     struct              callout *c_next;
684 };
685
686 static struct callout *callout = NULL;  /* Callout list */
687 static struct timeval timenow;          /* Current time */
688
689 /*
690  * timeout - Schedule a timeout.
691  *
692  * Note that this timeout takes the number of seconds, NOT hz (as in
693  * the kernel).
694  */
695 void
696 timeout(func, arg, time)
697     void (*func)();
698     caddr_t arg;
699     int time;
700 {
701     struct callout *newp, *p, **pp;
702   
703     MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
704                (long) func, (long) arg, time));
705   
706     /*
707      * Allocate timeout.
708      */
709     if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
710         syslog(LOG_ERR, "Out of memory in timeout()!");
711         die(1);
712     }
713     newp->c_arg = arg;
714     newp->c_func = func;
715     gettimeofday(&timenow, NULL);
716     newp->c_time.tv_sec = timenow.tv_sec + time;
717     newp->c_time.tv_usec = timenow.tv_usec;
718   
719     /*
720      * Find correct place and link it in.
721      */
722     for (pp = &callout; (p = *pp); pp = &p->c_next)
723         if (newp->c_time.tv_sec < p->c_time.tv_sec
724             || (newp->c_time.tv_sec == p->c_time.tv_sec
725                 && newp->c_time.tv_usec < p->c_time.tv_sec))
726             break;
727     newp->c_next = p;
728     *pp = newp;
729 }
730
731
732 /*
733  * untimeout - Unschedule a timeout.
734  */
735 void
736 untimeout(func, arg)
737     void (*func)();
738     caddr_t arg;
739 {
740     struct itimerval itv;
741     struct callout **copp, *freep;
742     int reschedule = 0;
743   
744     MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
745   
746     /*
747      * Find first matching timeout and remove it from the list.
748      */
749     for (copp = &callout; (freep = *copp); copp = &freep->c_next)
750         if (freep->c_func == func && freep->c_arg == arg) {
751             *copp = freep->c_next;
752             (void) free((char *) freep);
753             break;
754         }
755 }
756
757
758 /*
759  * calltimeout - Call any timeout routines which are now due.
760  */
761 void
762 calltimeout()
763 {
764     struct callout *p;
765
766     while (callout != NULL) {
767         p = callout;
768
769         if (gettimeofday(&timenow, NULL) < 0) {
770             syslog(LOG_ERR, "Failed to get time of day: %m");
771             die(1);
772         }
773         if (!(p->c_time.tv_sec < timenow.tv_sec
774               || (p->c_time.tv_sec == timenow.tv_sec
775                   && p->c_time.tv_usec <= timenow.tv_usec)))
776             break;              /* no, it's not time yet */
777
778         callout = p->c_next;
779         (*p->c_func)(p->c_arg);
780
781         free((char *) p);
782     }
783 }
784
785
786 /*
787  * timeleft - return the length of time until the next timeout is due.
788  */
789 struct timeval *
790 timeleft(tvp)
791     struct timeval *tvp;
792 {
793     if (callout == NULL)
794         return NULL;
795
796     gettimeofday(&timenow, NULL);
797     tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
798     tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
799     if (tvp->tv_usec < 0) {
800         tvp->tv_usec += 1000000;
801         tvp->tv_sec -= 1;
802     }
803     if (tvp->tv_sec < 0)
804         tvp->tv_sec = tvp->tv_usec = 0;
805
806     return tvp;
807 }
808     
809
810 /*
811  * hup - Catch SIGHUP signal.
812  *
813  * Indicates that the physical layer has been disconnected.
814  * We don't rely on this indication; if the user has sent this
815  * signal, we just take the link down.
816  */
817 static void
818 hup(sig)
819     int sig;
820 {
821     syslog(LOG_INFO, "Hangup (SIGHUP)");
822     kill_link = 1;
823 }
824
825
826 /*
827  * term - Catch SIGTERM signal and SIGINT signal (^C/del).
828  *
829  * Indicates that we should initiate a graceful disconnect and exit.
830  */
831 /*ARGSUSED*/
832 static void
833 term(sig)
834     int sig;
835 {
836     syslog(LOG_INFO, "Terminating on signal %d.", sig);
837     persist = 0;                /* don't try to restart */
838     kill_link = 1;
839 }
840
841
842 /*
843  * chld - Catch SIGCHLD signal.
844  * Calls reap_kids to get status for any dead kids.
845  */
846 static void
847 chld(sig)
848     int sig;
849 {
850     reap_kids();
851 }
852
853
854 /*
855  * toggle_debug - Catch SIGUSR1 signal.
856  *
857  * Toggle debug flag.
858  */
859 /*ARGSUSED*/
860 static void
861 toggle_debug(sig)
862     int sig;
863 {
864     debug = !debug;
865     note_debug_level();
866 }
867
868
869 /*
870  * open_ccp - Catch SIGUSR2 signal.
871  *
872  * Try to (re)negotiate compression.
873  */
874 /*ARGSUSED*/
875 static void
876 open_ccp(sig)
877     int sig;
878 {
879     open_ccp_flag = 1;
880 }
881
882
883 /*
884  * device_script - run a program to connect or disconnect the
885  * serial device.
886  */
887 int
888 device_script(program, in, out)
889     char *program;
890     int in, out;
891 {
892     int pid;
893     int status;
894     int errfd;
895
896     pid = fork();
897
898     if (pid < 0) {
899         syslog(LOG_ERR, "Failed to create child process: %m");
900         die(1);
901     }
902
903     if (pid == 0) {
904         sys_close();
905         dup2(in, 0);
906         dup2(out, 1);
907         errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0644);
908         if (errfd >= 0)
909             dup2(errfd, 2);
910         setuid(getuid());
911         setgid(getgid());
912         execl("/bin/sh", "sh", "-c", program, (char *)0);
913         syslog(LOG_ERR, "could not exec /bin/sh: %m");
914         _exit(99);
915         /* NOTREACHED */
916     }
917
918     while (waitpid(pid, &status, 0) < 0) {
919         if (errno == EINTR)
920             continue;
921         syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
922         die(1);
923     }
924
925     return (status == 0 ? 0 : -1);
926 }
927
928
929 /*
930  * run-program - execute a program with given arguments,
931  * but don't wait for it.
932  * If the program can't be executed, logs an error unless
933  * must_exist is 0 and the program file doesn't exist.
934  */
935 int
936 run_program(prog, args, must_exist)
937     char *prog;
938     char **args;
939     int must_exist;
940 {
941     int pid;
942     char *nullenv[1];
943
944     pid = fork();
945     if (pid == -1) {
946         syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
947         return -1;
948     }
949     if (pid == 0) {
950         int new_fd;
951
952         /* Leave the current location */
953         (void) setsid();    /* No controlling tty. */
954         (void) umask (S_IRWXG|S_IRWXO);
955         (void) chdir ("/"); /* no current directory. */
956         setuid(geteuid());
957         setgid(getegid());
958
959         /* Ensure that nothing of our device environment is inherited. */
960         sys_close();
961         close (0);
962         close (1);
963         close (2);
964         close (fd);  /* tty interface to the ppp device */
965
966         /* Don't pass handles to the PPP device, even by accident. */
967         new_fd = open (_PATH_DEVNULL, O_RDWR);
968         if (new_fd >= 0) {
969             if (new_fd != 0) {
970                 dup2  (new_fd, 0); /* stdin <- /dev/null */
971                 close (new_fd);
972             }
973             dup2 (0, 1); /* stdout -> /dev/null */
974             dup2 (0, 2); /* stderr -> /dev/null */
975         }
976
977 #ifdef BSD
978         /* Force the priority back to zero if pppd is running higher. */
979         if (setpriority (PRIO_PROCESS, 0, 0) < 0)
980             syslog (LOG_WARNING, "can't reset priority to 0: %m"); 
981 #endif
982
983         /* SysV recommends a second fork at this point. */
984
985         /* run the program; give it a null environment */
986         nullenv[0] = NULL;
987         execve(prog, args, nullenv);
988         if (must_exist || errno != ENOENT)
989             syslog(LOG_WARNING, "Can't execute %s: %m", prog);
990         _exit(-1);
991     }
992     MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
993     ++n_children;
994     return 0;
995 }
996
997
998 /*
999  * reap_kids - get status from any dead child processes,
1000  * and log a message for abnormal terminations.
1001  */
1002 void
1003 reap_kids()
1004 {
1005     int pid, status;
1006
1007     if (n_children == 0)
1008         return;
1009     if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1010         if (errno != ECHILD)
1011             syslog(LOG_ERR, "Error waiting for child process: %m");
1012         return;
1013     }
1014     if (pid > 0) {
1015         --n_children;
1016         if (WIFSIGNALED(status)) {
1017             syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1018                    pid, WTERMSIG(status));
1019         }
1020     }
1021 }
1022
1023
1024 /*
1025  * log_packet - format a packet and log it.
1026  */
1027
1028 char line[256];                 /* line to be logged accumulated here */
1029 char *linep;
1030
1031 void
1032 log_packet(p, len, prefix)
1033     u_char *p;
1034     int len;
1035     char *prefix;
1036 {
1037     strcpy(line, prefix);
1038     linep = line + strlen(line);
1039     format_packet(p, len, pr_log, NULL);
1040     if (linep != line)
1041         syslog(LOG_DEBUG, "%s", line);
1042 }
1043
1044 /*
1045  * format_packet - make a readable representation of a packet,
1046  * calling `printer(arg, format, ...)' to output it.
1047  */
1048 void
1049 format_packet(p, len, printer, arg)
1050     u_char *p;
1051     int len;
1052     void (*printer) __P((void *, char *, ...));
1053     void *arg;
1054 {
1055     int i, n;
1056     u_short proto;
1057     u_char x;
1058
1059     if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1060         p += 2;
1061         GETSHORT(proto, p);
1062         len -= PPP_HDRLEN;
1063         for (i = 0; i < N_PROTO; ++i)
1064             if (proto == prottbl[i].protocol)
1065                 break;
1066         if (i < N_PROTO) {
1067             printer(arg, "[%s", prottbl[i].name);
1068             n = (*prottbl[i].printpkt)(p, len, printer, arg);
1069             printer(arg, "]");
1070             p += n;
1071             len -= n;
1072         } else {
1073             printer(arg, "[proto=0x%x]", proto);
1074         }
1075     }
1076
1077     for (; len > 0; --len) {
1078         GETCHAR(x, p);
1079         printer(arg, " %.2x", x);
1080     }
1081 }
1082
1083 #ifdef __STDC__
1084 #include <stdarg.h>
1085
1086 void
1087 pr_log(void *arg, char *fmt, ...)
1088 {
1089     int n;
1090     va_list pvar;
1091     char buf[256];
1092
1093     va_start(pvar, fmt);
1094     vsprintf(buf, fmt, pvar);
1095     va_end(pvar);
1096
1097     n = strlen(buf);
1098     if (linep + n + 1 > line + sizeof(line)) {
1099         syslog(LOG_DEBUG, "%s", line);
1100         linep = line;
1101     }
1102     strcpy(linep, buf);
1103     linep += n;
1104 }
1105
1106 #else /* __STDC__ */
1107 #include <varargs.h>
1108
1109 void
1110 pr_log(arg, fmt, va_alist)
1111 void *arg;
1112 char *fmt;
1113 va_dcl
1114 {
1115     int n;
1116     va_list pvar;
1117     char buf[256];
1118
1119     va_start(pvar);
1120     vsprintf(buf, fmt, pvar);
1121     va_end(pvar);
1122
1123     n = strlen(buf);
1124     if (linep + n + 1 > line + sizeof(line)) {
1125         syslog(LOG_DEBUG, "%s", line);
1126         linep = line;
1127     }
1128     strcpy(linep, buf);
1129     linep += n;
1130 }
1131 #endif
1132
1133 /*
1134  * print_string - print a readable representation of a string using
1135  * printer.
1136  */
1137 void
1138 print_string(p, len, printer, arg)
1139     char *p;
1140     int len;
1141     void (*printer) __P((void *, char *, ...));
1142     void *arg;
1143 {
1144     int c;
1145
1146     printer(arg, "\"");
1147     for (; len > 0; --len) {
1148         c = *p++;
1149         if (' ' <= c && c <= '~')
1150             printer(arg, "%c", c);
1151         else
1152             printer(arg, "\\%.3o", c);
1153     }
1154     printer(arg, "\"");
1155 }
1156
1157 /*
1158  * novm - log an error message saying we ran out of memory, and die.
1159  */
1160 void
1161 novm(msg)
1162     char *msg;
1163 {
1164     syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1165     die(1);
1166 }