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.63 1999/03/19 04:23:40 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 static struct timeval start_time; /* Time when link was started. */
120 struct ppp_stats link_stats;
121 int link_stats_valid;
123 /* Prototypes for procedures local to this file. */
125 static void create_pidfile __P((void));
126 static void cleanup __P((void));
127 static void close_tty __P((void));
128 static void hangup_modem __P((int));
129 static void get_input __P((void));
130 static void calltimeout __P((void));
131 static struct timeval *timeleft __P((struct timeval *));
132 static void kill_my_pg __P((int));
133 static void hup __P((int));
134 static void term __P((int));
135 static void chld __P((int));
136 static void toggle_debug __P((int));
137 static void open_ccp __P((int));
138 static void bad_signal __P((int));
139 static void holdoff_end __P((void *));
140 static int device_script __P((char *, int));
141 static void reap_kids __P((void));
142 static void pr_log __P((void *, char *, ...));
143 static void logit __P((int, char *, va_list));
144 static void vslp_printer __P((void *, char *, ...));
145 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
148 extern char *ttyname __P((int));
149 extern char *getlogin __P((void));
150 int main __P((int, char *[]));
154 #define O_NONBLOCK O_NDELAY
158 #define setlogmask(x)
162 * PPP Data Link Layer "protocol" table.
163 * One entry per supported protocol.
164 * The last entry must be NULL.
166 struct protent *protocols[] = {
195 struct protent *protp;
200 phase = PHASE_INITIALIZE;
203 strlcpy(devnam, p, sizeof(devnam));
204 strlcpy(default_devnam, devnam, sizeof(default_devnam));
208 /* Initialize syslog facilities */
210 openlog("pppd", LOG_PID);
212 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
213 setlogmask(LOG_UPTO(LOG_INFO));
216 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
217 option_error("Couldn't get hostname: %m");
220 hostname[MAXNAMELEN-1] = 0;
223 privileged = uid == 0;
224 slprintf(numbuf, sizeof(numbuf), "%d", uid);
225 script_setenv("ORIG_UID", numbuf);
227 ngroups = getgroups(NGROUPS_MAX, groups);
230 * Initialize to the standard option set, then parse, in order,
231 * the system options file, the user's options file,
232 * the tty's options file, and the command line arguments.
234 for (i = 0; (protp = protocols[i]) != NULL; ++i)
239 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
240 || !options_from_user())
242 scan_args(argc-1, argv+1); /* look for tty name on command line */
243 if (!options_for_tty()
244 || !parse_args(argc-1, argv+1))
248 * Check that we are running as root.
250 if (geteuid() != 0) {
251 option_error("must be root to run %s, since it is not setuid-root",
256 if (!ppp_available()) {
257 option_error(no_ppp_msg);
262 * Check that the options given are valid and consistent.
264 if (!sys_check_options())
266 auth_check_options();
267 for (i = 0; (protp = protocols[i]) != NULL; ++i)
268 if (protp->check_options != NULL)
269 (*protp->check_options)();
270 if (demand && connector == 0) {
271 option_error("connect script is required for demand-dialling\n");
275 script_setenv("DEVICE", devnam);
276 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
277 script_setenv("SPEED", numbuf);
280 * If the user has specified the default device name explicitly,
281 * pretend they hadn't.
283 if (!default_device && strcmp(devnam, default_devnam) == 0)
287 log_to_fd = !default_device? 1: -1; /* default to stdout */
290 * Initialize system-dependent stuff and magic number package.
295 setlogmask(LOG_UPTO(LOG_DEBUG));
298 * Detach ourselves from the terminal, if required,
299 * and identify who is running us.
301 if (!nodetach && !updetach)
307 if (pw != NULL && pw->pw_name != NULL)
312 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
313 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
316 * Compute mask of all interesting signals and install signal handlers
317 * for each. Only one signal handler may be active at a time. Therefore,
318 * all other signals should be masked when any handler is executing.
321 sigaddset(&mask, SIGHUP);
322 sigaddset(&mask, SIGINT);
323 sigaddset(&mask, SIGTERM);
324 sigaddset(&mask, SIGCHLD);
325 sigaddset(&mask, SIGUSR2);
327 #define SIGNAL(s, handler) do { \
328 sa.sa_handler = handler; \
329 if (sigaction(s, &sa, NULL) < 0) \
330 fatal("Couldn't establish signal handler (%d): %m", s); \
335 SIGNAL(SIGHUP, hup); /* Hangup */
336 SIGNAL(SIGINT, term); /* Interrupt */
337 SIGNAL(SIGTERM, term); /* Terminate */
338 SIGNAL(SIGCHLD, chld);
340 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
341 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
344 * Install a handler for other signals which would otherwise
345 * cause pppd to exit without cleaning up.
347 SIGNAL(SIGABRT, bad_signal);
348 SIGNAL(SIGALRM, bad_signal);
349 SIGNAL(SIGFPE, bad_signal);
350 SIGNAL(SIGILL, bad_signal);
351 SIGNAL(SIGPIPE, bad_signal);
352 SIGNAL(SIGQUIT, bad_signal);
353 SIGNAL(SIGSEGV, bad_signal);
355 SIGNAL(SIGBUS, bad_signal);
358 SIGNAL(SIGEMT, bad_signal);
361 SIGNAL(SIGPOLL, bad_signal);
364 SIGNAL(SIGPROF, bad_signal);
367 SIGNAL(SIGSYS, bad_signal);
370 SIGNAL(SIGTRAP, bad_signal);
373 SIGNAL(SIGVTALRM, bad_signal);
376 SIGNAL(SIGXCPU, bad_signal);
379 SIGNAL(SIGXFSZ, bad_signal);
383 * Apparently we can get a SIGPIPE when we call syslog, if
384 * syslogd has died and been restarted. Ignoring it seems
387 signal(SIGPIPE, SIG_IGN);
392 * If we're doing dial-on-demand, set up the interface now.
396 * Open the loopback channel and set it up to be the ppp interface.
398 fd_loop = open_ppp_loopback();
400 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
401 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
402 script_setenv("IFNAME", ifname);
404 create_pidfile(); /* write pid to file */
407 * Configure the interface and mark it up, etc.
418 * Don't do anything until we see some activity.
421 phase = PHASE_DORMANT;
425 if (sigsetjmp(sigjmp, 1) == 0) {
426 sigprocmask(SIG_BLOCK, &mask, NULL);
428 sigprocmask(SIG_UNBLOCK, &mask, NULL);
431 sigprocmask(SIG_UNBLOCK, &mask, NULL);
432 wait_input(timeleft(&timo));
442 if (get_loop_output())
447 if (kill_link && !persist)
451 * Now we want to bring up the link.
454 info("Starting link");
458 * Lock the device if we've been asked to.
460 if (lockflag && !default_device) {
461 if (lock(devnam) < 0)
467 * Open the serial device and set it up to be the ppp interface.
468 * First we open it in non-blocking mode so we can set the
469 * various termios flags appropriately. If we aren't dialling
470 * out and we want to use the modem lines, we reopen it later
471 * in order to wait for the carrier detect signal from the modem.
476 /* If the user specified the device name, become the
477 user before opening it. */
478 if (!devnam_info.priv)
480 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
481 if (!devnam_info.priv)
486 error("Failed to open %s: %m", devnam);
487 if (!persist || errno != EINTR)
490 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
491 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
492 warn("Couldn't reset non-blocking mode on device: %m");
495 * Do the equivalent of `mesg n' to stop broadcast messages.
497 if (fstat(ttyfd, &statbuf) < 0
498 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
499 warn("Couldn't restrict write permissions to %s: %m", devnam);
501 tty_mode = statbuf.st_mode;
503 /* run connection script */
504 if (connector && connector[0]) {
505 MAINDEBUG(("Connecting with <%s>", connector));
507 if (!default_device && modem) {
508 hangup_modem(ttyfd); /* in case modem is off hook */
513 * Set line speed, flow control, etc.
514 * On most systems we set CLOCAL for now so that we can talk
515 * to the modem before carrier comes up. But this has the
516 * side effect that we might miss it if CD drops before we
517 * get to clear CLOCAL below. On systems where we can talk
518 * successfully to the modem with CLOCAL clear and CD down,
519 * we could clear CLOCAL at this point.
521 set_up_tty(ttyfd, 1);
523 if (device_script(connector, ttyfd) < 0) {
524 error("Connect script failed");
528 info("Serial connection established.");
529 sleep(1); /* give it time to set up its terminal */
532 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
533 set_up_tty(ttyfd, 0);
535 /* reopen tty if necessary to wait for carrier */
536 if (connector == NULL && modem) {
538 if ((i = open(devnam, O_RDWR)) >= 0)
541 error("Failed to reopen %s: %m", devnam);
542 if (!persist || errno != EINTR || hungup || kill_link)
548 /* run welcome script, if any */
549 if (welcomer && welcomer[0]) {
550 if (device_script(welcomer, ttyfd) < 0)
551 warn("Welcome script failed");
554 /* set up the serial device as a ppp interface */
555 fd_ppp = establish_ppp(ttyfd);
559 info("Using interface ppp%d", ifunit);
560 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
561 script_setenv("IFNAME", ifname);
563 create_pidfile(); /* write pid to file */
567 * Start opening the connection and wait for
568 * incoming events (reply, timeout, etc.).
570 notice("Connect: %s <--> %s", ifname, devnam);
571 gettimeofday(&start_time, NULL);
573 lcp_open(0); /* Start protocol */
576 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
577 if (sigsetjmp(sigjmp, 1) == 0) {
578 sigprocmask(SIG_BLOCK, &mask, NULL);
579 if (kill_link || open_ccp_flag) {
580 sigprocmask(SIG_UNBLOCK, &mask, NULL);
583 sigprocmask(SIG_UNBLOCK, &mask, NULL);
584 wait_input(timeleft(&timo));
591 lcp_close(0, "User request");
595 if (phase == PHASE_NETWORK) {
596 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
597 (*ccp_protent.open)(0);
601 reap_kids(); /* Don't leave dead kids lying around */
605 * Print connect time and statistics.
607 if (gettimeofday(&now, NULL) >= 0) {
608 int t = now.tv_sec - start_time.tv_sec;
609 t = (t + 5) / 6; /* now in 1/10ths of minutes */
610 info("Connect time %d.%d minutes", t/10, t%10);
612 if (link_stats_valid) {
613 info("Send %d bytes, received %d bytes",
614 link_stats.p.ppp_obytes, link_stats.p.ppp_ibytes);
618 * If we may want to bring the link up again, transfer
619 * the ppp unit back to the loopback. Set the
620 * real serial device back to its normal mode of operation.
626 disestablish_ppp(ttyfd);
629 * Run disconnector script, if requested.
630 * XXX we may not be able to do this if the line has hung up!
632 if (disconnector && !hungup) {
633 set_up_tty(ttyfd, 1);
634 if (device_script(disconnector, ttyfd) < 0) {
635 warn("disconnect script failed");
637 info("Serial link disconnected.");
652 if (pidfilename[0] != 0
653 && unlink(pidfilename) < 0 && errno != ENOENT)
654 warn("unable to delete pid file: %m");
664 if (holdoff > 0 && need_holdoff) {
665 phase = PHASE_HOLDOFF;
666 TIMEOUT(holdoff_end, NULL, holdoff);
668 if (sigsetjmp(sigjmp, 1) == 0) {
669 sigprocmask(SIG_BLOCK, &mask, NULL);
671 sigprocmask(SIG_UNBLOCK, &mask, NULL);
674 sigprocmask(SIG_UNBLOCK, &mask, NULL);
675 wait_input(timeleft(&timo));
682 phase = PHASE_DORMANT; /* allow signal to end holdoff */
685 } while (phase == PHASE_HOLDOFF);
691 /* Wait for scripts to finish */
692 while (n_children > 0)
700 * detach - detach us from the controlling terminal.
707 if (daemon(0, 0) < 0) {
708 perror("Couldn't detach from controlling terminal");
714 /* update pid file if it has been written already */
720 * Create a file containing our process ID.
728 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
729 _PATH_VARRUN, ifname);
730 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
731 fprintf(pidfile, "%d\n", pid);
732 (void) fclose(pidfile);
734 error("Failed to create pid file %s: %m", pidfilename);
737 slprintf(numbuf, sizeof(numbuf), "%d", pid);
738 script_setenv("PPPD_PID", numbuf);
742 * holdoff_end - called via a timeout when the holdoff period ends.
748 phase = PHASE_DORMANT;
752 * get_input - called when incoming data is available.
760 struct protent *protp;
762 p = inpacket_buf; /* point to beginning of packet buffer */
764 len = read_packet(inpacket_buf);
769 notice("Modem hangup");
771 lcp_lowerdown(0); /* serial link is no longer available */
776 if (debug /*&& (debugflags & DBG_INPACKET)*/)
777 dbglog("rcvd %P", p, len);
779 if (len < PPP_HDRLEN) {
780 MAINDEBUG(("io(): Received short packet."));
784 p += 2; /* Skip address and control */
785 GETSHORT(protocol, p);
789 * Toss all non-LCP packets unless LCP is OPEN.
791 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
792 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
797 * Until we get past the authentication phase, toss all packets
798 * except LCP, LQR and authentication packets.
800 if (phase <= PHASE_AUTHENTICATE
801 && !(protocol == PPP_LCP || protocol == PPP_LQR
802 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
803 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
809 * Upcall the proper protocol input routine.
811 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
812 if (protp->protocol == protocol && protp->enabled_flag) {
813 (*protp->input)(0, p, len);
816 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
817 && protp->datainput != NULL) {
818 (*protp->datainput)(0, p, len);
824 warn("Unsupported protocol (0x%x) received", protocol);
825 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
830 * die - clean up state and exit with the specified status.
837 syslog(LOG_INFO, "Exit.");
842 * cleanup - restore anything which needs to be restored before we exit
853 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
854 warn("unable to delete pid file: %m");
862 * close_tty - restore the terminal device and close it.
867 disestablish_ppp(ttyfd);
869 /* drop dtr to hang up */
870 if (!default_device && modem) {
873 * This sleep is in case the serial port has CLOCAL set by default,
874 * and consequently will reassert DTR when we close the device.
881 if (tty_mode != (mode_t) -1) {
882 if (fchmod(ttyfd, tty_mode) != 0) {
883 /* XXX if devnam is a symlink, this will change the link */
884 chmod(devnam, tty_mode);
893 * hangup_modem - hang up the modem by clearing DTR.
904 struct timeval c_time; /* time at which to call routine */
905 void *c_arg; /* argument to routine */
906 void (*c_func) __P((void *)); /* routine */
907 struct callout *c_next;
910 static struct callout *callout = NULL; /* Callout list */
911 static struct timeval timenow; /* Current time */
914 * timeout - Schedule a timeout.
916 * Note that this timeout takes the number of seconds, NOT hz (as in
920 timeout(func, arg, time)
921 void (*func) __P((void *));
925 struct callout *newp, *p, **pp;
927 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
932 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
933 fatal("Out of memory in timeout()!");
936 gettimeofday(&timenow, NULL);
937 newp->c_time.tv_sec = timenow.tv_sec + time;
938 newp->c_time.tv_usec = timenow.tv_usec;
941 * Find correct place and link it in.
943 for (pp = &callout; (p = *pp); pp = &p->c_next)
944 if (newp->c_time.tv_sec < p->c_time.tv_sec
945 || (newp->c_time.tv_sec == p->c_time.tv_sec
946 && newp->c_time.tv_usec < p->c_time.tv_usec))
954 * untimeout - Unschedule a timeout.
958 void (*func) __P((void *));
961 struct callout **copp, *freep;
963 MAINDEBUG(("Untimeout %p:%p.", func, arg));
966 * Find first matching timeout and remove it from the list.
968 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
969 if (freep->c_func == func && freep->c_arg == arg) {
970 *copp = freep->c_next;
971 (void) free((char *) freep);
978 * calltimeout - Call any timeout routines which are now due.
985 while (callout != NULL) {
988 if (gettimeofday(&timenow, NULL) < 0)
989 fatal("Failed to get time of day: %m");
990 if (!(p->c_time.tv_sec < timenow.tv_sec
991 || (p->c_time.tv_sec == timenow.tv_sec
992 && p->c_time.tv_usec <= timenow.tv_usec)))
993 break; /* no, it's not time yet */
996 (*p->c_func)(p->c_arg);
1004 * timeleft - return the length of time until the next timeout is due.
1006 static struct timeval *
1008 struct timeval *tvp;
1010 if (callout == NULL)
1013 gettimeofday(&timenow, NULL);
1014 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1015 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1016 if (tvp->tv_usec < 0) {
1017 tvp->tv_usec += 1000000;
1020 if (tvp->tv_sec < 0)
1021 tvp->tv_sec = tvp->tv_usec = 0;
1028 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1034 struct sigaction act, oldact;
1036 act.sa_handler = SIG_IGN;
1039 sigaction(sig, &act, &oldact);
1040 sigaction(sig, &oldact, NULL);
1045 * hup - Catch SIGHUP signal.
1047 * Indicates that the physical layer has been disconnected.
1048 * We don't rely on this indication; if the user has sent this
1049 * signal, we just take the link down.
1055 info("Hangup (SIGHUP)");
1058 /* Send the signal to the [dis]connector process(es) also */
1061 siglongjmp(sigjmp, 1);
1066 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1068 * Indicates that we should initiate a graceful disconnect and exit.
1075 info("Terminating on signal %d.", sig);
1076 persist = 0; /* don't try to restart */
1079 /* Send the signal to the [dis]connector process(es) also */
1082 siglongjmp(sigjmp, 1);
1087 * chld - Catch SIGCHLD signal.
1088 * Calls reap_kids to get status for any dead kids.
1095 siglongjmp(sigjmp, 1);
1100 * toggle_debug - Catch SIGUSR1 signal.
1102 * Toggle debug flag.
1111 setlogmask(LOG_UPTO(LOG_DEBUG));
1113 setlogmask(LOG_UPTO(LOG_WARNING));
1119 * open_ccp - Catch SIGUSR2 signal.
1121 * Try to (re)negotiate compression.
1130 siglongjmp(sigjmp, 1);
1135 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1141 static int crashed = 0;
1146 error("Fatal signal %d", sig);
1148 kill_my_pg(SIGTERM);
1154 * device_script - run a program to connect or disconnect the
1158 device_script(program, inout)
1171 fatal("Failed to create child process: %m");
1179 int newio = dup(inout);
1183 if (log_to_fd >= 0) {
1188 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1189 if (errfd >= 0 && errfd != 2) {
1200 if (getuid() != uid) {
1201 error("setuid failed");
1205 execl("/bin/sh", "sh", "-c", program, (char *)0);
1206 error("could not exec /bin/sh: %m");
1211 while (waitpid(pid, &status, 0) < 0) {
1214 fatal("error waiting for (dis)connection process: %m");
1218 return (status == 0 ? 0 : -1);
1223 * We maintain a list of child process pids and
1224 * functions to call when they exit.
1229 void (*done) __P((void *));
1231 struct subprocess *next;
1234 struct subprocess *children;
1237 * run-program - execute a program with given arguments,
1238 * but don't wait for it.
1239 * If the program can't be executed, logs an error unless
1240 * must_exist is 0 and the program file doesn't exist.
1241 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1242 * or isn't an executable plain file, or the process ID of the child.
1243 * If done != NULL, (*done)(arg) will be called later (within
1244 * reap_kids) iff the return value is > 0.
1247 run_program(prog, args, must_exist, done, arg)
1251 void (*done) __P((void *));
1255 struct subprocess *chp;
1259 * First check if the file exists and is executable.
1260 * We don't use access() because that would use the
1261 * real user-id, which might not be root, and the script
1262 * might be accessible only to root.
1265 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1266 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1267 if (must_exist || errno != ENOENT)
1268 warn("Can't execute %s: %m", prog);
1274 fatal("Failed to create child process for %s: %m", prog);
1278 /* Leave the current location */
1279 (void) setsid(); /* No controlling tty. */
1280 (void) umask (S_IRWXG|S_IRWXO);
1281 (void) chdir ("/"); /* no current directory. */
1282 setuid(0); /* set real UID = root */
1285 /* Ensure that nothing of our device environment is inherited. */
1291 close (ttyfd); /* tty interface to the ppp device */
1293 /* Don't pass handles to the PPP device, even by accident. */
1294 new_fd = open (_PATH_DEVNULL, O_RDWR);
1297 dup2 (new_fd, 0); /* stdin <- /dev/null */
1300 dup2 (0, 1); /* stdout -> /dev/null */
1301 dup2 (0, 2); /* stderr -> /dev/null */
1305 /* Force the priority back to zero if pppd is running higher. */
1306 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1307 warn("can't reset priority to 0: %m");
1310 /* SysV recommends a second fork at this point. */
1312 /* run the program */
1313 execve(prog, args, script_env);
1314 if (must_exist || errno != ENOENT)
1315 warn("Can't execute %s: %m", prog);
1320 dbglog("Script %s started; pid = %d", prog, pid);
1323 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1325 warn("losing track of %s process", prog);
1331 chp->next = children;
1340 * reap_kids - get status from any dead child processes,
1341 * and log a message for abnormal terminations.
1347 struct subprocess *chp, **prevp;
1349 if (n_children == 0)
1351 while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1353 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1354 if (chp->pid == pid)
1357 dbglog("process %d (%s) finished, status = 0x%x",
1358 pid, (chp? chp->prog: "??"), status);
1359 if (WIFSIGNALED(status)) {
1360 warn("Child process %s (pid %d) terminated with signal %d",
1361 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1363 if (chp && chp->done)
1364 (*chp->done)(chp->arg);
1366 if (pid == -1 && errno != ECHILD)
1367 error("Error waiting for child process: %m");
1372 * log_packet - format a packet and log it.
1375 char line[256]; /* line to be logged accumulated here */
1379 log_packet(p, len, prefix, level)
1385 strlcpy(line, prefix, sizeof(line));
1386 linep = line + strlen(line);
1387 format_packet(p, len, pr_log, NULL);
1389 syslog(level, "%s", line);
1393 * format_packet - make a readable representation of a packet,
1394 * calling `printer(arg, format, ...)' to output it.
1397 format_packet(p, len, printer, arg)
1400 void (*printer) __P((void *, char *, ...));
1405 struct protent *protp;
1407 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1411 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1412 if (proto == protp->protocol)
1414 if (protp != NULL) {
1415 printer(arg, "[%s", protp->name);
1416 n = (*protp->printpkt)(p, len, printer, arg);
1421 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1422 if (proto == (protp->protocol & ~0x8000))
1424 if (protp != 0 && protp->data_name != 0) {
1425 printer(arg, "[%s data]", protp->data_name);
1427 printer(arg, "%.8B ...", p);
1429 printer(arg, "%.*B", len, p);
1432 printer(arg, "[proto=0x%x]", proto);
1437 printer(arg, "%.32B ...", p);
1439 printer(arg, "%.*B", len, p);
1443 pr_log __V((void *arg, char *fmt, ...))
1450 va_start(pvar, fmt);
1455 arg = va_arg(pvar, void *);
1456 fmt = va_arg(pvar, char *);
1459 n = vslprintf(buf, sizeof(buf), fmt, pvar);
1462 if (linep + n + 1 > line + sizeof(line)) {
1463 syslog(LOG_DEBUG, "%s", line);
1466 strlcpy(linep, buf, line + sizeof(line) - linep);
1471 * vslp_printer - used in processing a %P format
1473 struct buffer_info {
1479 vslp_printer __V((void *arg, char *fmt, ...))
1483 struct buffer_info *bi;
1486 va_start(pvar, fmt);
1491 arg = va_arg(pvar, void *);
1492 fmt = va_arg(pvar, char *);
1495 bi = (struct buffer_info *) arg;
1496 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
1504 * print_string - print a readable representation of a string using
1508 print_string(p, len, printer, arg)
1511 void (*printer) __P((void *, char *, ...));
1517 for (; len > 0; --len) {
1519 if (' ' <= c && c <= '~') {
1520 if (c == '\\' || c == '"')
1522 printer(arg, "%c", c);
1526 printer(arg, "\\n");
1529 printer(arg, "\\r");
1532 printer(arg, "\\t");
1535 printer(arg, "\\%.3o", c);
1543 * novm - log an error message saying we ran out of memory, and die.
1549 fatal("Virtual memory exhausted allocating %s\n", msg);
1553 * slprintf - format a message into a buffer. Like sprintf except we
1554 * also specify the length of the output buffer, and we handle
1555 * %r (recursive format), %m (error message), %v (visible string),
1556 * %q (quoted string), %t (current time) and %I (IP address) formats.
1557 * Doesn't do floating-point formats.
1558 * Returns the number of chars put into buf.
1561 slprintf __V((char *buf, int buflen, char *fmt, ...))
1567 va_start(args, fmt);
1573 buf = va_arg(args, char *);
1574 buflen = va_arg(args, int);
1575 fmt = va_arg(args, char *);
1577 n = vslprintf(buf, buflen, fmt, args);
1583 * vslprintf - like slprintf, takes a va_list instead of a list of args.
1585 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1588 vslprintf(buf, buflen, fmt, args)
1595 int width, prec, fillch;
1596 int base, len, neg, quoted;
1597 unsigned long val = 0;
1598 char *str, *f, *buf0;
1603 static char hexchars[] = "0123456789abcdef";
1604 struct buffer_info bufinfo;
1608 while (buflen > 0) {
1609 for (f = fmt; *f != '%' && *f != 0; ++f)
1615 memcpy(buf, fmt, len);
1630 width = va_arg(args, int);
1633 while (isdigit(c)) {
1634 width = width * 10 + c - '0';
1641 prec = va_arg(args, int);
1644 while (isdigit(c)) {
1645 prec = prec * 10 + c - '0';
1656 i = va_arg(args, int);
1665 val = va_arg(args, unsigned int);
1670 val = va_arg(args, unsigned int);
1674 val = (unsigned long) va_arg(args, void *);
1679 str = va_arg(args, char *);
1682 num[0] = va_arg(args, int);
1687 str = strerror(errno);
1690 ip = va_arg(args, u_int32_t);
1692 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
1693 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
1697 f = va_arg(args, char *);
1699 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
1701 /* On the powerpc, a va_list is an array of 1 structure */
1702 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
1710 str += 4; /* chop off the day name */
1711 str[15] = 0; /* chop off year and newline */
1713 case 'v': /* "visible" string */
1714 case 'q': /* quoted string */
1716 p = va_arg(args, unsigned char *);
1717 if (fillch == '0' && prec > 0) {
1720 n = strlen((char *)p);
1721 if (prec > 0 && prec < n)
1724 while (n > 0 && buflen > 0) {
1727 if (!quoted && c >= 0x80) {
1732 if (quoted && (c == '"' || c == '\\'))
1734 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1738 case '\t': OUTCHAR('t'); break;
1739 case '\n': OUTCHAR('n'); break;
1740 case '\b': OUTCHAR('b'); break;
1741 case '\f': OUTCHAR('f'); break;
1744 OUTCHAR(hexchars[c >> 4]);
1745 OUTCHAR(hexchars[c & 0xf]);
1759 case 'P': /* print PPP packet */
1761 bufinfo.len = buflen + 1;
1762 p = va_arg(args, unsigned char *);
1763 n = va_arg(args, int);
1764 format_packet(p, n, vslp_printer, &bufinfo);
1766 buflen = bufinfo.len - 1;
1769 p = va_arg(args, unsigned char *);
1770 for (n = prec; n > 0; --n) {
1774 OUTCHAR(hexchars[(c >> 4) & 0xf]);
1775 OUTCHAR(hexchars[c & 0xf]);
1781 --fmt; /* so %z outputs %z etc. */
1786 str = num + sizeof(num);
1788 while (str > num + neg) {
1789 *--str = hexchars[val % base];
1791 if (--prec <= 0 && val == 0)
1803 len = num + sizeof(num) - 1 - str;
1806 if (prec > 0 && len > prec)
1812 if ((n = width - len) > 0) {
1820 memcpy(buf, str, len);
1829 * script_setenv - set an environment variable value to be used
1830 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1833 script_setenv(var, value)
1836 size_t vl = strlen(var) + strlen(value) + 2;
1838 char *p, *newstring;
1840 newstring = (char *) malloc(vl);
1843 slprintf(newstring, vl, "%s=%s", var, value);
1845 /* check if this variable is already set */
1846 if (script_env != 0) {
1847 for (i = 0; (p = script_env[i]) != 0; ++i) {
1848 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1850 script_env[i] = newstring;
1856 script_env = (char **) malloc(16 * sizeof(char *));
1857 if (script_env == 0)
1862 /* reallocate script_env with more space if needed */
1863 if (i + 1 >= s_env_nalloc) {
1865 char **newenv = (char **) realloc((void *)script_env,
1866 new_n * sizeof(char *));
1869 script_env = newenv;
1870 s_env_nalloc = new_n;
1873 script_env[i] = newstring;
1874 script_env[i+1] = 0;
1878 * script_unsetenv - remove a variable from the environment
1882 script_unsetenv(var)
1885 int vl = strlen(var);
1889 if (script_env == 0)
1891 for (i = 0; (p = script_env[i]) != 0; ++i) {
1892 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1894 while ((script_env[i] = script_env[i+1]) != 0)
1902 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
1903 * always leaves destination null-terminated (for len > 0).
1906 strlcpy(dest, src, len)
1911 size_t ret = strlen(src);
1917 strncpy(dest, src, len - 1);
1925 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
1926 * always leaves destination null-terminated (for len > 0).
1929 strlcat(dest, src, len)
1934 size_t dlen = strlen(dest);
1936 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
1940 * logit - does the hard work for fatal et al.
1943 logit(level, fmt, args)
1951 n = vslprintf(buf, sizeof(buf), fmt, args);
1952 syslog(level, "%s", buf);
1953 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
1954 if (buf[n-1] != '\n')
1956 if (write(log_to_fd, buf, n) != n)
1962 * fatal - log an error message and die horribly.
1965 fatal __V((char *fmt, ...))
1970 va_start(pvar, fmt);
1974 fmt = va_arg(pvar, char *);
1977 logit(LOG_ERR, fmt, pvar);
1980 die(1); /* as promised */
1984 * error - log an error message.
1987 error __V((char *fmt, ...))
1992 va_start(pvar, fmt);
1996 fmt = va_arg(pvar, char *);
1999 logit(LOG_ERR, fmt, pvar);
2004 * warn - log a warning message.
2007 warn __V((char *fmt, ...))
2012 va_start(pvar, fmt);
2016 fmt = va_arg(pvar, char *);
2019 logit(LOG_WARNING, fmt, pvar);
2024 * notice - log a notice-level message.
2027 notice __V((char *fmt, ...))
2032 va_start(pvar, fmt);
2036 fmt = va_arg(pvar, char *);
2039 logit(LOG_NOTICE, fmt, pvar);
2044 * info - log an informational message.
2047 info __V((char *fmt, ...))
2052 va_start(pvar, fmt);
2056 fmt = va_arg(pvar, char *);
2059 logit(LOG_INFO, fmt, pvar);
2064 * dbglog - log a debug message.
2067 dbglog __V((char *fmt, ...))
2072 va_start(pvar, fmt);
2076 fmt = va_arg(pvar, char *);
2079 logit(LOG_DEBUG, fmt, pvar);