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.
20 #define RCSID "$Id: main.c,v 1.87 1999/11/15 03:55:37 paulus Exp $"
35 #include <sys/param.h>
36 #include <sys/types.h>
39 #include <sys/resource.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
55 #include "pathnames.h"
56 #include "patchlevel.h"
64 #endif /* IPX_CHANGE */
69 static const char rcsid[] = RCSID;
72 char ifname[32]; /* Interface name */
73 int ifunit; /* Interface unit number */
75 char *progname; /* Name of this program */
76 char hostname[MAXNAMELEN]; /* Our hostname */
77 static char pidfilename[MAXPATHLEN]; /* name of pid file */
78 static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
79 static char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
80 static uid_t uid; /* Our real user-id */
81 static int conn_running; /* we have a [dis]connector running */
83 int ttyfd; /* Serial port file descriptor */
84 mode_t tty_mode = -1; /* Original access permissions to tty */
85 int baud_rate; /* Actual bits/second for serial device */
86 int hungup; /* terminal has been hung up */
87 int privileged; /* we're running as real uid root */
88 int need_holdoff; /* need holdoff period before restarting */
89 int detached; /* have detached from terminal */
90 struct stat devstat; /* result of stat() on devnam */
91 int prepass = 0; /* doing prepass to find device name */
92 int devnam_fixed; /* set while in options.ttyxx file */
93 volatile int status; /* exit status for pppd */
94 int unsuccess; /* # unsuccessful connection attempts */
95 int (*holdoff_hook) __P((void)) = NULL;
96 int (*new_phase_hook) __P((int)) = NULL;
98 static int fd_ppp = -1; /* fd for talking PPP */
99 static int fd_loop; /* fd for getting demand-dial packets */
100 static int pty_master; /* fd for master side of pty */
101 static int pty_slave; /* fd for slave side of pty */
102 static int real_ttyfd; /* fd for actual serial port (not pty) */
104 int phase; /* where the link is at */
109 static sigjmp_buf sigjmp;
111 char **script_env; /* Env. variable values for scripts */
112 int s_env_nalloc; /* # words avail at script_env */
114 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
115 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
117 static int n_children; /* # child processes still running */
118 static int got_sigchld; /* set if we have received a SIGCHLD */
120 static int locked; /* lock() has succeeded */
121 static int privopen; /* don't lock, open device as root */
123 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
125 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
126 int ngroups; /* How many groups valid in groups */
128 static struct timeval start_time; /* Time when link was started. */
130 struct pppd_stats link_stats;
131 int link_connect_time;
132 int link_stats_valid;
134 static int charshunt_pid; /* Process ID for charshunt */
137 * We maintain a list of child process pids and
138 * functions to call when they exit.
143 void (*done) __P((void *));
145 struct subprocess *next;
148 static struct subprocess *children;
150 /* Prototypes for procedures local to this file. */
152 static void create_pidfile __P((void));
153 static void create_linkpidfile __P((void));
154 static void cleanup __P((void));
155 static void close_tty __P((void));
156 static void get_input __P((void));
157 static void calltimeout __P((void));
158 static struct timeval *timeleft __P((struct timeval *));
159 static void kill_my_pg __P((int));
160 static void hup __P((int));
161 static void term __P((int));
162 static void chld __P((int));
163 static void toggle_debug __P((int));
164 static void open_ccp __P((int));
165 static void bad_signal __P((int));
166 static void holdoff_end __P((void *));
167 static int device_script __P((char *, int, int, int));
168 static int reap_kids __P((int waitfor));
169 static void record_child __P((int, char *, void (*) (void *), void *));
170 static int start_charshunt __P((int, int));
171 static void charshunt_done __P((void *));
172 static void charshunt __P((int, int, char *));
173 static int record_write __P((FILE *, int code, u_char *buf, int nb,
176 extern char *ttyname __P((int));
177 extern char *getlogin __P((void));
178 int main __P((int, char *[]));
182 #define O_NONBLOCK O_NDELAY
186 #define setlogmask(x)
190 * PPP Data Link Layer "protocol" table.
191 * One entry per supported protocol.
192 * The last entry must be NULL.
194 struct protent *protocols[] = {
226 struct protent *protp;
230 new_phase(PHASE_INITIALIZE);
233 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
234 * This way we can close 0, 1, 2 in detach() without clobbering
235 * a fd that we are using.
237 if ((i = open("/dev/null", O_RDWR)) >= 0) {
238 while (0 <= i && i <= 2)
246 /* Initialize syslog facilities */
249 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
250 option_error("Couldn't get hostname: %m");
253 hostname[MAXNAMELEN-1] = 0;
255 /* make sure we don't create world or group writable files. */
256 umask(umask(0777) | 022);
259 privileged = uid == 0;
260 slprintf(numbuf, sizeof(numbuf), "%d", uid);
261 script_setenv("ORIG_UID", numbuf);
263 ngroups = getgroups(NGROUPS_MAX, groups);
266 * Initialize magic number generator now so that protocols may
267 * use magic numbers in initialization.
272 * Initialize to the standard option set, then parse, in order,
273 * the system options file, the user's options file,
274 * the tty's options file, and the command line arguments.
276 for (i = 0; (protp = protocols[i]) != NULL; ++i)
282 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
283 || !options_from_user())
284 exit(EXIT_OPTION_ERROR);
286 /* scan command line and options files to find device name */
288 parse_args(argc-1, argv+1);
292 * Work out the device name, if it hasn't already been specified.
294 using_pty = notty || ptycommand != NULL;
295 if (!using_pty && default_device) {
297 if (!isatty(0) || (p = ttyname(0)) == NULL) {
298 option_error("no device specified and stdin is not a tty");
299 exit(EXIT_OPTION_ERROR);
301 strlcpy(devnam, p, sizeof(devnam));
302 if (stat(devnam, &devstat) < 0)
303 fatal("Couldn't stat default device %s: %m", devnam);
307 * Parse the tty options file and the command line.
308 * The per-tty options file should not change
309 * ptycommand, notty or devnam.
313 if (!options_for_tty())
314 exit(EXIT_OPTION_ERROR);
318 if (!parse_args(argc-1, argv+1))
319 exit(EXIT_OPTION_ERROR);
322 * Check that we are running as root.
324 if (geteuid() != 0) {
325 option_error("must be root to run %s, since it is not setuid-root",
330 if (!ppp_available()) {
331 option_error(no_ppp_msg);
332 exit(EXIT_NO_KERNEL_SUPPORT);
336 * Check that the options given are valid and consistent.
338 if (!sys_check_options())
339 exit(EXIT_OPTION_ERROR);
340 auth_check_options();
341 for (i = 0; (protp = protocols[i]) != NULL; ++i)
342 if (protp->check_options != NULL)
343 (*protp->check_options)();
344 if (demand && connector == 0) {
345 option_error("connect script is required for demand-dialling\n");
346 exit(EXIT_OPTION_ERROR);
348 /* default holdoff to 0 if no connect script has been given */
349 if (connector == 0 && !holdoff_specified)
353 if (!default_device) {
354 option_error("%s option precludes specifying device name",
355 notty? "notty": "pty");
356 exit(EXIT_OPTION_ERROR);
358 if (ptycommand != NULL && notty) {
359 option_error("pty option is incompatible with notty option");
360 exit(EXIT_OPTION_ERROR);
362 default_device = notty;
365 if (notty && log_to_fd <= 1)
369 * If the user has specified a device which is the same as
370 * the one on stdin, pretend they didn't specify any.
371 * If the device is already open read/write on stdin,
372 * we assume we don't need to lock it, and we can open it as root.
374 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
375 && statbuf.st_rdev == devstat.st_rdev) {
377 fdflags = fcntl(0, F_GETFL);
378 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
386 * Don't send log messages to the serial port, it tends to
387 * confuse the peer. :-)
389 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
390 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
393 script_setenv("DEVICE", devnam);
396 * Initialize system-dependent stuff.
400 setlogmask(LOG_UPTO(LOG_DEBUG));
403 * Detach ourselves from the terminal, if required,
404 * and identify who is running us.
406 if (!nodetach && !updetach)
411 if (pw != NULL && pw->pw_name != NULL)
416 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
417 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
418 script_setenv("PPPLOGNAME", p);
421 * Compute mask of all interesting signals and install signal handlers
422 * for each. Only one signal handler may be active at a time. Therefore,
423 * all other signals should be masked when any handler is executing.
426 sigaddset(&mask, SIGHUP);
427 sigaddset(&mask, SIGINT);
428 sigaddset(&mask, SIGTERM);
429 sigaddset(&mask, SIGCHLD);
430 sigaddset(&mask, SIGUSR2);
432 #define SIGNAL(s, handler) do { \
433 sa.sa_handler = handler; \
434 if (sigaction(s, &sa, NULL) < 0) \
435 fatal("Couldn't establish signal handler (%d): %m", s); \
440 SIGNAL(SIGHUP, hup); /* Hangup */
441 SIGNAL(SIGINT, term); /* Interrupt */
442 SIGNAL(SIGTERM, term); /* Terminate */
443 SIGNAL(SIGCHLD, chld);
445 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
446 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
449 * Install a handler for other signals which would otherwise
450 * cause pppd to exit without cleaning up.
452 SIGNAL(SIGABRT, bad_signal);
453 SIGNAL(SIGALRM, bad_signal);
454 SIGNAL(SIGFPE, bad_signal);
455 SIGNAL(SIGILL, bad_signal);
456 SIGNAL(SIGPIPE, bad_signal);
457 SIGNAL(SIGQUIT, bad_signal);
458 SIGNAL(SIGSEGV, bad_signal);
460 SIGNAL(SIGBUS, bad_signal);
463 SIGNAL(SIGEMT, bad_signal);
466 SIGNAL(SIGPOLL, bad_signal);
469 SIGNAL(SIGPROF, bad_signal);
472 SIGNAL(SIGSYS, bad_signal);
475 SIGNAL(SIGTRAP, bad_signal);
478 SIGNAL(SIGVTALRM, bad_signal);
481 SIGNAL(SIGXCPU, bad_signal);
484 SIGNAL(SIGXFSZ, bad_signal);
488 * Apparently we can get a SIGPIPE when we call syslog, if
489 * syslogd has died and been restarted. Ignoring it seems
492 signal(SIGPIPE, SIG_IGN);
496 create_linkpidfile();
499 * If we're doing dial-on-demand, set up the interface now.
503 * Open the loopback channel and set it up to be the ppp interface.
505 fd_loop = open_ppp_loopback();
507 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
508 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
509 script_setenv("IFNAME", ifname);
511 create_pidfile(); /* write pid to file */
514 * Configure the interface and mark it up, etc.
529 * Don't do anything until we see some activity.
532 new_phase(PHASE_DORMANT);
536 if (sigsetjmp(sigjmp, 1) == 0) {
537 sigprocmask(SIG_BLOCK, &mask, NULL);
538 if (kill_link || got_sigchld) {
539 sigprocmask(SIG_UNBLOCK, &mask, NULL);
542 sigprocmask(SIG_UNBLOCK, &mask, NULL);
543 wait_input(timeleft(&timo));
553 if (get_loop_output())
559 if (kill_link && !persist)
563 * Now we want to bring up the link.
566 info("Starting link");
569 new_phase(PHASE_SERIALCONN);
572 * Get a pty master/slave pair if the pty, notty, or record
573 * options were specified.
575 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
578 if (ptycommand != NULL || notty || record_file != NULL) {
579 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
580 error("Couldn't allocate pseudo-tty");
581 status = EXIT_FATAL_ERROR;
584 set_up_tty(pty_slave, 1);
588 * Lock the device if we've been asked to.
590 status = EXIT_LOCK_FAILED;
591 if (lockflag && !privopen) {
592 if (lock(devnam) < 0)
598 * Open the serial device and set it up to be the ppp interface.
599 * First we open it in non-blocking mode so we can set the
600 * various termios flags appropriately. If we aren't dialling
601 * out and we want to use the modem lines, we reopen it later
602 * in order to wait for the carrier detect signal from the modem.
606 if (devnam[0] != 0) {
608 /* If the user specified the device name, become the
609 user before opening it. */
611 if (!devnam_info.priv && !privopen)
613 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
615 if (!devnam_info.priv && !privopen)
621 error("Failed to open %s: %m", devnam);
622 status = EXIT_OPEN_FAILED;
624 if (!persist || err != EINTR)
627 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
628 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
629 warn("Couldn't reset non-blocking mode on device: %m");
632 * Do the equivalent of `mesg n' to stop broadcast messages.
634 if (fstat(ttyfd, &statbuf) < 0
635 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
636 warn("Couldn't restrict write permissions to %s: %m", devnam);
638 tty_mode = statbuf.st_mode;
641 * Set line speed, flow control, etc.
642 * If we have a non-null connection or initializer script,
643 * on most systems we set CLOCAL for now so that we can talk
644 * to the modem before carrier comes up. But this has the
645 * side effect that we might miss it if CD drops before we
646 * get to clear CLOCAL below. On systems where we can talk
647 * successfully to the modem with CLOCAL clear and CD down,
648 * we could clear CLOCAL at this point.
650 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
651 || initializer != NULL));
656 * If the notty and/or record option was specified,
657 * start up the character shunt now.
659 status = EXIT_PTYCMD_FAILED;
660 if (ptycommand != NULL) {
661 if (record_file != NULL) {
662 int ipipe[2], opipe[2], ok;
664 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
665 fatal("Couldn't create pipes for record option: %m");
666 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
667 && start_charshunt(ipipe[0], opipe[1]);
675 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
682 if (!start_charshunt(0, 1))
684 } else if (record_file != NULL) {
685 if (!start_charshunt(ttyfd, ttyfd))
689 /* run connection script */
690 if ((connector && connector[0]) || initializer) {
691 if (real_ttyfd != -1) {
692 if (!default_device && modem) {
693 setdtr(real_ttyfd, 0); /* in case modem is off hook */
695 setdtr(real_ttyfd, 1);
699 if (initializer && initializer[0]) {
700 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
701 error("Initializer script failed");
702 status = EXIT_INIT_FAILED;
708 info("Serial port initialized.");
711 if (connector && connector[0]) {
712 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
713 error("Connect script failed");
714 status = EXIT_CONNECT_FAILED;
720 info("Serial connection established.");
723 /* set line speed, flow control, etc.;
724 clear CLOCAL if modem option */
725 if (real_ttyfd != -1)
726 set_up_tty(real_ttyfd, 0);
729 /* reopen tty if necessary to wait for carrier */
730 if (connector == NULL && modem && devnam[0] != 0) {
732 if ((i = open(devnam, O_RDWR)) >= 0)
734 if (errno != EINTR) {
735 error("Failed to reopen %s: %m", devnam);
736 status = EXIT_OPEN_FAILED;
738 if (!persist || errno != EINTR || hungup || kill_link)
744 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
745 script_setenv("SPEED", numbuf);
747 /* run welcome script, if any */
748 if (welcomer && welcomer[0]) {
749 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
750 warn("Welcome script failed");
753 /* set up the serial device as a ppp interface */
754 fd_ppp = establish_ppp(ttyfd);
756 status = EXIT_FATAL_ERROR;
762 info("Using interface ppp%d", ifunit);
763 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
764 script_setenv("IFNAME", ifname);
766 create_pidfile(); /* write pid to file */
770 * Start opening the connection and wait for
771 * incoming events (reply, timeout, etc.).
773 notice("Connect: %s <--> %s", ifname, ppp_devnam);
774 gettimeofday(&start_time, NULL);
775 link_stats_valid = 0;
776 script_unsetenv("CONNECT_TIME");
777 script_unsetenv("BYTES_SENT");
778 script_unsetenv("BYTES_RCVD");
782 * If we are initiating this connection, wait for a short
783 * time for something from the peer. This can avoid bouncing
784 * our packets off his tty before he has it set up.
786 if (connector != NULL || ptycommand != NULL) {
793 lcp_open(0); /* Start protocol */
796 status = EXIT_NEGOTIATION_FAILED;
797 new_phase(PHASE_ESTABLISH);
798 while (phase != PHASE_DEAD) {
799 if (sigsetjmp(sigjmp, 1) == 0) {
800 sigprocmask(SIG_BLOCK, &mask, NULL);
801 if (kill_link || open_ccp_flag || got_sigchld) {
802 sigprocmask(SIG_UNBLOCK, &mask, NULL);
805 sigprocmask(SIG_UNBLOCK, &mask, NULL);
806 wait_input(timeleft(&timo));
813 lcp_close(0, "User request");
817 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
818 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
819 (*ccp_protent.open)(0);
824 reap_kids(0); /* Don't leave dead kids lying around */
828 * Print connect time and statistics.
830 if (link_stats_valid) {
831 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
832 info("Connect time %d.%d minutes.", t/10, t%10);
833 info("Sent %d bytes, received %d bytes.",
834 link_stats.bytes_out, link_stats.bytes_in);
838 * Delete pid file before disestablishing ppp. Otherwise it
839 * can happen that another pppd gets the same unit and then
840 * we delete its pid file.
843 if (pidfilename[0] != 0
844 && unlink(pidfilename) < 0 && errno != ENOENT)
845 warn("unable to delete pid file %s: %m", pidfilename);
850 * If we may want to bring the link up again, transfer
851 * the ppp unit back to the loopback. Set the
852 * real serial device back to its normal mode of operation.
858 disestablish_ppp(ttyfd);
864 * Run disconnector script, if requested.
865 * XXX we may not be able to do this if the line has hung up!
868 if (disconnector && !hungup) {
869 new_phase(PHASE_DISCONNECT);
871 set_up_tty(real_ttyfd, 1);
872 if (device_script(disconnector, ttyfd, ttyfd, 0) < 0) {
873 warn("disconnect script failed");
875 info("Serial link disconnected.");
892 if (pidfilename[0] != 0
893 && unlink(pidfilename) < 0 && errno != ENOENT)
894 warn("unable to delete pid file %s: %m", pidfilename);
898 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
904 t = need_holdoff? holdoff: 0;
906 t = (*holdoff_hook)();
908 new_phase(PHASE_HOLDOFF);
909 TIMEOUT(holdoff_end, NULL, t);
911 if (sigsetjmp(sigjmp, 1) == 0) {
912 sigprocmask(SIG_BLOCK, &mask, NULL);
913 if (kill_link || got_sigchld) {
914 sigprocmask(SIG_UNBLOCK, &mask, NULL);
917 sigprocmask(SIG_UNBLOCK, &mask, NULL);
918 wait_input(timeleft(&timo));
925 new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
929 } while (phase == PHASE_HOLDOFF);
935 /* Wait for scripts to finish */
936 /* XXX should have a timeout here */
937 while (n_children > 0) {
939 struct subprocess *chp;
940 dbglog("Waiting for %d child processes...", n_children);
941 for (chp = children; chp != NULL; chp = chp->next)
942 dbglog(" script %s, pid %d", chp->prog, chp->pid);
944 if (reap_kids(1) < 0)
953 * detach - detach us from the controlling terminal.
962 if ((pid = fork()) < 0) {
963 error("Couldn't detach (fork failed: %m)");
964 die(1); /* or just return? */
970 exit(0); /* parent dies */
979 /* update pid files if they have been written already */
983 create_linkpidfile();
987 * reopen_log - (re)open our connection to syslog.
993 openlog("pppd", LOG_PID);
995 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
996 setlogmask(LOG_UPTO(LOG_INFO));
1001 * Create a file containing our process ID.
1009 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1010 _PATH_VARRUN, ifname);
1011 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1012 fprintf(pidfile, "%d\n", getpid());
1013 (void) fclose(pidfile);
1015 error("Failed to create pid file %s: %m", pidfilename);
1018 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1019 script_setenv("PPPD_PID", numbuf);
1021 create_linkpidfile();
1025 create_linkpidfile()
1029 if (linkname[0] == 0)
1031 slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1032 _PATH_VARRUN, linkname);
1033 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1034 fprintf(pidfile, "%d\n", getpid());
1036 fprintf(pidfile, "%s\n", ifname);
1037 (void) fclose(pidfile);
1039 error("Failed to create pid file %s: %m", linkpidfile);
1042 script_setenv("LINKNAME", linkname);
1046 * holdoff_end - called via a timeout when the holdoff period ends.
1052 new_phase(PHASE_DORMANT);
1056 * get_input - called when incoming data is available.
1064 struct protent *protp;
1066 p = inpacket_buf; /* point to beginning of packet buffer */
1068 len = read_packet(inpacket_buf);
1073 notice("Modem hangup");
1075 status = EXIT_HANGUP;
1076 lcp_lowerdown(0); /* serial link is no longer available */
1081 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1082 dbglog("rcvd %P", p, len);
1084 if (len < PPP_HDRLEN) {
1085 MAINDEBUG(("io(): Received short packet."));
1089 p += 2; /* Skip address and control */
1090 GETSHORT(protocol, p);
1094 * Toss all non-LCP packets unless LCP is OPEN.
1096 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1097 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1102 * Until we get past the authentication phase, toss all packets
1103 * except LCP, LQR and authentication packets.
1105 if (phase <= PHASE_AUTHENTICATE
1106 && !(protocol == PPP_LCP || protocol == PPP_LQR
1107 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1108 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1114 * Upcall the proper protocol input routine.
1116 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1117 if (protp->protocol == protocol && protp->enabled_flag) {
1118 (*protp->input)(0, p, len);
1121 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1122 && protp->datainput != NULL) {
1123 (*protp->datainput)(0, p, len);
1129 warn("Unsupported protocol (0x%x) received", protocol);
1130 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1134 * new_phase - signal the start of a new phase of pppd's operation.
1142 (*new_phase_hook)(p);
1146 * die - clean up state and exit with the specified status.
1153 syslog(LOG_INFO, "Exit.");
1158 * cleanup - restore anything which needs to be restored before we exit
1167 disestablish_ppp(ttyfd);
1168 if (real_ttyfd >= 0)
1171 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1172 warn("unable to delete pid file %s: %m", pidfilename);
1174 if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
1175 warn("unable to delete pid file %s: %m", linkpidfile);
1183 * close_tty - restore the terminal device and close it.
1188 /* drop dtr to hang up */
1189 if (!default_device && modem) {
1190 setdtr(real_ttyfd, 0);
1192 * This sleep is in case the serial port has CLOCAL set by default,
1193 * and consequently will reassert DTR when we close the device.
1198 restore_tty(real_ttyfd);
1200 if (tty_mode != (mode_t) -1) {
1201 if (fchmod(real_ttyfd, tty_mode) != 0) {
1202 /* XXX if devnam is a symlink, this will change the link */
1203 chmod(devnam, tty_mode);
1212 * update_link_stats - get stats at link termination.
1215 update_link_stats(u)
1221 if (!get_ppp_stats(u, &link_stats)
1222 || gettimeofday(&now, NULL) < 0)
1224 link_connect_time = now.tv_sec - start_time.tv_sec;
1225 link_stats_valid = 1;
1227 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1228 script_setenv("CONNECT_TIME", numbuf);
1229 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1230 script_setenv("BYTES_SENT", numbuf);
1231 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1232 script_setenv("BYTES_RCVD", numbuf);
1237 struct timeval c_time; /* time at which to call routine */
1238 void *c_arg; /* argument to routine */
1239 void (*c_func) __P((void *)); /* routine */
1240 struct callout *c_next;
1243 static struct callout *callout = NULL; /* Callout list */
1244 static struct timeval timenow; /* Current time */
1247 * timeout - Schedule a timeout.
1249 * Note that this timeout takes the number of seconds, NOT hz (as in
1253 timeout(func, arg, time)
1254 void (*func) __P((void *));
1258 struct callout *newp, *p, **pp;
1260 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1265 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1266 fatal("Out of memory in timeout()!");
1268 newp->c_func = func;
1269 gettimeofday(&timenow, NULL);
1270 newp->c_time.tv_sec = timenow.tv_sec + time;
1271 newp->c_time.tv_usec = timenow.tv_usec;
1274 * Find correct place and link it in.
1276 for (pp = &callout; (p = *pp); pp = &p->c_next)
1277 if (newp->c_time.tv_sec < p->c_time.tv_sec
1278 || (newp->c_time.tv_sec == p->c_time.tv_sec
1279 && newp->c_time.tv_usec < p->c_time.tv_usec))
1287 * untimeout - Unschedule a timeout.
1290 untimeout(func, arg)
1291 void (*func) __P((void *));
1294 struct callout **copp, *freep;
1296 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1299 * Find first matching timeout and remove it from the list.
1301 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1302 if (freep->c_func == func && freep->c_arg == arg) {
1303 *copp = freep->c_next;
1304 free((char *) freep);
1311 * calltimeout - Call any timeout routines which are now due.
1318 while (callout != NULL) {
1321 if (gettimeofday(&timenow, NULL) < 0)
1322 fatal("Failed to get time of day: %m");
1323 if (!(p->c_time.tv_sec < timenow.tv_sec
1324 || (p->c_time.tv_sec == timenow.tv_sec
1325 && p->c_time.tv_usec <= timenow.tv_usec)))
1326 break; /* no, it's not time yet */
1328 callout = p->c_next;
1329 (*p->c_func)(p->c_arg);
1337 * timeleft - return the length of time until the next timeout is due.
1339 static struct timeval *
1341 struct timeval *tvp;
1343 if (callout == NULL)
1346 gettimeofday(&timenow, NULL);
1347 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1348 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1349 if (tvp->tv_usec < 0) {
1350 tvp->tv_usec += 1000000;
1353 if (tvp->tv_sec < 0)
1354 tvp->tv_sec = tvp->tv_usec = 0;
1361 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1367 struct sigaction act, oldact;
1369 act.sa_handler = SIG_IGN;
1372 sigaction(sig, &act, &oldact);
1373 sigaction(sig, &oldact, NULL);
1378 * hup - Catch SIGHUP signal.
1380 * Indicates that the physical layer has been disconnected.
1381 * We don't rely on this indication; if the user has sent this
1382 * signal, we just take the link down.
1388 info("Hangup (SIGHUP)");
1390 if (status != EXIT_HANGUP)
1391 status = EXIT_USER_REQUEST;
1393 /* Send the signal to the [dis]connector process(es) also */
1396 kill(charshunt_pid, sig);
1398 siglongjmp(sigjmp, 1);
1403 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1405 * Indicates that we should initiate a graceful disconnect and exit.
1412 info("Terminating on signal %d.", sig);
1413 persist = 0; /* don't try to restart */
1415 status = EXIT_USER_REQUEST;
1417 /* Send the signal to the [dis]connector process(es) also */
1420 kill(charshunt_pid, sig);
1422 siglongjmp(sigjmp, 1);
1427 * chld - Catch SIGCHLD signal.
1428 * Sets a flag so we will call reap_kids in the mainline.
1436 siglongjmp(sigjmp, 1);
1441 * toggle_debug - Catch SIGUSR1 signal.
1443 * Toggle debug flag.
1452 setlogmask(LOG_UPTO(LOG_DEBUG));
1454 setlogmask(LOG_UPTO(LOG_WARNING));
1460 * open_ccp - Catch SIGUSR2 signal.
1462 * Try to (re)negotiate compression.
1471 siglongjmp(sigjmp, 1);
1476 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1482 static int crashed = 0;
1487 error("Fatal signal %d", sig);
1489 kill_my_pg(SIGTERM);
1491 kill(charshunt_pid, SIGTERM);
1497 * device_script - run a program to talk to the serial device
1498 * (e.g. to run the connector or disconnector script).
1501 device_script(program, in, out, dont_wait)
1515 error("Failed to create child process: %m");
1524 int newin = dup(in);
1528 } else if (out == 2) {
1531 if (log_to_fd >= 0) {
1536 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1537 if (errfd >= 0 && errfd != 2) {
1557 if (getuid() != uid) {
1558 error("setuid failed");
1562 execl("/bin/sh", "sh", "-c", program, (char *)0);
1563 error("could not exec /bin/sh: %m");
1569 record_child(pid, program, NULL, NULL);
1572 while (waitpid(pid, &status, 0) < 0) {
1575 fatal("error waiting for (dis)connection process: %m");
1580 return (status == 0 ? 0 : -1);
1585 * run-program - execute a program with given arguments,
1586 * but don't wait for it.
1587 * If the program can't be executed, logs an error unless
1588 * must_exist is 0 and the program file doesn't exist.
1589 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1590 * or isn't an executable plain file, or the process ID of the child.
1591 * If done != NULL, (*done)(arg) will be called later (within
1592 * reap_kids) iff the return value is > 0.
1595 run_program(prog, args, must_exist, done, arg)
1599 void (*done) __P((void *));
1606 * First check if the file exists and is executable.
1607 * We don't use access() because that would use the
1608 * real user-id, which might not be root, and the script
1609 * might be accessible only to root.
1612 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1613 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1614 if (must_exist || errno != ENOENT)
1615 warn("Can't execute %s: %m", prog);
1621 error("Failed to create child process for %s: %m", prog);
1627 /* Leave the current location */
1628 (void) setsid(); /* No controlling tty. */
1629 (void) umask (S_IRWXG|S_IRWXO);
1630 (void) chdir ("/"); /* no current directory. */
1631 setuid(0); /* set real UID = root */
1634 /* Ensure that nothing of our device environment is inherited. */
1640 close (ttyfd); /* tty interface to the ppp device */
1641 if (real_ttyfd >= 0)
1644 /* Don't pass handles to the PPP device, even by accident. */
1645 new_fd = open (_PATH_DEVNULL, O_RDWR);
1648 dup2 (new_fd, 0); /* stdin <- /dev/null */
1651 dup2 (0, 1); /* stdout -> /dev/null */
1652 dup2 (0, 2); /* stderr -> /dev/null */
1656 /* Force the priority back to zero if pppd is running higher. */
1657 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1658 warn("can't reset priority to 0: %m");
1661 /* SysV recommends a second fork at this point. */
1663 /* run the program */
1664 execve(prog, args, script_env);
1665 if (must_exist || errno != ENOENT) {
1666 /* have to reopen the log, there's nowhere else
1667 for the message to go. */
1669 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1676 dbglog("Script %s started (pid %d)", prog, pid);
1677 record_child(pid, prog, done, arg);
1684 * record_child - add a child process to the list for reap_kids
1688 record_child(pid, prog, done, arg)
1691 void (*done) __P((void *));
1694 struct subprocess *chp;
1698 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1700 warn("losing track of %s process", prog);
1706 chp->next = children;
1713 * reap_kids - get status from any dead child processes,
1714 * and log a message for abnormal terminations.
1721 struct subprocess *chp, **prevp;
1724 if (n_children == 0)
1726 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1729 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1730 if (chp->pid == pid) {
1735 if (WIFSIGNALED(status)) {
1736 warn("Child process %s (pid %d) terminated with signal %d",
1737 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1739 dbglog("Script %s finished (pid %d), status = 0x%x",
1740 (chp? chp->prog: "??"), pid, status);
1741 if (chp && chp->done)
1742 (*chp->done)(chp->arg);
1747 if (errno == ECHILD)
1750 error("Error waiting for child process: %m");
1757 * novm - log an error message saying we ran out of memory, and die.
1763 fatal("Virtual memory exhausted allocating %s\n", msg);
1767 * script_setenv - set an environment variable value to be used
1768 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1771 script_setenv(var, value)
1774 size_t vl = strlen(var) + strlen(value) + 2;
1776 char *p, *newstring;
1778 newstring = (char *) malloc(vl);
1781 slprintf(newstring, vl, "%s=%s", var, value);
1783 /* check if this variable is already set */
1784 if (script_env != 0) {
1785 for (i = 0; (p = script_env[i]) != 0; ++i) {
1786 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1788 script_env[i] = newstring;
1793 /* no space allocated for script env. ptrs. yet */
1795 script_env = (char **) malloc(16 * sizeof(char *));
1796 if (script_env == 0)
1801 /* reallocate script_env with more space if needed */
1802 if (i + 1 >= s_env_nalloc) {
1804 char **newenv = (char **) realloc((void *)script_env,
1805 new_n * sizeof(char *));
1808 script_env = newenv;
1809 s_env_nalloc = new_n;
1812 script_env[i] = newstring;
1813 script_env[i+1] = 0;
1817 * script_unsetenv - remove a variable from the environment
1821 script_unsetenv(var)
1824 int vl = strlen(var);
1828 if (script_env == 0)
1830 for (i = 0; (p = script_env[i]) != 0; ++i) {
1831 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1833 while ((script_env[i] = script_env[i+1]) != 0)
1841 * start_charshunt - create a child process to run the character shunt.
1844 start_charshunt(ifd, ofd)
1851 error("Can't fork process for character shunt: %m");
1858 if (getuid() != uid)
1859 fatal("setuid failed");
1863 charshunt(ifd, ofd, record_file);
1866 charshunt_pid = cpid;
1870 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
1882 * charshunt - the character shunt, which passes characters between
1883 * the pty master side and the serial port (or stdin/stdout).
1884 * This runs as the user (not as root).
1885 * (We assume ofd >= ifd which is true the way this gets called. :-).
1888 charshunt(ifd, ofd, record_file)
1893 fd_set ready, writey;
1894 u_char *ibufp, *obufp;
1897 int pty_readable, stdin_readable;
1898 struct timeval lasttime;
1899 FILE *recordf = NULL;
1902 * Reset signal handlers.
1904 signal(SIGHUP, SIG_IGN); /* Hangup */
1905 signal(SIGINT, SIG_DFL); /* Interrupt */
1906 signal(SIGTERM, SIG_DFL); /* Terminate */
1907 signal(SIGCHLD, SIG_DFL);
1908 signal(SIGUSR1, SIG_DFL);
1909 signal(SIGUSR2, SIG_DFL);
1910 signal(SIGABRT, SIG_DFL);
1911 signal(SIGALRM, SIG_DFL);
1912 signal(SIGFPE, SIG_DFL);
1913 signal(SIGILL, SIG_DFL);
1914 signal(SIGPIPE, SIG_DFL);
1915 signal(SIGQUIT, SIG_DFL);
1916 signal(SIGSEGV, SIG_DFL);
1918 signal(SIGBUS, SIG_DFL);
1921 signal(SIGEMT, SIG_DFL);
1924 signal(SIGPOLL, SIG_DFL);
1927 signal(SIGPROF, SIG_DFL);
1930 signal(SIGSYS, SIG_DFL);
1933 signal(SIGTRAP, SIG_DFL);
1936 signal(SIGVTALRM, SIG_DFL);
1939 signal(SIGXCPU, SIG_DFL);
1942 signal(SIGXFSZ, SIG_DFL);
1946 * Open the record file if required.
1948 if (record_file != NULL) {
1949 recordf = fopen(record_file, "a");
1950 if (recordf == NULL)
1951 error("Couldn't create record file %s: %m", record_file);
1954 /* set all the fds to non-blocking mode */
1955 flags = fcntl(pty_master, F_GETFL);
1957 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1958 warn("couldn't set pty master to nonblock: %m");
1959 flags = fcntl(ifd, F_GETFL);
1961 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1962 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1964 flags = fcntl(ofd, F_GETFL);
1966 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1967 warn("couldn't set stdout to nonblock: %m");
1971 ibufp = obufp = NULL;
1972 pty_readable = stdin_readable = 1;
1973 nfds = (ofd > pty_master? ofd: pty_master) + 1;
1974 if (recordf != NULL) {
1975 gettimeofday(&lasttime, NULL);
1976 putc(7, recordf); /* put start marker */
1977 putc(lasttime.tv_sec >> 24, recordf);
1978 putc(lasttime.tv_sec >> 16, recordf);
1979 putc(lasttime.tv_sec >> 8, recordf);
1980 putc(lasttime.tv_sec, recordf);
1981 lasttime.tv_usec = 0;
1984 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1988 FD_SET(pty_master, &writey);
1989 else if (stdin_readable)
1990 FD_SET(ifd, &ready);
1992 FD_SET(ofd, &writey);
1993 else if (pty_readable)
1994 FD_SET(pty_master, &ready);
1995 if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
2000 if (FD_ISSET(ifd, &ready)) {
2001 ibufp = inpacket_buf;
2002 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2003 if (nibuf < 0 && errno == EIO)
2006 if (!(errno == EINTR || errno == EAGAIN)) {
2007 error("Error reading standard input: %m");
2011 } else if (nibuf == 0) {
2012 /* end of file from stdin */
2014 /* do a 0-length write, hopefully this will generate
2015 an EOF (hangup) on the slave side. */
2016 write(pty_master, inpacket_buf, 0);
2018 if (!record_write(recordf, 4, NULL, 0, &lasttime))
2021 FD_SET(pty_master, &writey);
2023 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2027 if (FD_ISSET(pty_master, &ready)) {
2028 obufp = outpacket_buf;
2029 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2030 if (nobuf < 0 && errno == EIO)
2033 if (!(errno == EINTR || errno == EAGAIN)) {
2034 error("Error reading pseudo-tty master: %m");
2038 } else if (nobuf == 0) {
2039 /* end of file from the pty - slave side has closed */
2041 stdin_readable = 0; /* pty is not writable now */
2045 if (!record_write(recordf, 3, NULL, 0, &lasttime))
2048 FD_SET(ofd, &writey);
2050 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2054 if (FD_ISSET(ofd, &writey)) {
2055 n = write(ofd, obufp, nobuf);
2058 error("Error writing standard output: %m");
2068 if (FD_ISSET(pty_master, &writey)) {
2069 n = write(pty_master, ibufp, nibuf);
2072 error("Error writing pseudo-tty master: %m");
2087 record_write(f, code, buf, nb, tp)
2097 gettimeofday(&now, NULL);
2098 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2099 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2103 putc(diff >> 24, f);
2104 putc(diff >> 16, f);
2117 fwrite(buf, nb, 1, f);
2121 error("Error writing record file: %m");