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