2 * main.c - Point-to-Point Protocol main module
4 * Copyright (c) 1989 Carnegie Mellon University.
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.
21 static char rcsid[] = "$Id: main.c,v 1.62 1999/03/19 01:26:41 paulus Exp $";
37 #include <sys/param.h>
38 #include <sys/types.h>
41 #include <sys/resource.h>
43 #include <sys/socket.h>
44 #include <netinet/in.h>
54 #include "pathnames.h"
55 #include "patchlevel.h"
62 extern char *strerror();
67 #endif /* IPX_CHANGE */
73 char ifname[32]; /* Interface name */
74 int ifunit; /* Interface unit number */
76 char *progname; /* Name of this program */
77 char hostname[MAXNAMELEN]; /* Our hostname */
78 static char pidfilename[MAXPATHLEN]; /* name of pid file */
79 static char default_devnam[MAXPATHLEN]; /* name of default device */
80 static pid_t pid; /* Our pid */
81 static uid_t uid; /* Our real user-id */
82 static int conn_running; /* we have a [dis]connector running */
84 int ttyfd = -1; /* Serial port file descriptor */
85 mode_t tty_mode = -1; /* Original access permissions to tty */
86 int baud_rate; /* Actual bits/second for serial device */
87 int hungup; /* terminal has been hung up */
88 int privileged; /* we're running as real uid root */
89 int need_holdoff; /* need holdoff period before restarting */
90 int detached; /* have detached from terminal */
91 int log_to_fd; /* send log messages to this fd too */
93 static int fd_ppp; /* fd for talking PPP */
94 static int fd_loop; /* fd for getting demand-dial packets */
96 int phase; /* where the link is at */
101 static sigjmp_buf sigjmp;
103 char **script_env; /* Env. variable values for scripts */
104 int s_env_nalloc; /* # words avail at script_env */
106 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
107 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
109 static int n_children; /* # child processes still running */
111 static int locked; /* lock() has succeeded */
113 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
115 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
116 int ngroups; /* How many groups valid in groups */
118 /* Prototypes for procedures local to this file. */
120 static void create_pidfile __P((void));
121 static void cleanup __P((void));
122 static void close_tty __P((void));
123 static void hangup_modem __P((int));
124 static void get_input __P((void));
125 static void calltimeout __P((void));
126 static struct timeval *timeleft __P((struct timeval *));
127 static void kill_my_pg __P((int));
128 static void hup __P((int));
129 static void term __P((int));
130 static void chld __P((int));
131 static void toggle_debug __P((int));
132 static void open_ccp __P((int));
133 static void bad_signal __P((int));
134 static void holdoff_end __P((void *));
135 static int device_script __P((char *, int));
136 static void reap_kids __P((void));
137 static void pr_log __P((void *, char *, ...));
138 static void logit __P((int, char *, va_list));
139 static void vslp_printer __P((void *, char *, ...));
140 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
143 extern char *ttyname __P((int));
144 extern char *getlogin __P((void));
145 int main __P((int, char *[]));
149 #define O_NONBLOCK O_NDELAY
153 #define setlogmask(x)
157 * PPP Data Link Layer "protocol" table.
158 * One entry per supported protocol.
159 * The last entry must be NULL.
161 struct protent *protocols[] = {
190 struct protent *protp;
194 phase = PHASE_INITIALIZE;
197 strlcpy(devnam, p, sizeof(devnam));
198 strlcpy(default_devnam, devnam, sizeof(default_devnam));
202 /* Initialize syslog facilities */
204 openlog("pppd", LOG_PID);
206 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
207 setlogmask(LOG_UPTO(LOG_INFO));
210 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
211 option_error("Couldn't get hostname: %m");
214 hostname[MAXNAMELEN-1] = 0;
217 privileged = uid == 0;
218 slprintf(numbuf, sizeof(numbuf), "%d", uid);
219 script_setenv("ORIG_UID", numbuf);
221 ngroups = getgroups(NGROUPS_MAX, groups);
224 * Initialize to the standard option set, then parse, in order,
225 * the system options file, the user's options file,
226 * the tty's options file, and the command line arguments.
228 for (i = 0; (protp = protocols[i]) != NULL; ++i)
233 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
234 || !options_from_user())
236 scan_args(argc-1, argv+1); /* look for tty name on command line */
237 if (!options_for_tty()
238 || !parse_args(argc-1, argv+1))
242 * Check that we are running as root.
244 if (geteuid() != 0) {
245 option_error("must be root to run %s, since it is not setuid-root",
250 if (!ppp_available()) {
251 option_error(no_ppp_msg);
256 * Check that the options given are valid and consistent.
258 if (!sys_check_options())
260 auth_check_options();
261 for (i = 0; (protp = protocols[i]) != NULL; ++i)
262 if (protp->check_options != NULL)
263 (*protp->check_options)();
264 if (demand && connector == 0) {
265 option_error("connect script is required for demand-dialling\n");
269 script_setenv("DEVICE", devnam);
270 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
271 script_setenv("SPEED", numbuf);
274 * If the user has specified the default device name explicitly,
275 * pretend they hadn't.
277 if (!default_device && strcmp(devnam, default_devnam) == 0)
281 log_to_fd = !default_device? 1: -1; /* default to stdout */
284 * Initialize system-dependent stuff and magic number package.
289 setlogmask(LOG_UPTO(LOG_DEBUG));
292 * Detach ourselves from the terminal, if required,
293 * and identify who is running us.
295 if (!nodetach && !updetach)
301 if (pw != NULL && pw->pw_name != NULL)
306 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
307 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
310 * Compute mask of all interesting signals and install signal handlers
311 * for each. Only one signal handler may be active at a time. Therefore,
312 * all other signals should be masked when any handler is executing.
315 sigaddset(&mask, SIGHUP);
316 sigaddset(&mask, SIGINT);
317 sigaddset(&mask, SIGTERM);
318 sigaddset(&mask, SIGCHLD);
319 sigaddset(&mask, SIGUSR2);
321 #define SIGNAL(s, handler) do { \
322 sa.sa_handler = handler; \
323 if (sigaction(s, &sa, NULL) < 0) \
324 fatal("Couldn't establish signal handler (%d): %m", s); \
329 SIGNAL(SIGHUP, hup); /* Hangup */
330 SIGNAL(SIGINT, term); /* Interrupt */
331 SIGNAL(SIGTERM, term); /* Terminate */
332 SIGNAL(SIGCHLD, chld);
334 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
335 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
338 * Install a handler for other signals which would otherwise
339 * cause pppd to exit without cleaning up.
341 SIGNAL(SIGABRT, bad_signal);
342 SIGNAL(SIGALRM, bad_signal);
343 SIGNAL(SIGFPE, bad_signal);
344 SIGNAL(SIGILL, bad_signal);
345 SIGNAL(SIGPIPE, bad_signal);
346 SIGNAL(SIGQUIT, bad_signal);
347 SIGNAL(SIGSEGV, bad_signal);
349 SIGNAL(SIGBUS, bad_signal);
352 SIGNAL(SIGEMT, bad_signal);
355 SIGNAL(SIGPOLL, bad_signal);
358 SIGNAL(SIGPROF, bad_signal);
361 SIGNAL(SIGSYS, bad_signal);
364 SIGNAL(SIGTRAP, bad_signal);
367 SIGNAL(SIGVTALRM, bad_signal);
370 SIGNAL(SIGXCPU, bad_signal);
373 SIGNAL(SIGXFSZ, bad_signal);
377 * Apparently we can get a SIGPIPE when we call syslog, if
378 * syslogd has died and been restarted. Ignoring it seems
381 signal(SIGPIPE, SIG_IGN);
386 * If we're doing dial-on-demand, set up the interface now.
390 * Open the loopback channel and set it up to be the ppp interface.
392 fd_loop = open_ppp_loopback();
394 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
395 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
396 script_setenv("IFNAME", ifname);
398 create_pidfile(); /* write pid to file */
401 * Configure the interface and mark it up, etc.
412 * Don't do anything until we see some activity.
415 phase = PHASE_DORMANT;
419 if (sigsetjmp(sigjmp, 1) == 0) {
420 sigprocmask(SIG_BLOCK, &mask, NULL);
422 sigprocmask(SIG_UNBLOCK, &mask, NULL);
425 sigprocmask(SIG_UNBLOCK, &mask, NULL);
426 wait_input(timeleft(&timo));
436 if (get_loop_output())
441 if (kill_link && !persist)
445 * Now we want to bring up the link.
448 info("Starting link");
452 * Lock the device if we've been asked to.
454 if (lockflag && !default_device) {
455 if (lock(devnam) < 0)
461 * Open the serial device and set it up to be the ppp interface.
462 * First we open it in non-blocking mode so we can set the
463 * various termios flags appropriately. If we aren't dialling
464 * out and we want to use the modem lines, we reopen it later
465 * in order to wait for the carrier detect signal from the modem.
470 /* If the user specified the device name, become the
471 user before opening it. */
472 if (!devnam_info.priv)
474 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
475 if (!devnam_info.priv)
480 error("Failed to open %s: %m", devnam);
481 if (!persist || errno != EINTR)
484 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
485 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
486 warn("Couldn't reset non-blocking mode on device: %m");
489 * Do the equivalent of `mesg n' to stop broadcast messages.
491 if (fstat(ttyfd, &statbuf) < 0
492 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
493 warn("Couldn't restrict write permissions to %s: %m", devnam);
495 tty_mode = statbuf.st_mode;
497 /* run connection script */
498 if (connector && connector[0]) {
499 MAINDEBUG(("Connecting with <%s>", connector));
501 if (!default_device && modem) {
502 hangup_modem(ttyfd); /* in case modem is off hook */
507 * Set line speed, flow control, etc.
508 * On most systems we set CLOCAL for now so that we can talk
509 * to the modem before carrier comes up. But this has the
510 * side effect that we might miss it if CD drops before we
511 * get to clear CLOCAL below. On systems where we can talk
512 * successfully to the modem with CLOCAL clear and CD down,
513 * we could clear CLOCAL at this point.
515 set_up_tty(ttyfd, 1);
517 if (device_script(connector, ttyfd) < 0) {
518 error("Connect script failed");
522 info("Serial connection established.");
523 sleep(1); /* give it time to set up its terminal */
526 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
527 set_up_tty(ttyfd, 0);
529 /* reopen tty if necessary to wait for carrier */
530 if (connector == NULL && modem) {
532 if ((i = open(devnam, O_RDWR)) >= 0)
535 error("Failed to reopen %s: %m", devnam);
536 if (!persist || errno != EINTR || hungup || kill_link)
542 /* run welcome script, if any */
543 if (welcomer && welcomer[0]) {
544 if (device_script(welcomer, ttyfd) < 0)
545 warn("Welcome script failed");
548 /* set up the serial device as a ppp interface */
549 fd_ppp = establish_ppp(ttyfd);
553 info("Using interface ppp%d", ifunit);
554 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
555 script_setenv("IFNAME", ifname);
557 create_pidfile(); /* write pid to file */
561 * Start opening the connection and wait for
562 * incoming events (reply, timeout, etc.).
564 notice("Connect: %s <--> %s", ifname, devnam);
566 lcp_open(0); /* Start protocol */
569 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
570 if (sigsetjmp(sigjmp, 1) == 0) {
571 sigprocmask(SIG_BLOCK, &mask, NULL);
572 if (kill_link || open_ccp_flag) {
573 sigprocmask(SIG_UNBLOCK, &mask, NULL);
576 sigprocmask(SIG_UNBLOCK, &mask, NULL);
577 wait_input(timeleft(&timo));
584 lcp_close(0, "User request");
588 if (phase == PHASE_NETWORK) {
589 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
590 (*ccp_protent.open)(0);
594 reap_kids(); /* Don't leave dead kids lying around */
598 * If we may want to bring the link up again, transfer
599 * the ppp unit back to the loopback. Set the
600 * real serial device back to its normal mode of operation.
606 disestablish_ppp(ttyfd);
609 * Run disconnector script, if requested.
610 * XXX we may not be able to do this if the line has hung up!
612 if (disconnector && !hungup) {
613 set_up_tty(ttyfd, 1);
614 if (device_script(disconnector, ttyfd) < 0) {
615 warn("disconnect script failed");
617 info("Serial link disconnected.");
632 if (pidfilename[0] != 0
633 && unlink(pidfilename) < 0 && errno != ENOENT)
634 warn("unable to delete pid file: %m");
644 if (holdoff > 0 && need_holdoff) {
645 phase = PHASE_HOLDOFF;
646 TIMEOUT(holdoff_end, NULL, holdoff);
648 if (sigsetjmp(sigjmp, 1) == 0) {
649 sigprocmask(SIG_BLOCK, &mask, NULL);
651 sigprocmask(SIG_UNBLOCK, &mask, NULL);
654 sigprocmask(SIG_UNBLOCK, &mask, NULL);
655 wait_input(timeleft(&timo));
662 phase = PHASE_DORMANT; /* allow signal to end holdoff */
665 } while (phase == PHASE_HOLDOFF);
671 /* Wait for scripts to finish */
672 while (n_children > 0)
680 * detach - detach us from the controlling terminal.
687 if (daemon(0, 0) < 0) {
688 perror("Couldn't detach from controlling terminal");
694 /* update pid file if it has been written already */
700 * Create a file containing our process ID.
708 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
709 _PATH_VARRUN, ifname);
710 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
711 fprintf(pidfile, "%d\n", pid);
712 (void) fclose(pidfile);
714 error("Failed to create pid file %s: %m", pidfilename);
717 slprintf(numbuf, sizeof(numbuf), "%d", pid);
718 script_setenv("PPPD_PID", numbuf);
722 * holdoff_end - called via a timeout when the holdoff period ends.
728 phase = PHASE_DORMANT;
732 * get_input - called when incoming data is available.
740 struct protent *protp;
742 p = inpacket_buf; /* point to beginning of packet buffer */
744 len = read_packet(inpacket_buf);
749 notice("Modem hangup");
751 lcp_lowerdown(0); /* serial link is no longer available */
756 if (debug /*&& (debugflags & DBG_INPACKET)*/)
757 dbglog("rcvd %P", p, len);
759 if (len < PPP_HDRLEN) {
760 MAINDEBUG(("io(): Received short packet."));
764 p += 2; /* Skip address and control */
765 GETSHORT(protocol, p);
769 * Toss all non-LCP packets unless LCP is OPEN.
771 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
772 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
777 * Until we get past the authentication phase, toss all packets
778 * except LCP, LQR and authentication packets.
780 if (phase <= PHASE_AUTHENTICATE
781 && !(protocol == PPP_LCP || protocol == PPP_LQR
782 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
783 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
789 * Upcall the proper protocol input routine.
791 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
792 if (protp->protocol == protocol && protp->enabled_flag) {
793 (*protp->input)(0, p, len);
796 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
797 && protp->datainput != NULL) {
798 (*protp->datainput)(0, p, len);
804 warn("Unsupported protocol (0x%x) received", protocol);
805 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
810 * die - clean up state and exit with the specified status.
817 syslog(LOG_INFO, "Exit.");
822 * cleanup - restore anything which needs to be restored before we exit
833 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
834 warn("unable to delete pid file: %m");
842 * close_tty - restore the terminal device and close it.
847 disestablish_ppp(ttyfd);
849 /* drop dtr to hang up */
850 if (!default_device && modem) {
853 * This sleep is in case the serial port has CLOCAL set by default,
854 * and consequently will reassert DTR when we close the device.
861 if (tty_mode != (mode_t) -1) {
862 if (fchmod(ttyfd, tty_mode) != 0) {
863 /* XXX if devnam is a symlink, this will change the link */
864 chmod(devnam, tty_mode);
873 * hangup_modem - hang up the modem by clearing DTR.
884 struct timeval c_time; /* time at which to call routine */
885 void *c_arg; /* argument to routine */
886 void (*c_func) __P((void *)); /* routine */
887 struct callout *c_next;
890 static struct callout *callout = NULL; /* Callout list */
891 static struct timeval timenow; /* Current time */
894 * timeout - Schedule a timeout.
896 * Note that this timeout takes the number of seconds, NOT hz (as in
900 timeout(func, arg, time)
901 void (*func) __P((void *));
905 struct callout *newp, *p, **pp;
907 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
912 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
913 fatal("Out of memory in timeout()!");
916 gettimeofday(&timenow, NULL);
917 newp->c_time.tv_sec = timenow.tv_sec + time;
918 newp->c_time.tv_usec = timenow.tv_usec;
921 * Find correct place and link it in.
923 for (pp = &callout; (p = *pp); pp = &p->c_next)
924 if (newp->c_time.tv_sec < p->c_time.tv_sec
925 || (newp->c_time.tv_sec == p->c_time.tv_sec
926 && newp->c_time.tv_usec < p->c_time.tv_usec))
934 * untimeout - Unschedule a timeout.
938 void (*func) __P((void *));
941 struct callout **copp, *freep;
943 MAINDEBUG(("Untimeout %p:%p.", func, arg));
946 * Find first matching timeout and remove it from the list.
948 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
949 if (freep->c_func == func && freep->c_arg == arg) {
950 *copp = freep->c_next;
951 (void) free((char *) freep);
958 * calltimeout - Call any timeout routines which are now due.
965 while (callout != NULL) {
968 if (gettimeofday(&timenow, NULL) < 0)
969 fatal("Failed to get time of day: %m");
970 if (!(p->c_time.tv_sec < timenow.tv_sec
971 || (p->c_time.tv_sec == timenow.tv_sec
972 && p->c_time.tv_usec <= timenow.tv_usec)))
973 break; /* no, it's not time yet */
976 (*p->c_func)(p->c_arg);
984 * timeleft - return the length of time until the next timeout is due.
986 static struct timeval *
993 gettimeofday(&timenow, NULL);
994 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
995 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
996 if (tvp->tv_usec < 0) {
997 tvp->tv_usec += 1000000;
1000 if (tvp->tv_sec < 0)
1001 tvp->tv_sec = tvp->tv_usec = 0;
1008 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1014 struct sigaction act, oldact;
1016 act.sa_handler = SIG_IGN;
1019 sigaction(sig, &act, &oldact);
1020 sigaction(sig, &oldact, NULL);
1025 * hup - Catch SIGHUP signal.
1027 * Indicates that the physical layer has been disconnected.
1028 * We don't rely on this indication; if the user has sent this
1029 * signal, we just take the link down.
1035 info("Hangup (SIGHUP)");
1038 /* Send the signal to the [dis]connector process(es) also */
1041 siglongjmp(sigjmp, 1);
1046 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1048 * Indicates that we should initiate a graceful disconnect and exit.
1055 info("Terminating on signal %d.", sig);
1056 persist = 0; /* don't try to restart */
1059 /* Send the signal to the [dis]connector process(es) also */
1062 siglongjmp(sigjmp, 1);
1067 * chld - Catch SIGCHLD signal.
1068 * Calls reap_kids to get status for any dead kids.
1075 siglongjmp(sigjmp, 1);
1080 * toggle_debug - Catch SIGUSR1 signal.
1082 * Toggle debug flag.
1091 setlogmask(LOG_UPTO(LOG_DEBUG));
1093 setlogmask(LOG_UPTO(LOG_WARNING));
1099 * open_ccp - Catch SIGUSR2 signal.
1101 * Try to (re)negotiate compression.
1110 siglongjmp(sigjmp, 1);
1115 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1121 static int crashed = 0;
1126 error("Fatal signal %d", sig);
1128 kill_my_pg(SIGTERM);
1134 * device_script - run a program to connect or disconnect the
1138 device_script(program, inout)
1151 fatal("Failed to create child process: %m");
1159 int newio = dup(inout);
1163 if (log_to_fd >= 0) {
1168 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1169 if (errfd >= 0 && errfd != 2) {
1180 if (getuid() != uid) {
1181 error("setuid failed");
1185 execl("/bin/sh", "sh", "-c", program, (char *)0);
1186 error("could not exec /bin/sh: %m");
1191 while (waitpid(pid, &status, 0) < 0) {
1194 fatal("error waiting for (dis)connection process: %m");
1198 return (status == 0 ? 0 : -1);
1203 * We maintain a list of child process pids and
1204 * functions to call when they exit.
1209 void (*done) __P((void *));
1211 struct subprocess *next;
1214 struct subprocess *children;
1217 * run-program - execute a program with given arguments,
1218 * but don't wait for it.
1219 * If the program can't be executed, logs an error unless
1220 * must_exist is 0 and the program file doesn't exist.
1221 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1222 * or isn't an executable plain file, or the process ID of the child.
1223 * If done != NULL, (*done)(arg) will be called later (within
1224 * reap_kids) iff the return value is > 0.
1227 run_program(prog, args, must_exist, done, arg)
1231 void (*done) __P((void *));
1235 struct subprocess *chp;
1239 * First check if the file exists and is executable.
1240 * We don't use access() because that would use the
1241 * real user-id, which might not be root, and the script
1242 * might be accessible only to root.
1245 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1246 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1247 if (must_exist || errno != ENOENT)
1248 warn("Can't execute %s: %m", prog);
1254 fatal("Failed to create child process for %s: %m", prog);
1258 /* Leave the current location */
1259 (void) setsid(); /* No controlling tty. */
1260 (void) umask (S_IRWXG|S_IRWXO);
1261 (void) chdir ("/"); /* no current directory. */
1262 setuid(0); /* set real UID = root */
1265 /* Ensure that nothing of our device environment is inherited. */
1271 close (ttyfd); /* tty interface to the ppp device */
1273 /* Don't pass handles to the PPP device, even by accident. */
1274 new_fd = open (_PATH_DEVNULL, O_RDWR);
1277 dup2 (new_fd, 0); /* stdin <- /dev/null */
1280 dup2 (0, 1); /* stdout -> /dev/null */
1281 dup2 (0, 2); /* stderr -> /dev/null */
1285 /* Force the priority back to zero if pppd is running higher. */
1286 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1287 warn("can't reset priority to 0: %m");
1290 /* SysV recommends a second fork at this point. */
1292 /* run the program */
1293 execve(prog, args, script_env);
1294 if (must_exist || errno != ENOENT)
1295 warn("Can't execute %s: %m", prog);
1300 dbglog("Script %s started; pid = %d", prog, pid);
1303 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1305 warn("losing track of %s process", prog);
1311 chp->next = children;
1320 * reap_kids - get status from any dead child processes,
1321 * and log a message for abnormal terminations.
1327 struct subprocess *chp, **prevp;
1329 if (n_children == 0)
1331 while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1333 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1334 if (chp->pid == pid)
1337 dbglog("process %d (%s) finished, status = 0x%x",
1338 pid, (chp? chp->prog: "??"), status);
1339 if (WIFSIGNALED(status)) {
1340 warn("Child process %s (pid %d) terminated with signal %d",
1341 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1343 if (chp && chp->done)
1344 (*chp->done)(chp->arg);
1346 if (pid == -1 && errno != ECHILD)
1347 error("Error waiting for child process: %m");
1352 * log_packet - format a packet and log it.
1355 char line[256]; /* line to be logged accumulated here */
1359 log_packet(p, len, prefix, level)
1365 strlcpy(line, prefix, sizeof(line));
1366 linep = line + strlen(line);
1367 format_packet(p, len, pr_log, NULL);
1369 syslog(level, "%s", line);
1373 * format_packet - make a readable representation of a packet,
1374 * calling `printer(arg, format, ...)' to output it.
1377 format_packet(p, len, printer, arg)
1380 void (*printer) __P((void *, char *, ...));
1385 struct protent *protp;
1387 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1391 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1392 if (proto == protp->protocol)
1394 if (protp != NULL) {
1395 printer(arg, "[%s", protp->name);
1396 n = (*protp->printpkt)(p, len, printer, arg);
1401 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1402 if (proto == (protp->protocol & ~0x8000))
1404 if (protp != 0 && protp->data_name != 0) {
1405 printer(arg, "[%s data]", protp->data_name);
1407 printer(arg, "%.8B ...", p);
1409 printer(arg, "%.*B", len, p);
1412 printer(arg, "[proto=0x%x]", proto);
1417 printer(arg, "%.32B ...", p);
1419 printer(arg, "%.*B", len, p);
1423 pr_log __V((void *arg, char *fmt, ...))
1430 va_start(pvar, fmt);
1435 arg = va_arg(pvar, void *);
1436 fmt = va_arg(pvar, char *);
1439 n = vslprintf(buf, sizeof(buf), fmt, pvar);
1442 if (linep + n + 1 > line + sizeof(line)) {
1443 syslog(LOG_DEBUG, "%s", line);
1446 strlcpy(linep, buf, line + sizeof(line) - linep);
1451 * vslp_printer - used in processing a %P format
1453 struct buffer_info {
1459 vslp_printer __V((void *arg, char *fmt, ...))
1463 struct buffer_info *bi;
1466 va_start(pvar, fmt);
1471 arg = va_arg(pvar, void *);
1472 fmt = va_arg(pvar, char *);
1475 bi = (struct buffer_info *) arg;
1476 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
1484 * print_string - print a readable representation of a string using
1488 print_string(p, len, printer, arg)
1491 void (*printer) __P((void *, char *, ...));
1497 for (; len > 0; --len) {
1499 if (' ' <= c && c <= '~') {
1500 if (c == '\\' || c == '"')
1502 printer(arg, "%c", c);
1506 printer(arg, "\\n");
1509 printer(arg, "\\r");
1512 printer(arg, "\\t");
1515 printer(arg, "\\%.3o", c);
1523 * novm - log an error message saying we ran out of memory, and die.
1529 fatal("Virtual memory exhausted allocating %s\n", msg);
1533 * slprintf - format a message into a buffer. Like sprintf except we
1534 * also specify the length of the output buffer, and we handle
1535 * %r (recursive format), %m (error message), %v (visible string),
1536 * %q (quoted string), %t (current time) and %I (IP address) formats.
1537 * Doesn't do floating-point formats.
1538 * Returns the number of chars put into buf.
1541 slprintf __V((char *buf, int buflen, char *fmt, ...))
1547 va_start(args, fmt);
1553 buf = va_arg(args, char *);
1554 buflen = va_arg(args, int);
1555 fmt = va_arg(args, char *);
1557 n = vslprintf(buf, buflen, fmt, args);
1563 * vslprintf - like slprintf, takes a va_list instead of a list of args.
1565 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1568 vslprintf(buf, buflen, fmt, args)
1575 int width, prec, fillch;
1576 int base, len, neg, quoted;
1577 unsigned long val = 0;
1578 char *str, *f, *buf0;
1583 static char hexchars[] = "0123456789abcdef";
1584 struct buffer_info bufinfo;
1588 while (buflen > 0) {
1589 for (f = fmt; *f != '%' && *f != 0; ++f)
1595 memcpy(buf, fmt, len);
1610 width = va_arg(args, int);
1613 while (isdigit(c)) {
1614 width = width * 10 + c - '0';
1621 prec = va_arg(args, int);
1624 while (isdigit(c)) {
1625 prec = prec * 10 + c - '0';
1636 i = va_arg(args, int);
1645 val = va_arg(args, unsigned int);
1650 val = va_arg(args, unsigned int);
1654 val = (unsigned long) va_arg(args, void *);
1659 str = va_arg(args, char *);
1662 num[0] = va_arg(args, int);
1667 str = strerror(errno);
1670 ip = va_arg(args, u_int32_t);
1672 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
1673 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
1677 f = va_arg(args, char *);
1679 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
1681 /* On the powerpc, a va_list is an array of 1 structure */
1682 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
1690 str += 4; /* chop off the day name */
1691 str[15] = 0; /* chop off year and newline */
1693 case 'v': /* "visible" string */
1694 case 'q': /* quoted string */
1696 p = va_arg(args, unsigned char *);
1697 if (fillch == '0' && prec > 0) {
1700 n = strlen((char *)p);
1701 if (prec > 0 && prec < n)
1704 while (n > 0 && buflen > 0) {
1707 if (!quoted && c >= 0x80) {
1712 if (quoted && (c == '"' || c == '\\'))
1714 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1718 case '\t': OUTCHAR('t'); break;
1719 case '\n': OUTCHAR('n'); break;
1720 case '\b': OUTCHAR('b'); break;
1721 case '\f': OUTCHAR('f'); break;
1724 OUTCHAR(hexchars[c >> 4]);
1725 OUTCHAR(hexchars[c & 0xf]);
1739 case 'P': /* print PPP packet */
1741 bufinfo.len = buflen + 1;
1742 p = va_arg(args, unsigned char *);
1743 n = va_arg(args, int);
1744 format_packet(p, n, vslp_printer, &bufinfo);
1746 buflen = bufinfo.len - 1;
1749 p = va_arg(args, unsigned char *);
1750 for (n = prec; n > 0; --n) {
1754 OUTCHAR(hexchars[(c >> 4) & 0xf]);
1755 OUTCHAR(hexchars[c & 0xf]);
1761 --fmt; /* so %z outputs %z etc. */
1766 str = num + sizeof(num);
1768 while (str > num + neg) {
1769 *--str = hexchars[val % base];
1771 if (--prec <= 0 && val == 0)
1783 len = num + sizeof(num) - 1 - str;
1786 if (prec > 0 && len > prec)
1792 if ((n = width - len) > 0) {
1800 memcpy(buf, str, len);
1809 * script_setenv - set an environment variable value to be used
1810 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1813 script_setenv(var, value)
1816 size_t vl = strlen(var) + strlen(value) + 2;
1818 char *p, *newstring;
1820 newstring = (char *) malloc(vl);
1823 slprintf(newstring, vl, "%s=%s", var, value);
1825 /* check if this variable is already set */
1826 if (script_env != 0) {
1827 for (i = 0; (p = script_env[i]) != 0; ++i) {
1828 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1830 script_env[i] = newstring;
1836 script_env = (char **) malloc(16 * sizeof(char *));
1837 if (script_env == 0)
1842 /* reallocate script_env with more space if needed */
1843 if (i + 1 >= s_env_nalloc) {
1845 char **newenv = (char **) realloc((void *)script_env,
1846 new_n * sizeof(char *));
1849 script_env = newenv;
1850 s_env_nalloc = new_n;
1853 script_env[i] = newstring;
1854 script_env[i+1] = 0;
1858 * script_unsetenv - remove a variable from the environment
1862 script_unsetenv(var)
1865 int vl = strlen(var);
1869 if (script_env == 0)
1871 for (i = 0; (p = script_env[i]) != 0; ++i) {
1872 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1874 while ((script_env[i] = script_env[i+1]) != 0)
1882 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
1883 * always leaves destination null-terminated (for len > 0).
1886 strlcpy(char *dest, const char *src, size_t len)
1888 size_t ret = strlen(src);
1894 strncpy(dest, src, len - 1);
1902 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
1903 * always leaves destination null-terminated (for len > 0).
1906 strlcat(char *dest, const char *src, size_t len)
1908 size_t dlen = strlen(dest);
1910 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
1914 * logit - does the hard work for fatal et al.
1917 logit(level, fmt, args)
1925 n = vslprintf(buf, sizeof(buf), fmt, args);
1926 syslog(level, "%s", buf);
1927 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
1928 if (buf[n-1] != '\n')
1930 if (write(log_to_fd, buf, n) != n)
1936 * fatal - log an error message and die horribly.
1939 fatal __V((char *fmt, ...))
1944 va_start(pvar, fmt);
1948 fmt = va_arg(pvar, char *);
1951 logit(LOG_ERR, fmt, pvar);
1954 die(1); /* as promised */
1958 * error - log an error message.
1961 error __V((char *fmt, ...))
1966 va_start(pvar, fmt);
1970 fmt = va_arg(pvar, char *);
1973 logit(LOG_ERR, fmt, pvar);
1978 * warn - log a warning message.
1981 warn __V((char *fmt, ...))
1986 va_start(pvar, fmt);
1990 fmt = va_arg(pvar, char *);
1993 logit(LOG_WARNING, fmt, pvar);
1998 * notice - log a notice-level message.
2001 notice __V((char *fmt, ...))
2006 va_start(pvar, fmt);
2010 fmt = va_arg(pvar, char *);
2013 logit(LOG_NOTICE, fmt, pvar);
2018 * info - log an informational message.
2021 info __V((char *fmt, ...))
2026 va_start(pvar, fmt);
2030 fmt = va_arg(pvar, char *);
2033 logit(LOG_INFO, fmt, pvar);
2038 * dbglog - log a debug message.
2041 dbglog __V((char *fmt, ...))
2046 va_start(pvar, fmt);
2050 fmt = va_arg(pvar, char *);
2053 logit(LOG_DEBUG, fmt, pvar);