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