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