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