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