2 * main.c - Point-to-Point Protocol main module
4 * Copyright (c) 1989 Carnegie Mellon University.
7 * Redistribution and use in source and binary forms are permitted
8 * provided that the above copyright notice and this paragraph are
9 * duplicated in all such forms and that any documentation,
10 * advertising materials, and other materials related to such
11 * distribution and use acknowledge that the software was developed
12 * by Carnegie Mellon University. The name of the
13 * University may not be used to endorse or promote products derived
14 * from this software without specific prior written permission.
15 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
21 static char rcsid[] = "$Id: main.c,v 1.78 1999/05/12 06:19:47 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 ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
76 static uid_t uid; /* Our real user-id */
77 static int conn_running; /* we have a [dis]connector running */
79 int ttyfd; /* Serial port file descriptor */
80 mode_t tty_mode = -1; /* Original access permissions to tty */
81 int baud_rate; /* Actual bits/second for serial device */
82 int hungup; /* terminal has been hung up */
83 int privileged; /* we're running as real uid root */
84 int need_holdoff; /* need holdoff period before restarting */
85 int detached; /* have detached from terminal */
86 struct stat devstat; /* result of stat() on devnam */
87 int prepass = 0; /* doing prepass to find device name */
88 volatile int status; /* exit status for pppd */
90 static int fd_ppp = -1; /* fd for talking PPP */
91 static int fd_loop; /* fd for getting demand-dial packets */
92 static int pty_master; /* fd for master side of pty */
93 static int pty_slave; /* fd for slave side of pty */
94 static int real_ttyfd; /* fd for actual serial port (not pty) */
96 int phase; /* where the link is at */
101 static sigjmp_buf sigjmp;
103 char **script_env; /* Env. variable values for scripts */
104 int s_env_nalloc; /* # words avail at script_env */
106 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
107 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
109 static int n_children; /* # child processes still running */
110 static int got_sigchld; /* set if we have received a SIGCHLD */
112 static int locked; /* lock() has succeeded */
113 static int privopen; /* don't lock, open device as root */
115 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
117 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
118 int ngroups; /* How many groups valid in groups */
120 static struct timeval start_time; /* Time when link was started. */
122 struct pppd_stats link_stats;
123 int link_stats_valid;
125 static int charshunt_pid; /* Process ID for charshunt */
128 * We maintain a list of child process pids and
129 * functions to call when they exit.
134 void (*done) __P((void *));
136 struct subprocess *next;
139 static struct subprocess *children;
141 /* Prototypes for procedures local to this file. */
143 static void create_pidfile __P((void));
144 static void cleanup __P((void));
145 static void close_tty __P((void));
146 static void get_input __P((void));
147 static void calltimeout __P((void));
148 static struct timeval *timeleft __P((struct timeval *));
149 static void kill_my_pg __P((int));
150 static void hup __P((int));
151 static void term __P((int));
152 static void chld __P((int));
153 static void toggle_debug __P((int));
154 static void open_ccp __P((int));
155 static void bad_signal __P((int));
156 static void holdoff_end __P((void *));
157 static int device_script __P((char *, int, int, int));
158 static void reap_kids __P((int waitfor));
159 static void record_child __P((int, char *, void (*) (void *), void *));
160 static int start_charshunt __P((int, int));
161 static void charshunt_done __P((void *));
162 static void charshunt __P((int, int, char *));
163 static int record_write __P((FILE *, int code, u_char *buf, int nb,
166 extern char *ttyname __P((int));
167 extern char *getlogin __P((void));
168 int main __P((int, char *[]));
172 #define O_NONBLOCK O_NDELAY
176 #define setlogmask(x)
180 * PPP Data Link Layer "protocol" table.
181 * One entry per supported protocol.
182 * The last entry must be NULL.
184 struct protent *protocols[] = {
213 struct protent *protp;
218 phase = PHASE_INITIALIZE;
221 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
222 * This way we can close 0, 1, 2 in detach() without clobbering
223 * a fd that we are using.
225 if ((i = open("/dev/null", O_RDWR)) >= 0) {
226 while (0 <= i && i <= 2)
234 /* Initialize syslog facilities */
237 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
238 option_error("Couldn't get hostname: %m");
241 hostname[MAXNAMELEN-1] = 0;
244 privileged = uid == 0;
245 slprintf(numbuf, sizeof(numbuf), "%d", uid);
246 script_setenv("ORIG_UID", numbuf);
248 ngroups = getgroups(NGROUPS_MAX, groups);
251 * Initialize to the standard option set, then parse, in order,
252 * the system options file, the user's options file,
253 * the tty's options file, and the command line arguments.
255 for (i = 0; (protp = protocols[i]) != NULL; ++i)
261 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
262 || !options_from_user())
263 exit(EXIT_OPTION_ERROR);
265 /* scan command line and options files to find device name */
267 parse_args(argc-1, argv+1);
271 * Work out the device name, if it hasn't already been specified.
273 using_pty = notty || ptycommand != NULL;
274 if (!using_pty && default_device) {
276 if (!isatty(0) || (p = ttyname(0)) == NULL) {
277 option_error("no device specified and stdin is not a tty");
278 exit(EXIT_OPTION_ERROR);
280 strlcpy(devnam, p, sizeof(devnam));
281 if (stat(devnam, &devstat) < 0)
282 fatal("Couldn't stat default device %s: %m", devnam);
286 * Parse the tty options file and the command line.
287 * The per-tty options file should not change
288 * ptycommand, notty or devnam.
291 int save_defdev = default_device;
294 if (!options_for_tty())
295 exit(EXIT_OPTION_ERROR);
296 if (notty || ptycommand != NULL) {
297 option_error("%s option may not be used in per-tty options file",
298 notty? "notty": "pty");
299 exit(EXIT_OPTION_ERROR);
301 if (!default_device) {
302 option_error("per-tty options file may not specify device name");
303 exit(EXIT_OPTION_ERROR);
305 default_device = save_defdev;
308 if (!parse_args(argc-1, argv+1))
309 exit(EXIT_OPTION_ERROR);
312 * Check that we are running as root.
314 if (geteuid() != 0) {
315 option_error("must be root to run %s, since it is not setuid-root",
320 if (!ppp_available()) {
321 option_error(no_ppp_msg);
322 exit(EXIT_NO_KERNEL_SUPPORT);
326 * Check that the options given are valid and consistent.
328 if (!sys_check_options())
329 exit(EXIT_OPTION_ERROR);
330 auth_check_options();
331 for (i = 0; (protp = protocols[i]) != NULL; ++i)
332 if (protp->check_options != NULL)
333 (*protp->check_options)();
334 if (demand && connector == 0) {
335 option_error("connect script is required for demand-dialling\n");
336 exit(EXIT_OPTION_ERROR);
340 if (!default_device) {
341 option_error("%s option precludes specifying device name",
342 notty? "notty": "pty");
343 exit(EXIT_OPTION_ERROR);
345 if (ptycommand != NULL && notty) {
346 option_error("pty option is incompatible with notty option");
347 exit(EXIT_OPTION_ERROR);
349 default_device = notty;
352 if (notty && log_to_fd <= 1)
356 * If the user has specified a device which is the same as
357 * the one on stdin, pretend they didn't specify any.
358 * If the device is already open read/write on stdin,
359 * we assume we don't need to lock it, and we can open it as root.
361 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
362 && statbuf.st_rdev == devstat.st_rdev) {
364 fdflags = fcntl(0, F_GETFL);
365 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
373 * Don't send log messages to the serial port, it tends to
374 * confuse the peer. :-)
376 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
377 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
380 script_setenv("DEVICE", devnam);
383 * Initialize system-dependent stuff and magic number package.
388 setlogmask(LOG_UPTO(LOG_DEBUG));
391 * Detach ourselves from the terminal, if required,
392 * and identify who is running us.
394 if (!nodetach && !updetach)
399 if (pw != NULL && pw->pw_name != NULL)
404 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
405 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
406 script_setenv("PPPLOGNAME", p);
409 * Compute mask of all interesting signals and install signal handlers
410 * for each. Only one signal handler may be active at a time. Therefore,
411 * all other signals should be masked when any handler is executing.
414 sigaddset(&mask, SIGHUP);
415 sigaddset(&mask, SIGINT);
416 sigaddset(&mask, SIGTERM);
417 sigaddset(&mask, SIGCHLD);
418 sigaddset(&mask, SIGUSR2);
420 #define SIGNAL(s, handler) do { \
421 sa.sa_handler = handler; \
422 if (sigaction(s, &sa, NULL) < 0) \
423 fatal("Couldn't establish signal handler (%d): %m", s); \
428 SIGNAL(SIGHUP, hup); /* Hangup */
429 SIGNAL(SIGINT, term); /* Interrupt */
430 SIGNAL(SIGTERM, term); /* Terminate */
431 SIGNAL(SIGCHLD, chld);
433 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
434 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
437 * Install a handler for other signals which would otherwise
438 * cause pppd to exit without cleaning up.
440 SIGNAL(SIGABRT, bad_signal);
441 SIGNAL(SIGALRM, bad_signal);
442 SIGNAL(SIGFPE, bad_signal);
443 SIGNAL(SIGILL, bad_signal);
444 SIGNAL(SIGPIPE, bad_signal);
445 SIGNAL(SIGQUIT, bad_signal);
446 SIGNAL(SIGSEGV, bad_signal);
448 SIGNAL(SIGBUS, bad_signal);
451 SIGNAL(SIGEMT, bad_signal);
454 SIGNAL(SIGPOLL, bad_signal);
457 SIGNAL(SIGPROF, bad_signal);
460 SIGNAL(SIGSYS, bad_signal);
463 SIGNAL(SIGTRAP, bad_signal);
466 SIGNAL(SIGVTALRM, bad_signal);
469 SIGNAL(SIGXCPU, bad_signal);
472 SIGNAL(SIGXFSZ, bad_signal);
476 * Apparently we can get a SIGPIPE when we call syslog, if
477 * syslogd has died and been restarted. Ignoring it seems
480 signal(SIGPIPE, SIG_IGN);
485 * If we're doing dial-on-demand, set up the interface now.
489 * Open the loopback channel and set it up to be the ppp interface.
491 fd_loop = open_ppp_loopback();
493 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
494 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
495 script_setenv("IFNAME", ifname);
497 create_pidfile(); /* write pid to file */
500 * Configure the interface and mark it up, etc.
514 * Don't do anything until we see some activity.
517 phase = PHASE_DORMANT;
521 if (sigsetjmp(sigjmp, 1) == 0) {
522 sigprocmask(SIG_BLOCK, &mask, NULL);
523 if (kill_link || got_sigchld) {
524 sigprocmask(SIG_UNBLOCK, &mask, NULL);
527 sigprocmask(SIG_UNBLOCK, &mask, NULL);
528 wait_input(timeleft(&timo));
538 if (get_loop_output())
544 if (kill_link && !persist)
548 * Now we want to bring up the link.
551 info("Starting link");
555 * Get a pty master/slave pair if the pty, notty, or record
556 * options were specified.
558 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
561 if (ptycommand != NULL || notty || record_file != NULL) {
562 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
563 error("Couldn't allocate pseudo-tty");
564 status = EXIT_FATAL_ERROR;
567 set_up_tty(pty_slave, 1);
571 * Lock the device if we've been asked to.
573 status = EXIT_LOCK_FAILED;
574 if (lockflag && !privopen) {
575 if (lock(devnam) < 0)
581 * Open the serial device and set it up to be the ppp interface.
582 * First we open it in non-blocking mode so we can set the
583 * various termios flags appropriately. If we aren't dialling
584 * out and we want to use the modem lines, we reopen it later
585 * in order to wait for the carrier detect signal from the modem.
589 if (devnam[0] != 0) {
591 /* If the user specified the device name, become the
592 user before opening it. */
594 if (!devnam_info.priv && !privopen)
596 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
598 if (!devnam_info.priv && !privopen)
604 error("Failed to open %s: %m", devnam);
605 status = EXIT_OPEN_FAILED;
607 if (!persist || err != EINTR)
610 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
611 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
612 warn("Couldn't reset non-blocking mode on device: %m");
615 * Do the equivalent of `mesg n' to stop broadcast messages.
617 if (fstat(ttyfd, &statbuf) < 0
618 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
619 warn("Couldn't restrict write permissions to %s: %m", devnam);
621 tty_mode = statbuf.st_mode;
624 * Set line speed, flow control, etc.
625 * If we have a non-null connection script,
626 * on most systems we set CLOCAL for now so that we can talk
627 * to the modem before carrier comes up. But this has the
628 * side effect that we might miss it if CD drops before we
629 * get to clear CLOCAL below. On systems where we can talk
630 * successfully to the modem with CLOCAL clear and CD down,
631 * we could clear CLOCAL at this point.
633 set_up_tty(ttyfd, (connector != NULL && connector[0] != 0));
638 * If the notty and/or record option was specified,
639 * start up the character shunt now.
641 status = EXIT_PTYCMD_FAILED;
642 if (ptycommand != NULL) {
643 if (record_file != NULL) {
644 int ipipe[2], opipe[2], ok;
646 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
647 fatal("Couldn't create pipes for record option: %m");
648 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
649 && start_charshunt(ipipe[0], opipe[1]);
657 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
664 if (!start_charshunt(0, 1))
666 } else if (record_file != NULL) {
667 if (!start_charshunt(ttyfd, ttyfd))
671 /* run connection script */
672 if (connector && connector[0]) {
673 MAINDEBUG(("Connecting with <%s>", connector));
675 if (real_ttyfd != -1) {
676 if (!default_device && modem) {
677 setdtr(real_ttyfd, 0); /* in case modem is off hook */
679 setdtr(real_ttyfd, 1);
683 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
684 error("Connect script failed");
685 status = EXIT_CONNECT_FAILED;
691 info("Serial connection established.");
693 /* set line speed, flow control, etc.;
694 clear CLOCAL if modem option */
695 if (real_ttyfd != -1)
696 set_up_tty(real_ttyfd, 0);
699 /* reopen tty if necessary to wait for carrier */
700 if (connector == NULL && modem && devnam[0] != 0) {
702 if ((i = open(devnam, O_RDWR)) >= 0)
704 if (errno != EINTR) {
705 error("Failed to reopen %s: %m", devnam);
706 status = EXIT_OPEN_FAILED;
708 if (!persist || errno != EINTR || hungup || kill_link)
714 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
715 script_setenv("SPEED", numbuf);
717 /* run welcome script, if any */
718 if (welcomer && welcomer[0]) {
719 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
720 warn("Welcome script failed");
723 /* set up the serial device as a ppp interface */
724 fd_ppp = establish_ppp(ttyfd);
726 status = EXIT_FATAL_ERROR;
732 info("Using interface ppp%d", ifunit);
733 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
734 script_setenv("IFNAME", ifname);
736 create_pidfile(); /* write pid to file */
740 * Start opening the connection and wait for
741 * incoming events (reply, timeout, etc.).
743 notice("Connect: %s <--> %s", ifname, ppp_devnam);
744 gettimeofday(&start_time, NULL);
748 * If we are initiating this connection, wait for a short
749 * time for something from the peer. This can avoid bouncing
750 * our packets off his tty before he has it set up.
752 if (connector != NULL || ptycommand != NULL) {
759 lcp_open(0); /* Start protocol */
762 status = EXIT_NEGOTIATION_FAILED;
763 for (phase = PHASE_ESTABLISH; phase != PHASE_DEAD; ) {
764 if (sigsetjmp(sigjmp, 1) == 0) {
765 sigprocmask(SIG_BLOCK, &mask, NULL);
766 if (kill_link || open_ccp_flag || got_sigchld) {
767 sigprocmask(SIG_UNBLOCK, &mask, NULL);
770 sigprocmask(SIG_UNBLOCK, &mask, NULL);
771 wait_input(timeleft(&timo));
778 lcp_close(0, "User request");
782 if (phase == PHASE_NETWORK) {
783 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
784 (*ccp_protent.open)(0);
789 reap_kids(0); /* Don't leave dead kids lying around */
793 * Print connect time and statistics.
795 if (gettimeofday(&now, NULL) >= 0) {
796 int t = now.tv_sec - start_time.tv_sec;
797 t = (t + 5) / 6; /* now in 1/10ths of minutes */
798 info("Connect time %d.%d minutes.", t/10, t%10);
800 if (link_stats_valid) {
801 info("Sent %d bytes, received %d bytes.",
802 link_stats.bytes_out, link_stats.bytes_in);
806 * If we may want to bring the link up again, transfer
807 * the ppp unit back to the loopback. Set the
808 * real serial device back to its normal mode of operation.
814 disestablish_ppp(ttyfd);
820 * Run disconnector script, if requested.
821 * XXX we may not be able to do this if the line has hung up!
824 if (disconnector && !hungup) {
826 set_up_tty(real_ttyfd, 1);
827 if (device_script(disconnector, ttyfd, ttyfd, 0) < 0) {
828 warn("disconnect script failed");
830 info("Serial link disconnected.");
847 if (pidfilename[0] != 0
848 && unlink(pidfilename) < 0 && errno != ENOENT)
849 warn("unable to delete pid file: %m");
859 if (holdoff > 0 && need_holdoff) {
860 phase = PHASE_HOLDOFF;
861 TIMEOUT(holdoff_end, NULL, holdoff);
863 if (sigsetjmp(sigjmp, 1) == 0) {
864 sigprocmask(SIG_BLOCK, &mask, NULL);
865 if (kill_link || got_sigchld) {
866 sigprocmask(SIG_UNBLOCK, &mask, NULL);
869 sigprocmask(SIG_UNBLOCK, &mask, NULL);
870 wait_input(timeleft(&timo));
877 phase = PHASE_DORMANT; /* allow signal to end holdoff */
881 } while (phase == PHASE_HOLDOFF);
887 /* Wait for scripts to finish */
888 while (n_children > 0) {
890 struct subprocess *chp;
891 dbglog("Waiting for %d child processes...", n_children);
892 for (chp = children; chp != NULL; chp = chp->next)
893 dbglog(" script %s, pid %d", chp->prog, chp->pid);
903 * detach - detach us from the controlling terminal.
912 if ((pid = fork()) < 0) {
913 error("Couldn't detach (fork failed: %m)");
914 die(1); /* or just return? */
920 exit(0); /* parent dies */
929 /* update pid file if it has been written already */
935 * reopen_log - (re)open our connection to syslog.
941 openlog("pppd", LOG_PID);
943 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
944 setlogmask(LOG_UPTO(LOG_INFO));
949 * Create a file containing our process ID.
957 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
958 _PATH_VARRUN, ifname);
959 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
960 fprintf(pidfile, "%d\n", getpid());
961 (void) fclose(pidfile);
963 error("Failed to create pid file %s: %m", pidfilename);
966 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
967 script_setenv("PPPD_PID", numbuf);
971 * holdoff_end - called via a timeout when the holdoff period ends.
977 phase = PHASE_DORMANT;
981 * get_input - called when incoming data is available.
989 struct protent *protp;
991 p = inpacket_buf; /* point to beginning of packet buffer */
993 len = read_packet(inpacket_buf);
998 notice("Modem hangup");
1000 status = EXIT_HANGUP;
1001 lcp_lowerdown(0); /* serial link is no longer available */
1006 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1007 dbglog("rcvd %P", p, len);
1009 if (len < PPP_HDRLEN) {
1010 MAINDEBUG(("io(): Received short packet."));
1014 p += 2; /* Skip address and control */
1015 GETSHORT(protocol, p);
1019 * Toss all non-LCP packets unless LCP is OPEN.
1021 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1022 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1027 * Until we get past the authentication phase, toss all packets
1028 * except LCP, LQR and authentication packets.
1030 if (phase <= PHASE_AUTHENTICATE
1031 && !(protocol == PPP_LCP || protocol == PPP_LQR
1032 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1033 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1039 * Upcall the proper protocol input routine.
1041 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1042 if (protp->protocol == protocol && protp->enabled_flag) {
1043 (*protp->input)(0, p, len);
1046 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1047 && protp->datainput != NULL) {
1048 (*protp->datainput)(0, p, len);
1054 warn("Unsupported protocol (0x%x) received", protocol);
1055 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1060 * die - clean up state and exit with the specified status.
1067 syslog(LOG_INFO, "Exit.");
1072 * cleanup - restore anything which needs to be restored before we exit
1081 disestablish_ppp(ttyfd);
1082 if (real_ttyfd >= 0)
1085 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1086 warn("unable to delete pid file: %m");
1094 * close_tty - restore the terminal device and close it.
1099 /* drop dtr to hang up */
1100 if (!default_device && modem) {
1101 setdtr(real_ttyfd, 0);
1103 * This sleep is in case the serial port has CLOCAL set by default,
1104 * and consequently will reassert DTR when we close the device.
1109 restore_tty(real_ttyfd);
1111 if (tty_mode != (mode_t) -1) {
1112 if (fchmod(real_ttyfd, tty_mode) != 0) {
1113 /* XXX if devnam is a symlink, this will change the link */
1114 chmod(devnam, tty_mode);
1124 struct timeval c_time; /* time at which to call routine */
1125 void *c_arg; /* argument to routine */
1126 void (*c_func) __P((void *)); /* routine */
1127 struct callout *c_next;
1130 static struct callout *callout = NULL; /* Callout list */
1131 static struct timeval timenow; /* Current time */
1134 * timeout - Schedule a timeout.
1136 * Note that this timeout takes the number of seconds, NOT hz (as in
1140 timeout(func, arg, time)
1141 void (*func) __P((void *));
1145 struct callout *newp, *p, **pp;
1147 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1152 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1153 fatal("Out of memory in timeout()!");
1155 newp->c_func = func;
1156 gettimeofday(&timenow, NULL);
1157 newp->c_time.tv_sec = timenow.tv_sec + time;
1158 newp->c_time.tv_usec = timenow.tv_usec;
1161 * Find correct place and link it in.
1163 for (pp = &callout; (p = *pp); pp = &p->c_next)
1164 if (newp->c_time.tv_sec < p->c_time.tv_sec
1165 || (newp->c_time.tv_sec == p->c_time.tv_sec
1166 && newp->c_time.tv_usec < p->c_time.tv_usec))
1174 * untimeout - Unschedule a timeout.
1177 untimeout(func, arg)
1178 void (*func) __P((void *));
1181 struct callout **copp, *freep;
1183 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1186 * Find first matching timeout and remove it from the list.
1188 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1189 if (freep->c_func == func && freep->c_arg == arg) {
1190 *copp = freep->c_next;
1191 (void) free((char *) freep);
1198 * calltimeout - Call any timeout routines which are now due.
1205 while (callout != NULL) {
1208 if (gettimeofday(&timenow, NULL) < 0)
1209 fatal("Failed to get time of day: %m");
1210 if (!(p->c_time.tv_sec < timenow.tv_sec
1211 || (p->c_time.tv_sec == timenow.tv_sec
1212 && p->c_time.tv_usec <= timenow.tv_usec)))
1213 break; /* no, it's not time yet */
1215 callout = p->c_next;
1216 (*p->c_func)(p->c_arg);
1224 * timeleft - return the length of time until the next timeout is due.
1226 static struct timeval *
1228 struct timeval *tvp;
1230 if (callout == NULL)
1233 gettimeofday(&timenow, NULL);
1234 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1235 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1236 if (tvp->tv_usec < 0) {
1237 tvp->tv_usec += 1000000;
1240 if (tvp->tv_sec < 0)
1241 tvp->tv_sec = tvp->tv_usec = 0;
1248 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1254 struct sigaction act, oldact;
1256 act.sa_handler = SIG_IGN;
1259 sigaction(sig, &act, &oldact);
1260 sigaction(sig, &oldact, NULL);
1265 * hup - Catch SIGHUP signal.
1267 * Indicates that the physical layer has been disconnected.
1268 * We don't rely on this indication; if the user has sent this
1269 * signal, we just take the link down.
1275 info("Hangup (SIGHUP)");
1277 if (status != EXIT_HANGUP)
1278 status = EXIT_USER_REQUEST;
1280 /* Send the signal to the [dis]connector process(es) also */
1283 kill(charshunt_pid, sig);
1285 siglongjmp(sigjmp, 1);
1290 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1292 * Indicates that we should initiate a graceful disconnect and exit.
1299 info("Terminating on signal %d.", sig);
1300 persist = 0; /* don't try to restart */
1302 status = EXIT_USER_REQUEST;
1304 /* Send the signal to the [dis]connector process(es) also */
1307 kill(charshunt_pid, sig);
1309 siglongjmp(sigjmp, 1);
1314 * chld - Catch SIGCHLD signal.
1315 * Sets a flag so we will call reap_kids in the mainline.
1323 siglongjmp(sigjmp, 1);
1328 * toggle_debug - Catch SIGUSR1 signal.
1330 * Toggle debug flag.
1339 setlogmask(LOG_UPTO(LOG_DEBUG));
1341 setlogmask(LOG_UPTO(LOG_WARNING));
1347 * open_ccp - Catch SIGUSR2 signal.
1349 * Try to (re)negotiate compression.
1358 siglongjmp(sigjmp, 1);
1363 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1369 static int crashed = 0;
1374 error("Fatal signal %d", sig);
1376 kill_my_pg(SIGTERM);
1378 kill(charshunt_pid, SIGTERM);
1384 * device_script - run a program to talk to the serial device
1385 * (e.g. to run the connector or disconnector script).
1388 device_script(program, in, out, dont_wait)
1402 error("Failed to create child process: %m");
1411 int newin = dup(in);
1415 } else if (out == 2) {
1418 if (log_to_fd >= 0) {
1423 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1424 if (errfd >= 0 && errfd != 2) {
1444 if (getuid() != uid) {
1445 error("setuid failed");
1449 execl("/bin/sh", "sh", "-c", program, (char *)0);
1450 error("could not exec /bin/sh: %m");
1456 record_child(pid, program, NULL, NULL);
1459 while (waitpid(pid, &status, 0) < 0) {
1462 fatal("error waiting for (dis)connection process: %m");
1467 return (status == 0 ? 0 : -1);
1472 * run-program - execute a program with given arguments,
1473 * but don't wait for it.
1474 * If the program can't be executed, logs an error unless
1475 * must_exist is 0 and the program file doesn't exist.
1476 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1477 * or isn't an executable plain file, or the process ID of the child.
1478 * If done != NULL, (*done)(arg) will be called later (within
1479 * reap_kids) iff the return value is > 0.
1482 run_program(prog, args, must_exist, done, arg)
1486 void (*done) __P((void *));
1493 * First check if the file exists and is executable.
1494 * We don't use access() because that would use the
1495 * real user-id, which might not be root, and the script
1496 * might be accessible only to root.
1499 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1500 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1501 if (must_exist || errno != ENOENT)
1502 warn("Can't execute %s: %m", prog);
1508 error("Failed to create child process for %s: %m", prog);
1514 /* Leave the current location */
1515 (void) setsid(); /* No controlling tty. */
1516 (void) umask (S_IRWXG|S_IRWXO);
1517 (void) chdir ("/"); /* no current directory. */
1518 setuid(0); /* set real UID = root */
1521 /* Ensure that nothing of our device environment is inherited. */
1527 close (ttyfd); /* tty interface to the ppp device */
1528 if (real_ttyfd >= 0)
1531 /* Don't pass handles to the PPP device, even by accident. */
1532 new_fd = open (_PATH_DEVNULL, O_RDWR);
1535 dup2 (new_fd, 0); /* stdin <- /dev/null */
1538 dup2 (0, 1); /* stdout -> /dev/null */
1539 dup2 (0, 2); /* stderr -> /dev/null */
1543 /* Force the priority back to zero if pppd is running higher. */
1544 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1545 warn("can't reset priority to 0: %m");
1548 /* SysV recommends a second fork at this point. */
1550 /* run the program */
1551 execve(prog, args, script_env);
1552 if (must_exist || errno != ENOENT) {
1553 /* have to reopen the log, there's nowhere else
1554 for the message to go. */
1556 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1563 dbglog("Script %s started (pid %d)", prog, pid);
1564 record_child(pid, prog, done, arg);
1571 * record_child - add a child process to the list for reap_kids
1575 record_child(pid, prog, done, arg)
1578 void (*done) __P((void *));
1581 struct subprocess *chp;
1585 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1587 warn("losing track of %s process", prog);
1593 chp->next = children;
1600 * reap_kids - get status from any dead child processes,
1601 * and log a message for abnormal terminations.
1608 struct subprocess *chp, **prevp;
1611 if (n_children == 0)
1613 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1616 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1617 if (chp->pid == pid) {
1622 if (WIFSIGNALED(status)) {
1623 warn("Child process %s (pid %d) terminated with signal %d",
1624 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1626 dbglog("Script %s finished (pid %d), status = 0x%x",
1627 (chp? chp->prog: "??"), pid, status);
1628 if (chp && chp->done)
1629 (*chp->done)(chp->arg);
1633 if (pid == -1 && errno != ECHILD && errno != EINTR)
1634 error("Error waiting for child process: %m");
1639 * novm - log an error message saying we ran out of memory, and die.
1645 fatal("Virtual memory exhausted allocating %s\n", msg);
1649 * script_setenv - set an environment variable value to be used
1650 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1653 script_setenv(var, value)
1656 size_t vl = strlen(var) + strlen(value) + 2;
1658 char *p, *newstring;
1660 newstring = (char *) malloc(vl);
1663 slprintf(newstring, vl, "%s=%s", var, value);
1665 /* check if this variable is already set */
1666 if (script_env != 0) {
1667 for (i = 0; (p = script_env[i]) != 0; ++i) {
1668 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1670 script_env[i] = newstring;
1676 script_env = (char **) malloc(16 * sizeof(char *));
1677 if (script_env == 0)
1682 /* reallocate script_env with more space if needed */
1683 if (i + 1 >= s_env_nalloc) {
1685 char **newenv = (char **) realloc((void *)script_env,
1686 new_n * sizeof(char *));
1689 script_env = newenv;
1690 s_env_nalloc = new_n;
1693 script_env[i] = newstring;
1694 script_env[i+1] = 0;
1698 * script_unsetenv - remove a variable from the environment
1702 script_unsetenv(var)
1705 int vl = strlen(var);
1709 if (script_env == 0)
1711 for (i = 0; (p = script_env[i]) != 0; ++i) {
1712 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1714 while ((script_env[i] = script_env[i+1]) != 0)
1722 * start_charshunt - create a child process to run the character shunt.
1725 start_charshunt(ifd, ofd)
1732 error("Can't fork process for character shunt: %m");
1739 if (getuid() != uid)
1740 fatal("setuid failed");
1744 charshunt(ifd, ofd, record_file);
1747 charshunt_pid = cpid;
1751 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
1763 * charshunt - the character shunt, which passes characters between
1764 * the pty master side and the serial port (or stdin/stdout).
1765 * This runs as the user (not as root).
1766 * (We assume ofd >= ifd which is true the way this gets called. :-).
1769 charshunt(ifd, ofd, record_file)
1774 fd_set ready, writey;
1775 u_char *ibufp, *obufp;
1778 int pty_readable, stdin_readable;
1779 struct timeval lasttime;
1780 FILE *recordf = NULL;
1783 * Reset signal handlers.
1785 signal(SIGHUP, SIG_IGN); /* Hangup */
1786 signal(SIGINT, SIG_DFL); /* Interrupt */
1787 signal(SIGTERM, SIG_DFL); /* Terminate */
1788 signal(SIGCHLD, SIG_DFL);
1789 signal(SIGUSR1, SIG_DFL);
1790 signal(SIGUSR2, SIG_DFL);
1791 signal(SIGABRT, SIG_DFL);
1792 signal(SIGALRM, SIG_DFL);
1793 signal(SIGFPE, SIG_DFL);
1794 signal(SIGILL, SIG_DFL);
1795 signal(SIGPIPE, SIG_DFL);
1796 signal(SIGQUIT, SIG_DFL);
1797 signal(SIGSEGV, SIG_DFL);
1799 signal(SIGBUS, SIG_DFL);
1802 signal(SIGEMT, SIG_DFL);
1805 signal(SIGPOLL, SIG_DFL);
1808 signal(SIGPROF, SIG_DFL);
1811 signal(SIGSYS, SIG_DFL);
1814 signal(SIGTRAP, SIG_DFL);
1817 signal(SIGVTALRM, SIG_DFL);
1820 signal(SIGXCPU, SIG_DFL);
1823 signal(SIGXFSZ, SIG_DFL);
1827 * Open the record file if required.
1829 if (record_file != NULL) {
1830 recordf = fopen(record_file, "a");
1831 if (recordf == NULL)
1832 error("Couldn't create record file %s: %m", record_file);
1835 /* set all the fds to non-blocking mode */
1836 flags = fcntl(pty_master, F_GETFL);
1838 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1839 warn("couldn't set pty master to nonblock: %m");
1840 flags = fcntl(ifd, F_GETFL);
1842 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1843 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1845 flags = fcntl(ofd, F_GETFL);
1847 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1848 warn("couldn't set stdout to nonblock: %m");
1852 ibufp = obufp = NULL;
1853 pty_readable = stdin_readable = 1;
1854 nfds = (ofd > pty_master? ofd: pty_master) + 1;
1855 if (recordf != NULL) {
1856 gettimeofday(&lasttime, NULL);
1857 putc(7, recordf); /* put start marker */
1858 putc(lasttime.tv_sec >> 24, recordf);
1859 putc(lasttime.tv_sec >> 16, recordf);
1860 putc(lasttime.tv_sec >> 8, recordf);
1861 putc(lasttime.tv_sec, recordf);
1862 lasttime.tv_usec = 0;
1865 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1869 FD_SET(pty_master, &writey);
1870 else if (stdin_readable)
1871 FD_SET(ifd, &ready);
1873 FD_SET(ofd, &writey);
1874 else if (pty_readable)
1875 FD_SET(pty_master, &ready);
1876 if (select(nfds, &ready, &writey, NULL, NULL) < 0) {
1881 if (FD_ISSET(ifd, &ready)) {
1882 ibufp = inpacket_buf;
1883 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
1884 if (nibuf < 0 && errno == EIO)
1887 if (!(errno == EINTR || errno == EAGAIN)) {
1888 error("Error reading standard input: %m");
1892 } else if (nibuf == 0) {
1893 /* end of file from stdin */
1895 /* do a 0-length write, hopefully this will generate
1896 an EOF (hangup) on the slave side. */
1897 write(pty_master, inpacket_buf, 0);
1899 if (!record_write(recordf, 4, NULL, 0, &lasttime))
1902 FD_SET(pty_master, &writey);
1904 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
1908 if (FD_ISSET(pty_master, &ready)) {
1909 obufp = outpacket_buf;
1910 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
1911 if (nobuf < 0 && errno == EIO)
1914 if (!(errno == EINTR || errno == EAGAIN)) {
1915 error("Error reading pseudo-tty master: %m");
1919 } else if (nobuf == 0) {
1920 /* end of file from the pty - slave side has closed */
1922 stdin_readable = 0; /* pty is not writable now */
1926 if (!record_write(recordf, 3, NULL, 0, &lasttime))
1929 FD_SET(ofd, &writey);
1931 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
1935 if (FD_ISSET(ofd, &writey)) {
1936 n = write(ofd, obufp, nobuf);
1939 error("Error writing standard output: %m");
1949 if (FD_ISSET(pty_master, &writey)) {
1950 n = write(pty_master, ibufp, nibuf);
1953 error("Error writing pseudo-tty master: %m");
1968 record_write(f, code, buf, nb, tp)
1978 gettimeofday(&now, NULL);
1979 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
1980 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
1984 putc(diff >> 24, f);
1985 putc(diff >> 16, f);
1998 fwrite(buf, nb, 1, f);
2002 error("Error writing record file: %m");