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.52 1999/01/19 23:59:39 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 jmp_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 /* Prototypes for procedures local to this file. */
112 static void create_pidfile __P((void));
113 static void cleanup __P((void));
114 static void close_tty __P((void));
115 static void get_input __P((void));
116 static void calltimeout __P((void));
117 static struct timeval *timeleft __P((struct timeval *));
118 static void kill_my_pg __P((int));
119 static void hup __P((int));
120 static void term __P((int));
121 static void chld __P((int));
122 static void toggle_debug __P((int));
123 static void open_ccp __P((int));
124 static void bad_signal __P((int));
125 static void holdoff_end __P((void *));
126 static int device_script __P((char *, int, int));
127 static void reap_kids __P((void));
128 static void pr_log __P((void *, char *, ...));
130 extern char *ttyname __P((int));
131 extern char *getlogin __P((void));
132 int main __P((int, char *[]));
136 #define O_NONBLOCK O_NDELAY
140 #define setlogmask(x)
144 * PPP Data Link Layer "protocol" table.
145 * One entry per supported protocol.
146 * The last entry must be NULL.
148 struct protent *protocols[] = {
177 struct protent *protp;
181 phase = PHASE_INITIALIZE;
185 strcpy(default_devnam, devnam);
189 /* Initialize syslog facilities */
191 openlog("pppd", LOG_PID);
193 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
194 setlogmask(LOG_UPTO(LOG_INFO));
197 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
198 option_error("Couldn't get hostname: %m");
201 hostname[MAXNAMELEN-1] = 0;
204 privileged = uid == 0;
205 sprintf(numbuf, "%d", uid);
206 script_setenv("ORIG_UID", numbuf);
209 * Initialize to the standard option set, then parse, in order,
210 * the system options file, the user's options file,
211 * the tty's options file, and the command line arguments.
213 for (i = 0; (protp = protocols[i]) != NULL; ++i)
218 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
219 || !options_from_user())
221 scan_args(argc-1, argv+1); /* look for tty name on command line */
222 if (!options_for_tty()
223 || !parse_args(argc-1, argv+1))
227 * Check that we are running as root.
229 if (geteuid() != 0) {
230 option_error("must be root to run %s, since it is not setuid-root",
235 if (!ppp_available()) {
236 option_error(no_ppp_msg);
241 * Check that the options given are valid and consistent.
243 if (!sys_check_options())
245 auth_check_options();
246 for (i = 0; (protp = protocols[i]) != NULL; ++i)
247 if (protp->check_options != NULL)
248 (*protp->check_options)();
249 if (demand && connector == 0) {
250 option_error("connect script is required for demand-dialling\n");
254 script_setenv("DEVICE", devnam);
255 sprintf(numbuf, "%d", baud_rate);
256 script_setenv("SPEED", numbuf);
259 * If the user has specified the default device name explicitly,
260 * pretend they hadn't.
262 if (!default_device && strcmp(devnam, default_devnam) == 0)
268 * Initialize system-dependent stuff and magic number package.
273 setlogmask(LOG_UPTO(LOG_DEBUG));
276 * Detach ourselves from the terminal, if required,
277 * and identify who is running us.
279 if (!nodetach && !updetach)
285 if (pw != NULL && pw->pw_name != NULL)
290 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
291 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
294 * Compute mask of all interesting signals and install signal handlers
295 * for each. Only one signal handler may be active at a time. Therefore,
296 * all other signals should be masked when any handler is executing.
299 sigaddset(&mask, SIGHUP);
300 sigaddset(&mask, SIGINT);
301 sigaddset(&mask, SIGTERM);
302 sigaddset(&mask, SIGCHLD);
303 sigaddset(&mask, SIGUSR2);
305 #define SIGNAL(s, handler) { \
306 sa.sa_handler = handler; \
307 if (sigaction(s, &sa, NULL) < 0) { \
308 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
315 SIGNAL(SIGHUP, hup); /* Hangup */
316 SIGNAL(SIGINT, term); /* Interrupt */
317 SIGNAL(SIGTERM, term); /* Terminate */
318 SIGNAL(SIGCHLD, chld);
320 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
321 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
324 * Install a handler for other signals which would otherwise
325 * cause pppd to exit without cleaning up.
327 SIGNAL(SIGABRT, bad_signal);
328 SIGNAL(SIGALRM, bad_signal);
329 SIGNAL(SIGFPE, bad_signal);
330 SIGNAL(SIGILL, bad_signal);
331 SIGNAL(SIGPIPE, bad_signal);
332 SIGNAL(SIGQUIT, bad_signal);
333 SIGNAL(SIGSEGV, bad_signal);
335 SIGNAL(SIGBUS, bad_signal);
338 SIGNAL(SIGEMT, bad_signal);
341 SIGNAL(SIGPOLL, bad_signal);
344 SIGNAL(SIGPROF, bad_signal);
347 SIGNAL(SIGSYS, bad_signal);
350 SIGNAL(SIGTRAP, bad_signal);
353 SIGNAL(SIGVTALRM, bad_signal);
356 SIGNAL(SIGXCPU, bad_signal);
359 SIGNAL(SIGXFSZ, bad_signal);
363 * Apparently we can get a SIGPIPE when we call syslog, if
364 * syslogd has died and been restarted. Ignoring it seems
367 signal(SIGPIPE, SIG_IGN);
370 sigprocmask(SIG_BLOCK, &mask, NULL);
373 * If we're doing dial-on-demand, set up the interface now.
377 * Open the loopback channel and set it up to be the ppp interface.
381 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
382 (void) sprintf(ifname, "ppp%d", ifunit);
383 script_setenv("IFNAME", ifname);
385 create_pidfile(); /* write pid to file */
388 * Configure the interface and mark it up, etc.
399 * Don't do anything until we see some activity.
401 phase = PHASE_DORMANT;
405 if (setjmp(sigjmp) == 0) {
407 sigprocmask(SIG_UNBLOCK, &mask, NULL);
408 wait_loop_output(timeleft(&timo));
410 sigprocmask(SIG_BLOCK, &mask, NULL);
418 if (get_loop_output())
426 * Now we want to bring up the link.
429 syslog(LOG_INFO, "Starting link");
433 * Lock the device if we've been asked to.
435 if (lockflag && !default_device) {
436 if (lock(devnam) < 0)
442 * Open the serial device and set it up to be the ppp interface.
443 * First we open it in non-blocking mode so we can set the
444 * various termios flags appropriately. If we aren't dialling
445 * out and we want to use the modem lines, we reopen it later
446 * in order to wait for the carrier detect signal from the modem.
450 sigprocmask(SIG_UNBLOCK, &mask, NULL);
451 while ((ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0)) < 0) {
453 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
454 if (!persist || errno != EINTR)
457 sigprocmask(SIG_BLOCK, &mask, NULL);
458 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
459 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
461 "Couldn't reset non-blocking mode on device: %m");
464 * Do the equivalent of `mesg n' to stop broadcast messages.
466 if (fstat(ttyfd, &statbuf) < 0
467 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
469 "Couldn't restrict write permissions to %s: %m", devnam);
471 tty_mode = statbuf.st_mode;
473 /* run connection script */
474 if (connector && connector[0]) {
475 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
477 if (!default_device && modem) {
478 hangup_modem(ttyfd); /* in case modem is off hook */
483 * Set line speed, flow control, etc.
484 * On most systems we set CLOCAL for now so that we can talk
485 * to the modem before carrier comes up. But this has the
486 * side effect that we might miss it if CD drops before we
487 * get to clear CLOCAL below. On systems where we can talk
488 * successfully to the modem with CLOCAL clear and CD down,
489 * we could clear CLOCAL at this point.
491 set_up_tty(ttyfd, 1);
493 if (device_script(connector, ttyfd, ttyfd) < 0) {
494 syslog(LOG_ERR, "Connect script failed");
498 syslog(LOG_INFO, "Serial connection established.");
499 sleep(1); /* give it time to set up its terminal */
502 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
503 set_up_tty(ttyfd, 0);
505 /* reopen tty if necessary to wait for carrier */
506 if (connector == NULL && modem) {
507 while ((i = open(devnam, O_RDWR)) < 0) {
509 syslog(LOG_ERR, "Failed to reopen %s: %m", devnam);
510 if (!persist || errno != EINTR || hungup || kill_link)
516 /* run welcome script, if any */
517 if (welcomer && welcomer[0]) {
518 if (device_script(welcomer, ttyfd, ttyfd) < 0)
519 syslog(LOG_WARNING, "Welcome script failed");
522 /* set up the serial device as a ppp interface */
523 establish_ppp(ttyfd);
527 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
528 (void) sprintf(ifname, "ppp%d", ifunit);
529 script_setenv("IFNAME", ifname);
531 create_pidfile(); /* write pid to file */
535 * Start opening the connection and wait for
536 * incoming events (reply, timeout, etc.).
538 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
540 lcp_open(0); /* Start protocol */
542 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
543 if (setjmp(sigjmp) == 0) {
545 sigprocmask(SIG_UNBLOCK, &mask, NULL);
546 wait_input(timeleft(&timo));
548 sigprocmask(SIG_BLOCK, &mask, NULL);
552 lcp_close(0, "User request");
557 if (phase == PHASE_NETWORK) {
558 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
559 (*ccp_protent.open)(0);
563 reap_kids(); /* Don't leave dead kids lying around */
567 * If we may want to bring the link up again, transfer
568 * the ppp unit back to the loopback. Set the
569 * real serial device back to its normal mode of operation.
574 disestablish_ppp(ttyfd);
577 * Run disconnector script, if requested.
578 * XXX we may not be able to do this if the line has hung up!
580 if (disconnector && !hungup) {
581 set_up_tty(ttyfd, 1);
582 if (device_script(disconnector, ttyfd, ttyfd) < 0) {
583 syslog(LOG_WARNING, "disconnect script failed");
585 syslog(LOG_INFO, "Serial link disconnected.");
598 if (pidfilename[0] != 0
599 && unlink(pidfilename) < 0 && errno != ENOENT)
600 syslog(LOG_WARNING, "unable to delete pid file: %m");
609 if (holdoff > 0 && need_holdoff) {
610 phase = PHASE_HOLDOFF;
611 TIMEOUT(holdoff_end, NULL, holdoff);
613 if (setjmp(sigjmp) == 0) {
615 sigprocmask(SIG_UNBLOCK, &mask, NULL);
616 wait_time(timeleft(&timo));
618 sigprocmask(SIG_BLOCK, &mask, NULL);
623 phase = PHASE_DORMANT; /* allow signal to end holdoff */
626 } while (phase == PHASE_HOLDOFF);
632 /* Wait for scripts to finish */
633 while (n_children > 0)
641 * detach - detach us from the controlling terminal.
648 if (daemon(0, 0) < 0) {
649 perror("Couldn't detach from controlling terminal");
654 /* update pid file if it has been written already */
660 * Create a file containing our process ID.
668 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
669 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
670 fprintf(pidfile, "%d\n", pid);
671 (void) fclose(pidfile);
673 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
676 sprintf(numbuf, "%d", pid);
677 script_setenv("PPPD_PID", numbuf);
681 * holdoff_end - called via a timeout when the holdoff period ends.
687 phase = PHASE_DORMANT;
691 * get_input - called when incoming data is available.
699 struct protent *protp;
701 p = inpacket_buf; /* point to beginning of packet buffer */
703 len = read_packet(inpacket_buf);
708 syslog(LOG_NOTICE, "Modem hangup");
710 lcp_lowerdown(0); /* serial link is no longer available */
715 if (debug /*&& (debugflags & DBG_INPACKET)*/)
716 log_packet(p, len, "rcvd ", LOG_DEBUG);
718 if (len < PPP_HDRLEN) {
719 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
723 p += 2; /* Skip address and control */
724 GETSHORT(protocol, p);
728 * Toss all non-LCP packets unless LCP is OPEN.
730 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
732 "get_input: Received non-LCP packet when LCP not open."));
737 * Until we get past the authentication phase, toss all packets
738 * except LCP, LQR and authentication packets.
740 if (phase <= PHASE_AUTHENTICATE
741 && !(protocol == PPP_LCP || protocol == PPP_LQR
742 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
743 MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
749 * Upcall the proper protocol input routine.
751 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
752 if (protp->protocol == protocol && protp->enabled_flag) {
753 (*protp->input)(0, p, len);
756 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
757 && protp->datainput != NULL) {
758 (*protp->datainput)(0, p, len);
764 syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
765 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
770 * quit - Clean up state and exit (with an error indication).
779 * die - like quit, except we can specify an exit status.
786 syslog(LOG_INFO, "Exit.");
791 * cleanup - restore anything which needs to be restored before we exit
802 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
803 syslog(LOG_WARNING, "unable to delete pid file: %m");
811 * close_tty - restore the terminal device and close it.
816 disestablish_ppp(ttyfd);
818 /* drop dtr to hang up */
819 if (!default_device && modem) {
822 * This sleep is in case the serial port has CLOCAL set by default,
823 * and consequently will reassert DTR when we close the device.
830 if (tty_mode != (mode_t) -1) {
831 if (fchmod(devnam, tty_mode) != 0) {
832 /* XXX if devnam is a symlink, this will change the link */
833 chmod(devnam, tty_mode);
843 struct timeval c_time; /* time at which to call routine */
844 void *c_arg; /* argument to routine */
845 void (*c_func) __P((void *)); /* routine */
846 struct callout *c_next;
849 static struct callout *callout = NULL; /* Callout list */
850 static struct timeval timenow; /* Current time */
853 * timeout - Schedule a timeout.
855 * Note that this timeout takes the number of seconds, NOT hz (as in
859 timeout(func, arg, time)
860 void (*func) __P((void *));
864 struct callout *newp, *p, **pp;
866 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
867 (long) func, (long) arg, time));
872 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
873 syslog(LOG_ERR, "Out of memory in timeout()!");
878 gettimeofday(&timenow, NULL);
879 newp->c_time.tv_sec = timenow.tv_sec + time;
880 newp->c_time.tv_usec = timenow.tv_usec;
883 * Find correct place and link it in.
885 for (pp = &callout; (p = *pp); pp = &p->c_next)
886 if (newp->c_time.tv_sec < p->c_time.tv_sec
887 || (newp->c_time.tv_sec == p->c_time.tv_sec
888 && newp->c_time.tv_usec < p->c_time.tv_usec))
896 * untimeout - Unschedule a timeout.
900 void (*func) __P((void *));
903 struct callout **copp, *freep;
905 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
908 * Find first matching timeout and remove it from the list.
910 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
911 if (freep->c_func == func && freep->c_arg == arg) {
912 *copp = freep->c_next;
913 (void) free((char *) freep);
920 * calltimeout - Call any timeout routines which are now due.
927 while (callout != NULL) {
930 if (gettimeofday(&timenow, NULL) < 0) {
931 syslog(LOG_ERR, "Failed to get time of day: %m");
934 if (!(p->c_time.tv_sec < timenow.tv_sec
935 || (p->c_time.tv_sec == timenow.tv_sec
936 && p->c_time.tv_usec <= timenow.tv_usec)))
937 break; /* no, it's not time yet */
940 (*p->c_func)(p->c_arg);
948 * timeleft - return the length of time until the next timeout is due.
950 static struct timeval *
957 gettimeofday(&timenow, NULL);
958 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
959 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
960 if (tvp->tv_usec < 0) {
961 tvp->tv_usec += 1000000;
965 tvp->tv_sec = tvp->tv_usec = 0;
972 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
978 struct sigaction act, oldact;
980 act.sa_handler = SIG_IGN;
983 sigaction(sig, &act, &oldact);
984 sigaction(sig, &oldact, NULL);
989 * hup - Catch SIGHUP signal.
991 * Indicates that the physical layer has been disconnected.
992 * We don't rely on this indication; if the user has sent this
993 * signal, we just take the link down.
999 syslog(LOG_INFO, "Hangup (SIGHUP)");
1002 /* Send the signal to the [dis]connector process(es) also */
1010 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1012 * Indicates that we should initiate a graceful disconnect and exit.
1019 syslog(LOG_INFO, "Terminating on signal %d.", sig);
1020 persist = 0; /* don't try to restart */
1023 /* Send the signal to the [dis]connector process(es) also */
1031 * chld - Catch SIGCHLD signal.
1032 * Calls reap_kids to get status for any dead kids.
1044 * toggle_debug - Catch SIGUSR1 signal.
1046 * Toggle debug flag.
1055 setlogmask(LOG_UPTO(LOG_DEBUG));
1057 setlogmask(LOG_UPTO(LOG_WARNING));
1063 * open_ccp - Catch SIGUSR2 signal.
1065 * Try to (re)negotiate compression.
1079 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1085 static int crashed = 0;
1090 syslog(LOG_ERR, "Fatal signal %d", sig);
1092 kill_my_pg(SIGTERM);
1098 * device_script - run a program to connect or disconnect the
1102 device_script(program, in, out)
1115 syslog(LOG_ERR, "Failed to create child process: %m");
1140 if (!nodetach && !updetach) {
1142 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1143 if (errfd >= 0 && errfd != 2) {
1150 execl("/bin/sh", "sh", "-c", program, (char *)0);
1151 syslog(LOG_ERR, "could not exec /bin/sh: %m");
1156 while (waitpid(pid, &status, 0) < 0) {
1159 syslog(LOG_ERR, "error waiting for (dis)connection process: %m");
1164 return (status == 0 ? 0 : -1);
1169 * We maintain a list of child process pids and
1170 * functions to call when they exit.
1175 void (*done) __P((void *));
1177 struct subprocess *next;
1180 struct subprocess *children;
1183 * run-program - execute a program with given arguments,
1184 * but don't wait for it.
1185 * If the program can't be executed, logs an error unless
1186 * must_exist is 0 and the program file doesn't exist.
1187 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1188 * or isn't an executable plain file, or the process ID of the child.
1189 * If done != NULL, (*done)(arg) will be called later (within
1190 * reap_kids) iff the return value is > 0.
1193 run_program(prog, args, must_exist, done, arg)
1197 void (*done) __P((void *));
1201 struct subprocess *chp;
1205 * First check if the file exists and is executable.
1206 * We don't use access() because that would use the
1207 * real user-id, which might not be root, and the script
1208 * might be accessible only to root.
1211 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1212 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1213 if (must_exist || errno != ENOENT)
1214 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1220 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1226 /* Leave the current location */
1227 (void) setsid(); /* No controlling tty. */
1228 (void) umask (S_IRWXG|S_IRWXO);
1229 (void) chdir ("/"); /* no current directory. */
1233 /* Ensure that nothing of our device environment is inherited. */
1239 close (ttyfd); /* tty interface to the ppp device */
1241 /* Don't pass handles to the PPP device, even by accident. */
1242 new_fd = open (_PATH_DEVNULL, O_RDWR);
1245 dup2 (new_fd, 0); /* stdin <- /dev/null */
1248 dup2 (0, 1); /* stdout -> /dev/null */
1249 dup2 (0, 2); /* stderr -> /dev/null */
1253 /* Force the priority back to zero if pppd is running higher. */
1254 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1255 syslog (LOG_WARNING, "can't reset priority to 0: %m");
1258 /* SysV recommends a second fork at this point. */
1260 /* run the program */
1261 execve(prog, args, script_env);
1262 if (must_exist || errno != ENOENT) {
1264 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1265 for (i = 0; args[i]; ++i)
1266 syslog(LOG_DEBUG, "args[%d] = '%s'", i, args[i]);
1267 for (i = 0; script_env[i]; ++i)
1268 syslog(LOG_DEBUG, "env[%d] = '%s'", i, script_env[i]);
1274 syslog(LOG_DEBUG, "Script %s started; pid = %d", prog, pid);
1277 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1279 syslog(LOG_WARNING, "losing track of %s process", prog);
1285 chp->next = children;
1294 * reap_kids - get status from any dead child processes,
1295 * and log a message for abnormal terminations.
1301 struct subprocess *chp, **prevp;
1303 if (n_children == 0)
1305 while ((pid = waitpid(-1, &status, WNOHANG)) != -1 && pid != 0) {
1307 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1308 if (chp->pid == pid)
1311 syslog(LOG_DEBUG, "process %d (%s) finished, status = 0x%x",
1312 pid, (chp? chp->prog: "??"), status);
1313 if (WIFSIGNALED(status)) {
1315 "Child process %s (pid %d) terminated with signal %d",
1316 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1318 if (chp && chp->done)
1319 (*chp->done)(chp->arg);
1321 if (pid == -1 && errno != ECHILD)
1322 syslog(LOG_ERR, "Error waiting for child process: %m");
1327 * log_packet - format a packet and log it.
1330 char line[256]; /* line to be logged accumulated here */
1334 log_packet(p, len, prefix, level)
1340 strcpy(line, prefix);
1341 linep = line + strlen(line);
1342 format_packet(p, len, pr_log, NULL);
1344 syslog(level, "%s", line);
1348 * format_packet - make a readable representation of a packet,
1349 * calling `printer(arg, format, ...)' to output it.
1352 format_packet(p, len, printer, arg)
1355 void (*printer) __P((void *, char *, ...));
1361 struct protent *protp;
1363 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1367 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1368 if (proto == protp->protocol)
1370 if (protp != NULL) {
1371 printer(arg, "[%s", protp->name);
1372 n = (*protp->printpkt)(p, len, printer, arg);
1377 printer(arg, "[proto=0x%x]", proto);
1381 for (; len > 0; --len) {
1383 printer(arg, " %.2x", x);
1388 pr_log __V((void *arg, char *fmt, ...))
1395 va_start(pvar, fmt);
1400 arg = va_arg(pvar, void *);
1401 fmt = va_arg(pvar, char *);
1404 n = vfmtmsg(buf, sizeof(buf), fmt, pvar);
1407 if (linep + n + 1 > line + sizeof(line)) {
1408 syslog(LOG_DEBUG, "%s", line);
1416 * print_string - print a readable representation of a string using
1420 print_string(p, len, printer, arg)
1423 void (*printer) __P((void *, char *, ...));
1429 for (; len > 0; --len) {
1431 if (' ' <= c && c <= '~') {
1432 if (c == '\\' || c == '"')
1434 printer(arg, "%c", c);
1438 printer(arg, "\\n");
1441 printer(arg, "\\r");
1444 printer(arg, "\\t");
1447 printer(arg, "\\%.3o", c);
1455 * novm - log an error message saying we ran out of memory, and die.
1461 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1466 * fmtmsg - format a message into a buffer. Like sprintf except we
1467 * also specify the length of the output buffer, and we handle
1468 * %r (recursive format), %m (error message) and %I (IP address) formats.
1469 * Doesn't do floating-point formats.
1470 * Returns the number of chars put into buf.
1473 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1479 va_start(args, fmt);
1485 buf = va_arg(args, char *);
1486 buflen = va_arg(args, int);
1487 fmt = va_arg(args, char *);
1489 n = vfmtmsg(buf, buflen, fmt, args);
1495 * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1497 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1500 vfmtmsg(buf, buflen, fmt, args)
1507 int width, prec, fillch;
1508 int base, len, neg, quoted;
1509 unsigned long val = 0;
1510 char *str, *f, *buf0;
1514 static char hexchars[] = "0123456789abcdef";
1518 while (buflen > 0) {
1519 for (f = fmt; *f != '%' && *f != 0; ++f)
1525 memcpy(buf, fmt, len);
1540 width = va_arg(args, int);
1543 while (isdigit(c)) {
1544 width = width * 10 + c - '0';
1551 prec = va_arg(args, int);
1554 while (isdigit(c)) {
1555 prec = prec * 10 + c - '0';
1566 i = va_arg(args, int);
1575 val = va_arg(args, unsigned int);
1579 val = va_arg(args, unsigned int);
1583 val = (unsigned long) va_arg(args, void *);
1588 str = va_arg(args, char *);
1591 num[0] = va_arg(args, int);
1596 str = strerror(errno);
1599 str = ip_ntoa(va_arg(args, u_int32_t));
1602 f = va_arg(args, char *);
1604 n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1606 /* On the powerpc, a va_list is an array of 1 structure */
1607 n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1615 str += 4; /* chop off the day name */
1616 str[15] = 0; /* chop off year and newline */
1618 case 'v': /* "visible" string */
1619 case 'q': /* quoted string */
1621 p = va_arg(args, unsigned char *);
1622 if (fillch == '0' && prec > 0) {
1625 n = strlen((char *)p);
1626 if (prec > 0 && prec < n)
1629 while (n > 0 && buflen > 0) {
1632 if (!quoted && c >= 0x80) {
1637 if (quoted && (c == '"' || c == '\\'))
1639 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1643 case '\t': OUTCHAR('t'); break;
1644 case '\n': OUTCHAR('n'); break;
1645 case '\b': OUTCHAR('b'); break;
1646 case '\f': OUTCHAR('f'); break;
1649 OUTCHAR(hexchars[c >> 4]);
1650 OUTCHAR(hexchars[c & 0xf]);
1667 --fmt; /* so %z outputs %z etc. */
1672 str = num + sizeof(num);
1674 while (str > num + neg) {
1675 *--str = hexchars[val % base];
1677 if (--prec <= 0 && val == 0)
1689 len = num + sizeof(num) - 1 - str;
1692 if (prec > 0 && len > prec)
1698 if ((n = width - len) > 0) {
1706 memcpy(buf, str, len);
1715 * script_setenv - set an environment variable value to be used
1716 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1719 script_setenv(var, value)
1722 int vl = strlen(var);
1724 char *p, *newstring;
1726 newstring = (char *) malloc(vl + strlen(value) + 2);
1729 strcpy(newstring, var);
1730 newstring[vl] = '=';
1731 strcpy(newstring+vl+1, value);
1733 /* check if this variable is already set */
1734 if (script_env != 0) {
1735 for (i = 0; (p = script_env[i]) != 0; ++i) {
1736 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1738 script_env[i] = newstring;
1744 script_env = (char **) malloc(16 * sizeof(char *));
1745 if (script_env == 0)
1750 /* reallocate script_env with more space if needed */
1751 if (i + 1 >= s_env_nalloc) {
1753 char **newenv = (char **) realloc((void *)script_env,
1754 new_n * sizeof(char *));
1757 script_env = newenv;
1758 s_env_nalloc = new_n;
1761 script_env[i] = newstring;
1762 script_env[i+1] = 0;
1766 * script_unsetenv - remove a variable from the environment
1770 script_unsetenv(var)
1773 int vl = strlen(var);
1777 if (script_env == 0)
1779 for (i = 0; (p = script_env[i]) != 0; ++i) {
1780 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1782 while ((script_env[i] = script_env[i+1]) != 0)