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.68 1999/03/30 04:22:57 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 */
218 openlog("pppd", LOG_PID);
220 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
221 setlogmask(LOG_UPTO(LOG_INFO));
224 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
225 option_error("Couldn't get hostname: %m");
228 hostname[MAXNAMELEN-1] = 0;
231 privileged = uid == 0;
232 slprintf(numbuf, sizeof(numbuf), "%d", uid);
233 script_setenv("ORIG_UID", numbuf);
235 ngroups = getgroups(NGROUPS_MAX, groups);
238 * Initialize to the standard option set, then parse, in order,
239 * the system options file, the user's options file,
240 * the tty's options file, and the command line arguments.
242 for (i = 0; (protp = protocols[i]) != NULL; ++i)
247 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
248 || !options_from_user())
250 using_pty = notty || ptycommand != NULL;
251 scan_args(argc-1, argv+1); /* look for tty name on command line */
254 * Work out the device name, if it hasn't already been specified.
257 p = isatty(0)? ttyname(0): NULL;
260 strlcpy(devnam, p, sizeof(devnam));
261 else if (strcmp(devnam, p) == 0)
267 * Parse the tty options file and the command line.
269 if (!options_for_tty()
270 || !parse_args(argc-1, argv+1))
274 * Check that we are running as root.
276 if (geteuid() != 0) {
277 option_error("must be root to run %s, since it is not setuid-root",
282 if (!ppp_available()) {
283 option_error(no_ppp_msg);
288 * Check that the options given are valid and consistent.
290 if (!sys_check_options())
292 auth_check_options();
293 for (i = 0; (protp = protocols[i]) != NULL; ++i)
294 if (protp->check_options != NULL)
295 (*protp->check_options)();
296 if (demand && connector == 0) {
297 option_error("connect script is required for demand-dialling\n");
302 if (!default_device) {
303 option_error("%s option precludes specifying device name",
304 notty? "notty": "pty");
307 if (ptycommand != NULL && notty) {
308 option_error("pty option is incompatible with notty option");
311 default_device = notty;
315 if (devnam[0] == 0) {
316 option_error("no device specified and stdin is not a tty");
323 log_to_fd = 1; /* default to stdout */
325 script_setenv("DEVICE", devnam);
326 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
327 script_setenv("SPEED", numbuf);
330 * Initialize system-dependent stuff and magic number package.
335 setlogmask(LOG_UPTO(LOG_DEBUG));
338 * Detach ourselves from the terminal, if required,
339 * and identify who is running us.
341 if (!nodetach && !updetach)
347 if (pw != NULL && pw->pw_name != NULL)
352 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
353 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
356 * Compute mask of all interesting signals and install signal handlers
357 * for each. Only one signal handler may be active at a time. Therefore,
358 * all other signals should be masked when any handler is executing.
361 sigaddset(&mask, SIGHUP);
362 sigaddset(&mask, SIGINT);
363 sigaddset(&mask, SIGTERM);
364 sigaddset(&mask, SIGCHLD);
365 sigaddset(&mask, SIGUSR2);
367 #define SIGNAL(s, handler) do { \
368 sa.sa_handler = handler; \
369 if (sigaction(s, &sa, NULL) < 0) \
370 fatal("Couldn't establish signal handler (%d): %m", s); \
375 SIGNAL(SIGHUP, hup); /* Hangup */
376 SIGNAL(SIGINT, term); /* Interrupt */
377 SIGNAL(SIGTERM, term); /* Terminate */
378 SIGNAL(SIGCHLD, chld);
380 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
381 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
384 * Install a handler for other signals which would otherwise
385 * cause pppd to exit without cleaning up.
387 SIGNAL(SIGABRT, bad_signal);
388 SIGNAL(SIGALRM, bad_signal);
389 SIGNAL(SIGFPE, bad_signal);
390 SIGNAL(SIGILL, bad_signal);
391 SIGNAL(SIGPIPE, bad_signal);
392 SIGNAL(SIGQUIT, bad_signal);
393 SIGNAL(SIGSEGV, bad_signal);
395 SIGNAL(SIGBUS, bad_signal);
398 SIGNAL(SIGEMT, bad_signal);
401 SIGNAL(SIGPOLL, bad_signal);
404 SIGNAL(SIGPROF, bad_signal);
407 SIGNAL(SIGSYS, bad_signal);
410 SIGNAL(SIGTRAP, bad_signal);
413 SIGNAL(SIGVTALRM, bad_signal);
416 SIGNAL(SIGXCPU, bad_signal);
419 SIGNAL(SIGXFSZ, bad_signal);
423 * Apparently we can get a SIGPIPE when we call syslog, if
424 * syslogd has died and been restarted. Ignoring it seems
427 signal(SIGPIPE, SIG_IGN);
432 * If we're doing dial-on-demand, set up the interface now.
436 * Open the loopback channel and set it up to be the ppp interface.
438 fd_loop = open_ppp_loopback();
440 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
441 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
442 script_setenv("IFNAME", ifname);
444 create_pidfile(); /* write pid to file */
447 * Configure the interface and mark it up, etc.
460 * Don't do anything until we see some activity.
463 phase = PHASE_DORMANT;
467 if (sigsetjmp(sigjmp, 1) == 0) {
468 sigprocmask(SIG_BLOCK, &mask, NULL);
470 sigprocmask(SIG_UNBLOCK, &mask, NULL);
473 sigprocmask(SIG_UNBLOCK, &mask, NULL);
474 wait_input(timeleft(&timo));
484 if (get_loop_output())
490 if (kill_link && !persist)
494 * Now we want to bring up the link.
497 info("Starting link");
501 * Get a pty master/slave pair if the pty, notty, or record
502 * options were specified.
504 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
507 if (ptycommand != NULL || notty || record_file != NULL) {
508 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
509 error("Couldn't allocate pseudo-tty");
512 set_up_tty(pty_slave, 1);
516 * Lock the device if we've been asked to.
518 if (lockflag && !default_device) {
519 if (lock(devnam) < 0)
525 * Open the serial device and set it up to be the ppp interface.
526 * First we open it in non-blocking mode so we can set the
527 * various termios flags appropriately. If we aren't dialling
528 * out and we want to use the modem lines, we reopen it later
529 * in order to wait for the carrier detect signal from the modem.
533 if (devnam[0] != 0) {
535 /* If the user specified the device name, become the
536 user before opening it. */
537 if (!devnam_info.priv && !default_device)
539 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
540 if (!devnam_info.priv && !default_device)
545 error("Failed to open %s: %m", devnam);
546 if (!persist || errno != EINTR)
549 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
550 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
551 warn("Couldn't reset non-blocking mode on device: %m");
554 * Do the equivalent of `mesg n' to stop broadcast messages.
556 if (fstat(ttyfd, &statbuf) < 0
557 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
558 warn("Couldn't restrict write permissions to %s: %m", devnam);
560 tty_mode = statbuf.st_mode;
563 * Set line speed, flow control, etc.
564 * If we have a non-null connection script,
565 * on most systems we set CLOCAL for now so that we can talk
566 * to the modem before carrier comes up. But this has the
567 * side effect that we might miss it if CD drops before we
568 * get to clear CLOCAL below. On systems where we can talk
569 * successfully to the modem with CLOCAL clear and CD down,
570 * we could clear CLOCAL at this point.
572 set_up_tty(ttyfd, (connector != NULL && connector[0] != 0));
577 * If the notty and/or record option was specified,
578 * start up the character shunt now.
580 if (ptycommand != NULL) {
581 if (record_file != NULL) {
582 int ipipe[2], opipe[2], ok;
584 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
585 fatal("Couldn't create pipes for record option: %m");
586 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
587 && start_charshunt(ipipe[0], opipe[1]);
595 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
602 if (!start_charshunt(0, 1))
604 } else if (record_file != NULL) {
605 if (!start_charshunt(ttyfd, ttyfd))
609 /* run connection script */
610 if (connector && connector[0]) {
611 MAINDEBUG(("Connecting with <%s>", connector));
613 if (real_ttyfd != -1) {
614 if (!default_device && modem) {
615 setdtr(real_ttyfd, 0); /* in case modem is off hook */
617 setdtr(real_ttyfd, 1);
621 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
622 error("Connect script failed");
626 info("Serial connection established.");
628 /* set line speed, flow control, etc.;
629 clear CLOCAL if modem option */
630 if (real_ttyfd != -1)
631 set_up_tty(real_ttyfd, 0);
634 /* reopen tty if necessary to wait for carrier */
635 if (connector == NULL && modem && devnam[0] != 0) {
637 if ((i = open(devnam, O_RDWR)) >= 0)
640 error("Failed to reopen %s: %m", devnam);
641 if (!persist || errno != EINTR || hungup || kill_link)
647 /* run welcome script, if any */
648 if (welcomer && welcomer[0]) {
649 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
650 warn("Welcome script failed");
653 /* set up the serial device as a ppp interface */
654 fd_ppp = establish_ppp(ttyfd);
660 info("Using interface ppp%d", ifunit);
661 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
662 script_setenv("IFNAME", ifname);
664 create_pidfile(); /* write pid to file */
668 * Start opening the connection and wait for
669 * incoming events (reply, timeout, etc.).
671 notice("Connect: %s <--> %s", ifname, ppp_devnam);
672 gettimeofday(&start_time, NULL);
676 * If we are initiating this connection, wait for a short
677 * time for something from the peer. This can avoid bouncing
678 * our packets off his tty before he has it set up.
680 if (connector != NULL || ptycommand != NULL) {
687 lcp_open(0); /* Start protocol */
690 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
691 if (sigsetjmp(sigjmp, 1) == 0) {
692 sigprocmask(SIG_BLOCK, &mask, NULL);
693 if (kill_link || open_ccp_flag) {
694 sigprocmask(SIG_UNBLOCK, &mask, NULL);
697 sigprocmask(SIG_UNBLOCK, &mask, NULL);
698 wait_input(timeleft(&timo));
705 lcp_close(0, "User request");
709 if (phase == PHASE_NETWORK) {
710 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
711 (*ccp_protent.open)(0);
716 reap_kids(0); /* Don't leave dead kids lying around */
720 * Print connect time and statistics.
722 if (gettimeofday(&now, NULL) >= 0) {
723 int t = now.tv_sec - start_time.tv_sec;
724 t = (t + 5) / 6; /* now in 1/10ths of minutes */
725 info("Connect time %d.%d minutes.", t/10, t%10);
727 if (link_stats_valid) {
728 info("Sent %d bytes, received %d bytes.",
729 link_stats.bytes_out, link_stats.bytes_in);
733 * If we may want to bring the link up again, transfer
734 * the ppp unit back to the loopback. Set the
735 * real serial device back to its normal mode of operation.
741 disestablish_ppp(ttyfd);
745 * Run disconnector script, if requested.
746 * XXX we may not be able to do this if the line has hung up!
748 if (disconnector && !hungup) {
750 set_up_tty(real_ttyfd, 1);
751 if (device_script(disconnector, ttyfd, ttyfd, 0) < 0) {
752 warn("disconnect script failed");
754 info("Serial link disconnected.");
773 if (pidfilename[0] != 0
774 && unlink(pidfilename) < 0 && errno != ENOENT)
775 warn("unable to delete pid file: %m");
785 if (holdoff > 0 && need_holdoff) {
786 phase = PHASE_HOLDOFF;
787 TIMEOUT(holdoff_end, NULL, holdoff);
789 if (sigsetjmp(sigjmp, 1) == 0) {
790 sigprocmask(SIG_BLOCK, &mask, NULL);
792 sigprocmask(SIG_UNBLOCK, &mask, NULL);
795 sigprocmask(SIG_UNBLOCK, &mask, NULL);
796 wait_input(timeleft(&timo));
803 phase = PHASE_DORMANT; /* allow signal to end holdoff */
807 } while (phase == PHASE_HOLDOFF);
813 /* Wait for scripts to finish */
814 while (n_children > 0)
822 * detach - detach us from the controlling terminal.
829 if (daemon(0, 0) < 0) {
830 perror("Couldn't detach from controlling terminal");
836 /* update pid file if it has been written already */
842 * Create a file containing our process ID.
850 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
851 _PATH_VARRUN, ifname);
852 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
853 fprintf(pidfile, "%d\n", pid);
854 (void) fclose(pidfile);
856 error("Failed to create pid file %s: %m", pidfilename);
859 slprintf(numbuf, sizeof(numbuf), "%d", pid);
860 script_setenv("PPPD_PID", numbuf);
864 * holdoff_end - called via a timeout when the holdoff period ends.
870 phase = PHASE_DORMANT;
874 * get_input - called when incoming data is available.
882 struct protent *protp;
884 p = inpacket_buf; /* point to beginning of packet buffer */
886 len = read_packet(inpacket_buf);
891 notice("Modem hangup");
893 lcp_lowerdown(0); /* serial link is no longer available */
898 if (debug /*&& (debugflags & DBG_INPACKET)*/)
899 dbglog("rcvd %P", p, len);
901 if (len < PPP_HDRLEN) {
902 MAINDEBUG(("io(): Received short packet."));
906 p += 2; /* Skip address and control */
907 GETSHORT(protocol, p);
911 * Toss all non-LCP packets unless LCP is OPEN.
913 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
914 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
919 * Until we get past the authentication phase, toss all packets
920 * except LCP, LQR and authentication packets.
922 if (phase <= PHASE_AUTHENTICATE
923 && !(protocol == PPP_LCP || protocol == PPP_LQR
924 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
925 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
931 * Upcall the proper protocol input routine.
933 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
934 if (protp->protocol == protocol && protp->enabled_flag) {
935 (*protp->input)(0, p, len);
938 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
939 && protp->datainput != NULL) {
940 (*protp->datainput)(0, p, len);
946 warn("Unsupported protocol (0x%x) received", protocol);
947 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
952 * die - clean up state and exit with the specified status.
959 syslog(LOG_INFO, "Exit.");
964 * cleanup - restore anything which needs to be restored before we exit
973 disestablish_ppp(ttyfd);
977 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
978 warn("unable to delete pid file: %m");
986 * close_tty - restore the terminal device and close it.
991 /* drop dtr to hang up */
992 if (!default_device && modem) {
993 setdtr(real_ttyfd, 0);
995 * This sleep is in case the serial port has CLOCAL set by default,
996 * and consequently will reassert DTR when we close the device.
1001 restore_tty(real_ttyfd);
1003 if (tty_mode != (mode_t) -1) {
1004 if (fchmod(real_ttyfd, tty_mode) != 0) {
1005 /* XXX if devnam is a symlink, this will change the link */
1006 chmod(devnam, tty_mode);
1016 struct timeval c_time; /* time at which to call routine */
1017 void *c_arg; /* argument to routine */
1018 void (*c_func) __P((void *)); /* routine */
1019 struct callout *c_next;
1022 static struct callout *callout = NULL; /* Callout list */
1023 static struct timeval timenow; /* Current time */
1026 * timeout - Schedule a timeout.
1028 * Note that this timeout takes the number of seconds, NOT hz (as in
1032 timeout(func, arg, time)
1033 void (*func) __P((void *));
1037 struct callout *newp, *p, **pp;
1039 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1044 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1045 fatal("Out of memory in timeout()!");
1047 newp->c_func = func;
1048 gettimeofday(&timenow, NULL);
1049 newp->c_time.tv_sec = timenow.tv_sec + time;
1050 newp->c_time.tv_usec = timenow.tv_usec;
1053 * Find correct place and link it in.
1055 for (pp = &callout; (p = *pp); pp = &p->c_next)
1056 if (newp->c_time.tv_sec < p->c_time.tv_sec
1057 || (newp->c_time.tv_sec == p->c_time.tv_sec
1058 && newp->c_time.tv_usec < p->c_time.tv_usec))
1066 * untimeout - Unschedule a timeout.
1069 untimeout(func, arg)
1070 void (*func) __P((void *));
1073 struct callout **copp, *freep;
1075 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1078 * Find first matching timeout and remove it from the list.
1080 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1081 if (freep->c_func == func && freep->c_arg == arg) {
1082 *copp = freep->c_next;
1083 (void) free((char *) freep);
1090 * calltimeout - Call any timeout routines which are now due.
1097 while (callout != NULL) {
1100 if (gettimeofday(&timenow, NULL) < 0)
1101 fatal("Failed to get time of day: %m");
1102 if (!(p->c_time.tv_sec < timenow.tv_sec
1103 || (p->c_time.tv_sec == timenow.tv_sec
1104 && p->c_time.tv_usec <= timenow.tv_usec)))
1105 break; /* no, it's not time yet */
1107 callout = p->c_next;
1108 (*p->c_func)(p->c_arg);
1116 * timeleft - return the length of time until the next timeout is due.
1118 static struct timeval *
1120 struct timeval *tvp;
1122 if (callout == NULL)
1125 gettimeofday(&timenow, NULL);
1126 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1127 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1128 if (tvp->tv_usec < 0) {
1129 tvp->tv_usec += 1000000;
1132 if (tvp->tv_sec < 0)
1133 tvp->tv_sec = tvp->tv_usec = 0;
1140 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1146 struct sigaction act, oldact;
1148 act.sa_handler = SIG_IGN;
1151 sigaction(sig, &act, &oldact);
1152 sigaction(sig, &oldact, NULL);
1157 * hup - Catch SIGHUP signal.
1159 * Indicates that the physical layer has been disconnected.
1160 * We don't rely on this indication; if the user has sent this
1161 * signal, we just take the link down.
1167 info("Hangup (SIGHUP)");
1170 /* Send the signal to the [dis]connector process(es) also */
1173 kill(charshunt_pid, sig);
1175 siglongjmp(sigjmp, 1);
1180 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1182 * Indicates that we should initiate a graceful disconnect and exit.
1189 info("Terminating on signal %d.", sig);
1190 persist = 0; /* don't try to restart */
1193 /* Send the signal to the [dis]connector process(es) also */
1196 kill(charshunt_pid, sig);
1198 siglongjmp(sigjmp, 1);
1203 * chld - Catch SIGCHLD signal.
1204 * Sets a flag so we will call reap_kids in the mainline.
1212 siglongjmp(sigjmp, 1);
1217 * toggle_debug - Catch SIGUSR1 signal.
1219 * Toggle debug flag.
1228 setlogmask(LOG_UPTO(LOG_DEBUG));
1230 setlogmask(LOG_UPTO(LOG_WARNING));
1236 * open_ccp - Catch SIGUSR2 signal.
1238 * Try to (re)negotiate compression.
1247 siglongjmp(sigjmp, 1);
1252 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1258 static int crashed = 0;
1263 error("Fatal signal %d", sig);
1265 kill_my_pg(SIGTERM);
1267 kill(charshunt_pid, SIGTERM);
1273 * device_script - run a program to talk to the serial device
1274 * (e.g. to run the connector or disconnector script).
1277 device_script(program, in, out, dont_wait)
1291 error("Failed to create child process: %m");
1300 int newin = dup(in);
1304 } else if (out == 2) {
1307 if (log_to_fd >= 0) {
1312 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1313 if (errfd >= 0 && errfd != 2) {
1337 if (getuid() != uid) {
1338 error("setuid failed");
1342 execl("/bin/sh", "sh", "-c", program, (char *)0);
1343 error("could not exec /bin/sh: %m");
1349 record_child(pid, program, NULL, NULL);
1351 while (waitpid(pid, &status, 0) < 0) {
1354 fatal("error waiting for (dis)connection process: %m");
1359 return (status == 0 ? 0 : -1);
1364 * We maintain a list of child process pids and
1365 * functions to call when they exit.
1370 void (*done) __P((void *));
1372 struct subprocess *next;
1375 struct subprocess *children;
1378 * run-program - execute a program with given arguments,
1379 * but don't wait for it.
1380 * If the program can't be executed, logs an error unless
1381 * must_exist is 0 and the program file doesn't exist.
1382 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1383 * or isn't an executable plain file, or the process ID of the child.
1384 * If done != NULL, (*done)(arg) will be called later (within
1385 * reap_kids) iff the return value is > 0.
1388 run_program(prog, args, must_exist, done, arg)
1392 void (*done) __P((void *));
1399 * First check if the file exists and is executable.
1400 * We don't use access() because that would use the
1401 * real user-id, which might not be root, and the script
1402 * might be accessible only to root.
1405 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1406 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1407 if (must_exist || errno != ENOENT)
1408 warn("Can't execute %s: %m", prog);
1414 error("Failed to create child process for %s: %m", prog);
1420 /* Leave the current location */
1421 (void) setsid(); /* No controlling tty. */
1422 (void) umask (S_IRWXG|S_IRWXO);
1423 (void) chdir ("/"); /* no current directory. */
1424 setuid(0); /* set real UID = root */
1427 /* Ensure that nothing of our device environment is inherited. */
1433 close (ttyfd); /* tty interface to the ppp device */
1434 if (real_ttyfd >= 0)
1437 /* Don't pass handles to the PPP device, even by accident. */
1438 new_fd = open (_PATH_DEVNULL, O_RDWR);
1441 dup2 (new_fd, 0); /* stdin <- /dev/null */
1444 dup2 (0, 1); /* stdout -> /dev/null */
1445 dup2 (0, 2); /* stderr -> /dev/null */
1449 /* Force the priority back to zero if pppd is running higher. */
1450 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1451 warn("can't reset priority to 0: %m");
1454 /* SysV recommends a second fork at this point. */
1456 /* run the program */
1457 execve(prog, args, script_env);
1458 if (must_exist || errno != ENOENT) {
1459 /* have to reopen the log, there's nowhere else
1460 for the message to go. */
1462 openlog("pppd", LOG_PID);
1464 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1465 setlogmask(LOG_UPTO(LOG_INFO));
1467 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1474 dbglog("Script %s started; pid = %d", prog, pid);
1475 record_child(pid, prog, done, arg);
1482 * record_child - add a child process to the list for reap_kids
1486 record_child(pid, prog, done, arg)
1489 void (*done) __P((void *));
1492 struct subprocess *chp;
1496 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1498 warn("losing track of %s process", prog);
1504 chp->next = children;
1511 * reap_kids - get status from any dead child processes,
1512 * and log a message for abnormal terminations.
1519 struct subprocess *chp, **prevp;
1522 if (n_children == 0)
1524 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1527 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next)
1528 if (chp->pid == pid)
1530 if (WIFSIGNALED(status)) {
1531 warn("Child process %s (pid %d) terminated with signal %d",
1532 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1534 dbglog("process %d (%s) finished, status = 0x%x",
1535 pid, (chp? chp->prog: "??"), status);
1536 if (chp && chp->done)
1537 (*chp->done)(chp->arg);
1539 if (pid == -1 && errno != ECHILD && errno != EINTR)
1540 error("Error waiting for child process: %m");
1545 * log_packet - format a packet and log it.
1548 char line[256]; /* line to be logged accumulated here */
1552 log_packet(p, len, prefix, level)
1558 strlcpy(line, prefix, sizeof(line));
1559 linep = line + strlen(line);
1560 format_packet(p, len, pr_log, NULL);
1562 syslog(level, "%s", line);
1566 * format_packet - make a readable representation of a packet,
1567 * calling `printer(arg, format, ...)' to output it.
1570 format_packet(p, len, printer, arg)
1573 void (*printer) __P((void *, char *, ...));
1578 struct protent *protp;
1580 if (len >= PPP_HDRLEN && p[0] == PPP_ALLSTATIONS && p[1] == PPP_UI) {
1584 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1585 if (proto == protp->protocol)
1587 if (protp != NULL) {
1588 printer(arg, "[%s", protp->name);
1589 n = (*protp->printpkt)(p, len, printer, arg);
1594 for (i = 0; (protp = protocols[i]) != NULL; ++i)
1595 if (proto == (protp->protocol & ~0x8000))
1597 if (protp != 0 && protp->data_name != 0) {
1598 printer(arg, "[%s data]", protp->data_name);
1600 printer(arg, "%.8B ...", p);
1602 printer(arg, "%.*B", len, p);
1605 printer(arg, "[proto=0x%x]", proto);
1610 printer(arg, "%.32B ...", p);
1612 printer(arg, "%.*B", len, p);
1616 pr_log __V((void *arg, char *fmt, ...))
1623 va_start(pvar, fmt);
1628 arg = va_arg(pvar, void *);
1629 fmt = va_arg(pvar, char *);
1632 n = vslprintf(buf, sizeof(buf), fmt, pvar);
1635 if (linep + n + 1 > line + sizeof(line)) {
1636 syslog(LOG_DEBUG, "%s", line);
1639 strlcpy(linep, buf, line + sizeof(line) - linep);
1644 * vslp_printer - used in processing a %P format
1646 struct buffer_info {
1652 vslp_printer __V((void *arg, char *fmt, ...))
1656 struct buffer_info *bi;
1659 va_start(pvar, fmt);
1664 arg = va_arg(pvar, void *);
1665 fmt = va_arg(pvar, char *);
1668 bi = (struct buffer_info *) arg;
1669 n = vslprintf(bi->ptr, bi->len, fmt, pvar);
1677 * print_string - print a readable representation of a string using
1681 print_string(p, len, printer, arg)
1684 void (*printer) __P((void *, char *, ...));
1690 for (; len > 0; --len) {
1692 if (' ' <= c && c <= '~') {
1693 if (c == '\\' || c == '"')
1695 printer(arg, "%c", c);
1699 printer(arg, "\\n");
1702 printer(arg, "\\r");
1705 printer(arg, "\\t");
1708 printer(arg, "\\%.3o", c);
1716 * novm - log an error message saying we ran out of memory, and die.
1722 fatal("Virtual memory exhausted allocating %s\n", msg);
1726 * slprintf - format a message into a buffer. Like sprintf except we
1727 * also specify the length of the output buffer, and we handle
1728 * %r (recursive format), %m (error message), %v (visible string),
1729 * %q (quoted string), %t (current time) and %I (IP address) formats.
1730 * Doesn't do floating-point formats.
1731 * Returns the number of chars put into buf.
1734 slprintf __V((char *buf, int buflen, char *fmt, ...))
1740 va_start(args, fmt);
1746 buf = va_arg(args, char *);
1747 buflen = va_arg(args, int);
1748 fmt = va_arg(args, char *);
1750 n = vslprintf(buf, buflen, fmt, args);
1756 * vslprintf - like slprintf, takes a va_list instead of a list of args.
1758 #define OUTCHAR(c) (buflen > 0? (--buflen, *buf++ = (c)): 0)
1761 vslprintf(buf, buflen, fmt, args)
1768 int width, prec, fillch;
1769 int base, len, neg, quoted;
1770 unsigned long val = 0;
1771 char *str, *f, *buf0;
1776 static char hexchars[] = "0123456789abcdef";
1777 struct buffer_info bufinfo;
1781 while (buflen > 0) {
1782 for (f = fmt; *f != '%' && *f != 0; ++f)
1788 memcpy(buf, fmt, len);
1803 width = va_arg(args, int);
1806 while (isdigit(c)) {
1807 width = width * 10 + c - '0';
1814 prec = va_arg(args, int);
1817 while (isdigit(c)) {
1818 prec = prec * 10 + c - '0';
1829 i = va_arg(args, int);
1838 val = va_arg(args, unsigned int);
1843 val = va_arg(args, unsigned int);
1847 val = (unsigned long) va_arg(args, void *);
1852 str = va_arg(args, char *);
1855 num[0] = va_arg(args, int);
1860 str = strerror(errno);
1863 ip = va_arg(args, u_int32_t);
1865 slprintf(num, sizeof(num), "%d.%d.%d.%d", (ip >> 24) & 0xff,
1866 (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
1870 f = va_arg(args, char *);
1872 n = vslprintf(buf, buflen + 1, f, va_arg(args, va_list));
1874 /* On the powerpc, a va_list is an array of 1 structure */
1875 n = vslprintf(buf, buflen + 1, f, va_arg(args, void *));
1883 str += 4; /* chop off the day name */
1884 str[15] = 0; /* chop off year and newline */
1886 case 'v': /* "visible" string */
1887 case 'q': /* quoted string */
1889 p = va_arg(args, unsigned char *);
1890 if (fillch == '0' && prec > 0) {
1893 n = strlen((char *)p);
1894 if (prec > 0 && prec < n)
1897 while (n > 0 && buflen > 0) {
1900 if (!quoted && c >= 0x80) {
1905 if (quoted && (c == '"' || c == '\\'))
1907 if (c < 0x20 || (0x7f <= c && c < 0xa0)) {
1911 case '\t': OUTCHAR('t'); break;
1912 case '\n': OUTCHAR('n'); break;
1913 case '\b': OUTCHAR('b'); break;
1914 case '\f': OUTCHAR('f'); break;
1917 OUTCHAR(hexchars[c >> 4]);
1918 OUTCHAR(hexchars[c & 0xf]);
1932 case 'P': /* print PPP packet */
1934 bufinfo.len = buflen + 1;
1935 p = va_arg(args, unsigned char *);
1936 n = va_arg(args, int);
1937 format_packet(p, n, vslp_printer, &bufinfo);
1939 buflen = bufinfo.len - 1;
1942 p = va_arg(args, unsigned char *);
1943 for (n = prec; n > 0; --n) {
1947 OUTCHAR(hexchars[(c >> 4) & 0xf]);
1948 OUTCHAR(hexchars[c & 0xf]);
1954 --fmt; /* so %z outputs %z etc. */
1959 str = num + sizeof(num);
1961 while (str > num + neg) {
1962 *--str = hexchars[val % base];
1964 if (--prec <= 0 && val == 0)
1976 len = num + sizeof(num) - 1 - str;
1979 if (prec > 0 && len > prec)
1985 if ((n = width - len) > 0) {
1993 memcpy(buf, str, len);
2002 * script_setenv - set an environment variable value to be used
2003 * for scripts that we run (e.g. ip-up, auth-up, etc.)
2006 script_setenv(var, value)
2009 size_t vl = strlen(var) + strlen(value) + 2;
2011 char *p, *newstring;
2013 newstring = (char *) malloc(vl);
2016 slprintf(newstring, vl, "%s=%s", var, value);
2018 /* check if this variable is already set */
2019 if (script_env != 0) {
2020 for (i = 0; (p = script_env[i]) != 0; ++i) {
2021 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2023 script_env[i] = newstring;
2029 script_env = (char **) malloc(16 * sizeof(char *));
2030 if (script_env == 0)
2035 /* reallocate script_env with more space if needed */
2036 if (i + 1 >= s_env_nalloc) {
2038 char **newenv = (char **) realloc((void *)script_env,
2039 new_n * sizeof(char *));
2042 script_env = newenv;
2043 s_env_nalloc = new_n;
2046 script_env[i] = newstring;
2047 script_env[i+1] = 0;
2051 * script_unsetenv - remove a variable from the environment
2055 script_unsetenv(var)
2058 int vl = strlen(var);
2062 if (script_env == 0)
2064 for (i = 0; (p = script_env[i]) != 0; ++i) {
2065 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2067 while ((script_env[i] = script_env[i+1]) != 0)
2075 * strlcpy - like strcpy/strncpy, doesn't overflow destination buffer,
2076 * always leaves destination null-terminated (for len > 0).
2079 strlcpy(dest, src, len)
2084 size_t ret = strlen(src);
2090 strncpy(dest, src, len - 1);
2098 * strlcat - like strcat/strncat, doesn't overflow destination buffer,
2099 * always leaves destination null-terminated (for len > 0).
2102 strlcat(dest, src, len)
2107 size_t dlen = strlen(dest);
2109 return dlen + strlcpy(dest + dlen, src, (len > dlen? len - dlen: 0));
2113 * logit - does the hard work for fatal et al.
2116 logit(level, fmt, args)
2124 n = vslprintf(buf, sizeof(buf), fmt, args);
2125 syslog(level, "%s", buf);
2126 if (log_to_fd >= 0 && (level != LOG_DEBUG || debug)) {
2127 if (buf[n-1] != '\n')
2129 if (write(log_to_fd, buf, n) != n)
2135 * fatal - log an error message and die horribly.
2138 fatal __V((char *fmt, ...))
2143 va_start(pvar, fmt);
2147 fmt = va_arg(pvar, char *);
2150 logit(LOG_ERR, fmt, pvar);
2153 die(1); /* as promised */
2157 * error - log an error message.
2160 error __V((char *fmt, ...))
2165 va_start(pvar, fmt);
2169 fmt = va_arg(pvar, char *);
2172 logit(LOG_ERR, fmt, pvar);
2177 * warn - log a warning message.
2180 warn __V((char *fmt, ...))
2185 va_start(pvar, fmt);
2189 fmt = va_arg(pvar, char *);
2192 logit(LOG_WARNING, fmt, pvar);
2197 * notice - log a notice-level message.
2200 notice __V((char *fmt, ...))
2205 va_start(pvar, fmt);
2209 fmt = va_arg(pvar, char *);
2212 logit(LOG_NOTICE, fmt, pvar);
2217 * info - log an informational message.
2220 info __V((char *fmt, ...))
2225 va_start(pvar, fmt);
2229 fmt = va_arg(pvar, char *);
2232 logit(LOG_INFO, fmt, pvar);
2237 * dbglog - log a debug message.
2240 dbglog __V((char *fmt, ...))
2245 va_start(pvar, fmt);
2249 fmt = va_arg(pvar, char *);
2252 logit(LOG_DEBUG, fmt, pvar);
2257 * start_charshunt - create a child process to run the character shunt.
2260 start_charshunt(ifd, ofd)
2267 error("Can't fork process for character shunt: %m");
2274 if (getuid() != uid)
2275 fatal("setuid failed");
2279 charshunt(ifd, ofd, record_file);
2282 charshunt_pid = cpid;
2286 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2298 * charshunt - the character shunt, which passes characters between
2299 * the pty master side and the serial port (or stdin/stdout).
2300 * This runs as the user (not as root).
2301 * (We assume ofd >= ifd which is true the way this gets called. :-).
2304 charshunt(ifd, ofd, record_file)
2309 fd_set ready, writey;
2310 u_char *ibufp, *obufp;
2313 int pty_readable, stdin_readable;
2314 struct timeval lasttime;
2315 FILE *recordf = NULL;
2318 * Reset signal handlers.
2320 signal(SIGHUP, SIG_IGN); /* Hangup */
2321 signal(SIGINT, SIG_DFL); /* Interrupt */
2322 signal(SIGTERM, SIG_DFL); /* Terminate */
2323 signal(SIGCHLD, SIG_DFL);
2324 signal(SIGUSR1, SIG_DFL);
2325 signal(SIGUSR2, SIG_DFL);
2326 signal(SIGABRT, SIG_DFL);
2327 signal(SIGALRM, SIG_DFL);
2328 signal(SIGFPE, SIG_DFL);
2329 signal(SIGILL, SIG_DFL);
2330 signal(SIGPIPE, SIG_DFL);
2331 signal(SIGQUIT, SIG_DFL);
2332 signal(SIGSEGV, SIG_DFL);
2334 signal(SIGBUS, SIG_DFL);
2337 signal(SIGEMT, SIG_DFL);
2340 signal(SIGPOLL, SIG_DFL);
2343 signal(SIGPROF, SIG_DFL);
2346 signal(SIGSYS, SIG_DFL);
2349 signal(SIGTRAP, SIG_DFL);
2352 signal(SIGVTALRM, SIG_DFL);
2355 signal(SIGXCPU, SIG_DFL);
2358 signal(SIGXFSZ, SIG_DFL);
2362 * Open the record file if required.
2364 if (record_file != NULL) {
2365 recordf = fopen(record_file, "a");
2366 if (recordf == NULL)
2367 error("Couldn't create record file %s: %m", record_file);
2370 /* set all the fds to non-blocking mode */
2371 flags = fcntl(pty_master, F_GETFL);
2373 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2374 warn("couldn't set pty master to nonblock: %m");
2375 flags = fcntl(ifd, F_GETFL);
2377 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2378 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2380 flags = fcntl(ofd, F_GETFL);
2382 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2383 warn("couldn't set stdout to nonblock: %m");
2387 ibufp = obufp = NULL;
2388 pty_readable = stdin_readable = 1;
2389 nfds = (ofd > pty_master? ofd: pty_master) + 1;
2390 if (recordf != NULL) {
2391 gettimeofday(&lasttime, NULL);
2392 putc(7, recordf); /* put start marker */
2393 putc(lasttime.tv_sec >> 24, recordf);
2394 putc(lasttime.tv_sec >> 16, recordf);
2395 putc(lasttime.tv_sec >> 8, recordf);
2396 putc(lasttime.tv_sec, recordf);
2397 lasttime.tv_usec = 0;
2400 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
2404 FD_SET(pty_master, &writey);
2405 else if (stdin_readable)
2406 FD_SET(ifd, &ready);
2408 FD_SET(ofd, &writey);
2409 else if (pty_readable)
2410 FD_SET(pty_master, &ready);
2411 if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
2416 if (FD_ISSET(ifd, &ready)) {
2417 ibufp = inpacket_buf;
2418 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2419 if (nibuf < 0 && errno == EIO)
2422 if (!(errno == EINTR || errno == EAGAIN)) {
2423 error("Error reading standard input: %m");
2427 } else if (nibuf == 0) {
2428 /* end of file from stdin */
2430 /* do a 0-length write, hopefully this will generate
2431 an EOF (hangup) on the slave side. */
2432 write(pty_master, inpacket_buf, 0);
2434 if (!record_write(recordf, 4, NULL, 0, &lasttime))
2437 FD_SET(pty_master, &writey);
2439 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2443 if (FD_ISSET(pty_master, &ready)) {
2444 obufp = outpacket_buf;
2445 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2446 if (nobuf < 0 && errno == EIO)
2449 if (!(errno == EINTR || errno == EAGAIN)) {
2450 error("Error reading pseudo-tty master: %m");
2454 } else if (nobuf == 0) {
2455 /* end of file from the pty - slave side has closed */
2457 stdin_readable = 0; /* pty is not writable now */
2461 if (!record_write(recordf, 3, NULL, 0, &lasttime))
2464 FD_SET(ofd, &writey);
2466 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2470 if (FD_ISSET(ofd, &writey)) {
2471 n = write(ofd, obufp, nobuf);
2474 error("Error writing standard output: %m");
2484 if (FD_ISSET(pty_master, &writey)) {
2485 n = write(pty_master, ibufp, nibuf);
2488 error("Error writing pseudo-tty master: %m");
2503 record_write(f, code, buf, nb, tp)
2513 gettimeofday(&now, NULL);
2514 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2515 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2519 putc(diff >> 24, f);
2520 putc(diff >> 16, f);
2533 fwrite(buf, nb, 1, f);
2537 error("Error writing record file: %m");