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.76 1999/04/16 11:35:06 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 ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
80 static uid_t uid; /* Our real user-id */
81 static int conn_running; /* we have a [dis]connector running */
83 int ttyfd; /* 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 */
90 int log_to_fd; /* send log messages to this fd too */
92 static int fd_ppp = -1; /* fd for talking PPP */
93 static int fd_loop; /* fd for getting demand-dial packets */
94 static int pty_master; /* fd for master side of pty */
95 static int pty_slave; /* fd for slave side of pty */
96 static int real_ttyfd; /* fd for actual serial port (not pty) */
98 int phase; /* where the link is at */
103 static sigjmp_buf sigjmp;
105 char **script_env; /* Env. variable values for scripts */
106 int s_env_nalloc; /* # words avail at script_env */
108 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
109 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
111 static int n_children; /* # child processes still running */
112 static int got_sigchld; /* set if we have received a SIGCHLD */
114 static int locked; /* lock() has succeeded */
116 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
118 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
119 int ngroups; /* How many groups valid in groups */
121 static struct timeval start_time; /* Time when link was started. */
123 struct pppd_stats link_stats;
124 int link_stats_valid;
126 static int charshunt_pid; /* Process ID for charshunt */
129 * We maintain a list of child process pids and
130 * functions to call when they exit.
135 void (*done) __P((void *));
137 struct subprocess *next;
140 static struct subprocess *children;
142 /* Prototypes for procedures local to this file. */
144 static void create_pidfile __P((void));
145 static void cleanup __P((void));
146 static void close_tty __P((void));
147 static void get_input __P((void));
148 static void calltimeout __P((void));
149 static struct timeval *timeleft __P((struct timeval *));
150 static void kill_my_pg __P((int));
151 static void hup __P((int));
152 static void term __P((int));
153 static void chld __P((int));
154 static void toggle_debug __P((int));
155 static void open_ccp __P((int));
156 static void bad_signal __P((int));
157 static void holdoff_end __P((void *));
158 static int device_script __P((char *, int, int, int));
159 static void reap_kids __P((int waitfor));
160 static void record_child __P((int, char *, void (*) (void *), void *));
161 static int start_charshunt __P((int, int));
162 static void charshunt_done __P((void *));
163 static void charshunt __P((int, int, char *));
164 static int record_write __P((FILE *, int code, u_char *buf, int nb,
167 extern char *ttyname __P((int));
168 extern char *getlogin __P((void));
169 int main __P((int, char *[]));
173 #define O_NONBLOCK O_NDELAY
177 #define setlogmask(x)
181 * PPP Data Link Layer "protocol" table.
182 * One entry per supported protocol.
183 * The last entry must be NULL.
185 struct protent *protocols[] = {
214 struct protent *protp;
219 phase = PHASE_INITIALIZE;
223 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
224 * This way we can close 0, 1, 2 in detach() without clobbering
225 * a fd that we are using.
227 if ((i = open("/dev/null", O_RDWR)) >= 0) {
228 while (0 <= i && i <= 2)
236 /* Initialize syslog facilities */
239 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
240 option_error("Couldn't get hostname: %m");
243 hostname[MAXNAMELEN-1] = 0;
246 privileged = uid == 0;
247 slprintf(numbuf, sizeof(numbuf), "%d", uid);
248 script_setenv("ORIG_UID", numbuf);
250 ngroups = getgroups(NGROUPS_MAX, groups);
253 * Initialize to the standard option set, then parse, in order,
254 * the system options file, the user's options file,
255 * the tty's options file, and the command line arguments.
257 for (i = 0; (protp = protocols[i]) != NULL; ++i)
262 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
263 || !options_from_user())
265 using_pty = notty || ptycommand != NULL;
266 scan_args(argc-1, argv+1); /* look for tty name on command line */
269 * Work out the device name, if it hasn't already been specified.
272 p = isatty(0)? ttyname(0): NULL;
275 strlcpy(devnam, p, sizeof(devnam));
276 else if (strcmp(devnam, p) == 0)
282 * Parse the tty options file and the command line.
284 if (!options_for_tty()
285 || !parse_args(argc-1, argv+1))
289 * Check that we are running as root.
291 if (geteuid() != 0) {
292 option_error("must be root to run %s, since it is not setuid-root",
297 if (!ppp_available()) {
298 option_error(no_ppp_msg);
303 * Check that the options given are valid and consistent.
305 if (!sys_check_options())
307 auth_check_options();
308 for (i = 0; (protp = protocols[i]) != NULL; ++i)
309 if (protp->check_options != NULL)
310 (*protp->check_options)();
311 if (demand && connector == 0) {
312 option_error("connect script is required for demand-dialling\n");
317 if (!default_device) {
318 option_error("%s option precludes specifying device name",
319 notty? "notty": "pty");
322 if (ptycommand != NULL && notty) {
323 option_error("pty option is incompatible with notty option");
326 default_device = notty;
330 if (devnam[0] == 0) {
331 option_error("no device specified and stdin is not a tty");
338 log_to_fd = 1; /* default to stdout */
340 script_setenv("DEVICE", devnam);
343 * Initialize system-dependent stuff and magic number package.
348 setlogmask(LOG_UPTO(LOG_DEBUG));
351 * Detach ourselves from the terminal, if required,
352 * and identify who is running us.
354 if (!nodetach && !updetach)
359 if (pw != NULL && pw->pw_name != NULL)
364 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
365 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
366 script_setenv("PPPLOGNAME", p);
369 * Compute mask of all interesting signals and install signal handlers
370 * for each. Only one signal handler may be active at a time. Therefore,
371 * all other signals should be masked when any handler is executing.
374 sigaddset(&mask, SIGHUP);
375 sigaddset(&mask, SIGINT);
376 sigaddset(&mask, SIGTERM);
377 sigaddset(&mask, SIGCHLD);
378 sigaddset(&mask, SIGUSR2);
380 #define SIGNAL(s, handler) do { \
381 sa.sa_handler = handler; \
382 if (sigaction(s, &sa, NULL) < 0) \
383 fatal("Couldn't establish signal handler (%d): %m", s); \
388 SIGNAL(SIGHUP, hup); /* Hangup */
389 SIGNAL(SIGINT, term); /* Interrupt */
390 SIGNAL(SIGTERM, term); /* Terminate */
391 SIGNAL(SIGCHLD, chld);
393 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
394 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
397 * Install a handler for other signals which would otherwise
398 * cause pppd to exit without cleaning up.
400 SIGNAL(SIGABRT, bad_signal);
401 SIGNAL(SIGALRM, bad_signal);
402 SIGNAL(SIGFPE, bad_signal);
403 SIGNAL(SIGILL, bad_signal);
404 SIGNAL(SIGPIPE, bad_signal);
405 SIGNAL(SIGQUIT, bad_signal);
406 SIGNAL(SIGSEGV, bad_signal);
408 SIGNAL(SIGBUS, bad_signal);
411 SIGNAL(SIGEMT, bad_signal);
414 SIGNAL(SIGPOLL, bad_signal);
417 SIGNAL(SIGPROF, bad_signal);
420 SIGNAL(SIGSYS, bad_signal);
423 SIGNAL(SIGTRAP, bad_signal);
426 SIGNAL(SIGVTALRM, bad_signal);
429 SIGNAL(SIGXCPU, bad_signal);
432 SIGNAL(SIGXFSZ, bad_signal);
436 * Apparently we can get a SIGPIPE when we call syslog, if
437 * syslogd has died and been restarted. Ignoring it seems
440 signal(SIGPIPE, SIG_IGN);
445 * If we're doing dial-on-demand, set up the interface now.
449 * Open the loopback channel and set it up to be the ppp interface.
451 fd_loop = open_ppp_loopback();
453 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
454 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
455 script_setenv("IFNAME", ifname);
457 create_pidfile(); /* write pid to file */
460 * Configure the interface and mark it up, etc.
473 * Don't do anything until we see some activity.
476 phase = PHASE_DORMANT;
480 if (sigsetjmp(sigjmp, 1) == 0) {
481 sigprocmask(SIG_BLOCK, &mask, NULL);
482 if (kill_link || got_sigchld) {
483 sigprocmask(SIG_UNBLOCK, &mask, NULL);
486 sigprocmask(SIG_UNBLOCK, &mask, NULL);
487 wait_input(timeleft(&timo));
497 if (get_loop_output())
503 if (kill_link && !persist)
507 * Now we want to bring up the link.
510 info("Starting link");
514 * Get a pty master/slave pair if the pty, notty, or record
515 * options were specified.
517 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
520 if (ptycommand != NULL || notty || record_file != NULL) {
521 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
522 error("Couldn't allocate pseudo-tty");
525 set_up_tty(pty_slave, 1);
529 * Lock the device if we've been asked to.
531 if (lockflag && !default_device) {
532 if (lock(devnam) < 0)
538 * Open the serial device and set it up to be the ppp interface.
539 * First we open it in non-blocking mode so we can set the
540 * various termios flags appropriately. If we aren't dialling
541 * out and we want to use the modem lines, we reopen it later
542 * in order to wait for the carrier detect signal from the modem.
546 if (devnam[0] != 0) {
548 /* If the user specified the device name, become the
549 user before opening it. */
551 if (!devnam_info.priv && !default_device)
553 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
555 if (!devnam_info.priv && !default_device)
561 error("Failed to open %s: %m", devnam);
562 if (!persist || err != EINTR)
565 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
566 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
567 warn("Couldn't reset non-blocking mode on device: %m");
570 * Do the equivalent of `mesg n' to stop broadcast messages.
572 if (fstat(ttyfd, &statbuf) < 0
573 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
574 warn("Couldn't restrict write permissions to %s: %m", devnam);
576 tty_mode = statbuf.st_mode;
579 * Set line speed, flow control, etc.
580 * If we have a non-null connection script,
581 * on most systems we set CLOCAL for now so that we can talk
582 * to the modem before carrier comes up. But this has the
583 * side effect that we might miss it if CD drops before we
584 * get to clear CLOCAL below. On systems where we can talk
585 * successfully to the modem with CLOCAL clear and CD down,
586 * we could clear CLOCAL at this point.
588 set_up_tty(ttyfd, (connector != NULL && connector[0] != 0));
593 * If the notty and/or record option was specified,
594 * start up the character shunt now.
596 if (ptycommand != NULL) {
597 if (record_file != NULL) {
598 int ipipe[2], opipe[2], ok;
600 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
601 fatal("Couldn't create pipes for record option: %m");
602 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
603 && start_charshunt(ipipe[0], opipe[1]);
611 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
618 if (!start_charshunt(0, 1))
620 } else if (record_file != NULL) {
621 if (!start_charshunt(ttyfd, ttyfd))
625 /* run connection script */
626 if (connector && connector[0]) {
627 MAINDEBUG(("Connecting with <%s>", connector));
629 if (real_ttyfd != -1) {
630 if (!default_device && modem) {
631 setdtr(real_ttyfd, 0); /* in case modem is off hook */
633 setdtr(real_ttyfd, 1);
637 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
638 error("Connect script failed");
644 info("Serial connection established.");
646 /* set line speed, flow control, etc.;
647 clear CLOCAL if modem option */
648 if (real_ttyfd != -1)
649 set_up_tty(real_ttyfd, 0);
652 /* reopen tty if necessary to wait for carrier */
653 if (connector == NULL && modem && devnam[0] != 0) {
655 if ((i = open(devnam, O_RDWR)) >= 0)
658 error("Failed to reopen %s: %m", devnam);
659 if (!persist || errno != EINTR || hungup || kill_link)
665 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
666 script_setenv("SPEED", numbuf);
668 /* run welcome script, if any */
669 if (welcomer && welcomer[0]) {
670 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
671 warn("Welcome script failed");
674 /* set up the serial device as a ppp interface */
675 fd_ppp = establish_ppp(ttyfd);
681 info("Using interface ppp%d", ifunit);
682 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
683 script_setenv("IFNAME", ifname);
685 create_pidfile(); /* write pid to file */
689 * Start opening the connection and wait for
690 * incoming events (reply, timeout, etc.).
692 notice("Connect: %s <--> %s", ifname, ppp_devnam);
693 gettimeofday(&start_time, NULL);
697 * If we are initiating this connection, wait for a short
698 * time for something from the peer. This can avoid bouncing
699 * our packets off his tty before he has it set up.
701 if (connector != NULL || ptycommand != NULL) {
708 lcp_open(0); /* Start protocol */
711 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
712 if (sigsetjmp(sigjmp, 1) == 0) {
713 sigprocmask(SIG_BLOCK, &mask, NULL);
714 if (kill_link || open_ccp_flag || got_sigchld) {
715 sigprocmask(SIG_UNBLOCK, &mask, NULL);
718 sigprocmask(SIG_UNBLOCK, &mask, NULL);
719 wait_input(timeleft(&timo));
726 lcp_close(0, "User request");
730 if (phase == PHASE_NETWORK) {
731 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
732 (*ccp_protent.open)(0);
737 reap_kids(0); /* Don't leave dead kids lying around */
741 * Print connect time and statistics.
743 if (gettimeofday(&now, NULL) >= 0) {
744 int t = now.tv_sec - start_time.tv_sec;
745 t = (t + 5) / 6; /* now in 1/10ths of minutes */
746 info("Connect time %d.%d minutes.", t/10, t%10);
748 if (link_stats_valid) {
749 info("Sent %d bytes, received %d bytes.",
750 link_stats.bytes_out, link_stats.bytes_in);
754 * If we may want to bring the link up again, transfer
755 * the ppp unit back to the loopback. Set the
756 * real serial device back to its normal mode of operation.
762 disestablish_ppp(ttyfd);
768 * Run disconnector script, if requested.
769 * XXX we may not be able to do this if the line has hung up!
772 if (disconnector && !hungup) {
774 set_up_tty(real_ttyfd, 1);
775 if (device_script(disconnector, ttyfd, ttyfd, 0) < 0) {
776 warn("disconnect script failed");
778 info("Serial link disconnected.");
795 if (pidfilename[0] != 0
796 && unlink(pidfilename) < 0 && errno != ENOENT)
797 warn("unable to delete pid file: %m");
807 if (holdoff > 0 && need_holdoff) {
808 phase = PHASE_HOLDOFF;
809 TIMEOUT(holdoff_end, NULL, holdoff);
811 if (sigsetjmp(sigjmp, 1) == 0) {
812 sigprocmask(SIG_BLOCK, &mask, NULL);
813 if (kill_link || got_sigchld) {
814 sigprocmask(SIG_UNBLOCK, &mask, NULL);
817 sigprocmask(SIG_UNBLOCK, &mask, NULL);
818 wait_input(timeleft(&timo));
825 phase = PHASE_DORMANT; /* allow signal to end holdoff */
829 } while (phase == PHASE_HOLDOFF);
835 /* Wait for scripts to finish */
836 while (n_children > 0) {
838 struct subprocess *chp;
839 dbglog("Waiting for %d child processes...", n_children);
840 for (chp = children; chp != NULL; chp = chp->next)
841 dbglog(" script %s, pid %d", chp->prog, chp->pid);
851 * detach - detach us from the controlling terminal.
860 if ((pid = fork()) < 0) {
861 error("Couldn't detach (fork failed: %m)");
862 die(1); /* or just return? */
868 exit(0); /* parent dies */
877 /* update pid file if it has been written already */
883 * reopen_log - (re)open our connection to syslog.
889 openlog("pppd", LOG_PID);
891 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
892 setlogmask(LOG_UPTO(LOG_INFO));
897 * Create a file containing our process ID.
905 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
906 _PATH_VARRUN, ifname);
907 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
908 fprintf(pidfile, "%d\n", getpid());
909 (void) fclose(pidfile);
911 error("Failed to create pid file %s: %m", pidfilename);
914 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
915 script_setenv("PPPD_PID", numbuf);
919 * holdoff_end - called via a timeout when the holdoff period ends.
925 phase = PHASE_DORMANT;
929 * get_input - called when incoming data is available.
937 struct protent *protp;
939 p = inpacket_buf; /* point to beginning of packet buffer */
941 len = read_packet(inpacket_buf);
946 notice("Modem hangup");
948 lcp_lowerdown(0); /* serial link is no longer available */
953 if (debug /*&& (debugflags & DBG_INPACKET)*/)
954 dbglog("rcvd %P", p, len);
956 if (len < PPP_HDRLEN) {
957 MAINDEBUG(("io(): Received short packet."));
961 p += 2; /* Skip address and control */
962 GETSHORT(protocol, p);
966 * Toss all non-LCP packets unless LCP is OPEN.
968 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
969 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
974 * Until we get past the authentication phase, toss all packets
975 * except LCP, LQR and authentication packets.
977 if (phase <= PHASE_AUTHENTICATE
978 && !(protocol == PPP_LCP || protocol == PPP_LQR
979 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
980 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
986 * Upcall the proper protocol input routine.
988 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
989 if (protp->protocol == protocol && protp->enabled_flag) {
990 (*protp->input)(0, p, len);
993 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
994 && protp->datainput != NULL) {
995 (*protp->datainput)(0, p, len);
1001 warn("Unsupported protocol (0x%x) received", protocol);
1002 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1007 * die - clean up state and exit with the specified status.
1014 syslog(LOG_INFO, "Exit.");
1019 * cleanup - restore anything which needs to be restored before we exit
1028 disestablish_ppp(ttyfd);
1029 if (real_ttyfd >= 0)
1032 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1033 warn("unable to delete pid file: %m");
1041 * close_tty - restore the terminal device and close it.
1046 /* drop dtr to hang up */
1047 if (!default_device && modem) {
1048 setdtr(real_ttyfd, 0);
1050 * This sleep is in case the serial port has CLOCAL set by default,
1051 * and consequently will reassert DTR when we close the device.
1056 restore_tty(real_ttyfd);
1058 if (tty_mode != (mode_t) -1) {
1059 if (fchmod(real_ttyfd, tty_mode) != 0) {
1060 /* XXX if devnam is a symlink, this will change the link */
1061 chmod(devnam, tty_mode);
1071 struct timeval c_time; /* time at which to call routine */
1072 void *c_arg; /* argument to routine */
1073 void (*c_func) __P((void *)); /* routine */
1074 struct callout *c_next;
1077 static struct callout *callout = NULL; /* Callout list */
1078 static struct timeval timenow; /* Current time */
1081 * timeout - Schedule a timeout.
1083 * Note that this timeout takes the number of seconds, NOT hz (as in
1087 timeout(func, arg, time)
1088 void (*func) __P((void *));
1092 struct callout *newp, *p, **pp;
1094 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1099 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1100 fatal("Out of memory in timeout()!");
1102 newp->c_func = func;
1103 gettimeofday(&timenow, NULL);
1104 newp->c_time.tv_sec = timenow.tv_sec + time;
1105 newp->c_time.tv_usec = timenow.tv_usec;
1108 * Find correct place and link it in.
1110 for (pp = &callout; (p = *pp); pp = &p->c_next)
1111 if (newp->c_time.tv_sec < p->c_time.tv_sec
1112 || (newp->c_time.tv_sec == p->c_time.tv_sec
1113 && newp->c_time.tv_usec < p->c_time.tv_usec))
1121 * untimeout - Unschedule a timeout.
1124 untimeout(func, arg)
1125 void (*func) __P((void *));
1128 struct callout **copp, *freep;
1130 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1133 * Find first matching timeout and remove it from the list.
1135 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1136 if (freep->c_func == func && freep->c_arg == arg) {
1137 *copp = freep->c_next;
1138 (void) free((char *) freep);
1145 * calltimeout - Call any timeout routines which are now due.
1152 while (callout != NULL) {
1155 if (gettimeofday(&timenow, NULL) < 0)
1156 fatal("Failed to get time of day: %m");
1157 if (!(p->c_time.tv_sec < timenow.tv_sec
1158 || (p->c_time.tv_sec == timenow.tv_sec
1159 && p->c_time.tv_usec <= timenow.tv_usec)))
1160 break; /* no, it's not time yet */
1162 callout = p->c_next;
1163 (*p->c_func)(p->c_arg);
1171 * timeleft - return the length of time until the next timeout is due.
1173 static struct timeval *
1175 struct timeval *tvp;
1177 if (callout == NULL)
1180 gettimeofday(&timenow, NULL);
1181 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1182 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1183 if (tvp->tv_usec < 0) {
1184 tvp->tv_usec += 1000000;
1187 if (tvp->tv_sec < 0)
1188 tvp->tv_sec = tvp->tv_usec = 0;
1195 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1201 struct sigaction act, oldact;
1203 act.sa_handler = SIG_IGN;
1206 sigaction(sig, &act, &oldact);
1207 sigaction(sig, &oldact, NULL);
1212 * hup - Catch SIGHUP signal.
1214 * Indicates that the physical layer has been disconnected.
1215 * We don't rely on this indication; if the user has sent this
1216 * signal, we just take the link down.
1222 info("Hangup (SIGHUP)");
1225 /* Send the signal to the [dis]connector process(es) also */
1228 kill(charshunt_pid, sig);
1230 siglongjmp(sigjmp, 1);
1235 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1237 * Indicates that we should initiate a graceful disconnect and exit.
1244 info("Terminating on signal %d.", sig);
1245 persist = 0; /* don't try to restart */
1248 /* Send the signal to the [dis]connector process(es) also */
1251 kill(charshunt_pid, sig);
1253 siglongjmp(sigjmp, 1);
1258 * chld - Catch SIGCHLD signal.
1259 * Sets a flag so we will call reap_kids in the mainline.
1267 siglongjmp(sigjmp, 1);
1272 * toggle_debug - Catch SIGUSR1 signal.
1274 * Toggle debug flag.
1283 setlogmask(LOG_UPTO(LOG_DEBUG));
1285 setlogmask(LOG_UPTO(LOG_WARNING));
1291 * open_ccp - Catch SIGUSR2 signal.
1293 * Try to (re)negotiate compression.
1302 siglongjmp(sigjmp, 1);
1307 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1313 static int crashed = 0;
1318 error("Fatal signal %d", sig);
1320 kill_my_pg(SIGTERM);
1322 kill(charshunt_pid, SIGTERM);
1328 * device_script - run a program to talk to the serial device
1329 * (e.g. to run the connector or disconnector script).
1332 device_script(program, in, out, dont_wait)
1346 error("Failed to create child process: %m");
1355 int newin = dup(in);
1359 } else if (out == 2) {
1362 if (log_to_fd >= 0) {
1367 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1368 if (errfd >= 0 && errfd != 2) {
1388 if (getuid() != uid) {
1389 error("setuid failed");
1393 execl("/bin/sh", "sh", "-c", program, (char *)0);
1394 error("could not exec /bin/sh: %m");
1400 record_child(pid, program, NULL, NULL);
1403 while (waitpid(pid, &status, 0) < 0) {
1406 fatal("error waiting for (dis)connection process: %m");
1411 return (status == 0 ? 0 : -1);
1416 * run-program - execute a program with given arguments,
1417 * but don't wait for it.
1418 * If the program can't be executed, logs an error unless
1419 * must_exist is 0 and the program file doesn't exist.
1420 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1421 * or isn't an executable plain file, or the process ID of the child.
1422 * If done != NULL, (*done)(arg) will be called later (within
1423 * reap_kids) iff the return value is > 0.
1426 run_program(prog, args, must_exist, done, arg)
1430 void (*done) __P((void *));
1437 * First check if the file exists and is executable.
1438 * We don't use access() because that would use the
1439 * real user-id, which might not be root, and the script
1440 * might be accessible only to root.
1443 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1444 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1445 if (must_exist || errno != ENOENT)
1446 warn("Can't execute %s: %m", prog);
1452 error("Failed to create child process for %s: %m", prog);
1458 /* Leave the current location */
1459 (void) setsid(); /* No controlling tty. */
1460 (void) umask (S_IRWXG|S_IRWXO);
1461 (void) chdir ("/"); /* no current directory. */
1462 setuid(0); /* set real UID = root */
1465 /* Ensure that nothing of our device environment is inherited. */
1471 close (ttyfd); /* tty interface to the ppp device */
1472 if (real_ttyfd >= 0)
1475 /* Don't pass handles to the PPP device, even by accident. */
1476 new_fd = open (_PATH_DEVNULL, O_RDWR);
1479 dup2 (new_fd, 0); /* stdin <- /dev/null */
1482 dup2 (0, 1); /* stdout -> /dev/null */
1483 dup2 (0, 2); /* stderr -> /dev/null */
1487 /* Force the priority back to zero if pppd is running higher. */
1488 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1489 warn("can't reset priority to 0: %m");
1492 /* SysV recommends a second fork at this point. */
1494 /* run the program */
1495 execve(prog, args, script_env);
1496 if (must_exist || errno != ENOENT) {
1497 /* have to reopen the log, there's nowhere else
1498 for the message to go. */
1500 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1507 dbglog("Script %s started (pid %d)", prog, pid);
1508 record_child(pid, prog, done, arg);
1515 * record_child - add a child process to the list for reap_kids
1519 record_child(pid, prog, done, arg)
1522 void (*done) __P((void *));
1525 struct subprocess *chp;
1529 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1531 warn("losing track of %s process", prog);
1537 chp->next = children;
1544 * reap_kids - get status from any dead child processes,
1545 * and log a message for abnormal terminations.
1552 struct subprocess *chp, **prevp;
1555 if (n_children == 0)
1557 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1560 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1561 if (chp->pid == pid)
1563 if (WIFSIGNALED(status)) {
1564 warn("Child process %s (pid %d) terminated with signal %d",
1565 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1567 dbglog("Script %s finished (pid %d), status = 0x%x",
1568 (chp? chp->prog: "??"), pid, status);
1569 if (chp && chp->done)
1570 (*chp->done)(chp->arg);
1572 if (pid == -1 && errno != ECHILD && errno != EINTR)
1573 error("Error waiting for child process: %m");
1578 * novm - log an error message saying we ran out of memory, and die.
1584 fatal("Virtual memory exhausted allocating %s\n", msg);
1588 * script_setenv - set an environment variable value to be used
1589 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1592 script_setenv(var, value)
1595 size_t vl = strlen(var) + strlen(value) + 2;
1597 char *p, *newstring;
1599 newstring = (char *) malloc(vl);
1602 slprintf(newstring, vl, "%s=%s", var, value);
1604 /* check if this variable is already set */
1605 if (script_env != 0) {
1606 for (i = 0; (p = script_env[i]) != 0; ++i) {
1607 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1609 script_env[i] = newstring;
1615 script_env = (char **) malloc(16 * sizeof(char *));
1616 if (script_env == 0)
1621 /* reallocate script_env with more space if needed */
1622 if (i + 1 >= s_env_nalloc) {
1624 char **newenv = (char **) realloc((void *)script_env,
1625 new_n * sizeof(char *));
1628 script_env = newenv;
1629 s_env_nalloc = new_n;
1632 script_env[i] = newstring;
1633 script_env[i+1] = 0;
1637 * script_unsetenv - remove a variable from the environment
1641 script_unsetenv(var)
1644 int vl = strlen(var);
1648 if (script_env == 0)
1650 for (i = 0; (p = script_env[i]) != 0; ++i) {
1651 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1653 while ((script_env[i] = script_env[i+1]) != 0)
1661 * start_charshunt - create a child process to run the character shunt.
1664 start_charshunt(ifd, ofd)
1671 error("Can't fork process for character shunt: %m");
1678 if (getuid() != uid)
1679 fatal("setuid failed");
1683 charshunt(ifd, ofd, record_file);
1686 charshunt_pid = cpid;
1690 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
1702 * charshunt - the character shunt, which passes characters between
1703 * the pty master side and the serial port (or stdin/stdout).
1704 * This runs as the user (not as root).
1705 * (We assume ofd >= ifd which is true the way this gets called. :-).
1708 charshunt(ifd, ofd, record_file)
1713 fd_set ready, writey;
1714 u_char *ibufp, *obufp;
1717 int pty_readable, stdin_readable;
1718 struct timeval lasttime;
1719 FILE *recordf = NULL;
1722 * Reset signal handlers.
1724 signal(SIGHUP, SIG_IGN); /* Hangup */
1725 signal(SIGINT, SIG_DFL); /* Interrupt */
1726 signal(SIGTERM, SIG_DFL); /* Terminate */
1727 signal(SIGCHLD, SIG_DFL);
1728 signal(SIGUSR1, SIG_DFL);
1729 signal(SIGUSR2, SIG_DFL);
1730 signal(SIGABRT, SIG_DFL);
1731 signal(SIGALRM, SIG_DFL);
1732 signal(SIGFPE, SIG_DFL);
1733 signal(SIGILL, SIG_DFL);
1734 signal(SIGPIPE, SIG_DFL);
1735 signal(SIGQUIT, SIG_DFL);
1736 signal(SIGSEGV, SIG_DFL);
1738 signal(SIGBUS, SIG_DFL);
1741 signal(SIGEMT, SIG_DFL);
1744 signal(SIGPOLL, SIG_DFL);
1747 signal(SIGPROF, SIG_DFL);
1750 signal(SIGSYS, SIG_DFL);
1753 signal(SIGTRAP, SIG_DFL);
1756 signal(SIGVTALRM, SIG_DFL);
1759 signal(SIGXCPU, SIG_DFL);
1762 signal(SIGXFSZ, SIG_DFL);
1766 * Open the record file if required.
1768 if (record_file != NULL) {
1769 recordf = fopen(record_file, "a");
1770 if (recordf == NULL)
1771 error("Couldn't create record file %s: %m", record_file);
1774 /* set all the fds to non-blocking mode */
1775 flags = fcntl(pty_master, F_GETFL);
1777 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1778 warn("couldn't set pty master to nonblock: %m");
1779 flags = fcntl(ifd, F_GETFL);
1781 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1782 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1784 flags = fcntl(ofd, F_GETFL);
1786 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1787 warn("couldn't set stdout to nonblock: %m");
1791 ibufp = obufp = NULL;
1792 pty_readable = stdin_readable = 1;
1793 nfds = (ofd > pty_master? ofd: pty_master) + 1;
1794 if (recordf != NULL) {
1795 gettimeofday(&lasttime, NULL);
1796 putc(7, recordf); /* put start marker */
1797 putc(lasttime.tv_sec >> 24, recordf);
1798 putc(lasttime.tv_sec >> 16, recordf);
1799 putc(lasttime.tv_sec >> 8, recordf);
1800 putc(lasttime.tv_sec, recordf);
1801 lasttime.tv_usec = 0;
1804 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1808 FD_SET(pty_master, &writey);
1809 else if (stdin_readable)
1810 FD_SET(ifd, &ready);
1812 FD_SET(ofd, &writey);
1813 else if (pty_readable)
1814 FD_SET(pty_master, &ready);
1815 if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
1820 if (FD_ISSET(ifd, &ready)) {
1821 ibufp = inpacket_buf;
1822 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
1823 if (nibuf < 0 && errno == EIO)
1826 if (!(errno == EINTR || errno == EAGAIN)) {
1827 error("Error reading standard input: %m");
1831 } else if (nibuf == 0) {
1832 /* end of file from stdin */
1834 /* do a 0-length write, hopefully this will generate
1835 an EOF (hangup) on the slave side. */
1836 write(pty_master, inpacket_buf, 0);
1838 if (!record_write(recordf, 4, NULL, 0, &lasttime))
1841 FD_SET(pty_master, &writey);
1843 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
1847 if (FD_ISSET(pty_master, &ready)) {
1848 obufp = outpacket_buf;
1849 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
1850 if (nobuf < 0 && errno == EIO)
1853 if (!(errno == EINTR || errno == EAGAIN)) {
1854 error("Error reading pseudo-tty master: %m");
1858 } else if (nobuf == 0) {
1859 /* end of file from the pty - slave side has closed */
1861 stdin_readable = 0; /* pty is not writable now */
1865 if (!record_write(recordf, 3, NULL, 0, &lasttime))
1868 FD_SET(ofd, &writey);
1870 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
1874 if (FD_ISSET(ofd, &writey)) {
1875 n = write(ofd, obufp, nobuf);
1878 error("Error writing standard output: %m");
1888 if (FD_ISSET(pty_master, &writey)) {
1889 n = write(pty_master, ibufp, nibuf);
1892 error("Error writing pseudo-tty master: %m");
1907 record_write(f, code, buf, nb, tp)
1917 gettimeofday(&now, NULL);
1918 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
1919 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
1923 putc(diff >> 24, f);
1924 putc(diff >> 16, f);
1937 fwrite(buf, nb, 1, f);
1941 error("Error writing record file: %m");