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 const char rcsid[] = "$Id: main.c,v 1.82 1999/08/13 01:57:35 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"
63 #endif /* IPX_CHANGE */
69 char ifname[32]; /* Interface name */
70 int ifunit; /* Interface unit number */
72 char *progname; /* Name of this program */
73 char hostname[MAXNAMELEN]; /* Our hostname */
74 static char pidfilename[MAXPATHLEN]; /* name of pid file */
75 static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
76 static char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
77 static uid_t uid; /* Our real user-id */
78 static int conn_running; /* we have a [dis]connector running */
80 int ttyfd; /* Serial port file descriptor */
81 mode_t tty_mode = -1; /* Original access permissions to tty */
82 int baud_rate; /* Actual bits/second for serial device */
83 int hungup; /* terminal has been hung up */
84 int privileged; /* we're running as real uid root */
85 int need_holdoff; /* need holdoff period before restarting */
86 int detached; /* have detached from terminal */
87 struct stat devstat; /* result of stat() on devnam */
88 int prepass = 0; /* doing prepass to find device name */
89 int devnam_fixed; /* set while in options.ttyxx file */
90 volatile int status; /* exit status for pppd */
91 int unsuccess; /* # unsuccessful connection attempts */
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 */
116 static int privopen; /* don't lock, open device as root */
118 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
120 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
121 int ngroups; /* How many groups valid in groups */
123 static struct timeval start_time; /* Time when link was started. */
125 struct pppd_stats link_stats;
126 int link_connect_time;
127 int link_stats_valid;
129 static int charshunt_pid; /* Process ID for charshunt */
132 * We maintain a list of child process pids and
133 * functions to call when they exit.
138 void (*done) __P((void *));
140 struct subprocess *next;
143 static struct subprocess *children;
145 /* Prototypes for procedures local to this file. */
147 static void create_pidfile __P((void));
148 static void create_linkpidfile __P((void));
149 static void cleanup __P((void));
150 static void close_tty __P((void));
151 static void get_input __P((void));
152 static void calltimeout __P((void));
153 static struct timeval *timeleft __P((struct timeval *));
154 static void kill_my_pg __P((int));
155 static void hup __P((int));
156 static void term __P((int));
157 static void chld __P((int));
158 static void toggle_debug __P((int));
159 static void open_ccp __P((int));
160 static void bad_signal __P((int));
161 static void holdoff_end __P((void *));
162 static int device_script __P((char *, int, int, int));
163 static void reap_kids __P((int waitfor));
164 static void record_child __P((int, char *, void (*) (void *), void *));
165 static int start_charshunt __P((int, int));
166 static void charshunt_done __P((void *));
167 static void charshunt __P((int, int, char *));
168 static int record_write __P((FILE *, int code, u_char *buf, int nb,
171 extern char *ttyname __P((int));
172 extern char *getlogin __P((void));
173 int main __P((int, char *[]));
177 #define O_NONBLOCK O_NDELAY
181 #define setlogmask(x)
185 * PPP Data Link Layer "protocol" table.
186 * One entry per supported protocol.
187 * The last entry must be NULL.
189 struct protent *protocols[] = {
218 struct protent *protp;
222 phase = PHASE_INITIALIZE;
225 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
226 * This way we can close 0, 1, 2 in detach() without clobbering
227 * a fd that we are using.
229 if ((i = open("/dev/null", O_RDWR)) >= 0) {
230 while (0 <= i && i <= 2)
238 /* Initialize syslog facilities */
241 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
242 option_error("Couldn't get hostname: %m");
245 hostname[MAXNAMELEN-1] = 0;
248 privileged = uid == 0;
249 slprintf(numbuf, sizeof(numbuf), "%d", uid);
250 script_setenv("ORIG_UID", numbuf);
252 ngroups = getgroups(NGROUPS_MAX, groups);
255 * Initialize to the standard option set, then parse, in order,
256 * the system options file, the user's options file,
257 * the tty's options file, and the command line arguments.
259 for (i = 0; (protp = protocols[i]) != NULL; ++i)
265 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
266 || !options_from_user())
267 exit(EXIT_OPTION_ERROR);
269 /* scan command line and options files to find device name */
271 parse_args(argc-1, argv+1);
275 * Work out the device name, if it hasn't already been specified.
277 using_pty = notty || ptycommand != NULL;
278 if (!using_pty && default_device) {
280 if (!isatty(0) || (p = ttyname(0)) == NULL) {
281 option_error("no device specified and stdin is not a tty");
282 exit(EXIT_OPTION_ERROR);
284 strlcpy(devnam, p, sizeof(devnam));
285 if (stat(devnam, &devstat) < 0)
286 fatal("Couldn't stat default device %s: %m", devnam);
290 * Parse the tty options file and the command line.
291 * The per-tty options file should not change
292 * ptycommand, notty or devnam.
296 if (!options_for_tty())
297 exit(EXIT_OPTION_ERROR);
301 if (!parse_args(argc-1, argv+1))
302 exit(EXIT_OPTION_ERROR);
305 * Check that we are running as root.
307 if (geteuid() != 0) {
308 option_error("must be root to run %s, since it is not setuid-root",
313 if (!ppp_available()) {
314 option_error(no_ppp_msg);
315 exit(EXIT_NO_KERNEL_SUPPORT);
319 * Check that the options given are valid and consistent.
321 if (!sys_check_options())
322 exit(EXIT_OPTION_ERROR);
323 auth_check_options();
324 for (i = 0; (protp = protocols[i]) != NULL; ++i)
325 if (protp->check_options != NULL)
326 (*protp->check_options)();
327 if (demand && connector == 0) {
328 option_error("connect script is required for demand-dialling\n");
329 exit(EXIT_OPTION_ERROR);
333 if (!default_device) {
334 option_error("%s option precludes specifying device name",
335 notty? "notty": "pty");
336 exit(EXIT_OPTION_ERROR);
338 if (ptycommand != NULL && notty) {
339 option_error("pty option is incompatible with notty option");
340 exit(EXIT_OPTION_ERROR);
342 default_device = notty;
345 if (notty && log_to_fd <= 1)
349 * If the user has specified a device which is the same as
350 * the one on stdin, pretend they didn't specify any.
351 * If the device is already open read/write on stdin,
352 * we assume we don't need to lock it, and we can open it as root.
354 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
355 && statbuf.st_rdev == devstat.st_rdev) {
357 fdflags = fcntl(0, F_GETFL);
358 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
366 * Don't send log messages to the serial port, it tends to
367 * confuse the peer. :-)
369 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
370 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
373 script_setenv("DEVICE", devnam);
376 * Initialize system-dependent stuff and magic number package.
381 setlogmask(LOG_UPTO(LOG_DEBUG));
384 * Detach ourselves from the terminal, if required,
385 * and identify who is running us.
387 if (!nodetach && !updetach)
392 if (pw != NULL && pw->pw_name != NULL)
397 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
398 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
399 script_setenv("PPPLOGNAME", p);
402 * Compute mask of all interesting signals and install signal handlers
403 * for each. Only one signal handler may be active at a time. Therefore,
404 * all other signals should be masked when any handler is executing.
407 sigaddset(&mask, SIGHUP);
408 sigaddset(&mask, SIGINT);
409 sigaddset(&mask, SIGTERM);
410 sigaddset(&mask, SIGCHLD);
411 sigaddset(&mask, SIGUSR2);
413 #define SIGNAL(s, handler) do { \
414 sa.sa_handler = handler; \
415 if (sigaction(s, &sa, NULL) < 0) \
416 fatal("Couldn't establish signal handler (%d): %m", s); \
421 SIGNAL(SIGHUP, hup); /* Hangup */
422 SIGNAL(SIGINT, term); /* Interrupt */
423 SIGNAL(SIGTERM, term); /* Terminate */
424 SIGNAL(SIGCHLD, chld);
426 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
427 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
430 * Install a handler for other signals which would otherwise
431 * cause pppd to exit without cleaning up.
433 SIGNAL(SIGABRT, bad_signal);
434 SIGNAL(SIGALRM, bad_signal);
435 SIGNAL(SIGFPE, bad_signal);
436 SIGNAL(SIGILL, bad_signal);
437 SIGNAL(SIGPIPE, bad_signal);
438 SIGNAL(SIGQUIT, bad_signal);
439 SIGNAL(SIGSEGV, bad_signal);
441 SIGNAL(SIGBUS, bad_signal);
444 SIGNAL(SIGEMT, bad_signal);
447 SIGNAL(SIGPOLL, bad_signal);
450 SIGNAL(SIGPROF, bad_signal);
453 SIGNAL(SIGSYS, bad_signal);
456 SIGNAL(SIGTRAP, bad_signal);
459 SIGNAL(SIGVTALRM, bad_signal);
462 SIGNAL(SIGXCPU, bad_signal);
465 SIGNAL(SIGXFSZ, bad_signal);
469 * Apparently we can get a SIGPIPE when we call syslog, if
470 * syslogd has died and been restarted. Ignoring it seems
473 signal(SIGPIPE, SIG_IGN);
477 create_linkpidfile();
480 * If we're doing dial-on-demand, set up the interface now.
484 * Open the loopback channel and set it up to be the ppp interface.
486 fd_loop = open_ppp_loopback();
488 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
489 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
490 script_setenv("IFNAME", ifname);
492 create_pidfile(); /* write pid to file */
495 * Configure the interface and mark it up, etc.
510 * Don't do anything until we see some activity.
513 phase = PHASE_DORMANT;
517 if (sigsetjmp(sigjmp, 1) == 0) {
518 sigprocmask(SIG_BLOCK, &mask, NULL);
519 if (kill_link || got_sigchld) {
520 sigprocmask(SIG_UNBLOCK, &mask, NULL);
523 sigprocmask(SIG_UNBLOCK, &mask, NULL);
524 wait_input(timeleft(&timo));
534 if (get_loop_output())
540 if (kill_link && !persist)
544 * Now we want to bring up the link.
547 info("Starting link");
550 phase = PHASE_SERIALCONN;
553 * Get a pty master/slave pair if the pty, notty, or record
554 * options were specified.
556 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
559 if (ptycommand != NULL || notty || record_file != NULL) {
560 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
561 error("Couldn't allocate pseudo-tty");
562 status = EXIT_FATAL_ERROR;
565 set_up_tty(pty_slave, 1);
569 * Lock the device if we've been asked to.
571 status = EXIT_LOCK_FAILED;
572 if (lockflag && !privopen) {
573 if (lock(devnam) < 0)
579 * Open the serial device and set it up to be the ppp interface.
580 * First we open it in non-blocking mode so we can set the
581 * various termios flags appropriately. If we aren't dialling
582 * out and we want to use the modem lines, we reopen it later
583 * in order to wait for the carrier detect signal from the modem.
587 if (devnam[0] != 0) {
589 /* If the user specified the device name, become the
590 user before opening it. */
592 if (!devnam_info.priv && !privopen)
594 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
596 if (!devnam_info.priv && !privopen)
602 error("Failed to open %s: %m", devnam);
603 status = EXIT_OPEN_FAILED;
605 if (!persist || err != EINTR)
608 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
609 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
610 warn("Couldn't reset non-blocking mode on device: %m");
613 * Do the equivalent of `mesg n' to stop broadcast messages.
615 if (fstat(ttyfd, &statbuf) < 0
616 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
617 warn("Couldn't restrict write permissions to %s: %m", devnam);
619 tty_mode = statbuf.st_mode;
622 * Set line speed, flow control, etc.
623 * If we have a non-null connection or initializer script,
624 * on most systems we set CLOCAL for now so that we can talk
625 * to the modem before carrier comes up. But this has the
626 * side effect that we might miss it if CD drops before we
627 * get to clear CLOCAL below. On systems where we can talk
628 * successfully to the modem with CLOCAL clear and CD down,
629 * we could clear CLOCAL at this point.
631 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
632 || initializer != NULL));
637 * If the notty and/or record option was specified,
638 * start up the character shunt now.
640 status = EXIT_PTYCMD_FAILED;
641 if (ptycommand != NULL) {
642 if (record_file != NULL) {
643 int ipipe[2], opipe[2], ok;
645 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
646 fatal("Couldn't create pipes for record option: %m");
647 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
648 && start_charshunt(ipipe[0], opipe[1]);
656 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
663 if (!start_charshunt(0, 1))
665 } else if (record_file != NULL) {
666 if (!start_charshunt(ttyfd, ttyfd))
670 /* run connection script */
671 if ((connector && connector[0]) || initializer) {
672 if (real_ttyfd != -1) {
673 if (!default_device && modem) {
674 setdtr(real_ttyfd, 0); /* in case modem is off hook */
676 setdtr(real_ttyfd, 1);
680 if (initializer && initializer[0]) {
681 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
682 error("Initializer script failed");
683 status = EXIT_INIT_FAILED;
689 info("Serial port initialized.");
692 if (connector && connector[0]) {
693 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
694 error("Connect script failed");
695 status = EXIT_CONNECT_FAILED;
701 info("Serial connection established.");
704 /* set line speed, flow control, etc.;
705 clear CLOCAL if modem option */
706 if (real_ttyfd != -1)
707 set_up_tty(real_ttyfd, 0);
710 /* reopen tty if necessary to wait for carrier */
711 if (connector == NULL && modem && devnam[0] != 0) {
713 if ((i = open(devnam, O_RDWR)) >= 0)
715 if (errno != EINTR) {
716 error("Failed to reopen %s: %m", devnam);
717 status = EXIT_OPEN_FAILED;
719 if (!persist || errno != EINTR || hungup || kill_link)
725 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
726 script_setenv("SPEED", numbuf);
728 /* run welcome script, if any */
729 if (welcomer && welcomer[0]) {
730 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
731 warn("Welcome script failed");
734 /* set up the serial device as a ppp interface */
735 fd_ppp = establish_ppp(ttyfd);
737 status = EXIT_FATAL_ERROR;
743 info("Using interface ppp%d", ifunit);
744 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
745 script_setenv("IFNAME", ifname);
747 create_pidfile(); /* write pid to file */
751 * Start opening the connection and wait for
752 * incoming events (reply, timeout, etc.).
754 notice("Connect: %s <--> %s", ifname, ppp_devnam);
755 gettimeofday(&start_time, NULL);
756 link_stats_valid = 0;
757 script_unsetenv("CONNECT_TIME");
758 script_unsetenv("BYTES_SENT");
759 script_unsetenv("BYTES_RCVD");
763 * If we are initiating this connection, wait for a short
764 * time for something from the peer. This can avoid bouncing
765 * our packets off his tty before he has it set up.
767 if (connector != NULL || ptycommand != NULL) {
774 lcp_open(0); /* Start protocol */
777 status = EXIT_NEGOTIATION_FAILED;
778 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
779 if (sigsetjmp(sigjmp, 1) == 0) {
780 sigprocmask(SIG_BLOCK, &mask, NULL);
781 if (kill_link || open_ccp_flag || got_sigchld) {
782 sigprocmask(SIG_UNBLOCK, &mask, NULL);
785 sigprocmask(SIG_UNBLOCK, &mask, NULL);
786 wait_input(timeleft(&timo));
793 lcp_close(0, "User request");
797 if (phase == PHASE_NETWORK) {
798 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
799 (*ccp_protent.open)(0);
804 reap_kids(0); /* Don't leave dead kids lying around */
808 * Print connect time and statistics.
810 if (link_stats_valid) {
811 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
812 info("Connect time %d.%d minutes.", t/10, t%10);
813 info("Sent %d bytes, received %d bytes.",
814 link_stats.bytes_out, link_stats.bytes_in);
818 * If we may want to bring the link up again, transfer
819 * the ppp unit back to the loopback. Set the
820 * real serial device back to its normal mode of operation.
826 disestablish_ppp(ttyfd);
832 * Run disconnector script, if requested.
833 * XXX we may not be able to do this if the line has hung up!
836 if (disconnector && !hungup) {
838 set_up_tty(real_ttyfd, 1);
839 if (device_script(disconnector, ttyfd, ttyfd, 0) < 0) {
840 warn("disconnect script failed");
842 info("Serial link disconnected.");
859 if (pidfilename[0] != 0
860 && unlink(pidfilename) < 0 && errno != ENOENT)
861 warn("unable to delete pid file %s: %m", pidfilename);
865 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
871 if (holdoff > 0 && need_holdoff) {
872 phase = PHASE_HOLDOFF;
873 TIMEOUT(holdoff_end, NULL, holdoff);
875 if (sigsetjmp(sigjmp, 1) == 0) {
876 sigprocmask(SIG_BLOCK, &mask, NULL);
877 if (kill_link || got_sigchld) {
878 sigprocmask(SIG_UNBLOCK, &mask, NULL);
881 sigprocmask(SIG_UNBLOCK, &mask, NULL);
882 wait_input(timeleft(&timo));
889 phase = PHASE_DORMANT; /* allow signal to end holdoff */
893 } while (phase == PHASE_HOLDOFF);
899 /* Wait for scripts to finish */
900 /* XXX should have a timeout here */
901 while (n_children > 0) {
903 struct subprocess *chp;
904 dbglog("Waiting for %d child processes...", n_children);
905 for (chp = children; chp != NULL; chp = chp->next)
906 dbglog(" script %s, pid %d", chp->prog, chp->pid);
916 * detach - detach us from the controlling terminal.
925 if ((pid = fork()) < 0) {
926 error("Couldn't detach (fork failed: %m)");
927 die(1); /* or just return? */
933 exit(0); /* parent dies */
942 /* update pid files if they have been written already */
946 create_linkpidfile();
950 * reopen_log - (re)open our connection to syslog.
956 openlog("pppd", LOG_PID);
958 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
959 setlogmask(LOG_UPTO(LOG_INFO));
964 * Create a file containing our process ID.
972 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
973 _PATH_VARRUN, ifname);
974 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
975 fprintf(pidfile, "%d\n", getpid());
976 (void) fclose(pidfile);
978 error("Failed to create pid file %s: %m", pidfilename);
981 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
982 script_setenv("PPPD_PID", numbuf);
984 create_linkpidfile();
992 if (linkname[0] == 0)
994 slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
995 _PATH_VARRUN, linkname);
996 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
997 fprintf(pidfile, "%d\n", getpid());
999 fprintf(pidfile, "%s\n", ifname);
1000 (void) fclose(pidfile);
1002 error("Failed to create pid file %s: %m", linkpidfile);
1005 script_setenv("LINKNAME", linkname);
1009 * holdoff_end - called via a timeout when the holdoff period ends.
1015 phase = PHASE_DORMANT;
1019 * get_input - called when incoming data is available.
1027 struct protent *protp;
1029 p = inpacket_buf; /* point to beginning of packet buffer */
1031 len = read_packet(inpacket_buf);
1036 notice("Modem hangup");
1038 status = EXIT_HANGUP;
1039 lcp_lowerdown(0); /* serial link is no longer available */
1044 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1045 dbglog("rcvd %P", p, len);
1047 if (len < PPP_HDRLEN) {
1048 MAINDEBUG(("io(): Received short packet."));
1052 p += 2; /* Skip address and control */
1053 GETSHORT(protocol, p);
1057 * Toss all non-LCP packets unless LCP is OPEN.
1059 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1060 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1065 * Until we get past the authentication phase, toss all packets
1066 * except LCP, LQR and authentication packets.
1068 if (phase <= PHASE_AUTHENTICATE
1069 && !(protocol == PPP_LCP || protocol == PPP_LQR
1070 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1071 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1077 * Upcall the proper protocol input routine.
1079 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1080 if (protp->protocol == protocol && protp->enabled_flag) {
1081 (*protp->input)(0, p, len);
1084 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1085 && protp->datainput != NULL) {
1086 (*protp->datainput)(0, p, len);
1092 warn("Unsupported protocol (0x%x) received", protocol);
1093 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1098 * die - clean up state and exit with the specified status.
1105 syslog(LOG_INFO, "Exit.");
1110 * cleanup - restore anything which needs to be restored before we exit
1119 disestablish_ppp(ttyfd);
1120 if (real_ttyfd >= 0)
1123 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1124 warn("unable to delete pid file %s: %m", pidfilename);
1126 if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
1127 warn("unable to delete pid file %s: %m", linkpidfile);
1135 * close_tty - restore the terminal device and close it.
1140 /* drop dtr to hang up */
1141 if (!default_device && modem) {
1142 setdtr(real_ttyfd, 0);
1144 * This sleep is in case the serial port has CLOCAL set by default,
1145 * and consequently will reassert DTR when we close the device.
1150 restore_tty(real_ttyfd);
1152 if (tty_mode != (mode_t) -1) {
1153 if (fchmod(real_ttyfd, tty_mode) != 0) {
1154 /* XXX if devnam is a symlink, this will change the link */
1155 chmod(devnam, tty_mode);
1164 * update_link_stats - get stats at link termination.
1167 update_link_stats(u)
1173 if (!get_ppp_stats(u, &link_stats)
1174 || gettimeofday(&now, NULL) < 0)
1176 link_connect_time = now.tv_sec - start_time.tv_sec;
1177 link_stats_valid = 1;
1179 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1180 script_setenv("CONNECT_TIME", numbuf);
1181 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1182 script_setenv("BYTES_SENT", numbuf);
1183 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1184 script_setenv("BYTES_RCVD", numbuf);
1189 struct timeval c_time; /* time at which to call routine */
1190 void *c_arg; /* argument to routine */
1191 void (*c_func) __P((void *)); /* routine */
1192 struct callout *c_next;
1195 static struct callout *callout = NULL; /* Callout list */
1196 static struct timeval timenow; /* Current time */
1199 * timeout - Schedule a timeout.
1201 * Note that this timeout takes the number of seconds, NOT hz (as in
1205 timeout(func, arg, time)
1206 void (*func) __P((void *));
1210 struct callout *newp, *p, **pp;
1212 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1217 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1218 fatal("Out of memory in timeout()!");
1220 newp->c_func = func;
1221 gettimeofday(&timenow, NULL);
1222 newp->c_time.tv_sec = timenow.tv_sec + time;
1223 newp->c_time.tv_usec = timenow.tv_usec;
1226 * Find correct place and link it in.
1228 for (pp = &callout; (p = *pp); pp = &p->c_next)
1229 if (newp->c_time.tv_sec < p->c_time.tv_sec
1230 || (newp->c_time.tv_sec == p->c_time.tv_sec
1231 && newp->c_time.tv_usec < p->c_time.tv_usec))
1239 * untimeout - Unschedule a timeout.
1242 untimeout(func, arg)
1243 void (*func) __P((void *));
1246 struct callout **copp, *freep;
1248 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1251 * Find first matching timeout and remove it from the list.
1253 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1254 if (freep->c_func == func && freep->c_arg == arg) {
1255 *copp = freep->c_next;
1256 (void) free((char *) freep);
1263 * calltimeout - Call any timeout routines which are now due.
1270 while (callout != NULL) {
1273 if (gettimeofday(&timenow, NULL) < 0)
1274 fatal("Failed to get time of day: %m");
1275 if (!(p->c_time.tv_sec < timenow.tv_sec
1276 || (p->c_time.tv_sec == timenow.tv_sec
1277 && p->c_time.tv_usec <= timenow.tv_usec)))
1278 break; /* no, it's not time yet */
1280 callout = p->c_next;
1281 (*p->c_func)(p->c_arg);
1289 * timeleft - return the length of time until the next timeout is due.
1291 static struct timeval *
1293 struct timeval *tvp;
1295 if (callout == NULL)
1298 gettimeofday(&timenow, NULL);
1299 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1300 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1301 if (tvp->tv_usec < 0) {
1302 tvp->tv_usec += 1000000;
1305 if (tvp->tv_sec < 0)
1306 tvp->tv_sec = tvp->tv_usec = 0;
1313 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1319 struct sigaction act, oldact;
1321 act.sa_handler = SIG_IGN;
1324 sigaction(sig, &act, &oldact);
1325 sigaction(sig, &oldact, NULL);
1330 * hup - Catch SIGHUP signal.
1332 * Indicates that the physical layer has been disconnected.
1333 * We don't rely on this indication; if the user has sent this
1334 * signal, we just take the link down.
1340 info("Hangup (SIGHUP)");
1342 if (status != EXIT_HANGUP)
1343 status = EXIT_USER_REQUEST;
1345 /* Send the signal to the [dis]connector process(es) also */
1348 kill(charshunt_pid, sig);
1350 siglongjmp(sigjmp, 1);
1355 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1357 * Indicates that we should initiate a graceful disconnect and exit.
1364 info("Terminating on signal %d.", sig);
1365 persist = 0; /* don't try to restart */
1367 status = EXIT_USER_REQUEST;
1369 /* Send the signal to the [dis]connector process(es) also */
1372 kill(charshunt_pid, sig);
1374 siglongjmp(sigjmp, 1);
1379 * chld - Catch SIGCHLD signal.
1380 * Sets a flag so we will call reap_kids in the mainline.
1388 siglongjmp(sigjmp, 1);
1393 * toggle_debug - Catch SIGUSR1 signal.
1395 * Toggle debug flag.
1404 setlogmask(LOG_UPTO(LOG_DEBUG));
1406 setlogmask(LOG_UPTO(LOG_WARNING));
1412 * open_ccp - Catch SIGUSR2 signal.
1414 * Try to (re)negotiate compression.
1423 siglongjmp(sigjmp, 1);
1428 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1434 static int crashed = 0;
1439 error("Fatal signal %d", sig);
1441 kill_my_pg(SIGTERM);
1443 kill(charshunt_pid, SIGTERM);
1449 * device_script - run a program to talk to the serial device
1450 * (e.g. to run the connector or disconnector script).
1453 device_script(program, in, out, dont_wait)
1467 error("Failed to create child process: %m");
1476 int newin = dup(in);
1480 } else if (out == 2) {
1483 if (log_to_fd >= 0) {
1488 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1489 if (errfd >= 0 && errfd != 2) {
1509 if (getuid() != uid) {
1510 error("setuid failed");
1514 execl("/bin/sh", "sh", "-c", program, (char *)0);
1515 error("could not exec /bin/sh: %m");
1521 record_child(pid, program, NULL, NULL);
1524 while (waitpid(pid, &status, 0) < 0) {
1527 fatal("error waiting for (dis)connection process: %m");
1532 return (status == 0 ? 0 : -1);
1537 * run-program - execute a program with given arguments,
1538 * but don't wait for it.
1539 * If the program can't be executed, logs an error unless
1540 * must_exist is 0 and the program file doesn't exist.
1541 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1542 * or isn't an executable plain file, or the process ID of the child.
1543 * If done != NULL, (*done)(arg) will be called later (within
1544 * reap_kids) iff the return value is > 0.
1547 run_program(prog, args, must_exist, done, arg)
1551 void (*done) __P((void *));
1558 * First check if the file exists and is executable.
1559 * We don't use access() because that would use the
1560 * real user-id, which might not be root, and the script
1561 * might be accessible only to root.
1564 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1565 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1566 if (must_exist || errno != ENOENT)
1567 warn("Can't execute %s: %m", prog);
1573 error("Failed to create child process for %s: %m", prog);
1579 /* Leave the current location */
1580 (void) setsid(); /* No controlling tty. */
1581 (void) umask (S_IRWXG|S_IRWXO);
1582 (void) chdir ("/"); /* no current directory. */
1583 setuid(0); /* set real UID = root */
1586 /* Ensure that nothing of our device environment is inherited. */
1592 close (ttyfd); /* tty interface to the ppp device */
1593 if (real_ttyfd >= 0)
1596 /* Don't pass handles to the PPP device, even by accident. */
1597 new_fd = open (_PATH_DEVNULL, O_RDWR);
1600 dup2 (new_fd, 0); /* stdin <- /dev/null */
1603 dup2 (0, 1); /* stdout -> /dev/null */
1604 dup2 (0, 2); /* stderr -> /dev/null */
1608 /* Force the priority back to zero if pppd is running higher. */
1609 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1610 warn("can't reset priority to 0: %m");
1613 /* SysV recommends a second fork at this point. */
1615 /* run the program */
1616 execve(prog, args, script_env);
1617 if (must_exist || errno != ENOENT) {
1618 /* have to reopen the log, there's nowhere else
1619 for the message to go. */
1621 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1628 dbglog("Script %s started (pid %d)", prog, pid);
1629 record_child(pid, prog, done, arg);
1636 * record_child - add a child process to the list for reap_kids
1640 record_child(pid, prog, done, arg)
1643 void (*done) __P((void *));
1646 struct subprocess *chp;
1650 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1652 warn("losing track of %s process", prog);
1658 chp->next = children;
1665 * reap_kids - get status from any dead child processes,
1666 * and log a message for abnormal terminations.
1673 struct subprocess *chp, **prevp;
1676 if (n_children == 0)
1678 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1681 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1682 if (chp->pid == pid) {
1687 if (WIFSIGNALED(status)) {
1688 warn("Child process %s (pid %d) terminated with signal %d",
1689 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1691 dbglog("Script %s finished (pid %d), status = 0x%x",
1692 (chp? chp->prog: "??"), pid, status);
1693 if (chp && chp->done)
1694 (*chp->done)(chp->arg);
1698 if (pid == -1 && errno != ECHILD && errno != EINTR)
1699 error("Error waiting for child process: %m");
1704 * novm - log an error message saying we ran out of memory, and die.
1710 fatal("Virtual memory exhausted allocating %s\n", msg);
1714 * script_setenv - set an environment variable value to be used
1715 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1718 script_setenv(var, value)
1721 size_t vl = strlen(var) + strlen(value) + 2;
1723 char *p, *newstring;
1725 newstring = (char *) malloc(vl);
1728 slprintf(newstring, vl, "%s=%s", var, value);
1730 /* check if this variable is already set */
1731 if (script_env != 0) {
1732 for (i = 0; (p = script_env[i]) != 0; ++i) {
1733 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1735 script_env[i] = newstring;
1741 script_env = (char **) malloc(16 * sizeof(char *));
1742 if (script_env == 0)
1747 /* reallocate script_env with more space if needed */
1748 if (i + 1 >= s_env_nalloc) {
1750 char **newenv = (char **) realloc((void *)script_env,
1751 new_n * sizeof(char *));
1754 script_env = newenv;
1755 s_env_nalloc = new_n;
1758 script_env[i] = newstring;
1759 script_env[i+1] = 0;
1763 * script_unsetenv - remove a variable from the environment
1767 script_unsetenv(var)
1770 int vl = strlen(var);
1774 if (script_env == 0)
1776 for (i = 0; (p = script_env[i]) != 0; ++i) {
1777 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1779 while ((script_env[i] = script_env[i+1]) != 0)
1787 * start_charshunt - create a child process to run the character shunt.
1790 start_charshunt(ifd, ofd)
1797 error("Can't fork process for character shunt: %m");
1804 if (getuid() != uid)
1805 fatal("setuid failed");
1809 charshunt(ifd, ofd, record_file);
1812 charshunt_pid = cpid;
1816 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
1828 * charshunt - the character shunt, which passes characters between
1829 * the pty master side and the serial port (or stdin/stdout).
1830 * This runs as the user (not as root).
1831 * (We assume ofd >= ifd which is true the way this gets called. :-).
1834 charshunt(ifd, ofd, record_file)
1839 fd_set ready, writey;
1840 u_char *ibufp, *obufp;
1843 int pty_readable, stdin_readable;
1844 struct timeval lasttime;
1845 FILE *recordf = NULL;
1848 * Reset signal handlers.
1850 signal(SIGHUP, SIG_IGN); /* Hangup */
1851 signal(SIGINT, SIG_DFL); /* Interrupt */
1852 signal(SIGTERM, SIG_DFL); /* Terminate */
1853 signal(SIGCHLD, SIG_DFL);
1854 signal(SIGUSR1, SIG_DFL);
1855 signal(SIGUSR2, SIG_DFL);
1856 signal(SIGABRT, SIG_DFL);
1857 signal(SIGALRM, SIG_DFL);
1858 signal(SIGFPE, SIG_DFL);
1859 signal(SIGILL, SIG_DFL);
1860 signal(SIGPIPE, SIG_DFL);
1861 signal(SIGQUIT, SIG_DFL);
1862 signal(SIGSEGV, SIG_DFL);
1864 signal(SIGBUS, SIG_DFL);
1867 signal(SIGEMT, SIG_DFL);
1870 signal(SIGPOLL, SIG_DFL);
1873 signal(SIGPROF, SIG_DFL);
1876 signal(SIGSYS, SIG_DFL);
1879 signal(SIGTRAP, SIG_DFL);
1882 signal(SIGVTALRM, SIG_DFL);
1885 signal(SIGXCPU, SIG_DFL);
1888 signal(SIGXFSZ, SIG_DFL);
1892 * Open the record file if required.
1894 if (record_file != NULL) {
1895 recordf = fopen(record_file, "a");
1896 if (recordf == NULL)
1897 error("Couldn't create record file %s: %m", record_file);
1900 /* set all the fds to non-blocking mode */
1901 flags = fcntl(pty_master, F_GETFL);
1903 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1904 warn("couldn't set pty master to nonblock: %m");
1905 flags = fcntl(ifd, F_GETFL);
1907 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1908 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1910 flags = fcntl(ofd, F_GETFL);
1912 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1913 warn("couldn't set stdout to nonblock: %m");
1917 ibufp = obufp = NULL;
1918 pty_readable = stdin_readable = 1;
1919 nfds = (ofd > pty_master? ofd: pty_master) + 1;
1920 if (recordf != NULL) {
1921 gettimeofday(&lasttime, NULL);
1922 putc(7, recordf); /* put start marker */
1923 putc(lasttime.tv_sec >> 24, recordf);
1924 putc(lasttime.tv_sec >> 16, recordf);
1925 putc(lasttime.tv_sec >> 8, recordf);
1926 putc(lasttime.tv_sec, recordf);
1927 lasttime.tv_usec = 0;
1930 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1934 FD_SET(pty_master, &writey);
1935 else if (stdin_readable)
1936 FD_SET(ifd, &ready);
1938 FD_SET(ofd, &writey);
1939 else if (pty_readable)
1940 FD_SET(pty_master, &ready);
1941 if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
1946 if (FD_ISSET(ifd, &ready)) {
1947 ibufp = inpacket_buf;
1948 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
1949 if (nibuf < 0 && errno == EIO)
1952 if (!(errno == EINTR || errno == EAGAIN)) {
1953 error("Error reading standard input: %m");
1957 } else if (nibuf == 0) {
1958 /* end of file from stdin */
1960 /* do a 0-length write, hopefully this will generate
1961 an EOF (hangup) on the slave side. */
1962 write(pty_master, inpacket_buf, 0);
1964 if (!record_write(recordf, 4, NULL, 0, &lasttime))
1967 FD_SET(pty_master, &writey);
1969 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
1973 if (FD_ISSET(pty_master, &ready)) {
1974 obufp = outpacket_buf;
1975 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
1976 if (nobuf < 0 && errno == EIO)
1979 if (!(errno == EINTR || errno == EAGAIN)) {
1980 error("Error reading pseudo-tty master: %m");
1984 } else if (nobuf == 0) {
1985 /* end of file from the pty - slave side has closed */
1987 stdin_readable = 0; /* pty is not writable now */
1991 if (!record_write(recordf, 3, NULL, 0, &lasttime))
1994 FD_SET(ofd, &writey);
1996 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2000 if (FD_ISSET(ofd, &writey)) {
2001 n = write(ofd, obufp, nobuf);
2004 error("Error writing standard output: %m");
2014 if (FD_ISSET(pty_master, &writey)) {
2015 n = write(pty_master, ibufp, nibuf);
2018 error("Error writing pseudo-tty master: %m");
2033 record_write(f, code, buf, nb, tp)
2043 gettimeofday(&now, NULL);
2044 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2045 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2049 putc(diff >> 24, f);
2050 putc(diff >> 16, f);
2063 fwrite(buf, nb, 1, f);
2067 error("Error writing record file: %m");