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