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.95 2000/04/15 10:10:24 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>
43 #include <arpa/inet.h>
56 #include "pathnames.h"
57 #include "patchlevel.h"
66 #endif /* IPX_CHANGE */
71 static const char rcsid[] = RCSID;
74 char ifname[32]; /* Interface name */
75 int ifunit; /* Interface unit number */
77 char *progname; /* Name of this program */
78 char hostname[MAXNAMELEN]; /* Our hostname */
79 static char pidfilename[MAXPATHLEN]; /* name of pid file */
80 static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
81 static char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
82 static uid_t uid; /* Our real user-id */
83 static int conn_running; /* we have a [dis]connector running */
85 int ttyfd; /* Serial port file descriptor */
86 mode_t tty_mode = (mode_t)-1; /* Original access permissions to tty */
87 int baud_rate; /* Actual bits/second for serial device */
88 int hungup; /* terminal has been hung up */
89 int privileged; /* we're running as real uid root */
90 int need_holdoff; /* need holdoff period before restarting */
91 int detached; /* have detached from terminal */
92 struct stat devstat; /* result of stat() on devnam */
93 int prepass = 0; /* doing prepass to find device name */
94 int devnam_fixed; /* set while in options.ttyxx file */
95 volatile int status; /* exit status for pppd */
96 int unsuccess; /* # unsuccessful connection attempts */
97 int do_callback; /* != 0 if we should do callback next */
98 int doing_callback; /* != 0 if we are doing callback */
99 char *callback_script; /* script for doing callback */
100 TDB_CONTEXT *pppdb; /* database for storing status etc. */
103 int (*holdoff_hook) __P((void)) = NULL;
104 int (*new_phase_hook) __P((int)) = NULL;
106 static int fd_ppp = -1; /* fd for talking PPP */
107 static int fd_loop; /* fd for getting demand-dial packets */
108 static int pty_master; /* fd for master side of pty */
109 static int pty_slave; /* fd for slave side of pty */
110 static int real_ttyfd; /* fd for actual serial port (not pty) */
112 int phase; /* where the link is at */
117 static sigjmp_buf sigjmp;
119 char **script_env; /* Env. variable values for scripts */
120 int s_env_nalloc; /* # words avail at script_env */
122 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
123 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
125 static int n_children; /* # child processes still running */
126 static int got_sigchld; /* set if we have received a SIGCHLD */
128 static int locked; /* lock() has succeeded */
129 static int privopen; /* don't lock, open device as root */
131 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
133 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
134 int ngroups; /* How many groups valid in groups */
136 static struct timeval start_time; /* Time when link was started. */
138 struct pppd_stats link_stats;
139 int link_connect_time;
140 int link_stats_valid;
142 static int charshunt_pid; /* Process ID for charshunt */
145 * We maintain a list of child process pids and
146 * functions to call when they exit.
151 void (*done) __P((void *));
153 struct subprocess *next;
156 static struct subprocess *children;
158 /* Prototypes for procedures local to this file. */
160 static void setup_signals __P((void));
161 static void create_pidfile __P((void));
162 static void create_linkpidfile __P((void));
163 static void cleanup __P((void));
164 static void close_tty __P((void));
165 static void get_input __P((void));
166 static void calltimeout __P((void));
167 static struct timeval *timeleft __P((struct timeval *));
168 static void kill_my_pg __P((int));
169 static void hup __P((int));
170 static void term __P((int));
171 static void chld __P((int));
172 static void toggle_debug __P((int));
173 static void open_ccp __P((int));
174 static void bad_signal __P((int));
175 static void holdoff_end __P((void *));
176 static int device_script __P((char *, int, int, int));
177 static int reap_kids __P((int waitfor));
178 static void record_child __P((int, char *, void (*) (void *), void *));
179 static void update_db_entry __P((void));
180 static void add_db_key __P((const char *));
181 static void delete_db_key __P((const char *));
182 static void cleanup_db __P((void));
183 static int open_socket __P((char *));
184 static int start_charshunt __P((int, int));
185 static void charshunt_done __P((void *));
186 static void charshunt __P((int, int, char *));
187 static int record_write __P((FILE *, int code, u_char *buf, int nb,
190 extern char *ttyname __P((int));
191 extern char *getlogin __P((void));
192 int main __P((int, char *[]));
196 #define O_NONBLOCK O_NDELAY
200 #define setlogmask(x)
204 * PPP Data Link Layer "protocol" table.
205 * One entry per supported protocol.
206 * The last entry must be NULL.
208 struct protent *protocols[] = {
239 struct protent *protp;
243 new_phase(PHASE_INITIALIZE);
246 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
247 * This way we can close 0, 1, 2 in detach() without clobbering
248 * a fd that we are using.
250 if ((i = open("/dev/null", O_RDWR)) >= 0) {
251 while (0 <= i && i <= 2)
259 /* Initialize syslog facilities */
262 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
263 option_error("Couldn't get hostname: %m");
266 hostname[MAXNAMELEN-1] = 0;
268 /* make sure we don't create world or group writable files. */
269 umask(umask(0777) | 022);
272 privileged = uid == 0;
273 slprintf(numbuf, sizeof(numbuf), "%d", uid);
274 script_setenv("ORIG_UID", numbuf, 0);
276 ngroups = getgroups(NGROUPS_MAX, groups);
279 * Initialize magic number generator now so that protocols may
280 * use magic numbers in initialization.
285 * Initialize to the standard option set, then parse, in order,
286 * the system options file, the user's options file,
287 * the tty's options file, and the command line arguments.
289 for (i = 0; (protp = protocols[i]) != NULL; ++i)
295 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
296 || !options_from_user())
297 exit(EXIT_OPTION_ERROR);
299 /* scan command line and options files to find device name */
301 parse_args(argc-1, argv+1);
305 * Work out the device name, if it hasn't already been specified.
307 using_pty = notty || ptycommand != NULL || pty_socket != NULL;
308 if (!using_pty && default_device) {
310 if (!isatty(0) || (p = ttyname(0)) == NULL) {
311 option_error("no device specified and stdin is not a tty");
312 exit(EXIT_OPTION_ERROR);
314 strlcpy(devnam, p, sizeof(devnam));
315 if (stat(devnam, &devstat) < 0)
316 fatal("Couldn't stat default device %s: %m", devnam);
320 * Parse the tty options file and the command line.
321 * The per-tty options file should not change
322 * ptycommand, pty_socket, notty or devnam.
326 if (!options_for_tty())
327 exit(EXIT_OPTION_ERROR);
331 if (!parse_args(argc-1, argv+1))
332 exit(EXIT_OPTION_ERROR);
335 * Check that we are running as root.
337 if (geteuid() != 0) {
338 option_error("must be root to run %s, since it is not setuid-root",
343 if (!ppp_available()) {
344 option_error(no_ppp_msg);
345 exit(EXIT_NO_KERNEL_SUPPORT);
349 * Check that the options given are valid and consistent.
351 if (!sys_check_options())
352 exit(EXIT_OPTION_ERROR);
353 auth_check_options();
354 #ifdef HAVE_MULTILINK
357 for (i = 0; (protp = protocols[i]) != NULL; ++i)
358 if (protp->check_options != NULL)
359 (*protp->check_options)();
360 if (demand && connect_script == 0) {
361 option_error("connect script is required for demand-dialling\n");
362 exit(EXIT_OPTION_ERROR);
364 /* default holdoff to 0 if no connect script has been given */
365 if (connect_script == 0 && !holdoff_specified)
369 if (!default_device) {
370 option_error("%s option precludes specifying device name",
371 notty? "notty": "pty");
372 exit(EXIT_OPTION_ERROR);
374 if (ptycommand != NULL && notty) {
375 option_error("pty option is incompatible with notty option");
376 exit(EXIT_OPTION_ERROR);
378 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
379 option_error("socket option is incompatible with pty and notty");
380 exit(EXIT_OPTION_ERROR);
382 default_device = notty;
385 if (notty && log_to_fd <= 1)
389 * If the user has specified a device which is the same as
390 * the one on stdin, pretend they didn't specify any.
391 * If the device is already open read/write on stdin,
392 * we assume we don't need to lock it, and we can open it as root.
394 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
395 && statbuf.st_rdev == devstat.st_rdev) {
397 fdflags = fcntl(0, F_GETFL);
398 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
406 * Don't send log messages to the serial port, it tends to
407 * confuse the peer. :-)
409 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
410 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
414 * Initialize system-dependent stuff.
418 setlogmask(LOG_UPTO(LOG_DEBUG));
420 pppdb = tdb_open(_PATH_PPPDB, 0, 0, O_RDWR|O_CREAT, 0644);
422 slprintf(db_key, sizeof(db_key), "pppd%d", getpid());
425 warn("Warning: couldn't open ppp database %s", _PATH_PPPDB);
427 warn("Warning: disabling multilink");
433 * Detach ourselves from the terminal, if required,
434 * and identify who is running us.
436 if (!nodetach && !updetach)
441 if (pw != NULL && pw->pw_name != NULL)
446 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
447 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
448 script_setenv("PPPLOGNAME", p, 0);
451 script_setenv("DEVICE", devnam, 1);
452 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
453 script_setenv("PPPD_PID", numbuf, 1);
459 create_linkpidfile();
462 * If we're doing dial-on-demand, set up the interface now.
466 * Open the loopback channel and set it up to be the ppp interface.
468 tdb_writelock(pppdb);
469 fd_loop = open_ppp_loopback();
471 tdb_writeunlock(pppdb);
474 * Configure the interface and mark it up, etc.
487 doing_callback = do_callback;
490 if (demand && !doing_callback) {
492 * Don't do anything until we see some activity.
495 new_phase(PHASE_DORMANT);
499 if (sigsetjmp(sigjmp, 1) == 0) {
500 sigprocmask(SIG_BLOCK, &mask, NULL);
501 if (kill_link || got_sigchld) {
502 sigprocmask(SIG_UNBLOCK, &mask, NULL);
505 sigprocmask(SIG_UNBLOCK, &mask, NULL);
506 wait_input(timeleft(&timo));
516 if (get_loop_output())
522 if (kill_link && !persist)
526 * Now we want to bring up the link.
529 info("Starting link");
532 new_phase(PHASE_SERIALCONN);
535 * Get a pty master/slave pair if the pty, notty, socket,
536 * or record options were specified.
538 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
541 if (using_pty || record_file != NULL) {
542 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
543 error("Couldn't allocate pseudo-tty");
544 status = EXIT_FATAL_ERROR;
547 set_up_tty(pty_slave, 1);
551 * Lock the device if we've been asked to.
553 status = EXIT_LOCK_FAILED;
554 if (lockflag && !privopen) {
555 if (lock(devnam) < 0)
561 * Open the serial device and set it up to be the ppp interface.
562 * First we open it in non-blocking mode so we can set the
563 * various termios flags appropriately. If we aren't dialling
564 * out and we want to use the modem lines, we reopen it later
565 * in order to wait for the carrier detect signal from the modem.
569 connector = doing_callback? callback_script: connect_script;
570 if (devnam[0] != 0) {
572 /* If the user specified the device name, become the
573 user before opening it. */
575 if (!devnam_info.priv && !privopen)
577 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
579 if (!devnam_info.priv && !privopen)
585 error("Failed to open %s: %m", devnam);
586 status = EXIT_OPEN_FAILED;
588 if (!persist || err != EINTR)
591 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
592 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
593 warn("Couldn't reset non-blocking mode on device: %m");
596 * Do the equivalent of `mesg n' to stop broadcast messages.
598 if (fstat(ttyfd, &statbuf) < 0
599 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
600 warn("Couldn't restrict write permissions to %s: %m", devnam);
602 tty_mode = statbuf.st_mode;
605 * Set line speed, flow control, etc.
606 * If we have a non-null connection or initializer script,
607 * on most systems we set CLOCAL for now so that we can talk
608 * to the modem before carrier comes up. But this has the
609 * side effect that we might miss it if CD drops before we
610 * get to clear CLOCAL below. On systems where we can talk
611 * successfully to the modem with CLOCAL clear and CD down,
612 * we could clear CLOCAL at this point.
614 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
615 || initializer != NULL));
620 * If the pty, socket, notty and/or record option was specified,
621 * start up the character shunt now.
623 status = EXIT_PTYCMD_FAILED;
624 if (ptycommand != NULL) {
625 if (record_file != NULL) {
626 int ipipe[2], opipe[2], ok;
628 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
629 fatal("Couldn't create pipes for record option: %m");
630 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
631 && start_charshunt(ipipe[0], opipe[1]);
639 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
645 } else if (pty_socket != NULL) {
646 int fd = open_socket(pty_socket);
649 if (!start_charshunt(fd, fd))
652 if (!start_charshunt(0, 1))
654 } else if (record_file != NULL) {
655 if (!start_charshunt(ttyfd, ttyfd))
659 /* run connection script */
660 if ((connector && connector[0]) || initializer) {
661 if (real_ttyfd != -1) {
662 /* XXX do this if doing_callback == CALLBACK_DIALIN? */
663 if (!default_device && modem) {
664 setdtr(real_ttyfd, 0); /* in case modem is off hook */
666 setdtr(real_ttyfd, 1);
670 if (initializer && initializer[0]) {
671 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
672 error("Initializer script failed");
673 status = EXIT_INIT_FAILED;
679 info("Serial port initialized.");
682 if (connector && connector[0]) {
683 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
684 error("Connect script failed");
685 status = EXIT_CONNECT_FAILED;
691 info("Serial connection established.");
694 /* set line speed, flow control, etc.;
695 clear CLOCAL if modem option */
696 if (real_ttyfd != -1)
697 set_up_tty(real_ttyfd, 0);
699 if (doing_callback == CALLBACK_DIALIN)
703 /* reopen tty if necessary to wait for carrier */
704 if (connector == NULL && modem && devnam[0] != 0) {
706 if ((i = open(devnam, O_RDWR)) >= 0)
708 if (errno != EINTR) {
709 error("Failed to reopen %s: %m", devnam);
710 status = EXIT_OPEN_FAILED;
712 if (!persist || errno != EINTR || hungup || kill_link)
718 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
719 script_setenv("SPEED", numbuf, 0);
721 /* run welcome script, if any */
722 if (welcomer && welcomer[0]) {
723 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
724 warn("Welcome script failed");
727 /* set up the serial device as a ppp interface */
728 tdb_writelock(pppdb);
729 fd_ppp = establish_ppp(ttyfd);
731 tdb_writeunlock(pppdb);
732 status = EXIT_FATAL_ERROR;
736 if (!demand && ifunit >= 0)
738 tdb_writeunlock(pppdb);
741 * Start opening the connection and wait for
742 * incoming events (reply, timeout, etc.).
744 notice("Connect: %s <--> %s", ifname, ppp_devnam);
745 gettimeofday(&start_time, NULL);
746 link_stats_valid = 0;
747 script_unsetenv("CONNECT_TIME");
748 script_unsetenv("BYTES_SENT");
749 script_unsetenv("BYTES_RCVD");
753 * If we are initiating this connection, wait for a short
754 * time for something from the peer. This can avoid bouncing
755 * our packets off his tty before he has it set up.
758 if (connect_delay != 0 && (connector != NULL || ptycommand != NULL)) {
760 t.tv_sec = connect_delay / 1000;
761 t.tv_usec = connect_delay % 1000;
765 lcp_open(0); /* Start protocol */
767 status = EXIT_NEGOTIATION_FAILED;
768 new_phase(PHASE_ESTABLISH);
769 while (phase != PHASE_DEAD) {
770 if (sigsetjmp(sigjmp, 1) == 0) {
771 sigprocmask(SIG_BLOCK, &mask, NULL);
772 if (kill_link || open_ccp_flag || got_sigchld) {
773 sigprocmask(SIG_UNBLOCK, &mask, NULL);
776 sigprocmask(SIG_UNBLOCK, &mask, NULL);
777 wait_input(timeleft(&timo));
784 lcp_close(0, "User request");
788 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
789 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
790 (*ccp_protent.open)(0);
795 reap_kids(0); /* Don't leave dead kids lying around */
799 * Print connect time and statistics.
801 if (link_stats_valid) {
802 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
803 info("Connect time %d.%d minutes.", t/10, t%10);
804 info("Sent %d bytes, received %d bytes.",
805 link_stats.bytes_out, link_stats.bytes_in);
809 * Delete pid file before disestablishing ppp. Otherwise it
810 * can happen that another pppd gets the same unit and then
811 * we delete its pid file.
814 if (pidfilename[0] != 0
815 && unlink(pidfilename) < 0 && errno != ENOENT)
816 warn("unable to delete pid file %s: %m", pidfilename);
821 * If we may want to bring the link up again, transfer
822 * the ppp unit back to the loopback. Set the
823 * real serial device back to its normal mode of operation.
829 disestablish_ppp(ttyfd);
834 script_unsetenv("IFNAME");
837 * Run disconnector script, if requested.
838 * XXX we may not be able to do this if the line has hung up!
841 if (disconnect_script && !hungup) {
842 new_phase(PHASE_DISCONNECT);
844 set_up_tty(real_ttyfd, 1);
845 if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
846 warn("disconnect script failed");
848 info("Serial link disconnected.");
865 if (pidfilename[0] != 0
866 && unlink(pidfilename) < 0 && errno != ENOENT)
867 warn("unable to delete pid file %s: %m", pidfilename);
871 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
877 t = need_holdoff? holdoff: 0;
879 t = (*holdoff_hook)();
881 new_phase(PHASE_HOLDOFF);
882 TIMEOUT(holdoff_end, NULL, t);
884 if (sigsetjmp(sigjmp, 1) == 0) {
885 sigprocmask(SIG_BLOCK, &mask, NULL);
886 if (kill_link || got_sigchld) {
887 sigprocmask(SIG_UNBLOCK, &mask, NULL);
890 sigprocmask(SIG_UNBLOCK, &mask, NULL);
891 wait_input(timeleft(&timo));
898 new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
902 } while (phase == PHASE_HOLDOFF);
908 /* Wait for scripts to finish */
909 /* XXX should have a timeout here */
910 while (n_children > 0) {
912 struct subprocess *chp;
913 dbglog("Waiting for %d child processes...", n_children);
914 for (chp = children; chp != NULL; chp = chp->next)
915 dbglog(" script %s, pid %d", chp->prog, chp->pid);
917 if (reap_kids(1) < 0)
926 * setup_signals - initialize signal handling.
935 * Compute mask of all interesting signals and install signal handlers
936 * for each. Only one signal handler may be active at a time. Therefore,
937 * all other signals should be masked when any handler is executing.
940 sigaddset(&mask, SIGHUP);
941 sigaddset(&mask, SIGINT);
942 sigaddset(&mask, SIGTERM);
943 sigaddset(&mask, SIGCHLD);
944 sigaddset(&mask, SIGUSR2);
946 #define SIGNAL(s, handler) do { \
947 sa.sa_handler = handler; \
948 if (sigaction(s, &sa, NULL) < 0) \
949 fatal("Couldn't establish signal handler (%d): %m", s); \
954 SIGNAL(SIGHUP, hup); /* Hangup */
955 SIGNAL(SIGINT, term); /* Interrupt */
956 SIGNAL(SIGTERM, term); /* Terminate */
957 SIGNAL(SIGCHLD, chld);
959 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
960 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
963 * Install a handler for other signals which would otherwise
964 * cause pppd to exit without cleaning up.
966 SIGNAL(SIGABRT, bad_signal);
967 SIGNAL(SIGALRM, bad_signal);
968 SIGNAL(SIGFPE, bad_signal);
969 SIGNAL(SIGILL, bad_signal);
970 SIGNAL(SIGPIPE, bad_signal);
971 SIGNAL(SIGQUIT, bad_signal);
972 SIGNAL(SIGSEGV, bad_signal);
974 SIGNAL(SIGBUS, bad_signal);
977 SIGNAL(SIGEMT, bad_signal);
980 SIGNAL(SIGPOLL, bad_signal);
983 SIGNAL(SIGPROF, bad_signal);
986 SIGNAL(SIGSYS, bad_signal);
989 SIGNAL(SIGTRAP, bad_signal);
992 SIGNAL(SIGVTALRM, bad_signal);
995 SIGNAL(SIGXCPU, bad_signal);
998 SIGNAL(SIGXFSZ, bad_signal);
1002 * Apparently we can get a SIGPIPE when we call syslog, if
1003 * syslogd has died and been restarted. Ignoring it seems
1006 signal(SIGPIPE, SIG_IGN);
1010 * set_ifunit - do things we need to do once we know which ppp
1011 * unit we are using.
1017 info("Using interface ppp%d", ifunit);
1018 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
1019 script_setenv("IFNAME", ifname, iskey);
1021 create_pidfile(); /* write pid to file */
1022 create_linkpidfile();
1027 * detach - detach us from the controlling terminal.
1037 if ((pid = fork()) < 0) {
1038 error("Couldn't detach (fork failed: %m)");
1039 die(1); /* or just return? */
1045 exit(0); /* parent dies */
1053 if (!log_to_file && !log_to_specific_fd)
1055 /* update pid files if they have been written already */
1059 create_linkpidfile();
1060 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1061 script_setenv("PPPD_PID", numbuf, 1);
1065 * reopen_log - (re)open our connection to syslog.
1071 openlog("pppd", LOG_PID);
1073 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1074 setlogmask(LOG_UPTO(LOG_INFO));
1079 * Create a file containing our process ID.
1086 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1087 _PATH_VARRUN, ifname);
1088 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1089 fprintf(pidfile, "%d\n", getpid());
1090 (void) fclose(pidfile);
1092 error("Failed to create pid file %s: %m", pidfilename);
1098 create_linkpidfile()
1102 if (linkname[0] == 0)
1104 script_setenv("LINKNAME", linkname, 1);
1105 slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1106 _PATH_VARRUN, linkname);
1107 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1108 fprintf(pidfile, "%d\n", getpid());
1110 fprintf(pidfile, "%s\n", ifname);
1111 (void) fclose(pidfile);
1113 error("Failed to create pid file %s: %m", linkpidfile);
1119 * holdoff_end - called via a timeout when the holdoff period ends.
1125 new_phase(PHASE_DORMANT);
1128 /* List of protocol names, to make our messages a little more informative. */
1129 struct protocol_list {
1132 } protocol_list[] = {
1134 { 0x23, "OSI Network Layer" },
1135 { 0x25, "Xerox NS IDP" },
1136 { 0x27, "DECnet Phase IV" },
1137 { 0x29, "Appletalk" },
1138 { 0x2b, "Novell IPX" },
1139 { 0x2d, "VJ compressed TCP/IP" },
1140 { 0x2f, "VJ uncompressed TCP/IP" },
1141 { 0x31, "Bridging PDU" },
1142 { 0x33, "Stream Protocol ST-II" },
1143 { 0x35, "Banyan Vines" },
1144 { 0x39, "AppleTalk EDDP" },
1145 { 0x3b, "AppleTalk SmartBuffered" },
1146 { 0x3d, "Multi-Link" },
1147 { 0x3f, "NETBIOS Framing" },
1148 { 0x41, "Cisco Systems" },
1149 { 0x43, "Ascom Timeplex" },
1150 { 0x45, "Fujitsu Link Backup and Load Balancing (LBLB)" },
1151 { 0x47, "DCA Remote Lan" },
1152 { 0x49, "Serial Data Transport Protocol (PPP-SDTP)" },
1153 { 0x4b, "SNA over 802.2" },
1155 { 0x4f, "IP6 Header Compression" },
1156 { 0x6f, "Stampede Bridging" },
1157 { 0xfb, "single-link compression" },
1158 { 0xfd, "1st choice compression" },
1159 { 0x0201, "802.1d Hello Packets" },
1160 { 0x0203, "IBM Source Routing BPDU" },
1161 { 0x0205, "DEC LANBridge100 Spanning Tree" },
1162 { 0x0231, "Luxcom" },
1163 { 0x0233, "Sigma Network Systems" },
1164 { 0x8021, "Internet Protocol Control Protocol" },
1165 { 0x8023, "OSI Network Layer Control Protocol" },
1166 { 0x8025, "Xerox NS IDP Control Protocol" },
1167 { 0x8027, "DECnet Phase IV Control Protocol" },
1168 { 0x8029, "Appletalk Control Protocol" },
1169 { 0x802b, "Novell IPX Control Protocol" },
1170 { 0x8031, "Bridging NCP" },
1171 { 0x8033, "Stream Protocol Control Protocol" },
1172 { 0x8035, "Banyan Vines Control Protocol" },
1173 { 0x803d, "Multi-Link Control Protocol" },
1174 { 0x803f, "NETBIOS Framing Control Protocol" },
1175 { 0x8041, "Cisco Systems Control Protocol" },
1176 { 0x8043, "Ascom Timeplex" },
1177 { 0x8045, "Fujitsu LBLB Control Protocol" },
1178 { 0x8047, "DCA Remote Lan Network Control Protocol (RLNCP)" },
1179 { 0x8049, "Serial Data Control Protocol (PPP-SDCP)" },
1180 { 0x804b, "SNA over 802.2 Control Protocol" },
1181 { 0x804d, "SNA Control Protocol" },
1182 { 0x804f, "IP6 Header Compression Control Protocol" },
1183 { 0x006f, "Stampede Bridging Control Protocol" },
1184 { 0x80fb, "Single Link Compression Control Protocol" },
1185 { 0x80fd, "Compression Control Protocol" },
1186 { 0xc021, "Link Control Protocol" },
1187 { 0xc023, "Password Authentication Protocol" },
1188 { 0xc025, "Link Quality Report" },
1189 { 0xc027, "Shiva Password Authentication Protocol" },
1190 { 0xc029, "CallBack Control Protocol (CBCP)" },
1191 { 0xc081, "Container Control Protocol" },
1192 { 0xc223, "Challenge Handshake Authentication Protocol" },
1193 { 0xc281, "Proprietary Authentication Protocol" },
1198 * protocol_name - find a name for a PPP protocol.
1201 protocol_name(proto)
1204 struct protocol_list *lp;
1206 for (lp = protocol_list; lp->proto != 0; ++lp)
1207 if (proto == lp->proto)
1213 * get_input - called when incoming data is available.
1221 struct protent *protp;
1223 p = inpacket_buf; /* point to beginning of packet buffer */
1225 len = read_packet(inpacket_buf);
1230 notice("Modem hangup");
1232 status = EXIT_HANGUP;
1233 lcp_lowerdown(0); /* serial link is no longer available */
1238 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1239 dbglog("rcvd %P", p, len);
1241 if (len < PPP_HDRLEN) {
1242 MAINDEBUG(("io(): Received short packet."));
1246 p += 2; /* Skip address and control */
1247 GETSHORT(protocol, p);
1251 * Toss all non-LCP packets unless LCP is OPEN.
1253 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1254 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1259 * Until we get past the authentication phase, toss all packets
1260 * except LCP, LQR and authentication packets.
1262 if (phase <= PHASE_AUTHENTICATE
1263 && !(protocol == PPP_LCP || protocol == PPP_LQR
1264 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1265 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1271 * Upcall the proper protocol input routine.
1273 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1274 if (protp->protocol == protocol && protp->enabled_flag) {
1275 (*protp->input)(0, p, len);
1278 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1279 && protp->datainput != NULL) {
1280 (*protp->datainput)(0, p, len);
1286 const char *pname = protocol_name(protocol);
1288 warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1290 warn("Unsupported protocol 0x%x received", protocol);
1292 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1296 * new_phase - signal the start of a new phase of pppd's operation.
1304 (*new_phase_hook)(p);
1308 * die - clean up state and exit with the specified status.
1315 syslog(LOG_INFO, "Exit.");
1320 * cleanup - restore anything which needs to be restored before we exit
1329 disestablish_ppp(ttyfd);
1330 if (real_ttyfd >= 0)
1333 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1334 warn("unable to delete pid file %s: %m", pidfilename);
1336 if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
1337 warn("unable to delete pid file %s: %m", linkpidfile);
1348 * close_tty - restore the terminal device and close it.
1353 /* drop dtr to hang up */
1354 if (!default_device && modem) {
1355 setdtr(real_ttyfd, 0);
1357 * This sleep is in case the serial port has CLOCAL set by default,
1358 * and consequently will reassert DTR when we close the device.
1363 restore_tty(real_ttyfd);
1365 if (tty_mode != (mode_t) -1) {
1366 if (fchmod(real_ttyfd, tty_mode) != 0) {
1367 /* XXX if devnam is a symlink, this will change the link */
1368 chmod(devnam, tty_mode);
1377 * update_link_stats - get stats at link termination.
1380 update_link_stats(u)
1386 if (!get_ppp_stats(u, &link_stats)
1387 || gettimeofday(&now, NULL) < 0)
1389 link_connect_time = now.tv_sec - start_time.tv_sec;
1390 link_stats_valid = 1;
1392 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1393 script_setenv("CONNECT_TIME", numbuf, 0);
1394 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1395 script_setenv("BYTES_SENT", numbuf, 0);
1396 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1397 script_setenv("BYTES_RCVD", numbuf, 0);
1402 struct timeval c_time; /* time at which to call routine */
1403 void *c_arg; /* argument to routine */
1404 void (*c_func) __P((void *)); /* routine */
1405 struct callout *c_next;
1408 static struct callout *callout = NULL; /* Callout list */
1409 static struct timeval timenow; /* Current time */
1412 * timeout - Schedule a timeout.
1414 * Note that this timeout takes the number of seconds, NOT hz (as in
1418 timeout(func, arg, time)
1419 void (*func) __P((void *));
1423 struct callout *newp, *p, **pp;
1425 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1430 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1431 fatal("Out of memory in timeout()!");
1433 newp->c_func = func;
1434 gettimeofday(&timenow, NULL);
1435 newp->c_time.tv_sec = timenow.tv_sec + time;
1436 newp->c_time.tv_usec = timenow.tv_usec;
1439 * Find correct place and link it in.
1441 for (pp = &callout; (p = *pp); pp = &p->c_next)
1442 if (newp->c_time.tv_sec < p->c_time.tv_sec
1443 || (newp->c_time.tv_sec == p->c_time.tv_sec
1444 && newp->c_time.tv_usec < p->c_time.tv_usec))
1452 * untimeout - Unschedule a timeout.
1455 untimeout(func, arg)
1456 void (*func) __P((void *));
1459 struct callout **copp, *freep;
1461 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1464 * Find first matching timeout and remove it from the list.
1466 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1467 if (freep->c_func == func && freep->c_arg == arg) {
1468 *copp = freep->c_next;
1469 free((char *) freep);
1476 * calltimeout - Call any timeout routines which are now due.
1483 while (callout != NULL) {
1486 if (gettimeofday(&timenow, NULL) < 0)
1487 fatal("Failed to get time of day: %m");
1488 if (!(p->c_time.tv_sec < timenow.tv_sec
1489 || (p->c_time.tv_sec == timenow.tv_sec
1490 && p->c_time.tv_usec <= timenow.tv_usec)))
1491 break; /* no, it's not time yet */
1493 callout = p->c_next;
1494 (*p->c_func)(p->c_arg);
1502 * timeleft - return the length of time until the next timeout is due.
1504 static struct timeval *
1506 struct timeval *tvp;
1508 if (callout == NULL)
1511 gettimeofday(&timenow, NULL);
1512 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1513 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1514 if (tvp->tv_usec < 0) {
1515 tvp->tv_usec += 1000000;
1518 if (tvp->tv_sec < 0)
1519 tvp->tv_sec = tvp->tv_usec = 0;
1526 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1532 struct sigaction act, oldact;
1534 act.sa_handler = SIG_IGN;
1537 sigaction(sig, &act, &oldact);
1538 sigaction(sig, &oldact, NULL);
1543 * hup - Catch SIGHUP signal.
1545 * Indicates that the physical layer has been disconnected.
1546 * We don't rely on this indication; if the user has sent this
1547 * signal, we just take the link down.
1553 info("Hangup (SIGHUP)");
1555 if (status != EXIT_HANGUP)
1556 status = EXIT_USER_REQUEST;
1558 /* Send the signal to the [dis]connector process(es) also */
1561 kill(charshunt_pid, sig);
1563 siglongjmp(sigjmp, 1);
1568 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1570 * Indicates that we should initiate a graceful disconnect and exit.
1577 info("Terminating on signal %d.", sig);
1578 persist = 0; /* don't try to restart */
1580 status = EXIT_USER_REQUEST;
1582 /* Send the signal to the [dis]connector process(es) also */
1585 kill(charshunt_pid, sig);
1587 siglongjmp(sigjmp, 1);
1592 * chld - Catch SIGCHLD signal.
1593 * Sets a flag so we will call reap_kids in the mainline.
1601 siglongjmp(sigjmp, 1);
1606 * toggle_debug - Catch SIGUSR1 signal.
1608 * Toggle debug flag.
1617 setlogmask(LOG_UPTO(LOG_DEBUG));
1619 setlogmask(LOG_UPTO(LOG_WARNING));
1625 * open_ccp - Catch SIGUSR2 signal.
1627 * Try to (re)negotiate compression.
1636 siglongjmp(sigjmp, 1);
1641 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1647 static int crashed = 0;
1652 error("Fatal signal %d", sig);
1654 kill_my_pg(SIGTERM);
1656 kill(charshunt_pid, SIGTERM);
1662 * device_script - run a program to talk to the serial device
1663 * (e.g. to run the connector or disconnector script).
1666 device_script(program, in, out, dont_wait)
1680 error("Failed to create child process: %m");
1689 int newin = dup(in);
1693 } else if (out == 2) {
1696 if (log_to_fd >= 0) {
1701 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1702 if (errfd >= 0 && errfd != 2) {
1722 if (getuid() != uid) {
1723 error("setuid failed");
1727 execl("/bin/sh", "sh", "-c", program, (char *)0);
1728 error("could not exec /bin/sh: %m");
1734 record_child(pid, program, NULL, NULL);
1737 while (waitpid(pid, &status, 0) < 0) {
1740 fatal("error waiting for (dis)connection process: %m");
1745 return (status == 0 ? 0 : -1);
1750 * run-program - execute a program with given arguments,
1751 * but don't wait for it.
1752 * If the program can't be executed, logs an error unless
1753 * must_exist is 0 and the program file doesn't exist.
1754 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1755 * or isn't an executable plain file, or the process ID of the child.
1756 * If done != NULL, (*done)(arg) will be called later (within
1757 * reap_kids) iff the return value is > 0.
1760 run_program(prog, args, must_exist, done, arg)
1764 void (*done) __P((void *));
1771 * First check if the file exists and is executable.
1772 * We don't use access() because that would use the
1773 * real user-id, which might not be root, and the script
1774 * might be accessible only to root.
1777 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1778 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1779 if (must_exist || errno != ENOENT)
1780 warn("Can't execute %s: %m", prog);
1786 error("Failed to create child process for %s: %m", prog);
1792 /* Leave the current location */
1793 (void) setsid(); /* No controlling tty. */
1794 (void) umask (S_IRWXG|S_IRWXO);
1795 (void) chdir ("/"); /* no current directory. */
1796 setuid(0); /* set real UID = root */
1799 /* Ensure that nothing of our device environment is inherited. */
1805 close (ttyfd); /* tty interface to the ppp device */
1806 if (real_ttyfd >= 0)
1809 /* Don't pass handles to the PPP device, even by accident. */
1810 new_fd = open (_PATH_DEVNULL, O_RDWR);
1813 dup2 (new_fd, 0); /* stdin <- /dev/null */
1816 dup2 (0, 1); /* stdout -> /dev/null */
1817 dup2 (0, 2); /* stderr -> /dev/null */
1821 /* Force the priority back to zero if pppd is running higher. */
1822 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1823 warn("can't reset priority to 0: %m");
1826 /* SysV recommends a second fork at this point. */
1828 /* run the program */
1829 execve(prog, args, script_env);
1830 if (must_exist || errno != ENOENT) {
1831 /* have to reopen the log, there's nowhere else
1832 for the message to go. */
1834 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1841 dbglog("Script %s started (pid %d)", prog, pid);
1842 record_child(pid, prog, done, arg);
1849 * record_child - add a child process to the list for reap_kids
1853 record_child(pid, prog, done, arg)
1856 void (*done) __P((void *));
1859 struct subprocess *chp;
1863 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1865 warn("losing track of %s process", prog);
1871 chp->next = children;
1878 * reap_kids - get status from any dead child processes,
1879 * and log a message for abnormal terminations.
1886 struct subprocess *chp, **prevp;
1889 if (n_children == 0)
1891 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1893 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1894 if (chp->pid == pid) {
1900 if (WIFSIGNALED(status)) {
1901 warn("Child process %s (pid %d) terminated with signal %d",
1902 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1904 dbglog("Script %s finished (pid %d), status = 0x%x",
1905 (chp? chp->prog: "??"), pid, status);
1906 if (chp && chp->done)
1907 (*chp->done)(chp->arg);
1912 if (errno == ECHILD)
1915 error("Error waiting for child process: %m");
1922 * novm - log an error message saying we ran out of memory, and die.
1928 fatal("Virtual memory exhausted allocating %s\n", msg);
1932 * script_setenv - set an environment variable value to be used
1933 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1936 script_setenv(var, value, iskey)
1940 size_t varl = strlen(var);
1941 size_t vl = varl + strlen(value) + 2;
1943 char *p, *newstring;
1945 newstring = (char *) malloc(vl+1);
1948 *newstring++ = iskey;
1949 slprintf(newstring, vl, "%s=%s", var, value);
1951 /* check if this variable is already set */
1952 if (script_env != 0) {
1953 for (i = 0; (p = script_env[i]) != 0; ++i) {
1954 if (strncmp(p, var, varl) == 0 && p[varl] == '=') {
1955 if (p[-1] && pppdb != NULL)
1958 script_env[i] = newstring;
1959 if (iskey && pppdb != NULL)
1960 add_db_key(newstring);
1966 /* no space allocated for script env. ptrs. yet */
1968 script_env = (char **) malloc(16 * sizeof(char *));
1969 if (script_env == 0)
1974 /* reallocate script_env with more space if needed */
1975 if (i + 1 >= s_env_nalloc) {
1977 char **newenv = (char **) realloc((void *)script_env,
1978 new_n * sizeof(char *));
1981 script_env = newenv;
1982 s_env_nalloc = new_n;
1985 script_env[i] = newstring;
1986 script_env[i+1] = 0;
1988 if (pppdb != NULL) {
1990 add_db_key(newstring);
1996 * script_unsetenv - remove a variable from the environment
2000 script_unsetenv(var)
2003 int vl = strlen(var);
2007 if (script_env == 0)
2009 for (i = 0; (p = script_env[i]) != 0; ++i) {
2010 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
2011 if (p[-1] && pppdb != NULL)
2014 while ((script_env[i] = script_env[i+1]) != 0)
2024 * update_db_entry - update our entry in the database.
2033 if (script_env == NULL)
2036 for (i = 0; (p = script_env[i]) != 0; ++i)
2037 vlen += strlen(p) + 1;
2038 vbuf = malloc(vlen);
2040 novm("database entry");
2042 for (i = 0; (p = script_env[i]) != 0; ++i)
2043 q += slprintf(q, vbuf + vlen - q, "%s;", p);
2046 key.dsize = strlen(db_key);
2049 if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2050 error("tdb_store failed: %s", tdb_error(pppdb));
2055 * add_db_key - add a key that we can use to look up our database entry.
2063 key.dptr = (char *) str;
2064 key.dsize = strlen(str);
2066 dbuf.dsize = strlen(db_key);
2067 if (tdb_store(pppdb, key, dbuf, TDB_REPLACE))
2068 error("tdb_store key failed: %s", tdb_error(pppdb));
2072 * delete_db_key - delete a key for looking up our database entry.
2080 key.dptr = (char *) str;
2081 key.dsize = strlen(str);
2082 tdb_delete(pppdb, key);
2086 * cleanup_db - delete all the entries we put in the database.
2096 key.dsize = strlen(db_key);
2097 tdb_delete(pppdb, key);
2098 for (i = 0; (p = script_env[i]) != 0; ++i)
2104 * open_socket - establish a stream socket connection to the nominated
2111 char *sep, *endp = NULL;
2112 int sock, port = -1;
2114 struct hostent *hent;
2115 struct sockaddr_in sad;
2117 /* parse host:port and resolve host to an IP address */
2118 sep = strchr(dest, ':');
2120 port = strtol(sep+1, &endp, 10);
2121 if (port < 0 || endp == sep+1 || sep == dest) {
2122 error("Can't parse host:port for socket destination");
2126 host = inet_addr(dest);
2127 if (host == (u_int32_t) -1) {
2128 hent = gethostbyname(dest);
2130 error("%s: unknown host in socket option", dest);
2134 host = *(u_int32_t *)(hent->h_addr_list[0]);
2138 /* get a socket and connect it to the other end */
2139 sock = socket(PF_INET, SOCK_STREAM, 0);
2141 error("Can't create socket: %m");
2144 memset(&sad, 0, sizeof(sad));
2145 sad.sin_family = AF_INET;
2146 sad.sin_port = htons(port);
2147 sad.sin_addr.s_addr = host;
2148 if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
2149 error("Can't connect to %s: %m", dest);
2158 * start_charshunt - create a child process to run the character shunt.
2161 start_charshunt(ifd, ofd)
2168 error("Can't fork process for character shunt: %m");
2175 if (getuid() != uid)
2176 fatal("setuid failed");
2180 charshunt(ifd, ofd, record_file);
2183 charshunt_pid = cpid;
2187 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2199 * charshunt - the character shunt, which passes characters between
2200 * the pty master side and the serial port (or stdin/stdout).
2201 * This runs as the user (not as root).
2202 * (We assume ofd >= ifd which is true the way this gets called. :-).
2205 charshunt(ifd, ofd, record_file)
2210 fd_set ready, writey;
2211 u_char *ibufp, *obufp;
2214 int pty_readable, stdin_readable;
2215 struct timeval lasttime;
2216 FILE *recordf = NULL;
2217 int ilevel, olevel, max_level;
2218 struct timeval levelt, tout, *top;
2221 * Reset signal handlers.
2223 signal(SIGHUP, SIG_IGN); /* Hangup */
2224 signal(SIGINT, SIG_DFL); /* Interrupt */
2225 signal(SIGTERM, SIG_DFL); /* Terminate */
2226 signal(SIGCHLD, SIG_DFL);
2227 signal(SIGUSR1, SIG_DFL);
2228 signal(SIGUSR2, SIG_DFL);
2229 signal(SIGABRT, SIG_DFL);
2230 signal(SIGALRM, SIG_DFL);
2231 signal(SIGFPE, SIG_DFL);
2232 signal(SIGILL, SIG_DFL);
2233 signal(SIGPIPE, SIG_DFL);
2234 signal(SIGQUIT, SIG_DFL);
2235 signal(SIGSEGV, SIG_DFL);
2237 signal(SIGBUS, SIG_DFL);
2240 signal(SIGEMT, SIG_DFL);
2243 signal(SIGPOLL, SIG_DFL);
2246 signal(SIGPROF, SIG_DFL);
2249 signal(SIGSYS, SIG_DFL);
2252 signal(SIGTRAP, SIG_DFL);
2255 signal(SIGVTALRM, SIG_DFL);
2258 signal(SIGXCPU, SIG_DFL);
2261 signal(SIGXFSZ, SIG_DFL);
2265 * Open the record file if required.
2267 if (record_file != NULL) {
2268 recordf = fopen(record_file, "a");
2269 if (recordf == NULL)
2270 error("Couldn't create record file %s: %m", record_file);
2273 /* set all the fds to non-blocking mode */
2274 flags = fcntl(pty_master, F_GETFL);
2276 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2277 warn("couldn't set pty master to nonblock: %m");
2278 flags = fcntl(ifd, F_GETFL);
2280 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2281 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2283 flags = fcntl(ofd, F_GETFL);
2285 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2286 warn("couldn't set stdout to nonblock: %m");
2290 ibufp = obufp = NULL;
2291 pty_readable = stdin_readable = 1;
2293 ilevel = olevel = 0;
2294 gettimeofday(&levelt, NULL);
2295 if (max_data_rate) {
2296 max_level = max_data_rate / 10;
2297 if (max_level < 100)
2300 max_level = sizeof(inpacket_buf) + 1;
2302 nfds = (ofd > pty_master? ofd: pty_master) + 1;
2303 if (recordf != NULL) {
2304 gettimeofday(&lasttime, NULL);
2305 putc(7, recordf); /* put start marker */
2306 putc(lasttime.tv_sec >> 24, recordf);
2307 putc(lasttime.tv_sec >> 16, recordf);
2308 putc(lasttime.tv_sec >> 8, recordf);
2309 putc(lasttime.tv_sec, recordf);
2310 lasttime.tv_usec = 0;
2313 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
2316 tout.tv_usec = 10000;
2320 if (ilevel >= max_level)
2323 FD_SET(pty_master, &writey);
2324 } else if (stdin_readable)
2325 FD_SET(ifd, &ready);
2327 if (olevel >= max_level)
2330 FD_SET(ofd, &writey);
2331 } else if (pty_readable)
2332 FD_SET(pty_master, &ready);
2333 if (select(nfds, &ready, &writey, NULL, top) < 0) {
2338 if (max_data_rate) {
2343 gettimeofday(&now, NULL);
2344 dt = (now.tv_sec - levelt.tv_sec
2345 + (now.tv_usec - levelt.tv_usec) / 1e6);
2346 nbt = (int)(dt * max_data_rate);
2347 ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
2348 olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
2351 ilevel = olevel = 0;
2352 if (FD_ISSET(ifd, &ready)) {
2353 ibufp = inpacket_buf;
2354 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2355 if (nibuf < 0 && errno == EIO)
2358 if (!(errno == EINTR || errno == EAGAIN)) {
2359 error("Error reading standard input: %m");
2363 } else if (nibuf == 0) {
2364 /* end of file from stdin */
2366 /* do a 0-length write, hopefully this will generate
2367 an EOF (hangup) on the slave side. */
2368 write(pty_master, inpacket_buf, 0);
2370 if (!record_write(recordf, 4, NULL, 0, &lasttime))
2373 FD_SET(pty_master, &writey);
2375 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2379 if (FD_ISSET(pty_master, &ready)) {
2380 obufp = outpacket_buf;
2381 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2382 if (nobuf < 0 && errno == EIO)
2385 if (!(errno == EINTR || errno == EAGAIN)) {
2386 error("Error reading pseudo-tty master: %m");
2390 } else if (nobuf == 0) {
2391 /* end of file from the pty - slave side has closed */
2393 stdin_readable = 0; /* pty is not writable now */
2397 if (!record_write(recordf, 3, NULL, 0, &lasttime))
2400 FD_SET(ofd, &writey);
2402 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2406 if (FD_ISSET(ofd, &writey)) {
2408 if (olevel + n > max_level)
2409 n = max_level - olevel;
2410 n = write(ofd, obufp, n);
2413 error("Error writing standard output: %m");
2424 if (FD_ISSET(pty_master, &writey)) {
2426 if (ilevel + n > max_level)
2427 n = max_level - ilevel;
2428 n = write(pty_master, ibufp, n);
2431 error("Error writing pseudo-tty master: %m");
2447 record_write(f, code, buf, nb, tp)
2457 gettimeofday(&now, NULL);
2458 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2459 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2463 putc(diff >> 24, f);
2464 putc(diff >> 16, f);
2477 fwrite(buf, nb, 1, f);
2481 error("Error writing record file: %m");