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[] = "$FreeBSD$";
36 #include <sys/param.h>
37 #include <sys/types.h>
40 #include <sys/resource.h>
42 #include <sys/socket.h>
55 #include "pathnames.h"
56 #include "patchlevel.h"
63 extern char *strerror();
68 #endif /* IPX_CHANGE */
74 char ifname[32]; /* Interface name */
75 int ifunit; /* Interface unit number */
77 char *progname; /* Name of this program */
78 char hostname[MAXNAMELEN]; /* Our hostname */
79 static char pidfilename[MAXPATHLEN]; /* name of pid file */
80 static char iffilename[MAXPATHLEN]; /* name of if file */
81 static char default_devnam[MAXPATHLEN]; /* name of default device */
82 static pid_t pid; /* Our pid */
83 static uid_t uid; /* Our real user-id */
84 time_t etime,stime; /* End and Start time */
85 int minutes; /* connection duration */
86 static int conn_running; /* we have a [dis]connector running */
88 int ttyfd = -1; /* Serial port file descriptor */
89 mode_t tty_mode = -1; /* Original access permissions to tty */
90 int baud_rate; /* Actual bits/second for serial device */
91 int hungup; /* terminal has been hung up */
92 int privileged; /* we're running as real uid root */
93 int need_holdoff; /* need holdoff period before restarting */
94 int detached; /* have detached from terminal */
96 int phase; /* where the link is at */
100 char **script_env; /* Env. variable values for scripts */
101 int s_env_nalloc; /* # words avail at script_env */
103 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
104 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
106 static int n_children; /* # child processes still running */
108 static int locked; /* lock() has succeeded */
110 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
112 /* Prototypes for procedures local to this file. */
114 static void create_pidfile __P((void));
115 static void cleanup __P((void));
116 static void close_tty __P((void));
117 static void get_input __P((void));
118 static void calltimeout __P((void));
119 static struct timeval *timeleft __P((struct timeval *));
120 static void kill_my_pg __P((int));
121 static void hup __P((int));
122 static void term __P((int));
123 static void chld __P((int));
124 static void toggle_debug __P((int));
125 static void open_ccp __P((int));
126 static void bad_signal __P((int));
127 static void holdoff_end __P((void *));
128 static int device_script __P((char *, int, int));
129 static void reap_kids __P((void));
130 static void pr_log __P((void *, char *, ...));
132 extern char *ttyname __P((int));
133 extern char *getlogin __P((void));
134 int main __P((int, char *[]));
138 #define O_NONBLOCK O_NDELAY
142 #define setlogmask(x)
146 * PPP Data Link Layer "protocol" table.
147 * One entry per supported protocol.
148 * The last entry must be NULL.
150 struct protent *protocols[] = {
183 struct protent *protp;
185 int connect_attempts = 0;
188 phase = PHASE_INITIALIZE;
192 strcpy(default_devnam, devnam);
196 /* Initialize syslog facilities */
198 openlog("pppd", LOG_PID);
200 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
201 setlogmask(LOG_UPTO(LOG_INFO));
204 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
205 option_error("Couldn't get hostname: %m");
208 hostname[MAXNAMELEN-1] = 0;
211 privileged = uid == 0;
212 sprintf(numbuf, "%d", uid);
213 script_setenv("UID", numbuf);
216 * Initialize to the standard option set, then parse, in order,
217 * the system options file, the user's options file,
218 * the tty's options file, and the command line arguments.
220 for (i = 0; (protp = protocols[i]) != NULL; ++i)
225 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
226 || !options_from_user())
228 scan_args(argc-1, argv+1); /* look for tty name on command line */
229 if (!options_for_tty()
230 || !parse_args(argc-1, argv+1))
234 * Check that we are running as root.
236 if (geteuid() != 0) {
237 option_error("must be root to run %s, since it is not setuid-root",
242 if (!ppp_available()) {
243 option_error(no_ppp_msg);
248 * Check that the options given are valid and consistent.
251 auth_check_options();
252 for (i = 0; (protp = protocols[i]) != NULL; ++i)
253 if (protp->check_options != NULL)
254 (*protp->check_options)();
255 if (demand && connector == 0) {
256 option_error("connect script required for demand-dialling\n");
260 script_setenv("DEVICE", devnam);
261 sprintf(numbuf, "%d", baud_rate);
262 script_setenv("SPEED", numbuf);
265 * If the user has specified the default device name explicitly,
266 * pretend they hadn't.
268 if (!default_device && strcmp(devnam, default_devnam) == 0)
274 * Initialize system-dependent stuff and magic number package.
279 setlogmask(LOG_UPTO(LOG_DEBUG));
282 * Detach ourselves from the terminal, if required,
283 * and identify who is running us.
289 stime = time((time_t *) NULL);
292 if (pw != NULL && pw->pw_name != NULL)
297 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
298 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
301 * Compute mask of all interesting signals and install signal handlers
302 * for each. Only one signal handler may be active at a time. Therefore,
303 * all other signals should be masked when any handler is executing.
306 sigaddset(&mask, SIGHUP);
307 sigaddset(&mask, SIGINT);
308 sigaddset(&mask, SIGTERM);
309 sigaddset(&mask, SIGCHLD);
311 #define SIGNAL(s, handler) { \
312 sa.sa_handler = handler; \
313 if (sigaction(s, &sa, NULL) < 0) { \
314 syslog(LOG_ERR, "Couldn't establish signal handler (%d): %m", s); \
321 SIGNAL(SIGHUP, hup); /* Hangup */
322 SIGNAL(SIGINT, term); /* Interrupt */
323 SIGNAL(SIGTERM, term); /* Terminate */
324 SIGNAL(SIGCHLD, chld);
326 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
327 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
330 * Install a handler for other signals which would otherwise
331 * cause pppd to exit without cleaning up.
333 SIGNAL(SIGABRT, bad_signal);
334 SIGNAL(SIGALRM, bad_signal);
335 SIGNAL(SIGFPE, bad_signal);
336 SIGNAL(SIGILL, bad_signal);
337 SIGNAL(SIGPIPE, bad_signal);
338 SIGNAL(SIGQUIT, bad_signal);
339 SIGNAL(SIGSEGV, bad_signal);
341 SIGNAL(SIGBUS, bad_signal);
344 SIGNAL(SIGEMT, bad_signal);
347 SIGNAL(SIGPOLL, bad_signal);
350 SIGNAL(SIGPROF, bad_signal);
353 SIGNAL(SIGSYS, bad_signal);
356 SIGNAL(SIGTRAP, bad_signal);
359 SIGNAL(SIGVTALRM, bad_signal);
362 SIGNAL(SIGXCPU, bad_signal);
365 SIGNAL(SIGXFSZ, bad_signal);
369 * Apparently we can get a SIGPIPE when we call syslog, if
370 * syslogd has died and been restarted. Ignoring it seems
373 signal(SIGPIPE, SIG_IGN);
376 * If we're doing dial-on-demand, set up the interface now.
380 * Open the loopback channel and set it up to be the ppp interface.
384 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
385 (void) sprintf(ifname, "ppp%d", ifunit);
386 script_setenv("IFNAME", ifname);
388 create_pidfile(); /* write pid to file */
391 * Configure the interface and mark it up, etc.
402 * Don't do anything until we see some activity.
404 phase = PHASE_DORMANT;
408 wait_loop_output(timeleft(&timo));
415 if (get_loop_output())
421 * Now we want to bring up the link.
424 syslog(LOG_INFO, "Starting link");
428 * Lock the device if we've been asked to.
430 if (lockflag && !default_device) {
431 if (lock(devnam) < 0)
437 * Open the serial device and set it up to be the ppp interface.
438 * First we open it in non-blocking mode so we can set the
439 * various termios flags appropriately. If we aren't dialling
440 * out and we want to use the modem lines, we reopen it later
441 * in order to wait for the carrier detect signal from the modem.
443 while ((ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0)) < 0) {
445 syslog(LOG_ERR, "Failed to open %s: %m", devnam);
446 if (!persist || errno != EINTR)
449 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
450 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
452 "Couldn't reset non-blocking mode on device: %m");
458 * Do the equivalent of `mesg n' to stop broadcast messages.
460 if (fstat(ttyfd, &statbuf) < 0
461 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
463 "Couldn't restrict write permissions to %s: %m", devnam);
465 tty_mode = statbuf.st_mode;
467 /* run connection script */
468 if (connector && connector[0]) {
469 MAINDEBUG((LOG_INFO, "Connecting with <%s>", connector));
472 * Set line speed, flow control, etc.
473 * On most systems we set CLOCAL for now so that we can talk
474 * to the modem before carrier comes up. But this has the
475 * side effect that we might miss it if CD drops before we
476 * get to clear CLOCAL below. On systems where we can talk
477 * successfully to the modem with CLOCAL clear and CD down,
478 * we can clear CLOCAL at this point.
480 set_up_tty(ttyfd, 1);
482 /* drop dtr to hang up in case modem is off hook */
483 if (!default_device && modem) {
484 setdtr(ttyfd, FALSE);
489 if (device_script(connector, ttyfd, ttyfd) < 0) {
490 syslog(LOG_ERR, "Connect script failed");
491 setdtr(ttyfd, FALSE);
497 syslog(LOG_INFO, "Serial connection established.");
498 sleep(1); /* give it time to set up its terminal */
501 connect_attempts = 0; /* we made it through ok */
503 /* set line speed, flow control, etc.; clear CLOCAL if modem option */
504 set_up_tty(ttyfd, 0);
506 /* reopen tty if necessary to wait for carrier */
507 if (connector == NULL && modem) {
508 while ((i = open(devnam, O_RDWR)) < 0) {
510 syslog(LOG_ERR, "Failed to reopen %s: %m", devnam);
511 if (!persist || errno != EINTR ||
518 /* run welcome script, if any */
519 if (welcomer && welcomer[0]) {
520 if (device_script(welcomer, ttyfd, ttyfd) < 0)
521 syslog(LOG_WARNING, "Welcome script failed");
524 /* set up the serial device as a ppp interface */
525 establish_ppp(ttyfd);
529 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
530 (void) sprintf(ifname, "ppp%d", ifunit);
532 create_pidfile(); /* write pid to file */
534 /* write interface unit number to file */
535 for (n = strlen(devnam); n > 0 ; n--)
536 if (devnam[n] == '/') {
540 (void) sprintf(iffilename, "%s%s.if", _PATH_VARRUN, &devnam[n]);
541 if ((iffile = fopen(iffilename, "w")) != NULL) {
542 fprintf(iffile, "ppp%d\n", ifunit);
543 (void) fclose(iffile);
545 syslog(LOG_ERR, "Failed to create if file %s: %m", iffilename);
549 script_setenv("IFNAME", ifname);
553 * Start opening the connection and wait for
554 * incoming events (reply, timeout, etc.).
556 syslog(LOG_NOTICE, "Connect: %s <--> %s", ifname, devnam);
557 stime = time((time_t *) NULL);
559 lcp_open(0); /* Start protocol */
560 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
561 wait_input(timeleft(&timo));
565 lcp_close(0, "User request");
569 if (phase == PHASE_NETWORK) {
570 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
571 (*ccp_protent.open)(0);
575 reap_kids(); /* Don't leave dead kids lying around */
579 * If we may want to bring the link up again, transfer
580 * the ppp unit back to the loopback. Set the
581 * real serial device back to its normal mode of operation.
586 disestablish_ppp(ttyfd);
589 * Run disconnector script, if requested.
590 * XXX we may not be able to do this if the line has hung up!
592 if (disconnector && !hungup) {
593 set_up_tty(ttyfd, 1);
594 if (device_script(disconnector, ttyfd, ttyfd) < 0) {
595 syslog(LOG_WARNING, "disconnect script failed");
597 syslog(LOG_INFO, "Serial link disconnected.");
610 if (pidfilename[0] != 0
611 && unlink(pidfilename) < 0 && errno != ENOENT)
612 syslog(LOG_WARNING, "unable to delete pid file: %m");
616 if (unlink(iffilename) < 0 && errno != ENOENT)
617 syslog(LOG_WARNING, "unable to delete if file: %m");
621 /* limit to retries? */
622 if (max_con_attempts)
623 if (connect_attempts >= max_con_attempts)
631 if (holdoff > 0 && need_holdoff) {
632 phase = PHASE_HOLDOFF;
633 TIMEOUT(holdoff_end, NULL, holdoff);
635 wait_time(timeleft(&timo));
641 phase = PHASE_DORMANT; /* allow signal to end holdoff */
644 } while (phase == PHASE_HOLDOFF);
653 * detach - detach us from the controlling terminal.
660 if (daemon(0, 0) < 0) {
661 perror("Couldn't detach from controlling terminal");
666 /* update pid file if it has been written already */
672 * Create a file containing our process ID.
679 (void) sprintf(pidfilename, "%s%s.pid", _PATH_VARRUN, ifname);
680 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
681 fprintf(pidfile, "%d\n", pid);
682 (void) fclose(pidfile);
684 syslog(LOG_ERR, "Failed to create pid file %s: %m", pidfilename);
690 * holdoff_end - called via a timeout when the holdoff period ends.
696 phase = PHASE_DORMANT;
700 * get_input - called when incoming data is available.
708 struct protent *protp;
710 p = inpacket_buf; /* point to beginning of packet buffer */
712 len = read_packet(inpacket_buf);
717 etime = time((time_t *) NULL);
718 minutes = (etime-stime)/60;
719 syslog(LOG_NOTICE, "Modem hangup, connected for %d minutes", (minutes >1) ? minutes : 1);
721 lcp_lowerdown(0); /* serial link is no longer available */
726 if (debug /*&& (debugflags & DBG_INPACKET)*/)
727 log_packet(p, len, "rcvd ", LOG_DEBUG);
729 if (len < PPP_HDRLEN) {
730 MAINDEBUG((LOG_INFO, "io(): Received short packet."));
734 p += 2; /* Skip address and control */
735 GETSHORT(protocol, p);
739 * Toss all non-LCP packets unless LCP is OPEN.
741 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
743 "get_input: Received non-LCP packet when LCP not open."));
748 * Until we get past the authentication phase, toss all packets
749 * except LCP, LQR and authentication packets.
751 if (phase <= PHASE_AUTHENTICATE
752 && !(protocol == PPP_LCP || protocol == PPP_LQR
753 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
754 MAINDEBUG((LOG_INFO, "get_input: discarding proto 0x%x in phase %d",
760 * Upcall the proper protocol input routine.
762 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
763 if (protp->protocol == protocol && protp->enabled_flag) {
764 (*protp->input)(0, p, len);
767 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
768 && protp->datainput != NULL) {
769 (*protp->datainput)(0, p, len);
775 syslog(LOG_WARNING, "Unsupported protocol (0x%x) received", protocol);
776 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
781 * quit - Clean up state and exit (with an error indication).
790 * die - like quit, except we can specify an exit status.
797 syslog(LOG_INFO, "Exit.");
802 * cleanup - restore anything which needs to be restored before we exit
813 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
814 syslog(LOG_WARNING, "unable to delete pid file: %m");
822 * close_tty - restore the terminal device and close it.
827 disestablish_ppp(ttyfd);
829 /* drop dtr to hang up */
831 setdtr(ttyfd, FALSE);
833 * This sleep is in case the serial port has CLOCAL set by default,
834 * and consequently will reassert DTR when we close the device.
841 if (tty_mode != (mode_t) -1)
842 fchmod(ttyfd, tty_mode);
850 struct timeval c_time; /* time at which to call routine */
851 void *c_arg; /* argument to routine */
852 void (*c_func) __P((void *)); /* routine */
853 struct callout *c_next;
856 static struct callout *callout = NULL; /* Callout list */
857 static struct timeval timenow; /* Current time */
860 * timeout - Schedule a timeout.
862 * Note that this timeout takes the number of seconds, NOT hz (as in
866 timeout(func, arg, time)
867 void (*func) __P((void *));
871 struct callout *newp, *p, **pp;
873 MAINDEBUG((LOG_DEBUG, "Timeout %lx:%lx in %d seconds.",
874 (long) func, (long) arg, time));
879 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL) {
880 syslog(LOG_ERR, "Out of memory in timeout()!");
885 gettimeofday(&timenow, NULL);
886 newp->c_time.tv_sec = timenow.tv_sec + time;
887 newp->c_time.tv_usec = timenow.tv_usec;
890 * Find correct place and link it in.
892 for (pp = &callout; (p = *pp); pp = &p->c_next)
893 if (newp->c_time.tv_sec < p->c_time.tv_sec
894 || (newp->c_time.tv_sec == p->c_time.tv_sec
895 && newp->c_time.tv_usec < p->c_time.tv_sec))
903 * untimeout - Unschedule a timeout.
907 void (*func) __P((void *));
910 struct callout **copp, *freep;
912 MAINDEBUG((LOG_DEBUG, "Untimeout %lx:%lx.", (long) func, (long) arg));
915 * Find first matching timeout and remove it from the list.
917 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
918 if (freep->c_func == func && freep->c_arg == arg) {
919 *copp = freep->c_next;
920 (void) free((char *) freep);
927 * calltimeout - Call any timeout routines which are now due.
934 while (callout != NULL) {
937 if (gettimeofday(&timenow, NULL) < 0) {
938 syslog(LOG_ERR, "Failed to get time of day: %m");
941 if (!(p->c_time.tv_sec < timenow.tv_sec
942 || (p->c_time.tv_sec == timenow.tv_sec
943 && p->c_time.tv_usec <= timenow.tv_usec)))
944 break; /* no, it's not time yet */
947 (*p->c_func)(p->c_arg);
955 * timeleft - return the length of time until the next timeout is due.
957 static struct timeval *
964 gettimeofday(&timenow, NULL);
965 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
966 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
967 if (tvp->tv_usec < 0) {
968 tvp->tv_usec += 1000000;
972 tvp->tv_sec = tvp->tv_usec = 0;
979 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
985 struct sigaction act, oldact;
987 act.sa_handler = SIG_IGN;
990 sigaction(sig, &act, &oldact);
991 sigaction(sig, &oldact, NULL);
996 * hup - Catch SIGHUP signal.
998 * Indicates that the physical layer has been disconnected.
999 * We don't rely on this indication; if the user has sent this
1000 * signal, we just take the link down.
1006 syslog(LOG_INFO, "Hangup (SIGHUP)");
1009 /* Send the signal to the [dis]connector process(es) also */
1015 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1017 * Indicates that we should initiate a graceful disconnect and exit.
1024 syslog(LOG_INFO, "Terminating on signal %d.", sig);
1025 persist = 0; /* don't try to restart */
1028 /* Send the signal to the [dis]connector process(es) also */
1034 * chld - Catch SIGCHLD signal.
1035 * Calls reap_kids to get status for any dead kids.
1046 * toggle_debug - Catch SIGUSR1 signal.
1048 * Toggle debug flag.
1057 setlogmask(LOG_UPTO(LOG_DEBUG));
1059 setlogmask(LOG_UPTO(LOG_WARNING));
1065 * open_ccp - Catch SIGUSR2 signal.
1067 * 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 == 0) {
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 * run-program - execute a program with given arguments,
1170 * but don't wait for it.
1171 * If the program can't be executed, logs an error unless
1172 * must_exist is 0 and the program file doesn't exist.
1175 run_program(prog, args, must_exist)
1184 syslog(LOG_ERR, "Failed to create child process for %s: %m", prog);
1190 /* Leave the current location */
1191 (void) setsid(); /* No controlling tty. */
1192 (void) umask (S_IRWXG|S_IRWXO);
1193 (void) chdir ("/"); /* no current directory. */
1197 /* Ensure that nothing of our device environment is inherited. */
1203 close (ttyfd); /* tty interface to the ppp device */
1205 /* Don't pass handles to the PPP device, even by accident. */
1206 new_fd = open (_PATH_DEVNULL, O_RDWR);
1209 dup2 (new_fd, 0); /* stdin <- /dev/null */
1212 dup2 (0, 1); /* stdout -> /dev/null */
1213 dup2 (0, 2); /* stderr -> /dev/null */
1217 /* Force the priority back to zero if pppd is running higher. */
1218 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1219 syslog (LOG_WARNING, "can't reset priority to 0: %m");
1222 /* SysV recommends a second fork at this point. */
1224 /* run the program; give it a null environment */
1225 execve(prog, args, script_env);
1226 if (must_exist || errno != ENOENT)
1227 syslog(LOG_WARNING, "Can't execute %s: %m", prog);
1230 MAINDEBUG((LOG_DEBUG, "Script %s started; pid = %d", prog, pid));
1237 * reap_kids - get status from any dead child processes,
1238 * and log a message for abnormal terminations.
1245 if (n_children == 0)
1247 if ((pid = waitpid(-1, &status, WNOHANG)) == -1) {
1248 if (errno != ECHILD)
1249 syslog(LOG_ERR, "Error waiting for child process: %m");
1254 if (WIFSIGNALED(status)) {
1255 syslog(LOG_WARNING, "Child process %d terminated with signal %d",
1256 pid, WTERMSIG(status));
1263 * log_packet - format a packet and log it.
1266 char line[256]; /* line to be logged accumulated here */
1270 log_packet(p, len, prefix, level)
1276 strcpy(line, prefix);
1277 linep = line + strlen(line);
1278 format_packet(p, len, pr_log, NULL);
1280 syslog(level, "%s", line);
1284 * format_packet - make a readable representation of a packet,
1285 * calling `printer(arg, format, ...)' to output it.
1288 format_packet(p, len, printer, arg)
1291 void (*printer) __P((void *, char *, ...));
1297 struct protent *protp;
1299 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1303 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1304 if (proto == protp->protocol)
1306 if (protp != NULL) {
1307 printer(arg, "[%s", protp->name);
1308 n = (*protp->printpkt)(p, len, printer, arg);
1313 printer(arg, "[proto=0x%x]", proto);
1317 for (; len > 0; --len) {
1319 printer(arg, " %.2x", x);
1324 pr_log __V((void *arg, char *fmt, ...))
1331 va_start(pvar, fmt);
1336 arg = va_arg(pvar, void *);
1337 fmt = va_arg(pvar, char *);
1340 n = vfmtmsg(buf, sizeof(buf), fmt, pvar);
1343 if (linep + n + 1 > line + sizeof(line)) {
1344 syslog(LOG_DEBUG, "%s", line);
1352 * print_string - print a readable representation of a string using
1356 print_string(p, len, printer, arg)
1359 void (*printer) __P((void *, char *, ...));
1365 for (; len > 0; --len) {
1367 if (' ' <= c && c <= '~') {
1368 if (c == '\\' || c == '"')
1370 printer(arg, "%c", c);
1374 printer(arg, "\\n");
1377 printer(arg, "\\r");
1380 printer(arg, "\\t");
1383 printer(arg, "\\%.3o", c);
1391 * novm - log an error message saying we ran out of memory, and die.
1397 syslog(LOG_ERR, "Virtual memory exhausted allocating %s\n", msg);
1402 * fmtmsg - format a message into a buffer. Like sprintf except we
1403 * also specify the length of the output buffer, and we handle
1404 * %r (recursive format), %m (error message) and %I (IP address) formats.
1405 * Doesn't do floating-point formats.
1406 * Returns the number of chars put into buf.
1409 fmtmsg __V((char *buf, int buflen, char *fmt, ...))
1415 va_start(args, fmt);
1421 buf = va_arg(args, char *);
1422 buflen = va_arg(args, int);
1423 fmt = va_arg(args, char *);
1425 n = vfmtmsg(buf, buflen, fmt, args);
1431 * vfmtmsg - like fmtmsg, takes a va_list instead of a list of args.
1433 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1436 vfmtmsg(buf, buflen, fmt, args)
1443 int width, prec, fillch;
1444 int base, len, neg, quoted;
1445 unsigned long val = 0;
1446 char *str, *f, *buf0;
1450 static char hexchars[] = "0123456789abcdef";
1454 while (buflen > 0) {
1455 for (f = fmt; *f != '%' && *f != 0; ++f)
1461 memcpy(buf, fmt, len);
1476 width = va_arg(args, int);
1479 while (isdigit(c)) {
1480 width = width * 10 + c - '0';
1487 prec = va_arg(args, int);
1490 while (isdigit(c)) {
1491 prec = prec * 10 + c - '0';
1502 i = va_arg(args, int);
1511 val = va_arg(args, unsigned int);
1515 val = va_arg(args, unsigned int);
1519 val = (unsigned long) va_arg(args, void *);
1524 str = va_arg(args, char *);
1527 num[0] = va_arg(args, int);
1532 str = strerror(errno);
1535 str = ip_ntoa(va_arg(args, u_int32_t));
1538 f = va_arg(args, char *);
1539 #if !defined(__powerpc__) && !defined(__amd64__)
1540 n = vfmtmsg(buf, buflen + 1, f, va_arg(args, va_list));
1542 /* On the powerpc, a va_list is an array of 1 structure */
1543 n = vfmtmsg(buf, buflen + 1, f, va_arg(args, void *));
1551 str += 4; /* chop off the day name */
1552 str[15] = 0; /* chop off year and newline */
1554 case 'v': /* "visible" string */
1555 case 'q': /* quoted string */
1557 p = va_arg(args, unsigned char *);
1558 if (fillch == '0' && prec > 0) {
1561 n = strlen((char *)p);
1562 if (prec > 0 && prec < n)
1565 while (n > 0 && buflen > 0) {
1568 if (!quoted && c >= 0x80) {
1573 if (quoted && (c == '"' || c == '\\'))
1575 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1579 case '\t': OUTCHAR('t'); break;
1580 case '\n': OUTCHAR('n'); break;
1581 case '\b': OUTCHAR('b'); break;
1582 case '\f': OUTCHAR('f'); break;
1585 OUTCHAR(hexchars[c >> 4]);
1586 OUTCHAR(hexchars[c & 0xf]);
1603 --fmt; /* so %z outputs %z etc. */
1608 str = num + sizeof(num);
1610 while (str > num + neg) {
1611 *--str = hexchars[val % base];
1613 if (--prec <= 0 && val == 0)
1625 len = num + sizeof(num) - 1 - str;
1628 if (prec > 0 && len > prec)
1634 if ((n = width - len) > 0) {
1642 memcpy(buf, str, len);
1651 * script_setenv - set an environment variable value to be used
1652 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1655 script_setenv(var, value)
1658 int vl = strlen(var);
1660 char *p, *newstring;
1662 newstring = (char *) malloc(vl + strlen(value) + 2);
1665 strcpy(newstring, var);
1666 newstring[vl] = '=';
1667 strcpy(newstring+vl+1, value);
1669 /* check if this variable is already set */
1670 if (script_env != 0) {
1671 for (i = 0; (p = script_env[i]) != 0; ++i) {
1672 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1674 script_env[i] = newstring;
1680 script_env = (char **) malloc(16 * sizeof(char *));
1681 if (script_env == 0)
1686 /* reallocate script_env with more space if needed */
1687 if (i + 1 >= s_env_nalloc) {
1689 char **newenv = (char **) realloc((void *)script_env,
1690 new_n * sizeof(char *));
1693 script_env = newenv;
1694 s_env_nalloc = new_n;
1697 script_env[i] = newstring;
1698 script_env[i+1] = 0;
1702 * script_unsetenv - remove a variable from the environment
1706 script_unsetenv(var)
1709 int vl = strlen(var);
1713 if (script_env == 0)
1715 for (i = 0; (p = script_env[i]) != 0; ++i) {
1716 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1718 while ((script_env[i] = script_env[i+1]) != 0)