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.60 1999/03/16 03:14:50 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_stderr; /* send log messages to stderr 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 get_input __P((void));
124 static void calltimeout __P((void));
125 static struct timeval *timeleft __P((struct timeval *));
126 static void kill_my_pg __P((int));
127 static void hup __P((int));
128 static void term __P((int));
129 static void chld __P((int));
130 static void toggle_debug __P((int));
131 static void open_ccp __P((int));
132 static void bad_signal __P((int));
133 static void holdoff_end __P((void *));
134 static int device_script __P((char *, int, int));
135 static void reap_kids __P((void));
136 static void pr_log __P((void *, char *, ...));
137 static void logit __P((int, char *, va_list));
138 static void vslp_printer __P((void *, char *, ...));
140 extern char *ttyname __P((int));
141 extern char *getlogin __P((void));
142 int main __P((int, char *[]));
146 #define O_NONBLOCK O_NDELAY
150 #define setlogmask(x)
154 * PPP Data Link Layer "protocol" table.
155 * One entry per supported protocol.
156 * The last entry must be NULL.
158 struct protent *protocols[] = {
187 struct protent *protp;
191 phase = PHASE_INITIALIZE;
194 strlcpy(devnam, sizeof(devnam), p);
195 strlcpy(default_devnam, sizeof(default_devnam), devnam);
199 /* Initialize syslog facilities */
201 openlog("pppd", LOG_PID);
203 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
204 setlogmask(LOG_UPTO(LOG_INFO));
207 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
208 option_error("Couldn't get hostname: %m");
211 hostname[MAXNAMELEN-1] = 0;
214 privileged = uid == 0;
215 slprintf(numbuf, sizeof(numbuf), "%d", uid);
216 script_setenv("ORIG_UID", numbuf);
218 ngroups = getgroups(NGROUPS_MAX, groups);
221 * Initialize to the standard option set, then parse, in order,
222 * the system options file, the user's options file,
223 * the tty's options file, and the command line arguments.
225 for (i = 0; (protp = protocols[i]) != NULL; ++i)
230 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
231 || !options_from_user())
233 scan_args(argc-1, argv+1); /* look for tty name on command line */
234 if (!options_for_tty()
235 || !parse_args(argc-1, argv+1))
239 * Check that we are running as root.
241 if (geteuid() != 0) {
242 option_error("must be root to run %s, since it is not setuid-root",
247 if (!ppp_available()) {
248 option_error(no_ppp_msg);
253 * Check that the options given are valid and consistent.
255 if (!sys_check_options())
257 auth_check_options();
258 for (i = 0; (protp = protocols[i]) != NULL; ++i)
259 if (protp->check_options != NULL)
260 (*protp->check_options)();
261 if (demand && connector == 0) {
262 option_error("connect script is required for demand-dialling\n");
266 script_setenv("DEVICE", devnam);
267 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
268 script_setenv("SPEED", numbuf);
271 * If the user has specified the default device name explicitly,
272 * pretend they hadn't.
274 if (!default_device && strcmp(devnam, default_devnam) == 0)
278 log_to_stderr = !default_device;
281 * Initialize system-dependent stuff and magic number package.
286 setlogmask(LOG_UPTO(LOG_DEBUG));
289 * Detach ourselves from the terminal, if required,
290 * and identify who is running us.
292 if (!nodetach && !updetach)
298 if (pw != NULL && pw->pw_name != NULL)
303 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
304 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
307 * Compute mask of all interesting signals and install signal handlers
308 * for each. Only one signal handler may be active at a time. Therefore,
309 * all other signals should be masked when any handler is executing.
312 sigaddset(&mask, SIGHUP);
313 sigaddset(&mask, SIGINT);
314 sigaddset(&mask, SIGTERM);
315 sigaddset(&mask, SIGCHLD);
316 sigaddset(&mask, SIGUSR2);
318 #define SIGNAL(s, handler) do { \
319 sa.sa_handler = handler; \
320 if (sigaction(s, &sa, NULL) < 0) \
321 fatal("Couldn't establish signal handler (%d): %m", s); \
326 SIGNAL(SIGHUP, hup); /* Hangup */
327 SIGNAL(SIGINT, term); /* Interrupt */
328 SIGNAL(SIGTERM, term); /* Terminate */
329 SIGNAL(SIGCHLD, chld);
331 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
332 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
335 * Install a handler for other signals which would otherwise
336 * cause pppd to exit without cleaning up.
338 SIGNAL(SIGABRT, bad_signal);
339 SIGNAL(SIGALRM, bad_signal);
340 SIGNAL(SIGFPE, bad_signal);
341 SIGNAL(SIGILL, bad_signal);
342 SIGNAL(SIGPIPE, bad_signal);
343 SIGNAL(SIGQUIT, bad_signal);
344 SIGNAL(SIGSEGV, bad_signal);
346 SIGNAL(SIGBUS, bad_signal);
349 SIGNAL(SIGEMT, bad_signal);
352 SIGNAL(SIGPOLL, bad_signal);
355 SIGNAL(SIGPROF, bad_signal);
358 SIGNAL(SIGSYS, bad_signal);
361 SIGNAL(SIGTRAP, bad_signal);
364 SIGNAL(SIGVTALRM, bad_signal);
367 SIGNAL(SIGXCPU, bad_signal);
370 SIGNAL(SIGXFSZ, bad_signal);
374 * Apparently we can get a SIGPIPE when we call syslog, if
375 * syslogd has died and been restarted. Ignoring it seems
378 signal(SIGPIPE, SIG_IGN);
383 * If we're doing dial-on-demand, set up the interface now.
387 * Open the loopback channel and set it up to be the ppp interface.
389 fd_loop = open_ppp_loopback();
391 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
392 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
393 script_setenv("IFNAME", ifname);
395 create_pidfile(); /* write pid to file */
398 * Configure the interface and mark it up, etc.
409 * Don't do anything until we see some activity.
412 phase = PHASE_DORMANT;
416 if (sigsetjmp(sigjmp, 1) == 0) {
417 sigprocmask(SIG_BLOCK, &mask, NULL);
419 sigprocmask(SIG_UNBLOCK, &mask, NULL);
422 sigprocmask(SIG_UNBLOCK, &mask, NULL);
423 wait_input(timeleft(&timo));
433 if (get_loop_output())
438 if (kill_link && !persist)
442 * Now we want to bring up the link.
445 info("Starting link");
449 * Lock the device if we've been asked to.
451 if (lockflag && !default_device) {
452 if (lock(devnam) < 0)
458 * Open the serial device and set it up to be the ppp interface.
459 * First we open it in non-blocking mode so we can set the
460 * various termios flags appropriately. If we aren't dialling
461 * out and we want to use the modem lines, we reopen it later
462 * in order to wait for the carrier detect signal from the modem.
467 /* If the user specified the device name, become the
468 user before opening it. */
469 if (!devnam_info.priv)
471 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
472 if (!devnam_info.priv)
477 error("Failed to open %s: %m", devnam);
478 if (!persist || errno != EINTR)
481 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
482 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
483 warn("Couldn't reset non-blocking mode on device: %m");
486 * Do the equivalent of `mesg n' to stop broadcast messages.
488 if (fstat(ttyfd, &statbuf) < 0
489 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
490 warn("Couldn't restrict write permissions to %s: %m", devnam);
492 tty_mode = statbuf.st_mode;
494 /* run connection script */
495 if (connector && connector[0]) {
496 MAINDEBUG(("Connecting with <%s>", connector));
498 if (!default_device && modem) {
499 hangup_modem(ttyfd); /* in case modem is off hook */
504 * Set line speed, flow control, etc.
505 * On most systems we set CLOCAL for now so that we can talk
506 * to the modem before carrier comes up. But this has the
507 * side effect that we might miss it if CD drops before we
508 * get to clear CLOCAL below. On systems where we can talk
509 * successfully to the modem with CLOCAL clear and CD down,
510 * we could clear CLOCAL at this point.
512 set_up_tty(ttyfd, 1);
514 if (device_script(connector, ttyfd, ttyfd) < 0) {
515 error("Connect script failed");
519 info("Serial connection established.");
520 sleep(1); /* give it time to set up its terminal */
523 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
524 set_up_tty(ttyfd, 0);
526 /* reopen tty if necessary to wait for carrier */
527 if (connector == NULL && modem) {
529 if ((i = open(devnam, O_RDWR)) >= 0)
532 error("Failed to reopen %s: %m", devnam);
533 if (!persist || errno != EINTR || hungup || kill_link)
539 /* run welcome script, if any */
540 if (welcomer && welcomer[0]) {
541 if (device_script(welcomer, ttyfd, ttyfd) < 0)
542 warn("Welcome script failed");
545 /* set up the serial device as a ppp interface */
546 fd_ppp = establish_ppp(ttyfd);
550 info("Using interface ppp%d", ifunit);
551 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
552 script_setenv("IFNAME", ifname);
554 create_pidfile(); /* write pid to file */
558 * Start opening the connection and wait for
559 * incoming events (reply, timeout, etc.).
561 notice("Connect: %s <--> %s", ifname, devnam);
563 lcp_open(0); /* Start protocol */
566 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
567 if (sigsetjmp(sigjmp, 1) == 0) {
568 sigprocmask(SIG_BLOCK, &mask, NULL);
569 if (kill_link || open_ccp_flag) {
570 sigprocmask(SIG_UNBLOCK, &mask, NULL);
573 sigprocmask(SIG_UNBLOCK, &mask, NULL);
574 wait_input(timeleft(&timo));
580 lcp_close(0, "User request");
585 if (phase == PHASE_NETWORK) {
586 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
587 (*ccp_protent.open)(0);
591 reap_kids(); /* Don't leave dead kids lying around */
595 * If we may want to bring the link up again, transfer
596 * the ppp unit back to the loopback. Set the
597 * real serial device back to its normal mode of operation.
603 disestablish_ppp(ttyfd);
606 * Run disconnector script, if requested.
607 * XXX we may not be able to do this if the line has hung up!
609 if (disconnector && !hungup) {
610 set_up_tty(ttyfd, 1);
611 if (device_script(disconnector, ttyfd, ttyfd) < 0) {
612 warn("disconnect script failed");
614 info("Serial link disconnected.");
627 if (pidfilename[0] != 0
628 && unlink(pidfilename) < 0 && errno != ENOENT)
629 warn("unable to delete pid file: %m");
639 if (holdoff > 0 && need_holdoff) {
640 phase = PHASE_HOLDOFF;
641 TIMEOUT(holdoff_end, NULL, holdoff);
643 if (sigsetjmp(sigjmp, 1) == 0) {
644 sigprocmask(SIG_BLOCK, &mask, NULL);
646 sigprocmask(SIG_UNBLOCK, &mask, NULL);
649 sigprocmask(SIG_UNBLOCK, &mask, NULL);
650 wait_input(timeleft(&timo));
657 phase = PHASE_DORMANT; /* allow signal to end holdoff */
660 } while (phase == PHASE_HOLDOFF);
666 /* Wait for scripts to finish */
667 while (n_children > 0)
675 * detach - detach us from the controlling terminal.
682 if (daemon(0, 0) < 0) {
683 perror("Couldn't detach from controlling terminal");
689 /* update pid file if it has been written already */
695 * Create a file containing our process ID.
703 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
704 _PATH_VARRUN, ifname);
705 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
706 fprintf(pidfile, "%d\n", pid);
707 (void) fclose(pidfile);
709 error("Failed to create pid file %s: %m", pidfilename);
712 slprintf(numbuf, sizeof(numbuf), "%d", pid);
713 script_setenv("PPPD_PID", numbuf);
717 * holdoff_end - called via a timeout when the holdoff period ends.
723 phase = PHASE_DORMANT;
727 * get_input - called when incoming data is available.
735 struct protent *protp;
737 p = inpacket_buf; /* point to beginning of packet buffer */
739 len = read_packet(inpacket_buf);
744 notice("Modem hangup");
746 lcp_lowerdown(0); /* serial link is no longer available */
751 if (debug /*&& (debugflags & DBG_INPACKET)*/)
752 dbglog("rcvd %P", p, len);
754 if (len < PPP_HDRLEN) {
755 MAINDEBUG(("io(): Received short packet."));
759 p += 2; /* Skip address and control */
760 GETSHORT(protocol, p);
764 * Toss all non-LCP packets unless LCP is OPEN.
766 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
767 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
772 * Until we get past the authentication phase, toss all packets
773 * except LCP, LQR and authentication packets.
775 if (phase <= PHASE_AUTHENTICATE
776 && !(protocol == PPP_LCP || protocol == PPP_LQR
777 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
778 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
784 * Upcall the proper protocol input routine.
786 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
787 if (protp->protocol == protocol && protp->enabled_flag) {
788 (*protp->input)(0, p, len);
791 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
792 && protp->datainput != NULL) {
793 (*protp->datainput)(0, p, len);
799 warn("Unsupported protocol (0x%x) received", protocol);
800 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
805 * quit - Clean up state and exit (with an error indication).
814 * die - like quit, except we can specify an exit status.
821 syslog(LOG_INFO, "Exit.");
826 * cleanup - restore anything which needs to be restored before we exit
837 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
838 warn("unable to delete pid file: %m");
846 * close_tty - restore the terminal device and close it.
851 disestablish_ppp(ttyfd);
853 /* drop dtr to hang up */
854 if (!default_device && modem) {
857 * This sleep is in case the serial port has CLOCAL set by default,
858 * and consequently will reassert DTR when we close the device.
865 if (tty_mode != (mode_t) -1) {
866 if (fchmod(ttyfd, tty_mode) != 0) {
867 /* XXX if devnam is a symlink, this will change the link */
868 chmod(devnam, tty_mode);
877 * hangup_modem - hang up the modem by clearing DTR.
879 void hangup_modem(ttyfd)
887 struct timeval c_time; /* time at which to call routine */
888 void *c_arg; /* argument to routine */
889 void (*c_func) __P((void *)); /* routine */
890 struct callout *c_next;
893 static struct callout *callout = NULL; /* Callout list */
894 static struct timeval timenow; /* Current time */
897 * timeout - Schedule a timeout.
899 * Note that this timeout takes the number of seconds, NOT hz (as in
903 timeout(func, arg, time)
904 void (*func) __P((void *));
908 struct callout *newp, *p, **pp;
910 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
915 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
916 fatal("Out of memory in timeout()!");
919 gettimeofday(&timenow, NULL);
920 newp->c_time.tv_sec = timenow.tv_sec + time;
921 newp->c_time.tv_usec = timenow.tv_usec;
924 * Find correct place and link it in.
926 for (pp = &callout; (p = *pp); pp = &p->c_next)
927 if (newp->c_time.tv_sec < p->c_time.tv_sec
928 || (newp->c_time.tv_sec == p->c_time.tv_sec
929 && newp->c_time.tv_usec < p->c_time.tv_usec))
937 * untimeout - Unschedule a timeout.
941 void (*func) __P((void *));
944 struct callout **copp, *freep;
946 MAINDEBUG(("Untimeout %p:%p.", func, arg));
949 * Find first matching timeout and remove it from the list.
951 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
952 if (freep->c_func == func && freep->c_arg == arg) {
953 *copp = freep->c_next;
954 (void) free((char *) freep);
961 * calltimeout - Call any timeout routines which are now due.
968 while (callout != NULL) {
971 if (gettimeofday(&timenow, NULL) < 0)
972 fatal("Failed to get time of day: %m");
973 if (!(p->c_time.tv_sec < timenow.tv_sec
974 || (p->c_time.tv_sec == timenow.tv_sec
975 && p->c_time.tv_usec <= timenow.tv_usec)))
976 break; /* no, it's not time yet */
979 (*p->c_func)(p->c_arg);
987 * timeleft - return the length of time until the next timeout is due.
989 static struct timeval *
996 gettimeofday(&timenow, NULL);
997 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
998 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
999 if (tvp->tv_usec < 0) {
1000 tvp->tv_usec += 1000000;
1003 if (tvp->tv_sec < 0)
1004 tvp->tv_sec = tvp->tv_usec = 0;
1011 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1017 struct sigaction act, oldact;
1019 act.sa_handler = SIG_IGN;
1022 sigaction(sig, &act, &oldact);
1023 sigaction(sig, &oldact, NULL);
1028 * hup - Catch SIGHUP signal.
1030 * Indicates that the physical layer has been disconnected.
1031 * We don't rely on this indication; if the user has sent this
1032 * signal, we just take the link down.
1038 info("Hangup (SIGHUP)");
1041 /* Send the signal to the [dis]connector process(es) also */
1044 siglongjmp(sigjmp, 1);
1049 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1051 * Indicates that we should initiate a graceful disconnect and exit.
1058 info("Terminating on signal %d.", sig);
1059 persist = 0; /* don't try to restart */
1062 /* Send the signal to the [dis]connector process(es) also */
1065 siglongjmp(sigjmp, 1);
1070 * chld - Catch SIGCHLD signal.
1071 * Calls reap_kids to get status for any dead kids.
1078 siglongjmp(sigjmp, 1);
1083 * toggle_debug - Catch SIGUSR1 signal.
1085 * Toggle debug flag.
1094 setlogmask(LOG_UPTO(LOG_DEBUG));
1096 setlogmask(LOG_UPTO(LOG_WARNING));
1102 * open_ccp - Catch SIGUSR2 signal.
1104 * Try to (re)negotiate compression.
1113 siglongjmp(sigjmp, 1);
1118 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1124 static int crashed = 0;
1129 error("Fatal signal %d", sig);
1131 kill_my_pg(SIGTERM);
1137 * device_script - run a program to connect or disconnect the
1141 device_script(program, in, out)
1154 fatal("Failed to create child process: %m");
1178 if (!nodetach && !updetach) {
1180 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1181 if (errfd >= 0 && errfd != 2) {
1187 if (getuid() != uid) {
1188 error("setuid failed");
1192 execl("/bin/sh", "sh", "-c", program, (char *)0);
1193 error("could not exec /bin/sh: %m");
1198 while (waitpid(pid, &status, 0) < 0) {
1201 fatal("error waiting for (dis)connection process: %m");
1205 return (status == 0 ? 0 : -1);
1210 * We maintain a list of child process pids and
1211 * functions to call when they exit.
1216 void (*done) __P((void *));
1218 struct subprocess *next;
1221 struct subprocess *children;
1224 * run-program - execute a program with given arguments,
1225 * but don't wait for it.
1226 * If the program can't be executed, logs an error unless
1227 * must_exist is 0 and the program file doesn't exist.
1228 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1229 * or isn't an executable plain file, or the process ID of the child.
1230 * If done != NULL, (*done)(arg) will be called later (within
1231 * reap_kids) iff the return value is > 0.
1234 run_program(prog, args, must_exist, done, arg)
1238 void (*done) __P((void *));
1242 struct subprocess *chp;
1246 * First check if the file exists and is executable.
1247 * We don't use access() because that would use the
1248 * real user-id, which might not be root, and the script
1249 * might be accessible only to root.
1252 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1253 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1254 if (must_exist || errno != ENOENT)
1255 warn("Can't execute %s: %m", prog);
1261 fatal("Failed to create child process for %s: %m", prog);
1265 /* Leave the current location */
1266 (void) setsid(); /* No controlling tty. */
1267 (void) umask (S_IRWXG|S_IRWXO);
1268 (void) chdir ("/"); /* no current directory. */
1269 setuid(0); /* set real UID = root */
1272 /* Ensure that nothing of our device environment is inherited. */
1278 close (ttyfd); /* tty interface to the ppp device */
1280 /* Don't pass handles to the PPP device, even by accident. */
1281 new_fd = open (_PATH_DEVNULL, O_RDWR);
1284 dup2 (new_fd, 0); /* stdin <- /dev/null */
1287 dup2 (0, 1); /* stdout -> /dev/null */
1288 dup2 (0, 2); /* stderr -> /dev/null */
1292 /* Force the priority back to zero if pppd is running higher. */
1293 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1294 warn("can't reset priority to 0: %m");
1297 /* SysV recommends a second fork at this point. */
1299 /* run the program */
1300 execve(prog, args, script_env);
1301 if (must_exist || errno != ENOENT)
1302 warn("Can't execute %s: %m", prog);
1307 dbglog("Script %s started; pid = %d", prog, pid);
1310 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1312 warn("losing track of %s process", prog);
1318 chp->next = children;
1327 * reap_kids - get status from any dead child processes,
1328 * and log a message for abnormal terminations.
1334 struct subprocess *chp, **prevp;
1336 if (n_children == 0)
1338 while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1340 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1341 if (chp->pid == pid)
1344 dbglog("process %d (%s) finished, status = 0x%x",
1345 pid, (chp? chp->prog: "??"), status);
1346 if (WIFSIGNALED(status)) {
1347 warn("Child process %s (pid %d) terminated with signal %d",
1348 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1350 if (chp && chp->done)
1351 (*chp->done)(chp->arg);
1353 if (pid == -1 && errno != ECHILD)
1354 error("Error waiting for child process: %m");
1359 * log_packet - format a packet and log it.
1362 char line[256]; /* line to be logged accumulated here */
1366 log_packet(p, len, prefix, level)
1372 strlcpy(line, sizeof(line), prefix);
1373 linep = line + strlen(line);
1374 format_packet(p, len, pr_log, NULL);
1376 syslog(level, "%s", line);
1380 * format_packet - make a readable representation of a packet,
1381 * calling `printer(arg, format, ...)' to output it.
1384 format_packet(p, len, printer, arg)
1387 void (*printer) __P((void *, char *, ...));
1393 struct protent *protp;
1395 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1399 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1400 if (proto == protp->protocol)
1402 if (protp != NULL) {
1403 printer(arg, "[%s", protp->name);
1404 n = (*protp->printpkt)(p, len, printer, arg);
1409 printer(arg, "[proto=0x%x]", proto);
1413 for (i = 0; i < len && i < 32; ++i) {
1415 printer(arg, " %.2x", x);
1418 printer(arg, " ...");
1422 pr_log __V((void *arg, char *fmt, ...))
1429 va_start(pvar, fmt);
1434 arg = va_arg(pvar, void *);
1435 fmt = va_arg(pvar, char *);
1438 n = vslprintf(buf, sizeof(buf), fmt, pvar);
1441 if (linep + n + 1 > line + sizeof(line)) {
1442 syslog(LOG_DEBUG, "%s", line);
1445 strlcpy(linep, line + sizeof(line) - linep, buf);
1450 * vslp_printer - used in processing a %P format
1452 struct buffer_info {
1458 vslp_printer __V((void *arg, char *fmt, ...))
1462 struct buffer_info *bi;
1465 va_start(pvar, fmt);
1470 arg = va_arg(pvar, void *);
1471 fmt = va_arg(pvar, char *);
1474 bi = (struct buffer_info *) arg;
1475 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
1483 * print_string - print a readable representation of a string using
1487 print_string(p, len, printer, arg)
1490 void (*printer) __P((void *, char *, ...));
1496 for (; len > 0; --len) {
1498 if (' ' <= c && c <= '~') {
1499 if (c == '\\' || c == '"')
1501 printer(arg, "%c", c);
1505 printer(arg, "\\n");
1508 printer(arg, "\\r");
1511 printer(arg, "\\t");
1514 printer(arg, "\\%.3o", c);
1522 * novm - log an error message saying we ran out of memory, and die.
1528 fatal("Virtual memory exhausted allocating %s\n", msg);
1532 * slprintf - format a message into a buffer. Like sprintf except we
1533 * also specify the length of the output buffer, and we handle
1534 * %r (recursive format), %m (error message), %v (visible string),
1535 * %q (quoted string), %t (current time) and %I (IP address) formats.
1536 * Doesn't do floating-point formats.
1537 * Returns the number of chars put into buf.
1540 slprintf __V((char *buf, int buflen, char *fmt, ...))
1546 va_start(args, fmt);
1552 buf = va_arg(args, char *);
1553 buflen = va_arg(args, int);
1554 fmt = va_arg(args, char *);
1556 n = vslprintf(buf, buflen, fmt, args);
1562 * vslprintf - like slprintf, takes a va_list instead of a list of args.
1564 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1567 vslprintf(buf, buflen, fmt, args)
1574 int width, prec, fillch;
1575 int base, len, neg, quoted;
1576 unsigned long val = 0;
1577 char *str, *f, *buf0;
1582 static char hexchars[] = "0123456789abcdef";
1583 struct buffer_info bufinfo;
1587 while (buflen > 0) {
1588 for (f = fmt; *f != '%' && *f != 0; ++f)
1594 memcpy(buf, fmt, len);
1609 width = va_arg(args, int);
1612 while (isdigit(c)) {
1613 width = width * 10 + c - '0';
1620 prec = va_arg(args, int);
1623 while (isdigit(c)) {
1624 prec = prec * 10 + c - '0';
1635 i = va_arg(args, int);
1644 val = va_arg(args, unsigned int);
1649 val = va_arg(args, unsigned int);
1653 val = (unsigned long) va_arg(args, void *);
1658 str = va_arg(args, char *);
1661 num[0] = va_arg(args, int);
1666 str = strerror(errno);
1669 ip = va_arg(args, u_int32_t);
1671 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
1672 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
1676 f = va_arg(args, char *);
1678 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
1680 /* On the powerpc, a va_list is an array of 1 structure */
1681 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
1689 str += 4; /* chop off the day name */
1690 str[15] = 0; /* chop off year and newline */
1692 case 'v': /* "visible" string */
1693 case 'q': /* quoted string */
1695 p = va_arg(args, unsigned char *);
1696 if (fillch == '0' && prec > 0) {
1699 n = strlen((char *)p);
1700 if (prec > 0 && prec < n)
1703 while (n > 0 && buflen > 0) {
1706 if (!quoted && c >= 0x80) {
1711 if (quoted && (c == '"' || c == '\\'))
1713 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1717 case '\t': OUTCHAR('t'); break;
1718 case '\n': OUTCHAR('n'); break;
1719 case '\b': OUTCHAR('b'); break;
1720 case '\f': OUTCHAR('f'); break;
1723 OUTCHAR(hexchars[c >> 4]);
1724 OUTCHAR(hexchars[c & 0xf]);
1738 case 'P': /* print PPP packet */
1740 bufinfo.len = buflen + 1;
1741 p = va_arg(args, unsigned char *);
1742 n = va_arg(args, int);
1743 format_packet(p, n, vslp_printer, &bufinfo);
1745 buflen = bufinfo.len - 1;
1748 p = va_arg(args, unsigned char *);
1749 for (n = prec; n > 0; --n) {
1753 OUTCHAR(hexchars[(c >> 4) & 0xf]);
1754 OUTCHAR(hexchars[c & 0xf]);
1760 --fmt; /* so %z outputs %z etc. */
1765 str = num + sizeof(num);
1767 while (str > num + neg) {
1768 *--str = hexchars[val % base];
1770 if (--prec <= 0 && val == 0)
1782 len = num + sizeof(num) - 1 - str;
1785 if (prec > 0 && len > prec)
1791 if ((n = width - len) > 0) {
1799 memcpy(buf, str, len);
1808 * script_setenv - set an environment variable value to be used
1809 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1812 script_setenv(var, value)
1815 size_t vl = strlen(var) + strlen(value) + 2;
1817 char *p, *newstring;
1819 newstring = (char *) malloc(vl);
1822 slprintf(newstring, vl, "%s=%s", var, value);
1824 /* check if this variable is already set */
1825 if (script_env != 0) {
1826 for (i = 0; (p = script_env[i]) != 0; ++i) {
1827 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1829 script_env[i] = newstring;
1835 script_env = (char **) malloc(16 * sizeof(char *));
1836 if (script_env == 0)
1841 /* reallocate script_env with more space if needed */
1842 if (i + 1 >= s_env_nalloc) {
1844 char **newenv = (char **) realloc((void *)script_env,
1845 new_n * sizeof(char *));
1848 script_env = newenv;
1849 s_env_nalloc = new_n;
1852 script_env[i] = newstring;
1853 script_env[i+1] = 0;
1857 * script_unsetenv - remove a variable from the environment
1861 script_unsetenv(var)
1864 int vl = strlen(var);
1868 if (script_env == 0)
1870 for (i = 0; (p = script_env[i]) != 0; ++i) {
1871 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1873 while ((script_env[i] = script_env[i+1]) != 0)
1881 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
1882 * always leaves destination null-terminated (for len > 0).
1885 strlcpy(char *dest, size_t len, const char *src)
1889 if (strlen(src) < len)
1892 strncpy(dest, src, len - 1);
1898 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
1899 * always leaves destination null-terminated (for len > 0).
1902 strlcat(char *dest, size_t len, const char *src)
1908 dlen = strlen(dest);
1910 strlcpy(dest + dlen, len - dlen, src);
1914 * logit - does the hard work for fatal et al.
1917 logit(level, fmt, args)
1924 static char nl = '\n';
1926 n = vslprintf(buf, sizeof(buf), fmt, args);
1927 syslog(level, "%s", buf);
1928 if (log_to_stderr && (level != LOG_DEBUG || debug)) {
1929 if (write(2, buf, n) != n
1930 || (buf[n-1] != '\n' && write(2, &nl, 1) != 1))
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);