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.91 2000/03/27 06:03:01 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"
65 #endif /* IPX_CHANGE */
70 static const char rcsid[] = RCSID;
73 char ifname[32]; /* Interface name */
74 int ifunit; /* Interface unit number */
76 char *progname; /* Name of this program */
77 char hostname[MAXNAMELEN]; /* Our hostname */
78 static char pidfilename[MAXPATHLEN]; /* name of pid file */
79 static char linkpidfile[MAXPATHLEN]; /* name of linkname pid file */
80 static char ppp_devnam[MAXPATHLEN]; /* name of PPP tty (maybe ttypx) */
81 static uid_t uid; /* Our real user-id */
82 static int conn_running; /* we have a [dis]connector running */
84 int ttyfd; /* Serial port file descriptor */
85 mode_t tty_mode = -1; /* Original access permissions to tty */
86 int baud_rate; /* Actual bits/second for serial device */
87 int hungup; /* terminal has been hung up */
88 int privileged; /* we're running as real uid root */
89 int need_holdoff; /* need holdoff period before restarting */
90 int detached; /* have detached from terminal */
91 struct stat devstat; /* result of stat() on devnam */
92 int prepass = 0; /* doing prepass to find device name */
93 int devnam_fixed; /* set while in options.ttyxx file */
94 volatile int status; /* exit status for pppd */
95 int unsuccess; /* # unsuccessful connection attempts */
96 int do_callback; /* != 0 if we should do callback next */
97 int doing_callback; /* != 0 if we are doing callback */
98 char *callback_script; /* script for doing callback */
100 int (*holdoff_hook) __P((void)) = NULL;
101 int (*new_phase_hook) __P((int)) = NULL;
103 static int fd_ppp = -1; /* fd for talking PPP */
104 static int fd_loop; /* fd for getting demand-dial packets */
105 static int pty_master; /* fd for master side of pty */
106 static int pty_slave; /* fd for slave side of pty */
107 static int real_ttyfd; /* fd for actual serial port (not pty) */
109 int phase; /* where the link is at */
114 static sigjmp_buf sigjmp;
116 char **script_env; /* Env. variable values for scripts */
117 int s_env_nalloc; /* # words avail at script_env */
119 u_char outpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for outgoing packet */
120 u_char inpacket_buf[PPP_MRU+PPP_HDRLEN]; /* buffer for incoming packet */
122 static int n_children; /* # child processes still running */
123 static int got_sigchld; /* set if we have received a SIGCHLD */
125 static int locked; /* lock() has succeeded */
126 static int privopen; /* don't lock, open device as root */
128 char *no_ppp_msg = "Sorry - this system lacks PPP kernel support\n";
130 GIDSET_TYPE groups[NGROUPS_MAX];/* groups the user is in */
131 int ngroups; /* How many groups valid in groups */
133 static struct timeval start_time; /* Time when link was started. */
135 struct pppd_stats link_stats;
136 int link_connect_time;
137 int link_stats_valid;
139 static int charshunt_pid; /* Process ID for charshunt */
142 * We maintain a list of child process pids and
143 * functions to call when they exit.
148 void (*done) __P((void *));
150 struct subprocess *next;
153 static struct subprocess *children;
155 /* Prototypes for procedures local to this file. */
157 static void create_pidfile __P((void));
158 static void create_linkpidfile __P((void));
159 static void cleanup __P((void));
160 static void close_tty __P((void));
161 static void get_input __P((void));
162 static void calltimeout __P((void));
163 static struct timeval *timeleft __P((struct timeval *));
164 static void kill_my_pg __P((int));
165 static void hup __P((int));
166 static void term __P((int));
167 static void chld __P((int));
168 static void toggle_debug __P((int));
169 static void open_ccp __P((int));
170 static void bad_signal __P((int));
171 static void holdoff_end __P((void *));
172 static int device_script __P((char *, int, int, int));
173 static int reap_kids __P((int waitfor));
174 static void record_child __P((int, char *, void (*) (void *), void *));
175 static int open_socket __P((char *));
176 static int start_charshunt __P((int, int));
177 static void charshunt_done __P((void *));
178 static void charshunt __P((int, int, char *));
179 static int record_write __P((FILE *, int code, u_char *buf, int nb,
182 extern char *ttyname __P((int));
183 extern char *getlogin __P((void));
184 int main __P((int, char *[]));
188 #define O_NONBLOCK O_NDELAY
192 #define setlogmask(x)
196 * PPP Data Link Layer "protocol" table.
197 * One entry per supported protocol.
198 * The last entry must be NULL.
200 struct protent *protocols[] = {
232 struct protent *protp;
236 new_phase(PHASE_INITIALIZE);
239 * Ensure that fds 0, 1, 2 are open, to /dev/null if nowhere else.
240 * This way we can close 0, 1, 2 in detach() without clobbering
241 * a fd that we are using.
243 if ((i = open("/dev/null", O_RDWR)) >= 0) {
244 while (0 <= i && i <= 2)
252 /* Initialize syslog facilities */
255 if (gethostname(hostname, MAXNAMELEN) < 0 ) {
256 option_error("Couldn't get hostname: %m");
259 hostname[MAXNAMELEN-1] = 0;
261 /* make sure we don't create world or group writable files. */
262 umask(umask(0777) | 022);
265 privileged = uid == 0;
266 slprintf(numbuf, sizeof(numbuf), "%d", uid);
267 script_setenv("ORIG_UID", numbuf);
269 ngroups = getgroups(NGROUPS_MAX, groups);
272 * Initialize magic number generator now so that protocols may
273 * use magic numbers in initialization.
278 * Initialize to the standard option set, then parse, in order,
279 * the system options file, the user's options file,
280 * the tty's options file, and the command line arguments.
282 for (i = 0; (protp = protocols[i]) != NULL; ++i)
288 if (!options_from_file(_PATH_SYSOPTIONS, !privileged, 0, 1)
289 || !options_from_user())
290 exit(EXIT_OPTION_ERROR);
292 /* scan command line and options files to find device name */
294 parse_args(argc-1, argv+1);
298 * Work out the device name, if it hasn't already been specified.
300 using_pty = notty || ptycommand != NULL || pty_socket != NULL;
301 if (!using_pty && default_device) {
303 if (!isatty(0) || (p = ttyname(0)) == NULL) {
304 option_error("no device specified and stdin is not a tty");
305 exit(EXIT_OPTION_ERROR);
307 strlcpy(devnam, p, sizeof(devnam));
308 if (stat(devnam, &devstat) < 0)
309 fatal("Couldn't stat default device %s: %m", devnam);
313 * Parse the tty options file and the command line.
314 * The per-tty options file should not change
315 * ptycommand, pty_socket, notty or devnam.
319 if (!options_for_tty())
320 exit(EXIT_OPTION_ERROR);
324 if (!parse_args(argc-1, argv+1))
325 exit(EXIT_OPTION_ERROR);
328 * Check that we are running as root.
330 if (geteuid() != 0) {
331 option_error("must be root to run %s, since it is not setuid-root",
336 if (!ppp_available()) {
337 option_error(no_ppp_msg);
338 exit(EXIT_NO_KERNEL_SUPPORT);
342 * Check that the options given are valid and consistent.
344 if (!sys_check_options())
345 exit(EXIT_OPTION_ERROR);
346 auth_check_options();
347 for (i = 0; (protp = protocols[i]) != NULL; ++i)
348 if (protp->check_options != NULL)
349 (*protp->check_options)();
350 if (demand && connect_script == 0) {
351 option_error("connect script is required for demand-dialling\n");
352 exit(EXIT_OPTION_ERROR);
354 /* default holdoff to 0 if no connect script has been given */
355 if (connect_script == 0 && !holdoff_specified)
359 if (!default_device) {
360 option_error("%s option precludes specifying device name",
361 notty? "notty": "pty");
362 exit(EXIT_OPTION_ERROR);
364 if (ptycommand != NULL && notty) {
365 option_error("pty option is incompatible with notty option");
366 exit(EXIT_OPTION_ERROR);
368 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
369 option_error("socket option is incompatible with pty and notty");
370 exit(EXIT_OPTION_ERROR);
372 default_device = notty;
375 if (notty && log_to_fd <= 1)
379 * If the user has specified a device which is the same as
380 * the one on stdin, pretend they didn't specify any.
381 * If the device is already open read/write on stdin,
382 * we assume we don't need to lock it, and we can open it as root.
384 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
385 && statbuf.st_rdev == devstat.st_rdev) {
387 fdflags = fcntl(0, F_GETFL);
388 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
396 * Don't send log messages to the serial port, it tends to
397 * confuse the peer. :-)
399 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
400 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
403 script_setenv("DEVICE", devnam);
406 * Initialize system-dependent stuff.
410 setlogmask(LOG_UPTO(LOG_DEBUG));
413 * Detach ourselves from the terminal, if required,
414 * and identify who is running us.
416 if (!nodetach && !updetach)
421 if (pw != NULL && pw->pw_name != NULL)
426 syslog(LOG_NOTICE, "pppd %s.%d%s started by %s, uid %d",
427 VERSION, PATCHLEVEL, IMPLEMENTATION, p, uid);
428 script_setenv("PPPLOGNAME", p);
431 * Compute mask of all interesting signals and install signal handlers
432 * for each. Only one signal handler may be active at a time. Therefore,
433 * all other signals should be masked when any handler is executing.
436 sigaddset(&mask, SIGHUP);
437 sigaddset(&mask, SIGINT);
438 sigaddset(&mask, SIGTERM);
439 sigaddset(&mask, SIGCHLD);
440 sigaddset(&mask, SIGUSR2);
442 #define SIGNAL(s, handler) do { \
443 sa.sa_handler = handler; \
444 if (sigaction(s, &sa, NULL) < 0) \
445 fatal("Couldn't establish signal handler (%d): %m", s); \
450 SIGNAL(SIGHUP, hup); /* Hangup */
451 SIGNAL(SIGINT, term); /* Interrupt */
452 SIGNAL(SIGTERM, term); /* Terminate */
453 SIGNAL(SIGCHLD, chld);
455 SIGNAL(SIGUSR1, toggle_debug); /* Toggle debug flag */
456 SIGNAL(SIGUSR2, open_ccp); /* Reopen CCP */
459 * Install a handler for other signals which would otherwise
460 * cause pppd to exit without cleaning up.
462 SIGNAL(SIGABRT, bad_signal);
463 SIGNAL(SIGALRM, bad_signal);
464 SIGNAL(SIGFPE, bad_signal);
465 SIGNAL(SIGILL, bad_signal);
466 SIGNAL(SIGPIPE, bad_signal);
467 SIGNAL(SIGQUIT, bad_signal);
468 SIGNAL(SIGSEGV, bad_signal);
470 SIGNAL(SIGBUS, bad_signal);
473 SIGNAL(SIGEMT, bad_signal);
476 SIGNAL(SIGPOLL, bad_signal);
479 SIGNAL(SIGPROF, bad_signal);
482 SIGNAL(SIGSYS, bad_signal);
485 SIGNAL(SIGTRAP, bad_signal);
488 SIGNAL(SIGVTALRM, bad_signal);
491 SIGNAL(SIGXCPU, bad_signal);
494 SIGNAL(SIGXFSZ, bad_signal);
498 * Apparently we can get a SIGPIPE when we call syslog, if
499 * syslogd has died and been restarted. Ignoring it seems
502 signal(SIGPIPE, SIG_IGN);
506 create_linkpidfile();
509 * If we're doing dial-on-demand, set up the interface now.
513 * Open the loopback channel and set it up to be the ppp interface.
515 fd_loop = open_ppp_loopback();
517 syslog(LOG_INFO, "Using interface ppp%d", ifunit);
518 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
519 script_setenv("IFNAME", ifname);
521 create_pidfile(); /* write pid to file */
524 * Configure the interface and mark it up, etc.
537 doing_callback = do_callback;
540 if (demand && !doing_callback) {
542 * Don't do anything until we see some activity.
545 new_phase(PHASE_DORMANT);
549 if (sigsetjmp(sigjmp, 1) == 0) {
550 sigprocmask(SIG_BLOCK, &mask, NULL);
551 if (kill_link || got_sigchld) {
552 sigprocmask(SIG_UNBLOCK, &mask, NULL);
555 sigprocmask(SIG_UNBLOCK, &mask, NULL);
556 wait_input(timeleft(&timo));
566 if (get_loop_output())
572 if (kill_link && !persist)
576 * Now we want to bring up the link.
579 info("Starting link");
582 new_phase(PHASE_SERIALCONN);
585 * Get a pty master/slave pair if the pty, notty, socket,
586 * or record options were specified.
588 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
591 if (using_pty || record_file != NULL) {
592 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
593 error("Couldn't allocate pseudo-tty");
594 status = EXIT_FATAL_ERROR;
597 set_up_tty(pty_slave, 1);
601 * Lock the device if we've been asked to.
603 status = EXIT_LOCK_FAILED;
604 if (lockflag && !privopen) {
605 if (lock(devnam) < 0)
611 * Open the serial device and set it up to be the ppp interface.
612 * First we open it in non-blocking mode so we can set the
613 * various termios flags appropriately. If we aren't dialling
614 * out and we want to use the modem lines, we reopen it later
615 * in order to wait for the carrier detect signal from the modem.
619 connector = doing_callback? callback_script: connect_script;
620 if (devnam[0] != 0) {
622 /* If the user specified the device name, become the
623 user before opening it. */
625 if (!devnam_info.priv && !privopen)
627 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
629 if (!devnam_info.priv && !privopen)
635 error("Failed to open %s: %m", devnam);
636 status = EXIT_OPEN_FAILED;
638 if (!persist || err != EINTR)
641 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
642 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
643 warn("Couldn't reset non-blocking mode on device: %m");
646 * Do the equivalent of `mesg n' to stop broadcast messages.
648 if (fstat(ttyfd, &statbuf) < 0
649 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
650 warn("Couldn't restrict write permissions to %s: %m", devnam);
652 tty_mode = statbuf.st_mode;
655 * Set line speed, flow control, etc.
656 * If we have a non-null connection or initializer script,
657 * on most systems we set CLOCAL for now so that we can talk
658 * to the modem before carrier comes up. But this has the
659 * side effect that we might miss it if CD drops before we
660 * get to clear CLOCAL below. On systems where we can talk
661 * successfully to the modem with CLOCAL clear and CD down,
662 * we could clear CLOCAL at this point.
664 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
665 || initializer != NULL));
670 * If the pty, socket, notty and/or record option was specified,
671 * start up the character shunt now.
673 status = EXIT_PTYCMD_FAILED;
674 if (ptycommand != NULL) {
675 if (record_file != NULL) {
676 int ipipe[2], opipe[2], ok;
678 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
679 fatal("Couldn't create pipes for record option: %m");
680 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
681 && start_charshunt(ipipe[0], opipe[1]);
689 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
695 } else if (pty_socket != NULL) {
696 int fd = open_socket(pty_socket);
699 if (!start_charshunt(fd, fd))
702 if (!start_charshunt(0, 1))
704 } else if (record_file != NULL) {
705 if (!start_charshunt(ttyfd, ttyfd))
709 /* run connection script */
710 if ((connector && connector[0]) || initializer) {
711 if (real_ttyfd != -1) {
712 /* XXX do this if doing_callback == CALLBACK_DIALIN? */
713 if (!default_device && modem) {
714 setdtr(real_ttyfd, 0); /* in case modem is off hook */
716 setdtr(real_ttyfd, 1);
720 if (initializer && initializer[0]) {
721 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
722 error("Initializer script failed");
723 status = EXIT_INIT_FAILED;
729 info("Serial port initialized.");
732 if (connector && connector[0]) {
733 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
734 error("Connect script failed");
735 status = EXIT_CONNECT_FAILED;
741 info("Serial connection established.");
744 /* set line speed, flow control, etc.;
745 clear CLOCAL if modem option */
746 if (real_ttyfd != -1)
747 set_up_tty(real_ttyfd, 0);
749 if (doing_callback == CALLBACK_DIALIN)
753 /* reopen tty if necessary to wait for carrier */
754 if (connector == NULL && modem && devnam[0] != 0) {
756 if ((i = open(devnam, O_RDWR)) >= 0)
758 if (errno != EINTR) {
759 error("Failed to reopen %s: %m", devnam);
760 status = EXIT_OPEN_FAILED;
762 if (!persist || errno != EINTR || hungup || kill_link)
768 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
769 script_setenv("SPEED", numbuf);
771 /* run welcome script, if any */
772 if (welcomer && welcomer[0]) {
773 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
774 warn("Welcome script failed");
777 /* set up the serial device as a ppp interface */
778 fd_ppp = establish_ppp(ttyfd);
780 status = EXIT_FATAL_ERROR;
784 if (!demand && ifunit >= 0) {
786 info("Using interface ppp%d", ifunit);
787 slprintf(ifname, sizeof(ifname), "ppp%d", ifunit);
788 script_setenv("IFNAME", ifname);
790 create_pidfile(); /* write pid to file */
794 * Start opening the connection and wait for
795 * incoming events (reply, timeout, etc.).
797 notice("Connect: %s <--> %s", ifname, ppp_devnam);
798 gettimeofday(&start_time, NULL);
799 link_stats_valid = 0;
800 script_unsetenv("CONNECT_TIME");
801 script_unsetenv("BYTES_SENT");
802 script_unsetenv("BYTES_RCVD");
806 * If we are initiating this connection, wait for a short
807 * time for something from the peer. This can avoid bouncing
808 * our packets off his tty before he has it set up.
811 if (connect_delay != 0 && (connector != NULL || ptycommand != NULL)) {
813 t.tv_sec = connect_delay / 1000;
814 t.tv_usec = connect_delay % 1000;
818 lcp_open(0); /* Start protocol */
820 status = EXIT_NEGOTIATION_FAILED;
821 new_phase(PHASE_ESTABLISH);
822 while (phase != PHASE_DEAD) {
823 if (sigsetjmp(sigjmp, 1) == 0) {
824 sigprocmask(SIG_BLOCK, &mask, NULL);
825 if (kill_link || open_ccp_flag || got_sigchld) {
826 sigprocmask(SIG_UNBLOCK, &mask, NULL);
829 sigprocmask(SIG_UNBLOCK, &mask, NULL);
830 wait_input(timeleft(&timo));
837 lcp_close(0, "User request");
841 if (phase == PHASE_NETWORK || phase == PHASE_RUNNING) {
842 ccp_fsm[0].flags = OPT_RESTART; /* clears OPT_SILENT */
843 (*ccp_protent.open)(0);
848 reap_kids(0); /* Don't leave dead kids lying around */
852 * Print connect time and statistics.
854 if (link_stats_valid) {
855 int t = (link_connect_time + 5) / 6; /* 1/10ths of minutes */
856 info("Connect time %d.%d minutes.", t/10, t%10);
857 info("Sent %d bytes, received %d bytes.",
858 link_stats.bytes_out, link_stats.bytes_in);
862 * Delete pid file before disestablishing ppp. Otherwise it
863 * can happen that another pppd gets the same unit and then
864 * we delete its pid file.
867 if (pidfilename[0] != 0
868 && unlink(pidfilename) < 0 && errno != ENOENT)
869 warn("unable to delete pid file %s: %m", pidfilename);
874 * If we may want to bring the link up again, transfer
875 * the ppp unit back to the loopback. Set the
876 * real serial device back to its normal mode of operation.
882 disestablish_ppp(ttyfd);
888 * Run disconnector script, if requested.
889 * XXX we may not be able to do this if the line has hung up!
892 if (disconnect_script && !hungup) {
893 new_phase(PHASE_DISCONNECT);
895 set_up_tty(real_ttyfd, 1);
896 if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
897 warn("disconnect script failed");
899 info("Serial link disconnected.");
916 if (pidfilename[0] != 0
917 && unlink(pidfilename) < 0 && errno != ENOENT)
918 warn("unable to delete pid file %s: %m", pidfilename);
922 if (!persist || (maxfail > 0 && unsuccess >= maxfail))
928 t = need_holdoff? holdoff: 0;
930 t = (*holdoff_hook)();
932 new_phase(PHASE_HOLDOFF);
933 TIMEOUT(holdoff_end, NULL, t);
935 if (sigsetjmp(sigjmp, 1) == 0) {
936 sigprocmask(SIG_BLOCK, &mask, NULL);
937 if (kill_link || got_sigchld) {
938 sigprocmask(SIG_UNBLOCK, &mask, NULL);
941 sigprocmask(SIG_UNBLOCK, &mask, NULL);
942 wait_input(timeleft(&timo));
949 new_phase(PHASE_DORMANT); /* allow signal to end holdoff */
953 } while (phase == PHASE_HOLDOFF);
959 /* Wait for scripts to finish */
960 /* XXX should have a timeout here */
961 while (n_children > 0) {
963 struct subprocess *chp;
964 dbglog("Waiting for %d child processes...", n_children);
965 for (chp = children; chp != NULL; chp = chp->next)
966 dbglog(" script %s, pid %d", chp->prog, chp->pid);
968 if (reap_kids(1) < 0)
977 * detach - detach us from the controlling terminal.
986 if ((pid = fork()) < 0) {
987 error("Couldn't detach (fork failed: %m)");
988 die(1); /* or just return? */
994 exit(0); /* parent dies */
1003 /* update pid files if they have been written already */
1007 create_linkpidfile();
1011 * reopen_log - (re)open our connection to syslog.
1017 openlog("pppd", LOG_PID);
1019 openlog("pppd", LOG_PID | LOG_NDELAY, LOG_PPP);
1020 setlogmask(LOG_UPTO(LOG_INFO));
1025 * Create a file containing our process ID.
1033 slprintf(pidfilename, sizeof(pidfilename), "%s%s.pid",
1034 _PATH_VARRUN, ifname);
1035 if ((pidfile = fopen(pidfilename, "w")) != NULL) {
1036 fprintf(pidfile, "%d\n", getpid());
1037 (void) fclose(pidfile);
1039 error("Failed to create pid file %s: %m", pidfilename);
1042 slprintf(numbuf, sizeof(numbuf), "%d", getpid());
1043 script_setenv("PPPD_PID", numbuf);
1045 create_linkpidfile();
1049 create_linkpidfile()
1053 if (linkname[0] == 0)
1055 slprintf(linkpidfile, sizeof(linkpidfile), "%sppp-%s.pid",
1056 _PATH_VARRUN, linkname);
1057 if ((pidfile = fopen(linkpidfile, "w")) != NULL) {
1058 fprintf(pidfile, "%d\n", getpid());
1060 fprintf(pidfile, "%s\n", ifname);
1061 (void) fclose(pidfile);
1063 error("Failed to create pid file %s: %m", linkpidfile);
1066 script_setenv("LINKNAME", linkname);
1070 * holdoff_end - called via a timeout when the holdoff period ends.
1076 new_phase(PHASE_DORMANT);
1079 /* List of protocol names, to make our messages a little more informative. */
1080 struct protocol_list {
1083 } protocol_list[] = {
1085 { 0x23, "OSI Network Layer" },
1086 { 0x25, "Xerox NS IDP" },
1087 { 0x27, "DECnet Phase IV" },
1088 { 0x29, "Appletalk" },
1089 { 0x2b, "Novell IPX" },
1090 { 0x2d, "VJ compressed TCP/IP" },
1091 { 0x2f, "VJ uncompressed TCP/IP" },
1092 { 0x31, "Bridging PDU" },
1093 { 0x33, "Stream Protocol ST-II" },
1094 { 0x35, "Banyan Vines" },
1095 { 0x39, "AppleTalk EDDP" },
1096 { 0x3b, "AppleTalk SmartBuffered" },
1097 { 0x3d, "Multi-Link" },
1098 { 0x3f, "NETBIOS Framing" },
1099 { 0x41, "Cisco Systems" },
1100 { 0x43, "Ascom Timeplex" },
1101 { 0x45, "Fujitsu Link Backup and Load Balancing (LBLB)" },
1102 { 0x47, "DCA Remote Lan" },
1103 { 0x49, "Serial Data Transport Protocol (PPP-SDTP)" },
1104 { 0x4b, "SNA over 802.2" },
1106 { 0x4f, "IP6 Header Compression" },
1107 { 0x6f, "Stampede Bridging" },
1108 { 0xfb, "single-link compression" },
1109 { 0xfd, "1st choice compression" },
1110 { 0x0201, "802.1d Hello Packets" },
1111 { 0x0203, "IBM Source Routing BPDU" },
1112 { 0x0205, "DEC LANBridge100 Spanning Tree" },
1113 { 0x0231, "Luxcom" },
1114 { 0x0233, "Sigma Network Systems" },
1115 { 0x8021, "Internet Protocol Control Protocol" },
1116 { 0x8023, "OSI Network Layer Control Protocol" },
1117 { 0x8025, "Xerox NS IDP Control Protocol" },
1118 { 0x8027, "DECnet Phase IV Control Protocol" },
1119 { 0x8029, "Appletalk Control Protocol" },
1120 { 0x802b, "Novell IPX Control Protocol" },
1121 { 0x8031, "Bridging NCP" },
1122 { 0x8033, "Stream Protocol Control Protocol" },
1123 { 0x8035, "Banyan Vines Control Protocol" },
1124 { 0x803d, "Multi-Link Control Protocol" },
1125 { 0x803f, "NETBIOS Framing Control Protocol" },
1126 { 0x8041, "Cisco Systems Control Protocol" },
1127 { 0x8043, "Ascom Timeplex" },
1128 { 0x8045, "Fujitsu LBLB Control Protocol" },
1129 { 0x8047, "DCA Remote Lan Network Control Protocol (RLNCP)" },
1130 { 0x8049, "Serial Data Control Protocol (PPP-SDCP)" },
1131 { 0x804b, "SNA over 802.2 Control Protocol" },
1132 { 0x804d, "SNA Control Protocol" },
1133 { 0x804f, "IP6 Header Compression Control Protocol" },
1134 { 0x006f, "Stampede Bridging Control Protocol" },
1135 { 0x80fb, "Single Link Compression Control Protocol" },
1136 { 0x80fd, "Compression Control Protocol" },
1137 { 0xc021, "Link Control Protocol" },
1138 { 0xc023, "Password Authentication Protocol" },
1139 { 0xc025, "Link Quality Report" },
1140 { 0xc027, "Shiva Password Authentication Protocol" },
1141 { 0xc029, "CallBack Control Protocol (CBCP)" },
1142 { 0xc081, "Container Control Protocol" },
1143 { 0xc223, "Challenge Handshake Authentication Protocol" },
1144 { 0xc281, "Proprietary Authentication Protocol" },
1149 * protocol_name - find a name for a PPP protocol.
1152 protocol_name(proto)
1155 struct protocol_list *lp;
1157 for (lp = protocol_list; lp->proto != 0; ++lp)
1158 if (proto == lp->proto)
1164 * get_input - called when incoming data is available.
1172 struct protent *protp;
1174 p = inpacket_buf; /* point to beginning of packet buffer */
1176 len = read_packet(inpacket_buf);
1181 notice("Modem hangup");
1183 status = EXIT_HANGUP;
1184 lcp_lowerdown(0); /* serial link is no longer available */
1189 if (debug /*&& (debugflags & DBG_INPACKET)*/)
1190 dbglog("rcvd %P", p, len);
1192 if (len < PPP_HDRLEN) {
1193 MAINDEBUG(("io(): Received short packet."));
1197 p += 2; /* Skip address and control */
1198 GETSHORT(protocol, p);
1202 * Toss all non-LCP packets unless LCP is OPEN.
1204 if (protocol != PPP_LCP && lcp_fsm[0].state != OPENED) {
1205 MAINDEBUG(("get_input: Received non-LCP packet when LCP not open."));
1210 * Until we get past the authentication phase, toss all packets
1211 * except LCP, LQR and authentication packets.
1213 if (phase <= PHASE_AUTHENTICATE
1214 && !(protocol == PPP_LCP || protocol == PPP_LQR
1215 || protocol == PPP_PAP || protocol == PPP_CHAP)) {
1216 MAINDEBUG(("get_input: discarding proto 0x%x in phase %d",
1222 * Upcall the proper protocol input routine.
1224 for (i = 0; (protp = protocols[i]) != NULL; ++i) {
1225 if (protp->protocol == protocol && protp->enabled_flag) {
1226 (*protp->input)(0, p, len);
1229 if (protocol == (protp->protocol & ~0x8000) && protp->enabled_flag
1230 && protp->datainput != NULL) {
1231 (*protp->datainput)(0, p, len);
1237 const char *pname = protocol_name(protocol);
1239 warn("Unsupported protocol '%s' (0x%x) received", pname, protocol);
1241 warn("Unsupported protocol 0x%x received", protocol);
1243 lcp_sprotrej(0, p - PPP_HDRLEN, len + PPP_HDRLEN);
1247 * new_phase - signal the start of a new phase of pppd's operation.
1255 (*new_phase_hook)(p);
1259 * die - clean up state and exit with the specified status.
1266 syslog(LOG_INFO, "Exit.");
1271 * cleanup - restore anything which needs to be restored before we exit
1280 disestablish_ppp(ttyfd);
1281 if (real_ttyfd >= 0)
1284 if (pidfilename[0] != 0 && unlink(pidfilename) < 0 && errno != ENOENT)
1285 warn("unable to delete pid file %s: %m", pidfilename);
1287 if (linkpidfile[0] != 0 && unlink(linkpidfile) < 0 && errno != ENOENT)
1288 warn("unable to delete pid file %s: %m", linkpidfile);
1296 * close_tty - restore the terminal device and close it.
1301 /* drop dtr to hang up */
1302 if (!default_device && modem) {
1303 setdtr(real_ttyfd, 0);
1305 * This sleep is in case the serial port has CLOCAL set by default,
1306 * and consequently will reassert DTR when we close the device.
1311 restore_tty(real_ttyfd);
1313 if (tty_mode != (mode_t) -1) {
1314 if (fchmod(real_ttyfd, tty_mode) != 0) {
1315 /* XXX if devnam is a symlink, this will change the link */
1316 chmod(devnam, tty_mode);
1325 * update_link_stats - get stats at link termination.
1328 update_link_stats(u)
1334 if (!get_ppp_stats(u, &link_stats)
1335 || gettimeofday(&now, NULL) < 0)
1337 link_connect_time = now.tv_sec - start_time.tv_sec;
1338 link_stats_valid = 1;
1340 slprintf(numbuf, sizeof(numbuf), "%d", link_connect_time);
1341 script_setenv("CONNECT_TIME", numbuf);
1342 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_out);
1343 script_setenv("BYTES_SENT", numbuf);
1344 slprintf(numbuf, sizeof(numbuf), "%d", link_stats.bytes_in);
1345 script_setenv("BYTES_RCVD", numbuf);
1350 struct timeval c_time; /* time at which to call routine */
1351 void *c_arg; /* argument to routine */
1352 void (*c_func) __P((void *)); /* routine */
1353 struct callout *c_next;
1356 static struct callout *callout = NULL; /* Callout list */
1357 static struct timeval timenow; /* Current time */
1360 * timeout - Schedule a timeout.
1362 * Note that this timeout takes the number of seconds, NOT hz (as in
1366 timeout(func, arg, time)
1367 void (*func) __P((void *));
1371 struct callout *newp, *p, **pp;
1373 MAINDEBUG(("Timeout %p:%p in %d seconds.", func, arg, time));
1378 if ((newp = (struct callout *) malloc(sizeof(struct callout))) == NULL)
1379 fatal("Out of memory in timeout()!");
1381 newp->c_func = func;
1382 gettimeofday(&timenow, NULL);
1383 newp->c_time.tv_sec = timenow.tv_sec + time;
1384 newp->c_time.tv_usec = timenow.tv_usec;
1387 * Find correct place and link it in.
1389 for (pp = &callout; (p = *pp); pp = &p->c_next)
1390 if (newp->c_time.tv_sec < p->c_time.tv_sec
1391 || (newp->c_time.tv_sec == p->c_time.tv_sec
1392 && newp->c_time.tv_usec < p->c_time.tv_usec))
1400 * untimeout - Unschedule a timeout.
1403 untimeout(func, arg)
1404 void (*func) __P((void *));
1407 struct callout **copp, *freep;
1409 MAINDEBUG(("Untimeout %p:%p.", func, arg));
1412 * Find first matching timeout and remove it from the list.
1414 for (copp = &callout; (freep = *copp); copp = &freep->c_next)
1415 if (freep->c_func == func && freep->c_arg == arg) {
1416 *copp = freep->c_next;
1417 free((char *) freep);
1424 * calltimeout - Call any timeout routines which are now due.
1431 while (callout != NULL) {
1434 if (gettimeofday(&timenow, NULL) < 0)
1435 fatal("Failed to get time of day: %m");
1436 if (!(p->c_time.tv_sec < timenow.tv_sec
1437 || (p->c_time.tv_sec == timenow.tv_sec
1438 && p->c_time.tv_usec <= timenow.tv_usec)))
1439 break; /* no, it's not time yet */
1441 callout = p->c_next;
1442 (*p->c_func)(p->c_arg);
1450 * timeleft - return the length of time until the next timeout is due.
1452 static struct timeval *
1454 struct timeval *tvp;
1456 if (callout == NULL)
1459 gettimeofday(&timenow, NULL);
1460 tvp->tv_sec = callout->c_time.tv_sec - timenow.tv_sec;
1461 tvp->tv_usec = callout->c_time.tv_usec - timenow.tv_usec;
1462 if (tvp->tv_usec < 0) {
1463 tvp->tv_usec += 1000000;
1466 if (tvp->tv_sec < 0)
1467 tvp->tv_sec = tvp->tv_usec = 0;
1474 * kill_my_pg - send a signal to our process group, and ignore it ourselves.
1480 struct sigaction act, oldact;
1482 act.sa_handler = SIG_IGN;
1485 sigaction(sig, &act, &oldact);
1486 sigaction(sig, &oldact, NULL);
1491 * hup - Catch SIGHUP signal.
1493 * Indicates that the physical layer has been disconnected.
1494 * We don't rely on this indication; if the user has sent this
1495 * signal, we just take the link down.
1501 info("Hangup (SIGHUP)");
1503 if (status != EXIT_HANGUP)
1504 status = EXIT_USER_REQUEST;
1506 /* Send the signal to the [dis]connector process(es) also */
1509 kill(charshunt_pid, sig);
1511 siglongjmp(sigjmp, 1);
1516 * term - Catch SIGTERM signal and SIGINT signal (^C/del).
1518 * Indicates that we should initiate a graceful disconnect and exit.
1525 info("Terminating on signal %d.", sig);
1526 persist = 0; /* don't try to restart */
1528 status = EXIT_USER_REQUEST;
1530 /* Send the signal to the [dis]connector process(es) also */
1533 kill(charshunt_pid, sig);
1535 siglongjmp(sigjmp, 1);
1540 * chld - Catch SIGCHLD signal.
1541 * Sets a flag so we will call reap_kids in the mainline.
1549 siglongjmp(sigjmp, 1);
1554 * toggle_debug - Catch SIGUSR1 signal.
1556 * Toggle debug flag.
1565 setlogmask(LOG_UPTO(LOG_DEBUG));
1567 setlogmask(LOG_UPTO(LOG_WARNING));
1573 * open_ccp - Catch SIGUSR2 signal.
1575 * Try to (re)negotiate compression.
1584 siglongjmp(sigjmp, 1);
1589 * bad_signal - We've caught a fatal signal. Clean up state and exit.
1595 static int crashed = 0;
1600 error("Fatal signal %d", sig);
1602 kill_my_pg(SIGTERM);
1604 kill(charshunt_pid, SIGTERM);
1610 * device_script - run a program to talk to the serial device
1611 * (e.g. to run the connector or disconnector script).
1614 device_script(program, in, out, dont_wait)
1628 error("Failed to create child process: %m");
1637 int newin = dup(in);
1641 } else if (out == 2) {
1644 if (log_to_fd >= 0) {
1649 errfd = open(_PATH_CONNERRS, O_WRONLY | O_APPEND | O_CREAT, 0600);
1650 if (errfd >= 0 && errfd != 2) {
1670 if (getuid() != uid) {
1671 error("setuid failed");
1675 execl("/bin/sh", "sh", "-c", program, (char *)0);
1676 error("could not exec /bin/sh: %m");
1682 record_child(pid, program, NULL, NULL);
1685 while (waitpid(pid, &status, 0) < 0) {
1688 fatal("error waiting for (dis)connection process: %m");
1693 return (status == 0 ? 0 : -1);
1698 * run-program - execute a program with given arguments,
1699 * but don't wait for it.
1700 * If the program can't be executed, logs an error unless
1701 * must_exist is 0 and the program file doesn't exist.
1702 * Returns -1 if it couldn't fork, 0 if the file doesn't exist
1703 * or isn't an executable plain file, or the process ID of the child.
1704 * If done != NULL, (*done)(arg) will be called later (within
1705 * reap_kids) iff the return value is > 0.
1708 run_program(prog, args, must_exist, done, arg)
1712 void (*done) __P((void *));
1719 * First check if the file exists and is executable.
1720 * We don't use access() because that would use the
1721 * real user-id, which might not be root, and the script
1722 * might be accessible only to root.
1725 if (stat(prog, &sbuf) < 0 || !S_ISREG(sbuf.st_mode)
1726 || (sbuf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) == 0) {
1727 if (must_exist || errno != ENOENT)
1728 warn("Can't execute %s: %m", prog);
1734 error("Failed to create child process for %s: %m", prog);
1740 /* Leave the current location */
1741 (void) setsid(); /* No controlling tty. */
1742 (void) umask (S_IRWXG|S_IRWXO);
1743 (void) chdir ("/"); /* no current directory. */
1744 setuid(0); /* set real UID = root */
1747 /* Ensure that nothing of our device environment is inherited. */
1753 close (ttyfd); /* tty interface to the ppp device */
1754 if (real_ttyfd >= 0)
1757 /* Don't pass handles to the PPP device, even by accident. */
1758 new_fd = open (_PATH_DEVNULL, O_RDWR);
1761 dup2 (new_fd, 0); /* stdin <- /dev/null */
1764 dup2 (0, 1); /* stdout -> /dev/null */
1765 dup2 (0, 2); /* stderr -> /dev/null */
1769 /* Force the priority back to zero if pppd is running higher. */
1770 if (setpriority (PRIO_PROCESS, 0, 0) < 0)
1771 warn("can't reset priority to 0: %m");
1774 /* SysV recommends a second fork at this point. */
1776 /* run the program */
1777 execve(prog, args, script_env);
1778 if (must_exist || errno != ENOENT) {
1779 /* have to reopen the log, there's nowhere else
1780 for the message to go. */
1782 syslog(LOG_ERR, "Can't execute %s: %m", prog);
1789 dbglog("Script %s started (pid %d)", prog, pid);
1790 record_child(pid, prog, done, arg);
1797 * record_child - add a child process to the list for reap_kids
1801 record_child(pid, prog, done, arg)
1804 void (*done) __P((void *));
1807 struct subprocess *chp;
1811 chp = (struct subprocess *) malloc(sizeof(struct subprocess));
1813 warn("losing track of %s process", prog);
1819 chp->next = children;
1826 * reap_kids - get status from any dead child processes,
1827 * and log a message for abnormal terminations.
1834 struct subprocess *chp, **prevp;
1837 if (n_children == 0)
1839 while ((pid = waitpid(-1, &status, (waitfor? 0: WNOHANG))) != -1
1841 for (prevp = &children; (chp = *prevp) != NULL; prevp = &chp->next) {
1842 if (chp->pid == pid) {
1848 if (WIFSIGNALED(status)) {
1849 warn("Child process %s (pid %d) terminated with signal %d",
1850 (chp? chp->prog: "??"), pid, WTERMSIG(status));
1852 dbglog("Script %s finished (pid %d), status = 0x%x",
1853 (chp? chp->prog: "??"), pid, status);
1854 if (chp && chp->done)
1855 (*chp->done)(chp->arg);
1860 if (errno == ECHILD)
1863 error("Error waiting for child process: %m");
1870 * novm - log an error message saying we ran out of memory, and die.
1876 fatal("Virtual memory exhausted allocating %s\n", msg);
1880 * script_setenv - set an environment variable value to be used
1881 * for scripts that we run (e.g. ip-up, auth-up, etc.)
1884 script_setenv(var, value)
1887 size_t vl = strlen(var) + strlen(value) + 2;
1889 char *p, *newstring;
1891 newstring = (char *) malloc(vl);
1894 slprintf(newstring, vl, "%s=%s", var, value);
1896 /* check if this variable is already set */
1897 if (script_env != 0) {
1898 for (i = 0; (p = script_env[i]) != 0; ++i) {
1899 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1901 script_env[i] = newstring;
1906 /* no space allocated for script env. ptrs. yet */
1908 script_env = (char **) malloc(16 * sizeof(char *));
1909 if (script_env == 0)
1914 /* reallocate script_env with more space if needed */
1915 if (i + 1 >= s_env_nalloc) {
1917 char **newenv = (char **) realloc((void *)script_env,
1918 new_n * sizeof(char *));
1921 script_env = newenv;
1922 s_env_nalloc = new_n;
1925 script_env[i] = newstring;
1926 script_env[i+1] = 0;
1930 * script_unsetenv - remove a variable from the environment
1934 script_unsetenv(var)
1937 int vl = strlen(var);
1941 if (script_env == 0)
1943 for (i = 0; (p = script_env[i]) != 0; ++i) {
1944 if (strncmp(p, var, vl) == 0 && p[vl] == '=') {
1946 while ((script_env[i] = script_env[i+1]) != 0)
1954 * open_socket - establish a stream socket connection to the nominated
1961 char *sep, *endp = NULL;
1962 int sock, port = -1;
1964 struct hostent *hent;
1965 struct sockaddr_in sad;
1967 /* parse host:port and resolve host to an IP address */
1968 sep = strchr(dest, ':');
1970 port = strtol(sep+1, &endp, 10);
1971 if (port < 0 || endp == sep+1 || sep == dest) {
1972 error("Can't parse host:port for socket destination");
1976 host = inet_addr(dest);
1977 if (host == (u_int32_t) -1) {
1978 hent = gethostbyname(dest);
1980 error("%s: unknown host in socket option", dest);
1984 host = *(u_int32_t *)(hent->h_addr_list[0]);
1988 /* get a socket and connect it to the other end */
1989 sock = socket(PF_INET, SOCK_STREAM, 0);
1991 error("Can't create socket: %m");
1994 memset(&sad, 0, sizeof(sad));
1995 sad.sin_family = AF_INET;
1996 sad.sin_port = htons(port);
1997 sad.sin_addr.s_addr = host;
1998 if (connect(sock, &sad, sizeof(sad)) < 0) {
1999 error("Can't connect to %s: %m", dest);
2008 * start_charshunt - create a child process to run the character shunt.
2011 start_charshunt(ifd, ofd)
2018 error("Can't fork process for character shunt: %m");
2025 if (getuid() != uid)
2026 fatal("setuid failed");
2030 charshunt(ifd, ofd, record_file);
2033 charshunt_pid = cpid;
2037 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
2049 * charshunt - the character shunt, which passes characters between
2050 * the pty master side and the serial port (or stdin/stdout).
2051 * This runs as the user (not as root).
2052 * (We assume ofd >= ifd which is true the way this gets called. :-).
2055 charshunt(ifd, ofd, record_file)
2060 fd_set ready, writey;
2061 u_char *ibufp, *obufp;
2064 int pty_readable, stdin_readable;
2065 struct timeval lasttime;
2066 FILE *recordf = NULL;
2067 int ilevel, olevel, max_level;
2068 struct timeval levelt, tout, *top;
2071 * Reset signal handlers.
2073 signal(SIGHUP, SIG_IGN); /* Hangup */
2074 signal(SIGINT, SIG_DFL); /* Interrupt */
2075 signal(SIGTERM, SIG_DFL); /* Terminate */
2076 signal(SIGCHLD, SIG_DFL);
2077 signal(SIGUSR1, SIG_DFL);
2078 signal(SIGUSR2, SIG_DFL);
2079 signal(SIGABRT, SIG_DFL);
2080 signal(SIGALRM, SIG_DFL);
2081 signal(SIGFPE, SIG_DFL);
2082 signal(SIGILL, SIG_DFL);
2083 signal(SIGPIPE, SIG_DFL);
2084 signal(SIGQUIT, SIG_DFL);
2085 signal(SIGSEGV, SIG_DFL);
2087 signal(SIGBUS, SIG_DFL);
2090 signal(SIGEMT, SIG_DFL);
2093 signal(SIGPOLL, SIG_DFL);
2096 signal(SIGPROF, SIG_DFL);
2099 signal(SIGSYS, SIG_DFL);
2102 signal(SIGTRAP, SIG_DFL);
2105 signal(SIGVTALRM, SIG_DFL);
2108 signal(SIGXCPU, SIG_DFL);
2111 signal(SIGXFSZ, SIG_DFL);
2115 * Open the record file if required.
2117 if (record_file != NULL) {
2118 recordf = fopen(record_file, "a");
2119 if (recordf == NULL)
2120 error("Couldn't create record file %s: %m", record_file);
2123 /* set all the fds to non-blocking mode */
2124 flags = fcntl(pty_master, F_GETFL);
2126 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
2127 warn("couldn't set pty master to nonblock: %m");
2128 flags = fcntl(ifd, F_GETFL);
2130 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
2131 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
2133 flags = fcntl(ofd, F_GETFL);
2135 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
2136 warn("couldn't set stdout to nonblock: %m");
2140 ibufp = obufp = NULL;
2141 pty_readable = stdin_readable = 1;
2143 ilevel = olevel = 0;
2144 gettimeofday(&levelt, NULL);
2145 if (max_data_rate) {
2146 max_level = max_data_rate / 10;
2147 if (max_level < 100)
2150 max_level = sizeof(inpacket_buf) + 1;
2152 nfds = (ofd > pty_master? ofd: pty_master) + 1;
2153 if (recordf != NULL) {
2154 gettimeofday(&lasttime, NULL);
2155 putc(7, recordf); /* put start marker */
2156 putc(lasttime.tv_sec >> 24, recordf);
2157 putc(lasttime.tv_sec >> 16, recordf);
2158 putc(lasttime.tv_sec >> 8, recordf);
2159 putc(lasttime.tv_sec, recordf);
2160 lasttime.tv_usec = 0;
2163 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
2166 tout.tv_usec = 10000;
2170 if (ilevel >= max_level)
2173 FD_SET(pty_master, &writey);
2174 } else if (stdin_readable)
2175 FD_SET(ifd, &ready);
2177 if (olevel >= max_level)
2180 FD_SET(ofd, &writey);
2181 } else if (pty_readable)
2182 FD_SET(pty_master, &ready);
2183 if (select(nfds, &ready, &writey, NULL, top) < 0) {
2188 if (max_data_rate) {
2193 gettimeofday(&now, NULL);
2194 dt = (now.tv_sec - levelt.tv_sec
2195 + (now.tv_usec - levelt.tv_usec) / 1e6);
2196 nbt = (int)(dt * max_data_rate);
2197 ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
2198 olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
2201 ilevel = olevel = 0;
2202 if (FD_ISSET(ifd, &ready)) {
2203 ibufp = inpacket_buf;
2204 nibuf = read(ifd, ibufp, sizeof(inpacket_buf));
2205 if (nibuf < 0 && errno == EIO)
2208 if (!(errno == EINTR || errno == EAGAIN)) {
2209 error("Error reading standard input: %m");
2213 } else if (nibuf == 0) {
2214 /* end of file from stdin */
2216 /* do a 0-length write, hopefully this will generate
2217 an EOF (hangup) on the slave side. */
2218 write(pty_master, inpacket_buf, 0);
2220 if (!record_write(recordf, 4, NULL, 0, &lasttime))
2223 FD_SET(pty_master, &writey);
2225 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
2229 if (FD_ISSET(pty_master, &ready)) {
2230 obufp = outpacket_buf;
2231 nobuf = read(pty_master, obufp, sizeof(outpacket_buf));
2232 if (nobuf < 0 && errno == EIO)
2235 if (!(errno == EINTR || errno == EAGAIN)) {
2236 error("Error reading pseudo-tty master: %m");
2240 } else if (nobuf == 0) {
2241 /* end of file from the pty - slave side has closed */
2243 stdin_readable = 0; /* pty is not writable now */
2247 if (!record_write(recordf, 3, NULL, 0, &lasttime))
2250 FD_SET(ofd, &writey);
2252 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
2256 if (FD_ISSET(ofd, &writey)) {
2258 if (olevel + n > max_level)
2259 n = max_level - olevel;
2260 n = write(ofd, obufp, n);
2263 error("Error writing standard output: %m");
2274 if (FD_ISSET(pty_master, &writey)) {
2276 if (ilevel + n > max_level)
2277 n = max_level - ilevel;
2278 n = write(pty_master, ibufp, n);
2281 error("Error writing pseudo-tty master: %m");
2297 record_write(f, code, buf, nb, tp)
2307 gettimeofday(&now, NULL);
2308 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
2309 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
2313 putc(diff >> 24, f);
2314 putc(diff >> 16, f);
2327 fwrite(buf, nb, 1, f);
2331 error("Error writing record file: %m");