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.58 1999/03/12 06:07:18 paulus Exp $";
37 #include <sys/param.h>
38 #include <sys/types.h>
41 #include <sys/resource.h>
43 #include <sys/socket.h>
53 #include "pathnames.h"
54 #include "patchlevel.h"
61 extern char *strerror();
66 #endif /* IPX_CHANGE */
72 char ifname[32]; /* Interface name */
73 int ifunit; /* Interface unit number */
75 char *progname; /* Name of this program */
76 char hostname[MAXNAMELEN]; /* Our hostname */
77 static char pidfilename[MAXPATHLEN]; /* name of pid file */
78 static char default_devnam[MAXPATHLEN]; /* name of default device */
79 static pid_t pid; /* Our pid */
80 static uid_t uid; /* Our real user-id */
81 static int conn_running; /* we have a [dis]connector running */
83 int ttyfd = -1; /* Serial port file descriptor */
84 mode_t tty_mode = -1; /* Original access permissions to tty */
85 int baud_rate; /* Actual bits/second for serial device */
86 int hungup; /* terminal has been hung up */
87 int privileged; /* we're running as real uid root */
88 int need_holdoff; /* need holdoff period before restarting */
89 int detached; /* have detached from terminal */
91 int phase; /* where the link is at */
96 static sigjmp_buf sigjmp;
98 char **script_env; /* Env. variable values for scripts */
99 int s_env_nalloc; /* # words avail at script_env */
101 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
102 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
104 static int n_children; /* # child processes still running */
106 static int locked; /* lock() has succeeded */
108 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
110 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
111 int ngroups; /* How many groups valid in groups */
113 /* Prototypes for procedures local to this file. */
115 static void create_pidfile __P((void));
116 static void cleanup __P((void));
117 static void close_tty __P((void));
118 static void get_input __P((void));
119 static void calltimeout __P((void));
120 static struct timeval *timeleft __P((struct timeval *));
121 static void kill_my_pg __P((int));
122 static void hup __P((int));
123 static void term __P((int));
124 static void chld __P((int));
125 static void toggle_debug __P((int));
126 static void open_ccp __P((int));
127 static void bad_signal __P((int));
128 static void holdoff_end __P((void *));
129 static int device_script __P((char *, int, int));
130 static void reap_kids __P((void));
131 static void pr_log __P((void *, char *, ...));
133 extern char *ttyname __P((int));
134 extern char *getlogin __P((void));
135 int main __P((int, char *[]));
139 #define O_NONBLOCK O_NDELAY
143 #define setlogmask(x)
147 * PPP Data Link Layer "protocol" table.
148 * One entry per supported protocol.
149 * The last entry must be NULL.
151 struct protent *protocols[] = {
180 struct protent *protp;
184 phase = PHASE_INITIALIZE;
187 strlcpy(devnam, sizeof(devnam), p);
188 strlcpy(default_devnam, sizeof(default_devnam), devnam);
192 /* Initialize syslog facilities */
194 openlog("pppd", LOG_PID);
196 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
197 setlogmask(LOG_UPTO(LOG_INFO));
200 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
201 option_error("Couldn't get hostname: %m");
204 hostname[MAXNAMELEN-1] = 0;
207 privileged = uid == 0;
208 sprintf(numbuf, "%d", uid);
209 script_setenv("ORIG_UID", numbuf);
211 ngroups = getgroups(NGROUPS_MAX, groups);
214 * Initialize to the standard option set, then parse, in order,
215 * the system options file, the user's options file,
216 * the tty's options file, and the command line arguments.
218 for (i = 0; (protp = protocols[i]) != NULL; ++i)
223 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
224 || !options_from_user())
226 scan_args(argc-1, argv+1); /* look for tty name on command line */
227 if (!options_for_tty()
228 || !parse_args(argc-1, argv+1))
232 * Check that we are running as root.
234 if (geteuid() != 0) {
235 option_error("must be root to run %s, since it is not setuid-root",
240 if (!ppp_available()) {
241 option_error(no_ppp_msg);
246 * Check that the options given are valid and consistent.
248 if (!sys_check_options())
250 auth_check_options();
251 for (i = 0; (protp = protocols[i]) != NULL; ++i)
252 if (protp->check_options != NULL)
253 (*protp->check_options)();
254 if (demand && connector == 0) {
255 option_error("connect script is required for demand-dialling\n");
259 script_setenv("DEVICE", devnam);
260 sprintf(numbuf, "%d", baud_rate);
261 script_setenv("SPEED", numbuf);
264 * If the user has specified the default device name explicitly,
265 * pretend they hadn't.
267 if (!default_device && strcmp(devnam, default_devnam) == 0)
273 * Initialize system-dependent stuff and magic number package.
278 setlogmask(LOG_UPTO(LOG_DEBUG));
281 * Detach ourselves from the terminal, if required,
282 * and identify who is running us.
284 if (!nodetach && !updetach)
290 if (pw != NULL && pw->pw_name != NULL)
295 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
296 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
299 * Compute mask of all interesting signals and install signal handlers
300 * for each. Only one signal handler may be active at a time. Therefore,
301 * all other signals should be masked when any handler is executing.
304 sigaddset(&mask, SIGHUP);
305 sigaddset(&mask, SIGINT);
306 sigaddset(&mask, SIGTERM);
307 sigaddset(&mask, SIGCHLD);
308 sigaddset(&mask, SIGUSR2);
310 #define SIGNAL(s, handler) do { \
311 sa.sa_handler = handler; \
312 if (sigaction(s, &sa, NULL) < 0) \
313 fatal("Couldn't establish signal handler (%d): %m", s); \
318 SIGNAL(SIGHUP, hup); /* Hangup */
319 SIGNAL(SIGINT, term); /* Interrupt */
320 SIGNAL(SIGTERM, term); /* Terminate */
321 SIGNAL(SIGCHLD, chld);
323 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
324 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
327 * Install a handler for other signals which would otherwise
328 * cause pppd to exit without cleaning up.
330 SIGNAL(SIGABRT, bad_signal);
331 SIGNAL(SIGALRM, bad_signal);
332 SIGNAL(SIGFPE, bad_signal);
333 SIGNAL(SIGILL, bad_signal);
334 SIGNAL(SIGPIPE, bad_signal);
335 SIGNAL(SIGQUIT, bad_signal);
336 SIGNAL(SIGSEGV, bad_signal);
338 SIGNAL(SIGBUS, bad_signal);
341 SIGNAL(SIGEMT, bad_signal);
344 SIGNAL(SIGPOLL, bad_signal);
347 SIGNAL(SIGPROF, bad_signal);
350 SIGNAL(SIGSYS, bad_signal);
353 SIGNAL(SIGTRAP, bad_signal);
356 SIGNAL(SIGVTALRM, bad_signal);
359 SIGNAL(SIGXCPU, bad_signal);
362 SIGNAL(SIGXFSZ, bad_signal);
366 * Apparently we can get a SIGPIPE when we call syslog, if
367 * syslogd has died and been restarted. Ignoring it seems
370 signal(SIGPIPE, SIG_IGN);
375 * If we're doing dial-on-demand, set up the interface now.
379 * Open the loopback channel and set it up to be the ppp interface.
383 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
384 (void) sprintf(ifname, "ppp%d", ifunit);
385 script_setenv("IFNAME", ifname);
387 create_pidfile(); /* write pid to file */
390 * Configure the interface and mark it up, etc.
401 * Don't do anything until we see some activity.
404 phase = PHASE_DORMANT;
407 if (sigsetjmp(sigjmp, 1) == 0) {
408 sigprocmask(SIG_BLOCK, &mask, NULL);
410 sigprocmask(SIG_UNBLOCK, &mask, NULL);
413 sigprocmask(SIG_UNBLOCK, &mask, NULL);
414 wait_loop_output(timeleft(&timo));
424 if (get_loop_output())
428 if (kill_link && !persist)
432 * Now we want to bring up the link.
435 info("Starting link");
439 * Lock the device if we've been asked to.
441 if (lockflag && !default_device) {
442 if (lock(devnam) < 0)
448 * Open the serial device and set it up to be the ppp interface.
449 * First we open it in non-blocking mode so we can set the
450 * various termios flags appropriately. If we aren't dialling
451 * out and we want to use the modem lines, we reopen it later
452 * in order to wait for the carrier detect signal from the modem.
457 /* If the user specified the device name, become the
458 user before opening it. */
459 if (!devnam_info.priv)
461 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
462 if (!devnam_info.priv)
467 error("Failed to open %s: %m", devnam);
468 if (!persist || errno != EINTR)
471 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
472 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
473 warn("Couldn't reset non-blocking mode on device: %m");
476 * Do the equivalent of `mesg n' to stop broadcast messages.
478 if (fstat(ttyfd, &statbuf) < 0
479 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
480 warn("Couldn't restrict write permissions to %s: %m", devnam);
482 tty_mode = statbuf.st_mode;
484 /* run connection script */
485 if (connector && connector[0]) {
486 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
488 if (!default_device && modem) {
489 hangup_modem(ttyfd); /* in case modem is off hook */
494 * Set line speed, flow control, etc.
495 * On most systems we set CLOCAL for now so that we can talk
496 * to the modem before carrier comes up. But this has the
497 * side effect that we might miss it if CD drops before we
498 * get to clear CLOCAL below. On systems where we can talk
499 * successfully to the modem with CLOCAL clear and CD down,
500 * we could clear CLOCAL at this point.
502 set_up_tty(ttyfd, 1);
504 if (device_script(connector, ttyfd, ttyfd) < 0) {
505 error("Connect script failed");
509 info("Serial connection established.");
510 sleep(1); /* give it time to set up its terminal */
513 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
514 set_up_tty(ttyfd, 0);
516 /* reopen tty if necessary to wait for carrier */
517 if (connector == NULL && modem) {
519 if (!devnam_info.priv)
521 i = open(devnam, O_RDWR);
522 if (!devnam_info.priv)
527 error("Failed to reopen %s: %m", devnam);
528 if (!persist || errno != EINTR || hungup || kill_link)
534 /* run welcome script, if any */
535 if (welcomer && welcomer[0]) {
536 if (device_script(welcomer, ttyfd, ttyfd) < 0)
537 warn("Welcome script failed");
540 /* set up the serial device as a ppp interface */
541 establish_ppp(ttyfd);
545 info("Using interface ppp%d", ifunit);
546 (void) sprintf(ifname, "ppp%d", ifunit);
547 script_setenv("IFNAME", ifname);
549 create_pidfile(); /* write pid to file */
553 * Start opening the connection and wait for
554 * incoming events (reply, timeout, etc.).
558 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
560 lcp_open(0); /* Start protocol */
562 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
563 if (sigsetjmp(sigjmp, 1) == 0) {
564 sigprocmask(SIG_BLOCK, &mask, NULL);
565 if (kill_link || open_ccp_flag) {
566 sigprocmask(SIG_UNBLOCK, &mask, NULL);
569 sigprocmask(SIG_UNBLOCK, &mask, NULL);
570 wait_input(timeleft(&timo));
576 lcp_close(0, "User request");
581 if (phase == PHASE_NETWORK) {
582 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
583 (*ccp_protent.open)(0);
587 reap_kids(); /* Don't leave dead kids lying around */
591 * If we may want to bring the link up again, transfer
592 * the ppp unit back to the loopback. Set the
593 * real serial device back to its normal mode of operation.
598 disestablish_ppp(ttyfd);
601 * Run disconnector script, if requested.
602 * XXX we may not be able to do this if the line has hung up!
604 if (disconnector && !hungup) {
605 set_up_tty(ttyfd, 1);
606 if (device_script(disconnector, ttyfd, ttyfd) < 0) {
607 warn("disconnect script failed");
609 info("Serial link disconnected.");
622 if (pidfilename[0] != 0
623 && unlink(pidfilename) < 0 && errno != ENOENT)
624 warn("unable to delete pid file: %m");
634 if (holdoff > 0 && need_holdoff) {
635 phase = PHASE_HOLDOFF;
636 TIMEOUT(holdoff_end, NULL, holdoff);
638 if (sigsetjmp(sigjmp, 1) == 0) {
639 sigprocmask(SIG_BLOCK, &mask, NULL);
641 sigprocmask(SIG_UNBLOCK, &mask, NULL);
644 sigprocmask(SIG_UNBLOCK, &mask, NULL);
645 wait_time(timeleft(&timo));
652 phase = PHASE_DORMANT; /* allow signal to end holdoff */
655 } while (phase == PHASE_HOLDOFF);
661 /* Wait for scripts to finish */
662 while (n_children > 0)
670 * detach - detach us from the controlling terminal.
677 if (daemon(0, 0) < 0) {
678 perror("Couldn't detach from controlling terminal");
683 /* update pid file if it has been written already */
689 * Create a file containing our process ID.
697 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
698 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
699 fprintf(pidfile, "%d\n", pid);
700 (void) fclose(pidfile);
702 error("Failed to create pid file %s: %m", pidfilename);
705 sprintf(numbuf, "%d", pid);
706 script_setenv("PPPD_PID", numbuf);
710 * holdoff_end - called via a timeout when the holdoff period ends.
716 phase = PHASE_DORMANT;
720 * get_input - called when incoming data is available.
728 struct protent *protp;
730 p = inpacket_buf; /* point to beginning of packet buffer */
732 len = read_packet(inpacket_buf);
737 notice("Modem hangup");
739 lcp_lowerdown(0); /* serial link is no longer available */
744 if (debug /*&& (debugflags & DBG_INPACKET)*/)
745 log_packet(p, len, "rcvd ", LOG_DEBUG);
747 if (len < PPP_HDRLEN) {
748 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
752 p += 2; /* Skip address and control */
753 GETSHORT(protocol, p);
757 * Toss all non-LCP packets unless LCP is OPEN.
759 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
761 "get_input: Received non-LCP packet when LCP not open."));
766 * Until we get past the authentication phase, toss all packets
767 * except LCP, LQR and authentication packets.
769 if (phase <= PHASE_AUTHENTICATE
770 && !(protocol == PPP_LCP || protocol == PPP_LQR
771 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
772 MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
778 * Upcall the proper protocol input routine.
780 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
781 if (protp->protocol == protocol && protp->enabled_flag) {
782 (*protp->input)(0, p, len);
785 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
786 && protp->datainput != NULL) {
787 (*protp->datainput)(0, p, len);
793 warn("Unsupported protocol (0x%x) received", protocol);
794 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
799 * quit - Clean up state and exit (with an error indication).
808 * die - like quit, except we can specify an exit status.
815 syslog(LOG_INFO, "Exit.");
820 * cleanup - restore anything which needs to be restored before we exit
831 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
832 warn("unable to delete pid file: %m");
840 * close_tty - restore the terminal device and close it.
845 disestablish_ppp(ttyfd);
847 /* drop dtr to hang up */
848 if (!default_device && modem) {
851 * This sleep is in case the serial port has CLOCAL set by default,
852 * and consequently will reassert DTR when we close the device.
859 if (tty_mode != (mode_t) -1) {
860 if (fchmod(ttyfd, tty_mode) != 0) {
861 /* XXX if devnam is a symlink, this will change the link */
862 chmod(devnam, tty_mode);
871 * hangup_modem - hang up the modem by clearing DTR.
873 void hangup_modem(ttyfd)
881 struct timeval c_time; /* time at which to call routine */
882 void *c_arg; /* argument to routine */
883 void (*c_func) __P((void *)); /* routine */
884 struct callout *c_next;
887 static struct callout *callout = NULL; /* Callout list */
888 static struct timeval timenow; /* Current time */
891 * timeout - Schedule a timeout.
893 * Note that this timeout takes the number of seconds, NOT hz (as in
897 timeout(func, arg, time)
898 void (*func) __P((void *));
902 struct callout *newp, *p, **pp;
904 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
905 (long) func, (long) arg, time));
910 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
911 fatal("Out of memory in timeout()!");
914 gettimeofday(&timenow, NULL);
915 newp->c_time.tv_sec = timenow.tv_sec + time;
916 newp->c_time.tv_usec = timenow.tv_usec;
919 * Find correct place and link it in.
921 for (pp = &callout; (p = *pp); pp = &p->c_next)
922 if (newp->c_time.tv_sec < p->c_time.tv_sec
923 || (newp->c_time.tv_sec == p->c_time.tv_sec
924 && newp->c_time.tv_usec < p->c_time.tv_usec))
932 * untimeout - Unschedule a timeout.
936 void (*func) __P((void *));
939 struct callout **copp, *freep;
941 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
944 * Find first matching timeout and remove it from the list.
946 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
947 if (freep->c_func == func && freep->c_arg == arg) {
948 *copp = freep->c_next;
949 (void) free((char *) freep);
956 * calltimeout - Call any timeout routines which are now due.
963 while (callout != NULL) {
966 if (gettimeofday(&timenow, NULL) < 0)
967 fatal("Failed to get time of day: %m");
968 if (!(p->c_time.tv_sec < timenow.tv_sec
969 || (p->c_time.tv_sec == timenow.tv_sec
970 && p->c_time.tv_usec <= timenow.tv_usec)))
971 break; /* no, it's not time yet */
974 (*p->c_func)(p->c_arg);
982 * timeleft - return the length of time until the next timeout is due.
984 static struct timeval *
991 gettimeofday(&timenow, NULL);
992 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
993 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
994 if (tvp->tv_usec < 0) {
995 tvp->tv_usec += 1000000;
999 tvp->tv_sec = tvp->tv_usec = 0;
1006 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1012 struct sigaction act, oldact;
1014 act.sa_handler = SIG_IGN;
1017 sigaction(sig, &act, &oldact);
1018 sigaction(sig, &oldact, NULL);
1023 * hup - Catch SIGHUP signal.
1025 * Indicates that the physical layer has been disconnected.
1026 * We don't rely on this indication; if the user has sent this
1027 * signal, we just take the link down.
1033 info("Hangup (SIGHUP)");
1036 /* Send the signal to the [dis]connector process(es) also */
1039 siglongjmp(sigjmp, 1);
1044 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1046 * Indicates that we should initiate a graceful disconnect and exit.
1053 info("Terminating on signal %d.", sig);
1054 persist = 0; /* don't try to restart */
1057 /* Send the signal to the [dis]connector process(es) also */
1060 siglongjmp(sigjmp, 1);
1065 * chld - Catch SIGCHLD signal.
1066 * Calls reap_kids to get status for any dead kids.
1073 siglongjmp(sigjmp, 1);
1078 * toggle_debug - Catch SIGUSR1 signal.
1080 * Toggle debug flag.
1089 setlogmask(LOG_UPTO(LOG_DEBUG));
1091 setlogmask(LOG_UPTO(LOG_WARNING));
1097 * open_ccp - Catch SIGUSR2 signal.
1099 * Try to (re)negotiate compression.
1108 siglongjmp(sigjmp, 1);
1113 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1119 static int crashed = 0;
1124 error("Fatal signal %d", sig);
1126 kill_my_pg(SIGTERM);
1132 * device_script - run a program to connect or disconnect the
1136 device_script(program, in, out)
1149 fatal("Failed to create child process: %m");
1173 if (!nodetach && !updetach) {
1175 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1176 if (errfd >= 0 && errfd != 2) {
1182 if (getuid() != uid) {
1183 syslog(LOG_ERR, "setuid failed");
1187 execl("/bin/sh", "sh", "-c", program, (char *)0);
1188 syslog(LOG_ERR, "could not exec /bin/sh: %m");
1193 while (waitpid(pid, &status, 0) < 0) {
1196 fatal("error waiting for (dis)connection process: %m");
1200 return (status == 0 ? 0 : -1);
1205 * We maintain a list of child process pids and
1206 * functions to call when they exit.
1211 void (*done) __P((void *));
1213 struct subprocess *next;
1216 struct subprocess *children;
1219 * run-program - execute a program with given arguments,
1220 * but don't wait for it.
1221 * If the program can't be executed, logs an error unless
1222 * must_exist is 0 and the program file doesn't exist.
1223 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1224 * or isn't an executable plain file, or the process ID of the child.
1225 * If done != NULL, (*done)(arg) will be called later (within
1226 * reap_kids) iff the return value is > 0.
1229 run_program(prog, args, must_exist, done, arg)
1233 void (*done) __P((void *));
1237 struct subprocess *chp;
1241 * First check if the file exists and is executable.
1242 * We don't use access() because that would use the
1243 * real user-id, which might not be root, and the script
1244 * might be accessible only to root.
1247 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1248 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1249 if (must_exist || errno != ENOENT)
1250 warn("Can't execute %s: %m", prog);
1256 fatal("Failed to create child process for %s: %m", prog);
1260 /* Leave the current location */
1261 (void) setsid(); /* No controlling tty. */
1262 (void) umask (S_IRWXG|S_IRWXO);
1263 (void) chdir ("/"); /* no current directory. */
1264 setuid(0); /* set real UID = root */
1267 /* Ensure that nothing of our device environment is inherited. */
1273 close (ttyfd); /* tty interface to the ppp device */
1275 /* Don't pass handles to the PPP device, even by accident. */
1276 new_fd = open (_PATH_DEVNULL, O_RDWR);
1279 dup2 (new_fd, 0); /* stdin <- /dev/null */
1282 dup2 (0, 1); /* stdout -> /dev/null */
1283 dup2 (0, 2); /* stderr -> /dev/null */
1287 /* Force the priority back to zero if pppd is running higher. */
1288 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1289 syslog(LOG_WARNING, "can't reset priority to 0: %m");
1292 /* SysV recommends a second fork at this point. */
1294 /* run the program */
1295 execve(prog, args, script_env);
1296 if (must_exist || errno != ENOENT)
1297 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1302 dbglog("Script %s started; pid = %d", prog, pid);
1305 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1307 warn("losing track of %s process", prog);
1313 chp->next = children;
1322 * reap_kids - get status from any dead child processes,
1323 * and log a message for abnormal terminations.
1329 struct subprocess *chp, **prevp;
1331 if (n_children == 0)
1333 while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1335 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1336 if (chp->pid == pid)
1339 dbglog("process %d (%s) finished, status = 0x%x",
1340 pid, (chp? chp->prog: "??"), status);
1341 if (WIFSIGNALED(status)) {
1342 warn("Child process %s (pid %d) terminated with signal %d",
1343 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1345 if (chp && chp->done)
1346 (*chp->done)(chp->arg);
1348 if (pid == -1 && errno != ECHILD)
1349 error("Error waiting for child process: %m");
1354 * log_packet - format a packet and log it.
1357 char line[256]; /* line to be logged accumulated here */
1361 log_packet(p, len, prefix, level)
1367 strlcpy(line, sizeof(line), prefix);
1368 linep = line + strlen(line);
1369 format_packet(p, len, pr_log, NULL);
1371 syslog(level, "%s", line);
1375 * format_packet - make a readable representation of a packet,
1376 * calling `printer(arg, format, ...)' to output it.
1379 format_packet(p, len, printer, arg)
1382 void (*printer) __P((void *, char *, ...));
1388 struct protent *protp;
1390 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1394 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1395 if (proto == protp->protocol)
1397 if (protp != NULL) {
1398 printer(arg, "[%s", protp->name);
1399 n = (*protp->printpkt)(p, len, printer, arg);
1404 printer(arg, "[proto=0x%x]", proto);
1408 for (i = 0; i < len && i < 32; ++i) {
1410 printer(arg, " %.2x", x);
1413 printer(arg, " ...");
1417 pr_log __V((void *arg, char *fmt, ...))
1424 va_start(pvar, fmt);
1429 arg = va_arg(pvar, void *);
1430 fmt = va_arg(pvar, char *);
1433 n = vslprintf(buf, sizeof(buf), fmt, pvar);
1436 if (linep + n + 1 > line + sizeof(line)) {
1437 syslog(LOG_DEBUG, "%s", line);
1440 strlcpy(linep, line + sizeof(line) - linep, buf);
1445 * print_string - print a readable representation of a string using
1449 print_string(p, len, printer, arg)
1452 void (*printer) __P((void *, char *, ...));
1458 for (; len > 0; --len) {
1460 if (' ' <= c && c <= '~') {
1461 if (c == '\\' || c == '"')
1463 printer(arg, "%c", c);
1467 printer(arg, "\\n");
1470 printer(arg, "\\r");
1473 printer(arg, "\\t");
1476 printer(arg, "\\%.3o", c);
1484 * novm - log an error message saying we ran out of memory, and die.
1490 fatal("Virtual memory exhausted allocating %s\n", msg);
1494 * slprintf - format a message into a buffer. Like sprintf except we
1495 * also specify the length of the output buffer, and we handle
1496 * %r (recursive format), %m (error message), %v (visible string),
1497 * %q (quoted string), %t (current time) and %I (IP address) formats.
1498 * Doesn't do floating-point formats.
1499 * Returns the number of chars put into buf.
1502 slprintf __V((char *buf, int buflen, char *fmt, ...))
1508 va_start(args, fmt);
1514 buf = va_arg(args, char *);
1515 buflen = va_arg(args, int);
1516 fmt = va_arg(args, char *);
1518 n = vslprintf(buf, buflen, fmt, args);
1524 * vslprintf - like slprintf, takes a va_list instead of a list of args.
1526 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1529 vslprintf(buf, buflen, fmt, args)
1536 int width, prec, fillch;
1537 int base, len, neg, quoted;
1538 unsigned long val = 0;
1539 char *str, *f, *buf0;
1543 static char hexchars[] = "0123456789abcdef";
1547 while (buflen > 0) {
1548 for (f = fmt; *f != '%' && *f != 0; ++f)
1554 memcpy(buf, fmt, len);
1569 width = va_arg(args, int);
1572 while (isdigit(c)) {
1573 width = width * 10 + c - '0';
1580 prec = va_arg(args, int);
1583 while (isdigit(c)) {
1584 prec = prec * 10 + c - '0';
1595 i = va_arg(args, int);
1604 val = va_arg(args, unsigned int);
1608 val = va_arg(args, unsigned int);
1612 val = (unsigned long) va_arg(args, void *);
1617 str = va_arg(args, char *);
1620 num[0] = va_arg(args, int);
1625 str = strerror(errno);
1628 str = ip_ntoa(va_arg(args, u_int32_t));
1631 f = va_arg(args, char *);
1633 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
1635 /* On the powerpc, a va_list is an array of 1 structure */
1636 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
1644 str += 4; /* chop off the day name */
1645 str[15] = 0; /* chop off year and newline */
1647 case 'v': /* "visible" string */
1648 case 'q': /* quoted string */
1650 p = va_arg(args, unsigned char *);
1651 if (fillch == '0' && prec > 0) {
1654 n = strlen((char *)p);
1655 if (prec > 0 && prec < n)
1658 while (n > 0 && buflen > 0) {
1661 if (!quoted && c >= 0x80) {
1666 if (quoted && (c == '"' || c == '\\'))
1668 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1672 case '\t': OUTCHAR('t'); break;
1673 case '\n': OUTCHAR('n'); break;
1674 case '\b': OUTCHAR('b'); break;
1675 case '\f': OUTCHAR('f'); break;
1678 OUTCHAR(hexchars[c >> 4]);
1679 OUTCHAR(hexchars[c & 0xf]);
1696 --fmt; /* so %z outputs %z etc. */
1701 str = num + sizeof(num);
1703 while (str > num + neg) {
1704 *--str = hexchars[val % base];
1706 if (--prec <= 0 && val == 0)
1718 len = num + sizeof(num) - 1 - str;
1721 if (prec > 0 && len > prec)
1727 if ((n = width - len) > 0) {
1735 memcpy(buf, str, len);
1744 * script_setenv - set an environment variable value to be used
1745 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1748 script_setenv(var, value)
1751 size_t vl = strlen(var) + strlen(value) + 2;
1753 char *p, *newstring;
1755 newstring = (char *) malloc(vl);
1758 slprintf(newstring, vl, "%s=%s", var, value);
1760 /* check if this variable is already set */
1761 if (script_env != 0) {
1762 for (i = 0; (p = script_env[i]) != 0; ++i) {
1763 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1765 script_env[i] = newstring;
1771 script_env = (char **) malloc(16 * sizeof(char *));
1772 if (script_env == 0)
1777 /* reallocate script_env with more space if needed */
1778 if (i + 1 >= s_env_nalloc) {
1780 char **newenv = (char **) realloc((void *)script_env,
1781 new_n * sizeof(char *));
1784 script_env = newenv;
1785 s_env_nalloc = new_n;
1788 script_env[i] = newstring;
1789 script_env[i+1] = 0;
1793 * script_unsetenv - remove a variable from the environment
1797 script_unsetenv(var)
1800 int vl = strlen(var);
1804 if (script_env == 0)
1806 for (i = 0; (p = script_env[i]) != 0; ++i) {
1807 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1809 while ((script_env[i] = script_env[i+1]) != 0)
1817 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
1818 * always leaves destination null-terminated (for len > 0).
1821 strlcpy(char *dest, size_t len, const char *src)
1825 if (strlen(src) < len)
1828 strncpy(dest, src, len - 1);
1834 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
1835 * always leaves destination null-terminated (for len > 0).
1838 strlcat(char *dest, size_t len, const char *src)
1844 dlen = strlen(dest);
1846 strlcpy(dest + dlen, len - dlen, src);
1850 * fatal - log an error message and die horribly.
1853 fatal __V((char *fmt, ...))
1858 va_start(pvar, fmt);
1862 fmt = va_arg(pvar, char *);
1865 vslprintf(line, sizeof(line), fmt, pvar);
1868 syslog(LOG_ERR, "%s", line);
1870 die(1); /* as promised */
1874 * error - log an error message.
1877 error __V((char *fmt, ...))
1882 va_start(pvar, fmt);
1886 fmt = va_arg(pvar, char *);
1889 vslprintf(line, sizeof(line), fmt, pvar);
1892 syslog(LOG_ERR, "%s", line);
1896 * warn - log a warning message.
1899 warn __V((char *fmt, ...))
1904 va_start(pvar, fmt);
1908 fmt = va_arg(pvar, char *);
1911 vslprintf(line, sizeof(line), fmt, pvar);
1914 syslog(LOG_WARNING, "%s", line);
1918 * notice - log a notice-level message.
1921 notice __V((char *fmt, ...))
1926 va_start(pvar, fmt);
1930 fmt = va_arg(pvar, char *);
1933 vslprintf(line, sizeof(line), fmt, pvar);
1936 syslog(LOG_NOTICE, "%s", line);
1940 * info - log an informational message.
1943 info __V((char *fmt, ...))
1948 va_start(pvar, fmt);
1952 fmt = va_arg(pvar, char *);
1955 vslprintf(line, sizeof(line), fmt, pvar);
1958 syslog(LOG_INFO, "%s", line);
1962 * dbglog - log a debug message.
1965 dbglog __V((char *fmt, ...))
1970 va_start(pvar, fmt);
1974 fmt = va_arg(pvar, char *);
1977 vslprintf(line, sizeof(line), fmt, pvar);
1980 syslog(LOG_DEBUG, "%s", line);