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.70 1999/03/31 05:39:42 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 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; /* 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 = -1; /* fd for talking PPP */
94 static int fd_loop; /* fd for getting demand-dial packets */
95 static int pty_master; /* fd for master side of pty */
96 static int pty_slave; /* fd for slave side of pty */
97 static int real_ttyfd; /* fd for actual serial port (not pty) */
99 int phase; /* where the link is at */
104 static sigjmp_buf sigjmp;
106 char **script_env; /* Env. variable values for scripts */
107 int s_env_nalloc; /* # words avail at script_env */
109 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
110 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
112 static int n_children; /* # child processes still running */
113 static int got_sigchld; /* set if we have received a SIGCHLD */
115 static int locked; /* lock() has succeeded */
117 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
119 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
120 int ngroups; /* How many groups valid in groups */
122 static struct timeval start_time; /* Time when link was started. */
124 struct pppd_stats link_stats;
125 int link_stats_valid;
127 static int charshunt_pid; /* Process ID for charshunt */
129 /* Prototypes for procedures local to this file. */
131 static void create_pidfile __P((void));
132 static void cleanup __P((void));
133 static void close_tty __P((void));
134 static void get_input __P((void));
135 static void calltimeout __P((void));
136 static struct timeval *timeleft __P((struct timeval *));
137 static void kill_my_pg __P((int));
138 static void hup __P((int));
139 static void term __P((int));
140 static void chld __P((int));
141 static void toggle_debug __P((int));
142 static void open_ccp __P((int));
143 static void bad_signal __P((int));
144 static void holdoff_end __P((void *));
145 static int device_script __P((char *, int, int, int));
146 static void reap_kids __P((int waitfor));
147 static void pr_log __P((void *, char *, ...));
148 static void logit __P((int, char *, va_list));
149 static void vslp_printer __P((void *, char *, ...));
150 static void format_packet __P((u_char *, int, void (*) (void *, char *, ...),
152 static void record_child __P((int, char *, void (*) (void *), void *));
153 static int start_charshunt __P((int, int));
154 static void charshunt_done __P((void *));
155 static void charshunt __P((int, int, char *));
156 static int record_write(FILE *, int code, u_char *buf, int nb,
159 extern char *ttyname __P((int));
160 extern char *getlogin __P((void));
161 int main __P((int, char *[]));
165 #define O_NONBLOCK O_NDELAY
169 #define setlogmask(x)
173 * PPP Data Link Layer "protocol" table.
174 * One entry per supported protocol.
175 * The last entry must be NULL.
177 struct protent *protocols[] = {
206 struct protent *protp;
211 phase = PHASE_INITIALIZE;
216 /* Initialize syslog facilities */
219 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
220 option_error("Couldn't get hostname: %m");
223 hostname[MAXNAMELEN-1] = 0;
226 privileged = uid == 0;
227 slprintf(numbuf, sizeof(numbuf), "%d", uid);
228 script_setenv("ORIG_UID", numbuf);
230 ngroups = getgroups(NGROUPS_MAX, groups);
233 * Initialize to the standard option set, then parse, in order,
234 * the system options file, the user's options file,
235 * the tty's options file, and the command line arguments.
237 for (i = 0; (protp = protocols[i]) != NULL; ++i)
242 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
243 || !options_from_user())
245 using_pty = notty || ptycommand != NULL;
246 scan_args(argc-1, argv+1); /* look for tty name on command line */
249 * Work out the device name, if it hasn't already been specified.
252 p = isatty(0)? ttyname(0): NULL;
255 strlcpy(devnam, p, sizeof(devnam));
256 else if (strcmp(devnam, p) == 0)
262 * Parse the tty options file and the command line.
264 if (!options_for_tty()
265 || !parse_args(argc-1, argv+1))
269 * Check that we are running as root.
271 if (geteuid() != 0) {
272 option_error("must be root to run %s, since it is not setuid-root",
277 if (!ppp_available()) {
278 option_error(no_ppp_msg);
283 * Check that the options given are valid and consistent.
285 if (!sys_check_options())
287 auth_check_options();
288 for (i = 0; (protp = protocols[i]) != NULL; ++i)
289 if (protp->check_options != NULL)
290 (*protp->check_options)();
291 if (demand && connector == 0) {
292 option_error("connect script is required for demand-dialling\n");
297 if (!default_device) {
298 option_error("%s option precludes specifying device name",
299 notty? "notty": "pty");
302 if (ptycommand != NULL && notty) {
303 option_error("pty option is incompatible with notty option");
306 default_device = notty;
310 if (devnam[0] == 0) {
311 option_error("no device specified and stdin is not a tty");
318 log_to_fd = 1; /* default to stdout */
320 script_setenv("DEVICE", devnam);
323 * Initialize system-dependent stuff and magic number package.
328 setlogmask(LOG_UPTO(LOG_DEBUG));
331 * Detach ourselves from the terminal, if required,
332 * and identify who is running us.
334 if (!nodetach && !updetach)
340 if (pw != NULL && pw->pw_name != NULL)
345 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
346 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
349 * Compute mask of all interesting signals and install signal handlers
350 * for each. Only one signal handler may be active at a time. Therefore,
351 * all other signals should be masked when any handler is executing.
354 sigaddset(&mask, SIGHUP);
355 sigaddset(&mask, SIGINT);
356 sigaddset(&mask, SIGTERM);
357 sigaddset(&mask, SIGCHLD);
358 sigaddset(&mask, SIGUSR2);
360 #define SIGNAL(s, handler) do { \
361 sa.sa_handler = handler; \
362 if (sigaction(s, &sa, NULL) < 0) \
363 fatal("Couldn't establish signal handler (%d): %m", s); \
368 SIGNAL(SIGHUP, hup); /* Hangup */
369 SIGNAL(SIGINT, term); /* Interrupt */
370 SIGNAL(SIGTERM, term); /* Terminate */
371 SIGNAL(SIGCHLD, chld);
373 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
374 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
377 * Install a handler for other signals which would otherwise
378 * cause pppd to exit without cleaning up.
380 SIGNAL(SIGABRT, bad_signal);
381 SIGNAL(SIGALRM, bad_signal);
382 SIGNAL(SIGFPE, bad_signal);
383 SIGNAL(SIGILL, bad_signal);
384 SIGNAL(SIGPIPE, bad_signal);
385 SIGNAL(SIGQUIT, bad_signal);
386 SIGNAL(SIGSEGV, bad_signal);
388 SIGNAL(SIGBUS, bad_signal);
391 SIGNAL(SIGEMT, bad_signal);
394 SIGNAL(SIGPOLL, bad_signal);
397 SIGNAL(SIGPROF, bad_signal);
400 SIGNAL(SIGSYS, bad_signal);
403 SIGNAL(SIGTRAP, bad_signal);
406 SIGNAL(SIGVTALRM, bad_signal);
409 SIGNAL(SIGXCPU, bad_signal);
412 SIGNAL(SIGXFSZ, bad_signal);
416 * Apparently we can get a SIGPIPE when we call syslog, if
417 * syslogd has died and been restarted. Ignoring it seems
420 signal(SIGPIPE, SIG_IGN);
425 * If we're doing dial-on-demand, set up the interface now.
429 * Open the loopback channel and set it up to be the ppp interface.
431 fd_loop = open_ppp_loopback();
433 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
434 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
435 script_setenv("IFNAME", ifname);
437 create_pidfile(); /* write pid to file */
440 * Configure the interface and mark it up, etc.
453 * Don't do anything until we see some activity.
456 phase = PHASE_DORMANT;
460 if (sigsetjmp(sigjmp, 1) == 0) {
461 sigprocmask(SIG_BLOCK, &mask, NULL);
463 sigprocmask(SIG_UNBLOCK, &mask, NULL);
466 sigprocmask(SIG_UNBLOCK, &mask, NULL);
467 wait_input(timeleft(&timo));
477 if (get_loop_output())
483 if (kill_link && !persist)
487 * Now we want to bring up the link.
490 info("Starting link");
494 * Get a pty master/slave pair if the pty, notty, or record
495 * options were specified.
497 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
500 if (ptycommand != NULL || notty || record_file != NULL) {
501 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
502 error("Couldn't allocate pseudo-tty");
505 set_up_tty(pty_slave, 1);
509 * Lock the device if we've been asked to.
511 if (lockflag && !default_device) {
512 if (lock(devnam) < 0)
518 * Open the serial device and set it up to be the ppp interface.
519 * First we open it in non-blocking mode so we can set the
520 * various termios flags appropriately. If we aren't dialling
521 * out and we want to use the modem lines, we reopen it later
522 * in order to wait for the carrier detect signal from the modem.
526 if (devnam[0] != 0) {
528 /* If the user specified the device name, become the
529 user before opening it. */
530 if (!devnam_info.priv && !default_device)
532 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
533 if (!devnam_info.priv && !default_device)
538 error("Failed to open %s: %m", devnam);
539 if (!persist || errno != EINTR)
542 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
543 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
544 warn("Couldn't reset non-blocking mode on device: %m");
547 * Do the equivalent of `mesg n' to stop broadcast messages.
549 if (fstat(ttyfd, &statbuf) < 0
550 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
551 warn("Couldn't restrict write permissions to %s: %m", devnam);
553 tty_mode = statbuf.st_mode;
556 * Set line speed, flow control, etc.
557 * If we have a non-null connection script,
558 * on most systems we set CLOCAL for now so that we can talk
559 * to the modem before carrier comes up. But this has the
560 * side effect that we might miss it if CD drops before we
561 * get to clear CLOCAL below. On systems where we can talk
562 * successfully to the modem with CLOCAL clear and CD down,
563 * we could clear CLOCAL at this point.
565 set_up_tty(ttyfd, (connector != NULL && connector[0] != 0));
570 * If the notty and/or record option was specified,
571 * start up the character shunt now.
573 if (ptycommand != NULL) {
574 if (record_file != NULL) {
575 int ipipe[2], opipe[2], ok;
577 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
578 fatal("Couldn't create pipes for record option: %m");
579 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
580 && start_charshunt(ipipe[0], opipe[1]);
588 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
595 if (!start_charshunt(0, 1))
597 } else if (record_file != NULL) {
598 if (!start_charshunt(ttyfd, ttyfd))
602 /* run connection script */
603 if (connector && connector[0]) {
604 MAINDEBUG(("Connecting with <%s>", connector));
606 if (real_ttyfd != -1) {
607 if (!default_device && modem) {
608 setdtr(real_ttyfd, 0); /* in case modem is off hook */
610 setdtr(real_ttyfd, 1);
614 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
615 error("Connect script failed");
619 info("Serial connection established.");
621 /* set line speed, flow control, etc.;
622 clear CLOCAL if modem option */
623 if (real_ttyfd != -1)
624 set_up_tty(real_ttyfd, 0);
627 /* reopen tty if necessary to wait for carrier */
628 if (connector == NULL && modem && devnam[0] != 0) {
630 if ((i = open(devnam, O_RDWR)) >= 0)
633 error("Failed to reopen %s: %m", devnam);
634 if (!persist || errno != EINTR || hungup || kill_link)
640 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
641 script_setenv("SPEED", numbuf);
643 /* run welcome script, if any */
644 if (welcomer && welcomer[0]) {
645 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
646 warn("Welcome script failed");
649 /* set up the serial device as a ppp interface */
650 fd_ppp = establish_ppp(ttyfd);
656 info("Using interface ppp%d", ifunit);
657 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
658 script_setenv("IFNAME", ifname);
660 create_pidfile(); /* write pid to file */
664 * Start opening the connection and wait for
665 * incoming events (reply, timeout, etc.).
667 notice("Connect: %s <--> %s", ifname, ppp_devnam);
668 gettimeofday(&start_time, NULL);
672 * If we are initiating this connection, wait for a short
673 * time for something from the peer. This can avoid bouncing
674 * our packets off his tty before he has it set up.
676 if (connector != NULL || ptycommand != NULL) {
683 lcp_open(0); /* Start protocol */
686 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
687 if (sigsetjmp(sigjmp, 1) == 0) {
688 sigprocmask(SIG_BLOCK, &mask, NULL);
689 if (kill_link || open_ccp_flag) {
690 sigprocmask(SIG_UNBLOCK, &mask, NULL);
693 sigprocmask(SIG_UNBLOCK, &mask, NULL);
694 wait_input(timeleft(&timo));
701 lcp_close(0, "User request");
705 if (phase == PHASE_NETWORK) {
706 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
707 (*ccp_protent.open)(0);
712 reap_kids(0); /* Don't leave dead kids lying around */
716 * Print connect time and statistics.
718 if (gettimeofday(&now, NULL) >= 0) {
719 int t = now.tv_sec - start_time.tv_sec;
720 t = (t + 5) / 6; /* now in 1/10ths of minutes */
721 info("Connect time %d.%d minutes.", t/10, t%10);
723 if (link_stats_valid) {
724 info("Sent %d bytes, received %d bytes.",
725 link_stats.bytes_out, link_stats.bytes_in);
729 * If we may want to bring the link up again, transfer
730 * the ppp unit back to the loopback. Set the
731 * real serial device back to its normal mode of operation.
737 disestablish_ppp(ttyfd);
741 * Run disconnector script, if requested.
742 * XXX we may not be able to do this if the line has hung up!
744 if (disconnector && !hungup) {
746 set_up_tty(real_ttyfd, 1);
747 if (device_script(disconnector, ttyfd, ttyfd, 0) < 0) {
748 warn("disconnect script failed");
750 info("Serial link disconnected.");
769 if (pidfilename[0] != 0
770 && unlink(pidfilename) < 0 && errno != ENOENT)
771 warn("unable to delete pid file: %m");
781 if (holdoff > 0 && need_holdoff) {
782 phase = PHASE_HOLDOFF;
783 TIMEOUT(holdoff_end, NULL, holdoff);
785 if (sigsetjmp(sigjmp, 1) == 0) {
786 sigprocmask(SIG_BLOCK, &mask, NULL);
788 sigprocmask(SIG_UNBLOCK, &mask, NULL);
791 sigprocmask(SIG_UNBLOCK, &mask, NULL);
792 wait_input(timeleft(&timo));
799 phase = PHASE_DORMANT; /* allow signal to end holdoff */
803 } while (phase == PHASE_HOLDOFF);
809 /* Wait for scripts to finish */
810 while (n_children > 0)
818 * detach - detach us from the controlling terminal.
825 if (daemon(0, 0) < 0) {
826 perror("Couldn't detach from controlling terminal");
832 /* update pid file if it has been written already */
838 * reopen_log - (re)open our connection to syslog.
844 openlog("pppd", LOG_PID);
846 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
847 setlogmask(LOG_UPTO(LOG_INFO));
852 * Create a file containing our process ID.
860 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
861 _PATH_VARRUN, ifname);
862 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
863 fprintf(pidfile, "%d\n", pid);
864 (void) fclose(pidfile);
866 error("Failed to create pid file %s: %m", pidfilename);
869 slprintf(numbuf, sizeof(numbuf), "%d", pid);
870 script_setenv("PPPD_PID", numbuf);
874 * holdoff_end - called via a timeout when the holdoff period ends.
880 phase = PHASE_DORMANT;
884 * get_input - called when incoming data is available.
892 struct protent *protp;
894 p = inpacket_buf; /* point to beginning of packet buffer */
896 len = read_packet(inpacket_buf);
901 notice("Modem hangup");
903 lcp_lowerdown(0); /* serial link is no longer available */
908 if (debug /*&& (debugflags & DBG_INPACKET)*/)
909 dbglog("rcvd %P", p, len);
911 if (len < PPP_HDRLEN) {
912 MAINDEBUG(("io(): Received short packet."));
916 p += 2; /* Skip address and control */
917 GETSHORT(protocol, p);
921 * Toss all non-LCP packets unless LCP is OPEN.
923 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
924 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
929 * Until we get past the authentication phase, toss all packets
930 * except LCP, LQR and authentication packets.
932 if (phase <= PHASE_AUTHENTICATE
933 && !(protocol == PPP_LCP || protocol == PPP_LQR
934 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
935 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
941 * Upcall the proper protocol input routine.
943 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
944 if (protp->protocol == protocol && protp->enabled_flag) {
945 (*protp->input)(0, p, len);
948 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
949 && protp->datainput != NULL) {
950 (*protp->datainput)(0, p, len);
956 warn("Unsupported protocol (0x%x) received", protocol);
957 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
962 * die - clean up state and exit with the specified status.
969 syslog(LOG_INFO, "Exit.");
974 * cleanup - restore anything which needs to be restored before we exit
983 disestablish_ppp(ttyfd);
987 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
988 warn("unable to delete pid file: %m");
996 * close_tty - restore the terminal device and close it.
1001 /* drop dtr to hang up */
1002 if (!default_device && modem) {
1003 setdtr(real_ttyfd, 0);
1005 * This sleep is in case the serial port has CLOCAL set by default,
1006 * and consequently will reassert DTR when we close the device.
1011 restore_tty(real_ttyfd);
1013 if (tty_mode != (mode_t) -1) {
1014 if (fchmod(real_ttyfd, tty_mode) != 0) {
1015 /* XXX if devnam is a symlink, this will change the link */
1016 chmod(devnam, tty_mode);
1026 struct timeval c_time; /* time at which to call routine */
1027 void *c_arg; /* argument to routine */
1028 void (*c_func) __P((void *)); /* routine */
1029 struct callout *c_next;
1032 static struct callout *callout = NULL; /* Callout list */
1033 static struct timeval timenow; /* Current time */
1036 * timeout - Schedule a timeout.
1038 * Note that this timeout takes the number of seconds, NOT hz (as in
1042 timeout(func, arg, time)
1043 void (*func) __P((void *));
1047 struct callout *newp, *p, **pp;
1049 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1054 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1055 fatal("Out of memory in timeout()!");
1057 newp->c_func = func;
1058 gettimeofday(&timenow, NULL);
1059 newp->c_time.tv_sec = timenow.tv_sec + time;
1060 newp->c_time.tv_usec = timenow.tv_usec;
1063 * Find correct place and link it in.
1065 for (pp = &callout; (p = *pp); pp = &p->c_next)
1066 if (newp->c_time.tv_sec < p->c_time.tv_sec
1067 || (newp->c_time.tv_sec == p->c_time.tv_sec
1068 && newp->c_time.tv_usec < p->c_time.tv_usec))
1076 * untimeout - Unschedule a timeout.
1079 untimeout(func, arg)
1080 void (*func) __P((void *));
1083 struct callout **copp, *freep;
1085 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1088 * Find first matching timeout and remove it from the list.
1090 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1091 if (freep->c_func == func && freep->c_arg == arg) {
1092 *copp = freep->c_next;
1093 (void) free((char *) freep);
1100 * calltimeout - Call any timeout routines which are now due.
1107 while (callout != NULL) {
1110 if (gettimeofday(&timenow, NULL) < 0)
1111 fatal("Failed to get time of day: %m");
1112 if (!(p->c_time.tv_sec < timenow.tv_sec
1113 || (p->c_time.tv_sec == timenow.tv_sec
1114 && p->c_time.tv_usec <= timenow.tv_usec)))
1115 break; /* no, it's not time yet */
1117 callout = p->c_next;
1118 (*p->c_func)(p->c_arg);
1126 * timeleft - return the length of time until the next timeout is due.
1128 static struct timeval *
1130 struct timeval *tvp;
1132 if (callout == NULL)
1135 gettimeofday(&timenow, NULL);
1136 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1137 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1138 if (tvp->tv_usec < 0) {
1139 tvp->tv_usec += 1000000;
1142 if (tvp->tv_sec < 0)
1143 tvp->tv_sec = tvp->tv_usec = 0;
1150 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1156 struct sigaction act, oldact;
1158 act.sa_handler = SIG_IGN;
1161 sigaction(sig, &act, &oldact);
1162 sigaction(sig, &oldact, NULL);
1167 * hup - Catch SIGHUP signal.
1169 * Indicates that the physical layer has been disconnected.
1170 * We don't rely on this indication; if the user has sent this
1171 * signal, we just take the link down.
1177 info("Hangup (SIGHUP)");
1180 /* Send the signal to the [dis]connector process(es) also */
1183 kill(charshunt_pid, sig);
1185 siglongjmp(sigjmp, 1);
1190 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1192 * Indicates that we should initiate a graceful disconnect and exit.
1199 info("Terminating on signal %d.", sig);
1200 persist = 0; /* don't try to restart */
1203 /* Send the signal to the [dis]connector process(es) also */
1206 kill(charshunt_pid, sig);
1208 siglongjmp(sigjmp, 1);
1213 * chld - Catch SIGCHLD signal.
1214 * Sets a flag so we will call reap_kids in the mainline.
1222 siglongjmp(sigjmp, 1);
1227 * toggle_debug - Catch SIGUSR1 signal.
1229 * Toggle debug flag.
1238 setlogmask(LOG_UPTO(LOG_DEBUG));
1240 setlogmask(LOG_UPTO(LOG_WARNING));
1246 * open_ccp - Catch SIGUSR2 signal.
1248 * Try to (re)negotiate compression.
1257 siglongjmp(sigjmp, 1);
1262 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1268 static int crashed = 0;
1273 error("Fatal signal %d", sig);
1275 kill_my_pg(SIGTERM);
1277 kill(charshunt_pid, SIGTERM);
1283 * device_script - run a program to talk to the serial device
1284 * (e.g. to run the connector or disconnector script).
1287 device_script(program, in, out, dont_wait)
1301 error("Failed to create child process: %m");
1310 int newin = dup(in);
1314 } else if (out == 2) {
1317 if (log_to_fd >= 0) {
1322 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1323 if (errfd >= 0 && errfd != 2) {
1347 if (getuid() != uid) {
1348 error("setuid failed");
1352 execl("/bin/sh", "sh", "-c", program, (char *)0);
1353 error("could not exec /bin/sh: %m");
1359 record_child(pid, program, NULL, NULL);
1361 while (waitpid(pid, &status, 0) < 0) {
1364 fatal("error waiting for (dis)connection process: %m");
1369 return (status == 0 ? 0 : -1);
1374 * We maintain a list of child process pids and
1375 * functions to call when they exit.
1380 void (*done) __P((void *));
1382 struct subprocess *next;
1385 struct subprocess *children;
1388 * run-program - execute a program with given arguments,
1389 * but don't wait for it.
1390 * If the program can't be executed, logs an error unless
1391 * must_exist is 0 and the program file doesn't exist.
1392 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1393 * or isn't an executable plain file, or the process ID of the child.
1394 * If done != NULL, (*done)(arg) will be called later (within
1395 * reap_kids) iff the return value is > 0.
1398 run_program(prog, args, must_exist, done, arg)
1402 void (*done) __P((void *));
1409 * First check if the file exists and is executable.
1410 * We don't use access() because that would use the
1411 * real user-id, which might not be root, and the script
1412 * might be accessible only to root.
1415 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1416 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1417 if (must_exist || errno != ENOENT)
1418 warn("Can't execute %s: %m", prog);
1424 error("Failed to create child process for %s: %m", prog);
1430 /* Leave the current location */
1431 (void) setsid(); /* No controlling tty. */
1432 (void) umask (S_IRWXG|S_IRWXO);
1433 (void) chdir ("/"); /* no current directory. */
1434 setuid(0); /* set real UID = root */
1437 /* Ensure that nothing of our device environment is inherited. */
1443 close (ttyfd); /* tty interface to the ppp device */
1444 if (real_ttyfd >= 0)
1447 /* Don't pass handles to the PPP device, even by accident. */
1448 new_fd = open (_PATH_DEVNULL, O_RDWR);
1451 dup2 (new_fd, 0); /* stdin <- /dev/null */
1454 dup2 (0, 1); /* stdout -> /dev/null */
1455 dup2 (0, 2); /* stderr -> /dev/null */
1459 /* Force the priority back to zero if pppd is running higher. */
1460 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1461 warn("can't reset priority to 0: %m");
1464 /* SysV recommends a second fork at this point. */
1466 /* run the program */
1467 execve(prog, args, script_env);
1468 if (must_exist || errno != ENOENT) {
1469 /* have to reopen the log, there's nowhere else
1470 for the message to go. */
1472 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1479 dbglog("Script %s started; pid = %d", prog, pid);
1480 record_child(pid, prog, done, arg);
1487 * record_child - add a child process to the list for reap_kids
1491 record_child(pid, prog, done, arg)
1494 void (*done) __P((void *));
1497 struct subprocess *chp;
1501 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1503 warn("losing track of %s process", prog);
1509 chp->next = children;
1516 * reap_kids - get status from any dead child processes,
1517 * and log a message for abnormal terminations.
1524 struct subprocess *chp, **prevp;
1527 if (n_children == 0)
1529 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1532 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1533 if (chp->pid == pid)
1535 if (WIFSIGNALED(status)) {
1536 warn("Child process %s (pid %d) terminated with signal %d",
1537 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1539 dbglog("process %d (%s) finished, status = 0x%x",
1540 pid, (chp? chp->prog: "??"), status);
1541 if (chp && chp->done)
1542 (*chp->done)(chp->arg);
1544 if (pid == -1 && errno != ECHILD && errno != EINTR)
1545 error("Error waiting for child process: %m");
1550 * log_packet - format a packet and log it.
1553 char line[256]; /* line to be logged accumulated here */
1557 log_packet(p, len, prefix, level)
1563 strlcpy(line, prefix, sizeof(line));
1564 linep = line + strlen(line);
1565 format_packet(p, len, pr_log, NULL);
1567 syslog(level, "%s", line);
1571 * format_packet - make a readable representation of a packet,
1572 * calling `printer(arg, format, ...)' to output it.
1575 format_packet(p, len, printer, arg)
1578 void (*printer) __P((void *, char *, ...));
1583 struct protent *protp;
1585 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1589 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1590 if (proto == protp->protocol)
1592 if (protp != NULL) {
1593 printer(arg, "[%s", protp->name);
1594 n = (*protp->printpkt)(p, len, printer, arg);
1599 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1600 if (proto == (protp->protocol & ~0x8000))
1602 if (protp != 0 && protp->data_name != 0) {
1603 printer(arg, "[%s data]", protp->data_name);
1605 printer(arg, "%.8B ...", p);
1607 printer(arg, "%.*B", len, p);
1610 printer(arg, "[proto=0x%x]", proto);
1615 printer(arg, "%.32B ...", p);
1617 printer(arg, "%.*B", len, p);
1621 pr_log __V((void *arg, char *fmt, ...))
1628 va_start(pvar, fmt);
1633 arg = va_arg(pvar, void *);
1634 fmt = va_arg(pvar, char *);
1637 n = vslprintf(buf, sizeof(buf), fmt, pvar);
1640 if (linep + n + 1 > line + sizeof(line)) {
1641 syslog(LOG_DEBUG, "%s", line);
1644 strlcpy(linep, buf, line + sizeof(line) - linep);
1649 * vslp_printer - used in processing a %P format
1651 struct buffer_info {
1657 vslp_printer __V((void *arg, char *fmt, ...))
1661 struct buffer_info *bi;
1664 va_start(pvar, fmt);
1669 arg = va_arg(pvar, void *);
1670 fmt = va_arg(pvar, char *);
1673 bi = (struct buffer_info *) arg;
1674 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
1682 * print_string - print a readable representation of a string using
1686 print_string(p, len, printer, arg)
1689 void (*printer) __P((void *, char *, ...));
1695 for (; len > 0; --len) {
1697 if (' ' <= c && c <= '~') {
1698 if (c == '\\' || c == '"')
1700 printer(arg, "%c", c);
1704 printer(arg, "\\n");
1707 printer(arg, "\\r");
1710 printer(arg, "\\t");
1713 printer(arg, "\\%.3o", c);
1721 * novm - log an error message saying we ran out of memory, and die.
1727 fatal("Virtual memory exhausted allocating %s\n", msg);
1731 * slprintf - format a message into a buffer. Like sprintf except we
1732 * also specify the length of the output buffer, and we handle
1733 * %r (recursive format), %m (error message), %v (visible string),
1734 * %q (quoted string), %t (current time) and %I (IP address) formats.
1735 * Doesn't do floating-point formats.
1736 * Returns the number of chars put into buf.
1739 slprintf __V((char *buf, int buflen, char *fmt, ...))
1745 va_start(args, fmt);
1751 buf = va_arg(args, char *);
1752 buflen = va_arg(args, int);
1753 fmt = va_arg(args, char *);
1755 n = vslprintf(buf, buflen, fmt, args);
1761 * vslprintf - like slprintf, takes a va_list instead of a list of args.
1763 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1766 vslprintf(buf, buflen, fmt, args)
1773 int width, prec, fillch;
1774 int base, len, neg, quoted;
1775 unsigned long val = 0;
1776 char *str, *f, *buf0;
1781 static char hexchars[] = "0123456789abcdef";
1782 struct buffer_info bufinfo;
1786 while (buflen > 0) {
1787 for (f = fmt; *f != '%' && *f != 0; ++f)
1793 memcpy(buf, fmt, len);
1808 width = va_arg(args, int);
1811 while (isdigit(c)) {
1812 width = width * 10 + c - '0';
1819 prec = va_arg(args, int);
1822 while (isdigit(c)) {
1823 prec = prec * 10 + c - '0';
1834 i = va_arg(args, int);
1843 val = va_arg(args, unsigned int);
1848 val = va_arg(args, unsigned int);
1852 val = (unsigned long) va_arg(args, void *);
1857 str = va_arg(args, char *);
1860 num[0] = va_arg(args, int);
1865 str = strerror(errno);
1868 ip = va_arg(args, u_int32_t);
1870 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
1871 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
1875 f = va_arg(args, char *);
1877 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
1879 /* On the powerpc, a va_list is an array of 1 structure */
1880 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
1888 str += 4; /* chop off the day name */
1889 str[15] = 0; /* chop off year and newline */
1891 case 'v': /* "visible" string */
1892 case 'q': /* quoted string */
1894 p = va_arg(args, unsigned char *);
1895 if (fillch == '0' && prec > 0) {
1898 n = strlen((char *)p);
1899 if (prec > 0 && prec < n)
1902 while (n > 0 && buflen > 0) {
1905 if (!quoted && c >= 0x80) {
1910 if (quoted && (c == '"' || c == '\\'))
1912 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1916 case '\t': OUTCHAR('t'); break;
1917 case '\n': OUTCHAR('n'); break;
1918 case '\b': OUTCHAR('b'); break;
1919 case '\f': OUTCHAR('f'); break;
1922 OUTCHAR(hexchars[c >> 4]);
1923 OUTCHAR(hexchars[c & 0xf]);
1937 case 'P': /* print PPP packet */
1939 bufinfo.len = buflen + 1;
1940 p = va_arg(args, unsigned char *);
1941 n = va_arg(args, int);
1942 format_packet(p, n, vslp_printer, &bufinfo);
1944 buflen = bufinfo.len - 1;
1947 p = va_arg(args, unsigned char *);
1948 for (n = prec; n > 0; --n) {
1952 OUTCHAR(hexchars[(c >> 4) & 0xf]);
1953 OUTCHAR(hexchars[c & 0xf]);
1959 --fmt; /* so %z outputs %z etc. */
1964 str = num + sizeof(num);
1966 while (str > num + neg) {
1967 *--str = hexchars[val % base];
1969 if (--prec <= 0 && val == 0)
1981 len = num + sizeof(num) - 1 - str;
1984 if (prec > 0 && len > prec)
1990 if ((n = width - len) > 0) {
1998 memcpy(buf, str, len);
2007 * script_setenv - set an environment variable value to be used
2008 * for scripts that we run (e.g. ip-up, auth-up, etc.)
2011 script_setenv(var, value)
2014 size_t vl = strlen(var) + strlen(value) + 2;
2016 char *p, *newstring;
2018 newstring = (char *) malloc(vl);
2021 slprintf(newstring, vl, "%s=%s", var, value);
2023 /* check if this variable is already set */
2024 if (script_env != 0) {
2025 for (i = 0; (p = script_env[i]) != 0; ++i) {
2026 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2028 script_env[i] = newstring;
2034 script_env = (char **) malloc(16 * sizeof(char *));
2035 if (script_env == 0)
2040 /* reallocate script_env with more space if needed */
2041 if (i + 1 >= s_env_nalloc) {
2043 char **newenv = (char **) realloc((void *)script_env,
2044 new_n * sizeof(char *));
2047 script_env = newenv;
2048 s_env_nalloc = new_n;
2051 script_env[i] = newstring;
2052 script_env[i+1] = 0;
2056 * script_unsetenv - remove a variable from the environment
2060 script_unsetenv(var)
2063 int vl = strlen(var);
2067 if (script_env == 0)
2069 for (i = 0; (p = script_env[i]) != 0; ++i) {
2070 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2072 while ((script_env[i] = script_env[i+1]) != 0)
2080 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
2081 * always leaves destination null-terminated (for len > 0).
2084 strlcpy(dest, src, len)
2089 size_t ret = strlen(src);
2095 strncpy(dest, src, len - 1);
2103 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
2104 * always leaves destination null-terminated (for len > 0).
2107 strlcat(dest, src, len)
2112 size_t dlen = strlen(dest);
2114 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
2118 * logit - does the hard work for fatal et al.
2121 logit(level, fmt, args)
2129 n = vslprintf(buf, sizeof(buf), fmt, args);
2130 syslog(level, "%s", buf);
2131 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
2132 if (buf[n-1] != '\n')
2134 if (write(log_to_fd, buf, n) != n)
2140 * fatal - log an error message and die horribly.
2143 fatal __V((char *fmt, ...))
2148 va_start(pvar, fmt);
2152 fmt = va_arg(pvar, char *);
2155 logit(LOG_ERR, fmt, pvar);
2158 die(1); /* as promised */
2162 * error - log an error message.
2165 error __V((char *fmt, ...))
2170 va_start(pvar, fmt);
2174 fmt = va_arg(pvar, char *);
2177 logit(LOG_ERR, fmt, pvar);
2182 * warn - log a warning message.
2185 warn __V((char *fmt, ...))
2190 va_start(pvar, fmt);
2194 fmt = va_arg(pvar, char *);
2197 logit(LOG_WARNING, fmt, pvar);
2202 * notice - log a notice-level message.
2205 notice __V((char *fmt, ...))
2210 va_start(pvar, fmt);
2214 fmt = va_arg(pvar, char *);
2217 logit(LOG_NOTICE, fmt, pvar);
2222 * info - log an informational message.
2225 info __V((char *fmt, ...))
2230 va_start(pvar, fmt);
2234 fmt = va_arg(pvar, char *);
2237 logit(LOG_INFO, fmt, pvar);
2242 * dbglog - log a debug message.
2245 dbglog __V((char *fmt, ...))
2250 va_start(pvar, fmt);
2254 fmt = va_arg(pvar, char *);
2257 logit(LOG_DEBUG, fmt, pvar);
2262 * start_charshunt - create a child process to run the character shunt.
2265 start_charshunt(ifd, ofd)
2272 error("Can't fork process for character shunt: %m");
2279 if (getuid() != uid)
2280 fatal("setuid failed");
2284 charshunt(ifd, ofd, record_file);
2287 charshunt_pid = cpid;
2291 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2303 * charshunt - the character shunt, which passes characters between
2304 * the pty master side and the serial port (or stdin/stdout).
2305 * This runs as the user (not as root).
2306 * (We assume ofd >= ifd which is true the way this gets called. :-).
2309 charshunt(ifd, ofd, record_file)
2314 fd_set ready, writey;
2315 u_char *ibufp, *obufp;
2318 int pty_readable, stdin_readable;
2319 struct timeval lasttime;
2320 FILE *recordf = NULL;
2323 * Reset signal handlers.
2325 signal(SIGHUP, SIG_IGN); /* Hangup */
2326 signal(SIGINT, SIG_DFL); /* Interrupt */
2327 signal(SIGTERM, SIG_DFL); /* Terminate */
2328 signal(SIGCHLD, SIG_DFL);
2329 signal(SIGUSR1, SIG_DFL);
2330 signal(SIGUSR2, SIG_DFL);
2331 signal(SIGABRT, SIG_DFL);
2332 signal(SIGALRM, SIG_DFL);
2333 signal(SIGFPE, SIG_DFL);
2334 signal(SIGILL, SIG_DFL);
2335 signal(SIGPIPE, SIG_DFL);
2336 signal(SIGQUIT, SIG_DFL);
2337 signal(SIGSEGV, SIG_DFL);
2339 signal(SIGBUS, SIG_DFL);
2342 signal(SIGEMT, SIG_DFL);
2345 signal(SIGPOLL, SIG_DFL);
2348 signal(SIGPROF, SIG_DFL);
2351 signal(SIGSYS, SIG_DFL);
2354 signal(SIGTRAP, SIG_DFL);
2357 signal(SIGVTALRM, SIG_DFL);
2360 signal(SIGXCPU, SIG_DFL);
2363 signal(SIGXFSZ, SIG_DFL);
2367 * Open the record file if required.
2369 if (record_file != NULL) {
2370 recordf = fopen(record_file, "a");
2371 if (recordf == NULL)
2372 error("Couldn't create record file %s: %m", record_file);
2375 /* set all the fds to non-blocking mode */
2376 flags = fcntl(pty_master, F_GETFL);
2378 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2379 warn("couldn't set pty master to nonblock: %m");
2380 flags = fcntl(ifd, F_GETFL);
2382 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2383 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2385 flags = fcntl(ofd, F_GETFL);
2387 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2388 warn("couldn't set stdout to nonblock: %m");
2392 ibufp = obufp = NULL;
2393 pty_readable = stdin_readable = 1;
2394 nfds = (ofd > pty_master? ofd: pty_master) + 1;
2395 if (recordf != NULL) {
2396 gettimeofday(&lasttime, NULL);
2397 putc(7, recordf); /* put start marker */
2398 putc(lasttime.tv_sec >> 24, recordf);
2399 putc(lasttime.tv_sec >> 16, recordf);
2400 putc(lasttime.tv_sec >> 8, recordf);
2401 putc(lasttime.tv_sec, recordf);
2402 lasttime.tv_usec = 0;
2405 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
2409 FD_SET(pty_master, &writey);
2410 else if (stdin_readable)
2411 FD_SET(ifd, &ready);
2413 FD_SET(ofd, &writey);
2414 else if (pty_readable)
2415 FD_SET(pty_master, &ready);
2416 if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
2421 if (FD_ISSET(ifd, &ready)) {
2422 ibufp = inpacket_buf;
2423 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2424 if (nibuf < 0 && errno == EIO)
2427 if (!(errno == EINTR || errno == EAGAIN)) {
2428 error("Error reading standard input: %m");
2432 } else if (nibuf == 0) {
2433 /* end of file from stdin */
2435 /* do a 0-length write, hopefully this will generate
2436 an EOF (hangup) on the slave side. */
2437 write(pty_master, inpacket_buf, 0);
2439 if (!record_write(recordf, 4, NULL, 0, &lasttime))
2442 FD_SET(pty_master, &writey);
2444 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2448 if (FD_ISSET(pty_master, &ready)) {
2449 obufp = outpacket_buf;
2450 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2451 if (nobuf < 0 && errno == EIO)
2454 if (!(errno == EINTR || errno == EAGAIN)) {
2455 error("Error reading pseudo-tty master: %m");
2459 } else if (nobuf == 0) {
2460 /* end of file from the pty - slave side has closed */
2462 stdin_readable = 0; /* pty is not writable now */
2466 if (!record_write(recordf, 3, NULL, 0, &lasttime))
2469 FD_SET(ofd, &writey);
2471 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2475 if (FD_ISSET(ofd, &writey)) {
2476 n = write(ofd, obufp, nobuf);
2479 error("Error writing standard output: %m");
2489 if (FD_ISSET(pty_master, &writey)) {
2490 n = write(pty_master, ibufp, nibuf);
2493 error("Error writing pseudo-tty master: %m");
2508 record_write(f, code, buf, nb, tp)
2518 gettimeofday(&now, NULL);
2519 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2520 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2524 putc(diff >> 24, f);
2525 putc(diff >> 16, f);
2538 fwrite(buf, nb, 1, f);
2542 error("Error writing record file: %m");