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.86 1999/09/11 12:08:57 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;
256 privileged = uid == 0;
257 slprintf(numbuf, sizeof(numbuf), "%d", uid);
258 script_setenv("ORIG_UID", numbuf);
260 ngroups = getgroups(NGROUPS_MAX, groups);
263 * Initialize magic number generator now so that protocols may
264 * use magic numbers in initialization.
269 * Initialize to the standard option set, then parse, in order,
270 * the system options file, the user's options file,
271 * the tty's options file, and the command line arguments.
273 for (i = 0; (protp = protocols[i]) != NULL; ++i)
279 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
280 || !options_from_user())
281 exit(EXIT_OPTION_ERROR);
283 /* scan command line and options files to find device name */
285 parse_args(argc-1, argv+1);
289 * Work out the device name, if it hasn't already been specified.
291 using_pty = notty || ptycommand != NULL;
292 if (!using_pty && default_device) {
294 if (!isatty(0) || (p = ttyname(0)) == NULL) {
295 option_error("no device specified and stdin is not a tty");
296 exit(EXIT_OPTION_ERROR);
298 strlcpy(devnam, p, sizeof(devnam));
299 if (stat(devnam, &devstat) < 0)
300 fatal("Couldn't stat default device %s: %m", devnam);
304 * Parse the tty options file and the command line.
305 * The per-tty options file should not change
306 * ptycommand, notty or devnam.
310 if (!options_for_tty())
311 exit(EXIT_OPTION_ERROR);
315 if (!parse_args(argc-1, argv+1))
316 exit(EXIT_OPTION_ERROR);
319 * Check that we are running as root.
321 if (geteuid() != 0) {
322 option_error("must be root to run %s, since it is not setuid-root",
327 if (!ppp_available()) {
328 option_error(no_ppp_msg);
329 exit(EXIT_NO_KERNEL_SUPPORT);
333 * Check that the options given are valid and consistent.
335 if (!sys_check_options())
336 exit(EXIT_OPTION_ERROR);
337 auth_check_options();
338 for (i = 0; (protp = protocols[i]) != NULL; ++i)
339 if (protp->check_options != NULL)
340 (*protp->check_options)();
341 if (demand && connector == 0) {
342 option_error("connect script is required for demand-dialling\n");
343 exit(EXIT_OPTION_ERROR);
345 /* default holdoff to 0 if no connect script has been given */
346 if (connector == 0 && !holdoff_specified)
350 if (!default_device) {
351 option_error("%s option precludes specifying device name",
352 notty? "notty": "pty");
353 exit(EXIT_OPTION_ERROR);
355 if (ptycommand != NULL && notty) {
356 option_error("pty option is incompatible with notty option");
357 exit(EXIT_OPTION_ERROR);
359 default_device = notty;
362 if (notty && log_to_fd <= 1)
366 * If the user has specified a device which is the same as
367 * the one on stdin, pretend they didn't specify any.
368 * If the device is already open read/write on stdin,
369 * we assume we don't need to lock it, and we can open it as root.
371 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
372 && statbuf.st_rdev == devstat.st_rdev) {
374 fdflags = fcntl(0, F_GETFL);
375 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
383 * Don't send log messages to the serial port, it tends to
384 * confuse the peer. :-)
386 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
387 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
390 script_setenv("DEVICE", devnam);
393 * Initialize system-dependent stuff.
397 setlogmask(LOG_UPTO(LOG_DEBUG));
400 * Detach ourselves from the terminal, if required,
401 * and identify who is running us.
403 if (!nodetach && !updetach)
408 if (pw != NULL && pw->pw_name != NULL)
413 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
414 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
415 script_setenv("PPPLOGNAME", p);
418 * Compute mask of all interesting signals and install signal handlers
419 * for each. Only one signal handler may be active at a time. Therefore,
420 * all other signals should be masked when any handler is executing.
423 sigaddset(&mask, SIGHUP);
424 sigaddset(&mask, SIGINT);
425 sigaddset(&mask, SIGTERM);
426 sigaddset(&mask, SIGCHLD);
427 sigaddset(&mask, SIGUSR2);
429 #define SIGNAL(s, handler) do { \
430 sa.sa_handler = handler; \
431 if (sigaction(s, &sa, NULL) < 0) \
432 fatal("Couldn't establish signal handler (%d): %m", s); \
437 SIGNAL(SIGHUP, hup); /* Hangup */
438 SIGNAL(SIGINT, term); /* Interrupt */
439 SIGNAL(SIGTERM, term); /* Terminate */
440 SIGNAL(SIGCHLD, chld);
442 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
443 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
446 * Install a handler for other signals which would otherwise
447 * cause pppd to exit without cleaning up.
449 SIGNAL(SIGABRT, bad_signal);
450 SIGNAL(SIGALRM, bad_signal);
451 SIGNAL(SIGFPE, bad_signal);
452 SIGNAL(SIGILL, bad_signal);
453 SIGNAL(SIGPIPE, bad_signal);
454 SIGNAL(SIGQUIT, bad_signal);
455 SIGNAL(SIGSEGV, bad_signal);
457 SIGNAL(SIGBUS, bad_signal);
460 SIGNAL(SIGEMT, bad_signal);
463 SIGNAL(SIGPOLL, bad_signal);
466 SIGNAL(SIGPROF, bad_signal);
469 SIGNAL(SIGSYS, bad_signal);
472 SIGNAL(SIGTRAP, bad_signal);
475 SIGNAL(SIGVTALRM, bad_signal);
478 SIGNAL(SIGXCPU, bad_signal);
481 SIGNAL(SIGXFSZ, bad_signal);
485 * Apparently we can get a SIGPIPE when we call syslog, if
486 * syslogd has died and been restarted. Ignoring it seems
489 signal(SIGPIPE, SIG_IGN);
493 create_linkpidfile();
496 * If we're doing dial-on-demand, set up the interface now.
500 * Open the loopback channel and set it up to be the ppp interface.
502 fd_loop = open_ppp_loopback();
504 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
505 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
506 script_setenv("IFNAME", ifname);
508 create_pidfile(); /* write pid to file */
511 * Configure the interface and mark it up, etc.
526 * Don't do anything until we see some activity.
529 new_phase(PHASE_DORMANT);
533 if (sigsetjmp(sigjmp, 1) == 0) {
534 sigprocmask(SIG_BLOCK, &mask, NULL);
535 if (kill_link || got_sigchld) {
536 sigprocmask(SIG_UNBLOCK, &mask, NULL);
539 sigprocmask(SIG_UNBLOCK, &mask, NULL);
540 wait_input(timeleft(&timo));
550 if (get_loop_output())
556 if (kill_link && !persist)
560 * Now we want to bring up the link.
563 info("Starting link");
566 new_phase(PHASE_SERIALCONN);
569 * Get a pty master/slave pair if the pty, notty, or record
570 * options were specified.
572 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
575 if (ptycommand != NULL || notty || record_file != NULL) {
576 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
577 error("Couldn't allocate pseudo-tty");
578 status = EXIT_FATAL_ERROR;
581 set_up_tty(pty_slave, 1);
585 * Lock the device if we've been asked to.
587 status = EXIT_LOCK_FAILED;
588 if (lockflag && !privopen) {
589 if (lock(devnam) < 0)
595 * Open the serial device and set it up to be the ppp interface.
596 * First we open it in non-blocking mode so we can set the
597 * various termios flags appropriately. If we aren't dialling
598 * out and we want to use the modem lines, we reopen it later
599 * in order to wait for the carrier detect signal from the modem.
603 if (devnam[0] != 0) {
605 /* If the user specified the device name, become the
606 user before opening it. */
608 if (!devnam_info.priv && !privopen)
610 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
612 if (!devnam_info.priv && !privopen)
618 error("Failed to open %s: %m", devnam);
619 status = EXIT_OPEN_FAILED;
621 if (!persist || err != EINTR)
624 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
625 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
626 warn("Couldn't reset non-blocking mode on device: %m");
629 * Do the equivalent of `mesg n' to stop broadcast messages.
631 if (fstat(ttyfd, &statbuf) < 0
632 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
633 warn("Couldn't restrict write permissions to %s: %m", devnam);
635 tty_mode = statbuf.st_mode;
638 * Set line speed, flow control, etc.
639 * If we have a non-null connection or initializer script,
640 * on most systems we set CLOCAL for now so that we can talk
641 * to the modem before carrier comes up. But this has the
642 * side effect that we might miss it if CD drops before we
643 * get to clear CLOCAL below. On systems where we can talk
644 * successfully to the modem with CLOCAL clear and CD down,
645 * we could clear CLOCAL at this point.
647 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
648 || initializer != NULL));
653 * If the notty and/or record option was specified,
654 * start up the character shunt now.
656 status = EXIT_PTYCMD_FAILED;
657 if (ptycommand != NULL) {
658 if (record_file != NULL) {
659 int ipipe[2], opipe[2], ok;
661 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
662 fatal("Couldn't create pipes for record option: %m");
663 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
664 && start_charshunt(ipipe[0], opipe[1]);
672 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
679 if (!start_charshunt(0, 1))
681 } else if (record_file != NULL) {
682 if (!start_charshunt(ttyfd, ttyfd))
686 /* run connection script */
687 if ((connector && connector[0]) || initializer) {
688 if (real_ttyfd != -1) {
689 if (!default_device && modem) {
690 setdtr(real_ttyfd, 0); /* in case modem is off hook */
692 setdtr(real_ttyfd, 1);
696 if (initializer && initializer[0]) {
697 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
698 error("Initializer script failed");
699 status = EXIT_INIT_FAILED;
705 info("Serial port initialized.");
708 if (connector && connector[0]) {
709 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
710 error("Connect script failed");
711 status = EXIT_CONNECT_FAILED;
717 info("Serial connection established.");
720 /* set line speed, flow control, etc.;
721 clear CLOCAL if modem option */
722 if (real_ttyfd != -1)
723 set_up_tty(real_ttyfd, 0);
726 /* reopen tty if necessary to wait for carrier */
727 if (connector == NULL && modem && devnam[0] != 0) {
729 if ((i = open(devnam, O_RDWR)) >= 0)
731 if (errno != EINTR) {
732 error("Failed to reopen %s: %m", devnam);
733 status = EXIT_OPEN_FAILED;
735 if (!persist || errno != EINTR || hungup || kill_link)
741 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
742 script_setenv("SPEED", numbuf);
744 /* run welcome script, if any */
745 if (welcomer && welcomer[0]) {
746 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
747 warn("Welcome script failed");
750 /* set up the serial device as a ppp interface */
751 fd_ppp = establish_ppp(ttyfd);
753 status = EXIT_FATAL_ERROR;
759 info("Using interface ppp%d", ifunit);
760 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
761 script_setenv("IFNAME", ifname);
763 create_pidfile(); /* write pid to file */
767 * Start opening the connection and wait for
768 * incoming events (reply, timeout, etc.).
770 notice("Connect: %s <--> %s", ifname, ppp_devnam);
771 gettimeofday(&start_time, NULL);
772 link_stats_valid = 0;
773 script_unsetenv("CONNECT_TIME");
774 script_unsetenv("BYTES_SENT");
775 script_unsetenv("BYTES_RCVD");
779 * If we are initiating this connection, wait for a short
780 * time for something from the peer. This can avoid bouncing
781 * our packets off his tty before he has it set up.
783 if (connector != NULL || ptycommand != NULL) {
790 lcp_open(0); /* Start protocol */
793 status = EXIT_NEGOTIATION_FAILED;
794 new_phase(PHASE_ESTABLISH);
795 while (phase != PHASE_DEAD) {
796 if (sigsetjmp(sigjmp, 1) == 0) {
797 sigprocmask(SIG_BLOCK, &mask, NULL);
798 if (kill_link || open_ccp_flag || got_sigchld) {
799 sigprocmask(SIG_UNBLOCK, &mask, NULL);
802 sigprocmask(SIG_UNBLOCK, &mask, NULL);
803 wait_input(timeleft(&timo));
810 lcp_close(0, "User request");
814 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
815 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
816 (*ccp_protent.open)(0);
821 reap_kids(0); /* Don't leave dead kids lying around */
825 * Print connect time and statistics.
827 if (link_stats_valid) {
828 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
829 info("Connect time %d.%d minutes.", t/10, t%10);
830 info("Sent %d bytes, received %d bytes.",
831 link_stats.bytes_out, link_stats.bytes_in);
835 * Delete pid file before disestablishing ppp. Otherwise it
836 * can happen that another pppd gets the same unit and then
837 * we delete its pid file.
840 if (pidfilename[0] != 0
841 && unlink(pidfilename) < 0 && errno != ENOENT)
842 warn("unable to delete pid file %s: %m", pidfilename);
847 * If we may want to bring the link up again, transfer
848 * the ppp unit back to the loopback. Set the
849 * real serial device back to its normal mode of operation.
855 disestablish_ppp(ttyfd);
861 * Run disconnector script, if requested.
862 * XXX we may not be able to do this if the line has hung up!
865 if (disconnector && !hungup) {
866 new_phase(PHASE_DISCONNECT);
868 set_up_tty(real_ttyfd, 1);
869 if (device_script(disconnector, ttyfd, ttyfd, 0) < 0) {
870 warn("disconnect script failed");
872 info("Serial link disconnected.");
889 if (pidfilename[0] != 0
890 && unlink(pidfilename) < 0 && errno != ENOENT)
891 warn("unable to delete pid file %s: %m", pidfilename);
895 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
901 t = need_holdoff? holdoff: 0;
903 t = (*holdoff_hook)();
905 new_phase(PHASE_HOLDOFF);
906 TIMEOUT(holdoff_end, NULL, t);
908 if (sigsetjmp(sigjmp, 1) == 0) {
909 sigprocmask(SIG_BLOCK, &mask, NULL);
910 if (kill_link || got_sigchld) {
911 sigprocmask(SIG_UNBLOCK, &mask, NULL);
914 sigprocmask(SIG_UNBLOCK, &mask, NULL);
915 wait_input(timeleft(&timo));
922 new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
926 } while (phase == PHASE_HOLDOFF);
932 /* Wait for scripts to finish */
933 /* XXX should have a timeout here */
934 while (n_children > 0) {
936 struct subprocess *chp;
937 dbglog("Waiting for %d child processes...", n_children);
938 for (chp = children; chp != NULL; chp = chp->next)
939 dbglog(" script %s, pid %d", chp->prog, chp->pid);
941 if (reap_kids(1) < 0)
950 * detach - detach us from the controlling terminal.
959 if ((pid = fork()) < 0) {
960 error("Couldn't detach (fork failed: %m)");
961 die(1); /* or just return? */
967 exit(0); /* parent dies */
976 /* update pid files if they have been written already */
980 create_linkpidfile();
984 * reopen_log - (re)open our connection to syslog.
990 openlog("pppd", LOG_PID);
992 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
993 setlogmask(LOG_UPTO(LOG_INFO));
998 * Create a file containing our process ID.
1006 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1007 _PATH_VARRUN, ifname);
1008 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1009 fprintf(pidfile, "%d\n", getpid());
1010 (void) fclose(pidfile);
1012 error("Failed to create pid file %s: %m", pidfilename);
1015 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1016 script_setenv("PPPD_PID", numbuf);
1018 create_linkpidfile();
1022 create_linkpidfile()
1026 if (linkname[0] == 0)
1028 slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1029 _PATH_VARRUN, linkname);
1030 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1031 fprintf(pidfile, "%d\n", getpid());
1033 fprintf(pidfile, "%s\n", ifname);
1034 (void) fclose(pidfile);
1036 error("Failed to create pid file %s: %m", linkpidfile);
1039 script_setenv("LINKNAME", linkname);
1043 * holdoff_end - called via a timeout when the holdoff period ends.
1049 new_phase(PHASE_DORMANT);
1053 * get_input - called when incoming data is available.
1061 struct protent *protp;
1063 p = inpacket_buf; /* point to beginning of packet buffer */
1065 len = read_packet(inpacket_buf);
1070 notice("Modem hangup");
1072 status = EXIT_HANGUP;
1073 lcp_lowerdown(0); /* serial link is no longer available */
1078 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1079 dbglog("rcvd %P", p, len);
1081 if (len < PPP_HDRLEN) {
1082 MAINDEBUG(("io(): Received short packet."));
1086 p += 2; /* Skip address and control */
1087 GETSHORT(protocol, p);
1091 * Toss all non-LCP packets unless LCP is OPEN.
1093 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1094 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1099 * Until we get past the authentication phase, toss all packets
1100 * except LCP, LQR and authentication packets.
1102 if (phase <= PHASE_AUTHENTICATE
1103 && !(protocol == PPP_LCP || protocol == PPP_LQR
1104 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1105 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1111 * Upcall the proper protocol input routine.
1113 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1114 if (protp->protocol == protocol && protp->enabled_flag) {
1115 (*protp->input)(0, p, len);
1118 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1119 && protp->datainput != NULL) {
1120 (*protp->datainput)(0, p, len);
1126 warn("Unsupported protocol (0x%x) received", protocol);
1127 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1131 * new_phase - signal the start of a new phase of pppd's operation.
1139 (*new_phase_hook)(p);
1143 * die - clean up state and exit with the specified status.
1150 syslog(LOG_INFO, "Exit.");
1155 * cleanup - restore anything which needs to be restored before we exit
1164 disestablish_ppp(ttyfd);
1165 if (real_ttyfd >= 0)
1168 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1169 warn("unable to delete pid file %s: %m", pidfilename);
1171 if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
1172 warn("unable to delete pid file %s: %m", linkpidfile);
1180 * close_tty - restore the terminal device and close it.
1185 /* drop dtr to hang up */
1186 if (!default_device && modem) {
1187 setdtr(real_ttyfd, 0);
1189 * This sleep is in case the serial port has CLOCAL set by default,
1190 * and consequently will reassert DTR when we close the device.
1195 restore_tty(real_ttyfd);
1197 if (tty_mode != (mode_t) -1) {
1198 if (fchmod(real_ttyfd, tty_mode) != 0) {
1199 /* XXX if devnam is a symlink, this will change the link */
1200 chmod(devnam, tty_mode);
1209 * update_link_stats - get stats at link termination.
1212 update_link_stats(u)
1218 if (!get_ppp_stats(u, &link_stats)
1219 || gettimeofday(&now, NULL) < 0)
1221 link_connect_time = now.tv_sec - start_time.tv_sec;
1222 link_stats_valid = 1;
1224 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1225 script_setenv("CONNECT_TIME", numbuf);
1226 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1227 script_setenv("BYTES_SENT", numbuf);
1228 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1229 script_setenv("BYTES_RCVD", numbuf);
1234 struct timeval c_time; /* time at which to call routine */
1235 void *c_arg; /* argument to routine */
1236 void (*c_func) __P((void *)); /* routine */
1237 struct callout *c_next;
1240 static struct callout *callout = NULL; /* Callout list */
1241 static struct timeval timenow; /* Current time */
1244 * timeout - Schedule a timeout.
1246 * Note that this timeout takes the number of seconds, NOT hz (as in
1250 timeout(func, arg, time)
1251 void (*func) __P((void *));
1255 struct callout *newp, *p, **pp;
1257 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1262 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1263 fatal("Out of memory in timeout()!");
1265 newp->c_func = func;
1266 gettimeofday(&timenow, NULL);
1267 newp->c_time.tv_sec = timenow.tv_sec + time;
1268 newp->c_time.tv_usec = timenow.tv_usec;
1271 * Find correct place and link it in.
1273 for (pp = &callout; (p = *pp); pp = &p->c_next)
1274 if (newp->c_time.tv_sec < p->c_time.tv_sec
1275 || (newp->c_time.tv_sec == p->c_time.tv_sec
1276 && newp->c_time.tv_usec < p->c_time.tv_usec))
1284 * untimeout - Unschedule a timeout.
1287 untimeout(func, arg)
1288 void (*func) __P((void *));
1291 struct callout **copp, *freep;
1293 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1296 * Find first matching timeout and remove it from the list.
1298 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1299 if (freep->c_func == func && freep->c_arg == arg) {
1300 *copp = freep->c_next;
1301 free((char *) freep);
1308 * calltimeout - Call any timeout routines which are now due.
1315 while (callout != NULL) {
1318 if (gettimeofday(&timenow, NULL) < 0)
1319 fatal("Failed to get time of day: %m");
1320 if (!(p->c_time.tv_sec < timenow.tv_sec
1321 || (p->c_time.tv_sec == timenow.tv_sec
1322 && p->c_time.tv_usec <= timenow.tv_usec)))
1323 break; /* no, it's not time yet */
1325 callout = p->c_next;
1326 (*p->c_func)(p->c_arg);
1334 * timeleft - return the length of time until the next timeout is due.
1336 static struct timeval *
1338 struct timeval *tvp;
1340 if (callout == NULL)
1343 gettimeofday(&timenow, NULL);
1344 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1345 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1346 if (tvp->tv_usec < 0) {
1347 tvp->tv_usec += 1000000;
1350 if (tvp->tv_sec < 0)
1351 tvp->tv_sec = tvp->tv_usec = 0;
1358 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1364 struct sigaction act, oldact;
1366 act.sa_handler = SIG_IGN;
1369 sigaction(sig, &act, &oldact);
1370 sigaction(sig, &oldact, NULL);
1375 * hup - Catch SIGHUP signal.
1377 * Indicates that the physical layer has been disconnected.
1378 * We don't rely on this indication; if the user has sent this
1379 * signal, we just take the link down.
1385 info("Hangup (SIGHUP)");
1387 if (status != EXIT_HANGUP)
1388 status = EXIT_USER_REQUEST;
1390 /* Send the signal to the [dis]connector process(es) also */
1393 kill(charshunt_pid, sig);
1395 siglongjmp(sigjmp, 1);
1400 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1402 * Indicates that we should initiate a graceful disconnect and exit.
1409 info("Terminating on signal %d.", sig);
1410 persist = 0; /* don't try to restart */
1412 status = EXIT_USER_REQUEST;
1414 /* Send the signal to the [dis]connector process(es) also */
1417 kill(charshunt_pid, sig);
1419 siglongjmp(sigjmp, 1);
1424 * chld - Catch SIGCHLD signal.
1425 * Sets a flag so we will call reap_kids in the mainline.
1433 siglongjmp(sigjmp, 1);
1438 * toggle_debug - Catch SIGUSR1 signal.
1440 * Toggle debug flag.
1449 setlogmask(LOG_UPTO(LOG_DEBUG));
1451 setlogmask(LOG_UPTO(LOG_WARNING));
1457 * open_ccp - Catch SIGUSR2 signal.
1459 * Try to (re)negotiate compression.
1468 siglongjmp(sigjmp, 1);
1473 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1479 static int crashed = 0;
1484 error("Fatal signal %d", sig);
1486 kill_my_pg(SIGTERM);
1488 kill(charshunt_pid, SIGTERM);
1494 * device_script - run a program to talk to the serial device
1495 * (e.g. to run the connector or disconnector script).
1498 device_script(program, in, out, dont_wait)
1512 error("Failed to create child process: %m");
1521 int newin = dup(in);
1525 } else if (out == 2) {
1528 if (log_to_fd >= 0) {
1533 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1534 if (errfd >= 0 && errfd != 2) {
1554 if (getuid() != uid) {
1555 error("setuid failed");
1559 execl("/bin/sh", "sh", "-c", program, (char *)0);
1560 error("could not exec /bin/sh: %m");
1566 record_child(pid, program, NULL, NULL);
1569 while (waitpid(pid, &status, 0) < 0) {
1572 fatal("error waiting for (dis)connection process: %m");
1577 return (status == 0 ? 0 : -1);
1582 * run-program - execute a program with given arguments,
1583 * but don't wait for it.
1584 * If the program can't be executed, logs an error unless
1585 * must_exist is 0 and the program file doesn't exist.
1586 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1587 * or isn't an executable plain file, or the process ID of the child.
1588 * If done != NULL, (*done)(arg) will be called later (within
1589 * reap_kids) iff the return value is > 0.
1592 run_program(prog, args, must_exist, done, arg)
1596 void (*done) __P((void *));
1603 * First check if the file exists and is executable.
1604 * We don't use access() because that would use the
1605 * real user-id, which might not be root, and the script
1606 * might be accessible only to root.
1609 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1610 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1611 if (must_exist || errno != ENOENT)
1612 warn("Can't execute %s: %m", prog);
1618 error("Failed to create child process for %s: %m", prog);
1624 /* Leave the current location */
1625 (void) setsid(); /* No controlling tty. */
1626 (void) umask (S_IRWXG|S_IRWXO);
1627 (void) chdir ("/"); /* no current directory. */
1628 setuid(0); /* set real UID = root */
1631 /* Ensure that nothing of our device environment is inherited. */
1637 close (ttyfd); /* tty interface to the ppp device */
1638 if (real_ttyfd >= 0)
1641 /* Don't pass handles to the PPP device, even by accident. */
1642 new_fd = open (_PATH_DEVNULL, O_RDWR);
1645 dup2 (new_fd, 0); /* stdin <- /dev/null */
1648 dup2 (0, 1); /* stdout -> /dev/null */
1649 dup2 (0, 2); /* stderr -> /dev/null */
1653 /* Force the priority back to zero if pppd is running higher. */
1654 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1655 warn("can't reset priority to 0: %m");
1658 /* SysV recommends a second fork at this point. */
1660 /* run the program */
1661 execve(prog, args, script_env);
1662 if (must_exist || errno != ENOENT) {
1663 /* have to reopen the log, there's nowhere else
1664 for the message to go. */
1666 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1673 dbglog("Script %s started (pid %d)", prog, pid);
1674 record_child(pid, prog, done, arg);
1681 * record_child - add a child process to the list for reap_kids
1685 record_child(pid, prog, done, arg)
1688 void (*done) __P((void *));
1691 struct subprocess *chp;
1695 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1697 warn("losing track of %s process", prog);
1703 chp->next = children;
1710 * reap_kids - get status from any dead child processes,
1711 * and log a message for abnormal terminations.
1718 struct subprocess *chp, **prevp;
1721 if (n_children == 0)
1723 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1726 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1727 if (chp->pid == pid) {
1732 if (WIFSIGNALED(status)) {
1733 warn("Child process %s (pid %d) terminated with signal %d",
1734 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1736 dbglog("Script %s finished (pid %d), status = 0x%x",
1737 (chp? chp->prog: "??"), pid, status);
1738 if (chp && chp->done)
1739 (*chp->done)(chp->arg);
1744 if (errno == ECHILD)
1747 error("Error waiting for child process: %m");
1754 * novm - log an error message saying we ran out of memory, and die.
1760 fatal("Virtual memory exhausted allocating %s\n", msg);
1764 * script_setenv - set an environment variable value to be used
1765 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1768 script_setenv(var, value)
1771 size_t vl = strlen(var) + strlen(value) + 2;
1773 char *p, *newstring;
1775 newstring = (char *) malloc(vl);
1778 slprintf(newstring, vl, "%s=%s", var, value);
1780 /* check if this variable is already set */
1781 if (script_env != 0) {
1782 for (i = 0; (p = script_env[i]) != 0; ++i) {
1783 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1785 script_env[i] = newstring;
1790 /* no space allocated for script env. ptrs. yet */
1792 script_env = (char **) malloc(16 * sizeof(char *));
1793 if (script_env == 0)
1798 /* reallocate script_env with more space if needed */
1799 if (i + 1 >= s_env_nalloc) {
1801 char **newenv = (char **) realloc((void *)script_env,
1802 new_n * sizeof(char *));
1805 script_env = newenv;
1806 s_env_nalloc = new_n;
1809 script_env[i] = newstring;
1810 script_env[i+1] = 0;
1814 * script_unsetenv - remove a variable from the environment
1818 script_unsetenv(var)
1821 int vl = strlen(var);
1825 if (script_env == 0)
1827 for (i = 0; (p = script_env[i]) != 0; ++i) {
1828 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1830 while ((script_env[i] = script_env[i+1]) != 0)
1838 * start_charshunt - create a child process to run the character shunt.
1841 start_charshunt(ifd, ofd)
1848 error("Can't fork process for character shunt: %m");
1855 if (getuid() != uid)
1856 fatal("setuid failed");
1860 charshunt(ifd, ofd, record_file);
1863 charshunt_pid = cpid;
1867 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
1879 * charshunt - the character shunt, which passes characters between
1880 * the pty master side and the serial port (or stdin/stdout).
1881 * This runs as the user (not as root).
1882 * (We assume ofd >= ifd which is true the way this gets called. :-).
1885 charshunt(ifd, ofd, record_file)
1890 fd_set ready, writey;
1891 u_char *ibufp, *obufp;
1894 int pty_readable, stdin_readable;
1895 struct timeval lasttime;
1896 FILE *recordf = NULL;
1899 * Reset signal handlers.
1901 signal(SIGHUP, SIG_IGN); /* Hangup */
1902 signal(SIGINT, SIG_DFL); /* Interrupt */
1903 signal(SIGTERM, SIG_DFL); /* Terminate */
1904 signal(SIGCHLD, SIG_DFL);
1905 signal(SIGUSR1, SIG_DFL);
1906 signal(SIGUSR2, SIG_DFL);
1907 signal(SIGABRT, SIG_DFL);
1908 signal(SIGALRM, SIG_DFL);
1909 signal(SIGFPE, SIG_DFL);
1910 signal(SIGILL, SIG_DFL);
1911 signal(SIGPIPE, SIG_DFL);
1912 signal(SIGQUIT, SIG_DFL);
1913 signal(SIGSEGV, SIG_DFL);
1915 signal(SIGBUS, SIG_DFL);
1918 signal(SIGEMT, SIG_DFL);
1921 signal(SIGPOLL, SIG_DFL);
1924 signal(SIGPROF, SIG_DFL);
1927 signal(SIGSYS, SIG_DFL);
1930 signal(SIGTRAP, SIG_DFL);
1933 signal(SIGVTALRM, SIG_DFL);
1936 signal(SIGXCPU, SIG_DFL);
1939 signal(SIGXFSZ, SIG_DFL);
1943 * Open the record file if required.
1945 if (record_file != NULL) {
1946 recordf = fopen(record_file, "a");
1947 if (recordf == NULL)
1948 error("Couldn't create record file %s: %m", record_file);
1951 /* set all the fds to non-blocking mode */
1952 flags = fcntl(pty_master, F_GETFL);
1954 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1955 warn("couldn't set pty master to nonblock: %m");
1956 flags = fcntl(ifd, F_GETFL);
1958 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1959 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1961 flags = fcntl(ofd, F_GETFL);
1963 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1964 warn("couldn't set stdout to nonblock: %m");
1968 ibufp = obufp = NULL;
1969 pty_readable = stdin_readable = 1;
1970 nfds = (ofd > pty_master? ofd: pty_master) + 1;
1971 if (recordf != NULL) {
1972 gettimeofday(&lasttime, NULL);
1973 putc(7, recordf); /* put start marker */
1974 putc(lasttime.tv_sec >> 24, recordf);
1975 putc(lasttime.tv_sec >> 16, recordf);
1976 putc(lasttime.tv_sec >> 8, recordf);
1977 putc(lasttime.tv_sec, recordf);
1978 lasttime.tv_usec = 0;
1981 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1985 FD_SET(pty_master, &writey);
1986 else if (stdin_readable)
1987 FD_SET(ifd, &ready);
1989 FD_SET(ofd, &writey);
1990 else if (pty_readable)
1991 FD_SET(pty_master, &ready);
1992 if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
1997 if (FD_ISSET(ifd, &ready)) {
1998 ibufp = inpacket_buf;
1999 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2000 if (nibuf < 0 && errno == EIO)
2003 if (!(errno == EINTR || errno == EAGAIN)) {
2004 error("Error reading standard input: %m");
2008 } else if (nibuf == 0) {
2009 /* end of file from stdin */
2011 /* do a 0-length write, hopefully this will generate
2012 an EOF (hangup) on the slave side. */
2013 write(pty_master, inpacket_buf, 0);
2015 if (!record_write(recordf, 4, NULL, 0, &lasttime))
2018 FD_SET(pty_master, &writey);
2020 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2024 if (FD_ISSET(pty_master, &ready)) {
2025 obufp = outpacket_buf;
2026 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2027 if (nobuf < 0 && errno == EIO)
2030 if (!(errno == EINTR || errno == EAGAIN)) {
2031 error("Error reading pseudo-tty master: %m");
2035 } else if (nobuf == 0) {
2036 /* end of file from the pty - slave side has closed */
2038 stdin_readable = 0; /* pty is not writable now */
2042 if (!record_write(recordf, 3, NULL, 0, &lasttime))
2045 FD_SET(ofd, &writey);
2047 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2051 if (FD_ISSET(ofd, &writey)) {
2052 n = write(ofd, obufp, nobuf);
2055 error("Error writing standard output: %m");
2065 if (FD_ISSET(pty_master, &writey)) {
2066 n = write(pty_master, ibufp, nibuf);
2069 error("Error writing pseudo-tty master: %m");
2084 record_write(f, code, buf, nb, tp)
2094 gettimeofday(&now, NULL);
2095 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2096 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2100 putc(diff >> 24, f);
2101 putc(diff >> 16, f);
2114 fwrite(buf, nb, 1, f);
2118 error("Error writing record file: %m");