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