2 * tty.c - code for handling serial ports in pppd.
4 * Copyright (C) 2000-2002 Paul Mackerras. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in
15 * the documentation and/or other materials provided with the
18 * 3. The name(s) of the authors of this software must not be used to
19 * endorse or promote products derived from this software without
20 * prior written permission.
22 * 4. Redistributions of any form whatsoever must retain the following
24 * "This product includes software developed by Paul Mackerras
25 * <paulus@samba.org>".
27 * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
28 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
29 * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
30 * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
31 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
32 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
33 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
35 * Portions derived from main.c, which is:
37 * Copyright (c) 1984-2000 Carnegie Mellon University. All rights reserved.
39 * Redistribution and use in source and binary forms, with or without
40 * modification, are permitted provided that the following conditions
43 * 1. Redistributions of source code must retain the above copyright
44 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in
48 * the documentation and/or other materials provided with the
51 * 3. The name "Carnegie Mellon University" must not be used to
52 * endorse or promote products derived from this software without
53 * prior written permission. For permission or any legal
54 * details, please contact
55 * Office of Technology Transfer
56 * Carnegie Mellon University
58 * Pittsburgh, PA 15213-3890
59 * (412) 268-4387, fax: (412) 268-7395
60 * tech-transfer@andrew.cmu.edu
62 * 4. Redistributions of any form whatsoever must retain the following
64 * "This product includes software developed by Computing Services
65 * at Carnegie Mellon University (http://www.cmu.edu/computing/)."
67 * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
68 * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
69 * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
70 * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
71 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
72 * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
73 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
76 #define RCSID "$Id: tty.c,v 1.16 2004/10/28 00:16:37 paulus Exp $"
91 #include <sys/param.h>
92 #include <sys/types.h>
95 #include <sys/resource.h>
97 #include <sys/socket.h>
98 #include <netinet/in.h>
99 #include <arpa/inet.h>
105 void tty_process_extra_options __P((void));
106 void tty_check_options __P((void));
107 int connect_tty __P((void));
108 void disconnect_tty __P((void));
109 void tty_close_fds __P((void));
110 void cleanup_tty __P((void));
111 void tty_do_send_config __P((int, u_int32_t, int, int));
113 static int setdevname __P((char *, char **, int));
114 static int setspeed __P((char *, char **, int));
115 static int setxonxoff __P((char **));
116 static int setescape __P((char **));
117 static void printescape __P((option_t *, void (*)(void *, char *,...),void *));
118 static void finish_tty __P((void));
119 static int start_charshunt __P((int, int));
120 static void stop_charshunt __P((void *, int));
121 static void charshunt_done __P((void *));
122 static void charshunt __P((int, int, char *));
123 static int record_write __P((FILE *, int code, u_char *buf, int nb,
125 static int open_socket __P((char *));
126 static void maybe_relock __P((void *, int));
128 static int pty_master; /* fd for master side of pty */
129 static int pty_slave; /* fd for slave side of pty */
130 static int real_ttyfd; /* fd for actual serial port (not pty) */
131 static int ttyfd; /* Serial port file descriptor */
132 static char speed_str[16]; /* Serial port speed as string */
134 mode_t tty_mode = (mode_t)-1; /* Original access permissions to tty */
135 int baud_rate; /* Actual bits/second for serial device */
136 char *callback_script; /* script for doing callback */
137 int charshunt_pid; /* Process ID for charshunt */
138 int locked; /* lock() has succeeded */
139 struct stat devstat; /* result of stat() on devnam */
141 /* option variables */
142 int crtscts = 0; /* Use hardware flow control */
143 bool modem = 1; /* Use modem control lines */
144 int inspeed = 0; /* Input/Output speed requested */
145 bool lockflag = 0; /* Create lock file to lock the serial dev */
146 char *initializer = NULL; /* Script to initialize physical link */
147 char *connect_script = NULL; /* Script to establish physical link */
148 char *disconnect_script = NULL; /* Script to disestablish physical link */
149 char *welcomer = NULL; /* Script to run after phys link estab. */
150 char *ptycommand = NULL; /* Command to run on other side of pty */
151 bool notty = 0; /* Stdin/out is not a tty */
152 char *record_file = NULL; /* File to record chars sent/received */
153 int max_data_rate; /* max bytes/sec through charshunt */
154 bool sync_serial = 0; /* Device is synchronous serial device */
155 char *pty_socket = NULL; /* Socket to connect to pty */
156 int using_pty = 0; /* we're allocating a pty as the device */
159 extern int kill_link;
162 extern int privopen; /* don't lock, open device as root */
164 u_int32_t xmit_accm[8]; /* extended transmit ACCM */
166 /* option descriptors */
167 option_t tty_options[] = {
168 /* device name must be first, or change connect_tty() below! */
169 { "device name", o_wild, (void *) &setdevname,
170 "Serial port device name",
171 OPT_DEVNAM | OPT_PRIVFIX | OPT_NOARG | OPT_A2STRVAL | OPT_STATIC,
174 { "tty speed", o_wild, (void *) &setspeed,
175 "Baud rate for serial port",
176 OPT_PRIO | OPT_NOARG | OPT_A2STRVAL | OPT_STATIC, speed_str },
178 { "lock", o_bool, &lockflag,
179 "Lock serial device with UUCP-style lock file", OPT_PRIO | 1 },
180 { "nolock", o_bool, &lockflag,
181 "Don't lock serial device", OPT_PRIOSUB | OPT_PRIV },
183 { "init", o_string, &initializer,
184 "A program to initialize the device", OPT_PRIO | OPT_PRIVFIX },
186 { "connect", o_string, &connect_script,
187 "A program to set up a connection", OPT_PRIO | OPT_PRIVFIX },
189 { "disconnect", o_string, &disconnect_script,
190 "Program to disconnect serial device", OPT_PRIO | OPT_PRIVFIX },
192 { "welcome", o_string, &welcomer,
193 "Script to welcome client", OPT_PRIO | OPT_PRIVFIX },
195 { "pty", o_string, &ptycommand,
196 "Script to run on pseudo-tty master side",
197 OPT_PRIO | OPT_PRIVFIX | OPT_DEVNAM },
199 { "notty", o_bool, ¬ty,
200 "Input/output is not a tty", OPT_DEVNAM | 1 },
202 { "socket", o_string, &pty_socket,
203 "Send and receive over socket, arg is host:port",
204 OPT_PRIO | OPT_DEVNAM },
206 { "record", o_string, &record_file,
207 "Record characters sent/received to file", OPT_PRIO },
209 { "crtscts", o_int, &crtscts,
210 "Set hardware (RTS/CTS) flow control",
211 OPT_PRIO | OPT_NOARG | OPT_VAL(1) },
212 { "cdtrcts", o_int, &crtscts,
213 "Set alternate hardware (DTR/CTS) flow control",
214 OPT_PRIOSUB | OPT_NOARG | OPT_VAL(2) },
215 { "nocrtscts", o_int, &crtscts,
216 "Disable hardware flow control",
217 OPT_PRIOSUB | OPT_NOARG | OPT_VAL(-1) },
218 { "-crtscts", o_int, &crtscts,
219 "Disable hardware flow control",
220 OPT_PRIOSUB | OPT_ALIAS | OPT_NOARG | OPT_VAL(-1) },
221 { "nocdtrcts", o_int, &crtscts,
222 "Disable hardware flow control",
223 OPT_PRIOSUB | OPT_ALIAS | OPT_NOARG | OPT_VAL(-1) },
224 { "xonxoff", o_special_noarg, (void *)setxonxoff,
225 "Set software (XON/XOFF) flow control", OPT_PRIOSUB },
227 { "modem", o_bool, &modem,
228 "Use modem control lines", OPT_PRIO | 1 },
229 { "local", o_bool, &modem,
230 "Don't use modem control lines", OPT_PRIOSUB | 0 },
232 { "sync", o_bool, &sync_serial,
233 "Use synchronous HDLC serial encoding", 1 },
235 { "datarate", o_int, &max_data_rate,
236 "Maximum data rate in bytes/sec (with pty, notty or record option)",
239 { "escape", o_special, (void *)setescape,
240 "List of character codes to escape on transmission",
241 OPT_A2PRINTER, (void *)printescape },
247 struct channel tty_channel = {
249 &tty_process_extra_options,
254 &tty_disestablish_ppp,
262 * setspeed - Set the serial port baud rate.
263 * If doit is 0, the call is to check whether this option is
264 * potentially a speed value.
267 setspeed(arg, argv, doit)
275 spd = strtol(arg, &ptr, 0);
276 if (ptr == arg || *ptr != 0 || spd == 0)
280 slprintf(speed_str, sizeof(speed_str), "%d", spd);
287 * setdevname - Set the device name.
288 * If doit is 0, the call is to check whether this option is
289 * potentially a device name.
292 setdevname(cp, argv, doit)
298 char dev[MAXPATHLEN];
304 strlcpy(dev, "/dev/", sizeof(dev));
305 strlcat(dev, cp, sizeof(dev));
310 * Check if there is a character device by this name.
312 if (stat(cp, &statbuf) < 0) {
314 return errno != ENOENT;
315 option_error("Couldn't stat %s: %m", cp);
318 if (!S_ISCHR(statbuf.st_mode)) {
320 option_error("%s is not a character device", cp);
325 strlcpy(devnam, cp, sizeof(devnam));
337 lcp_wantoptions[0].asyncmap |= 0x000A0000; /* escape ^S and ^Q */
338 lcp_wantoptions[0].neg_asyncmap = 1;
345 * setescape - add chars to the set we escape on transmission.
357 n = strtol(p, &endp, 16);
359 option_error("escape parameter contains invalid hex number '%s'",
364 if (n < 0 || n == 0x5E || n > 0xFF) {
365 option_error("can't escape character 0x%x", n);
368 xmit_accm[n >> 5] |= 1 << (n & 0x1F);
369 while (*p == ',' || *p == ' ')
372 lcp_allowoptions[0].asyncmap = xmit_accm[0];
377 printescape(opt, printer, arg)
379 void (*printer) __P((void *, char *, ...));
385 for (n = 0; n < 256; ++n) {
387 n += 2; /* skip 7d, 7e */
388 if (xmit_accm[n >> 5] & (1 << (n & 0x1f))) {
393 printer(arg, "%x", n);
397 printer(arg, "oops # nothing escaped");
401 * tty_init - do various tty-related initializations.
405 add_notifier(&pidchange, maybe_relock, 0);
406 the_channel = &tty_channel;
407 xmit_accm[3] = 0x60000000;
411 * tty_process_extra_options - work out which tty device we are using
412 * and read its options file.
414 void tty_process_extra_options()
416 using_pty = notty || ptycommand != NULL || pty_socket != NULL;
419 if (default_device) {
421 if (!isatty(0) || (p = ttyname(0)) == NULL) {
422 option_error("no device specified and stdin is not a tty");
423 exit(EXIT_OPTION_ERROR);
425 strlcpy(devnam, p, sizeof(devnam));
426 if (stat(devnam, &devstat) < 0)
427 fatal("Couldn't stat default device %s: %m", devnam);
432 * Parse the tty options file.
433 * The per-tty options file should not change
434 * ptycommand, pty_socket, notty or devnam.
435 * options_for_tty doesn't override options set on the command line,
436 * except for some privileged options.
438 if (!options_for_tty())
439 exit(EXIT_OPTION_ERROR);
443 * tty_check_options - do consistency checks on the options we were given.
451 if (demand && connect_script == 0) {
452 option_error("connect script is required for demand-dialling\n");
453 exit(EXIT_OPTION_ERROR);
455 /* default holdoff to 0 if no connect script has been given */
456 if (connect_script == 0 && !holdoff_specified)
460 if (!default_device) {
461 option_error("%s option precludes specifying device name",
462 notty? "notty": "pty");
463 exit(EXIT_OPTION_ERROR);
465 if (ptycommand != NULL && notty) {
466 option_error("pty option is incompatible with notty option");
467 exit(EXIT_OPTION_ERROR);
469 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
470 option_error("socket option is incompatible with pty and notty");
471 exit(EXIT_OPTION_ERROR);
473 default_device = notty;
476 if (notty && log_to_fd <= 1)
480 * If the user has specified a device which is the same as
481 * the one on stdin, pretend they didn't specify any.
482 * If the device is already open read/write on stdin,
483 * we assume we don't need to lock it, and we can open it
486 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
487 && statbuf.st_rdev == devstat.st_rdev) {
489 fdflags = fcntl(0, F_GETFL);
490 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
498 * Don't send log messages to the serial port, it tends to
499 * confuse the peer. :-)
501 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
502 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
507 * connect_tty - get the serial port ready to start doing PPP.
508 * That is, open the serial port, set its speed and mode, and run
509 * the connector and/or welcomer.
521 * Get a pty master/slave pair if the pty, notty, socket,
522 * or record options were specified.
524 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
528 if (using_pty || record_file != NULL) {
529 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
530 error("Couldn't allocate pseudo-tty");
531 status = EXIT_FATAL_ERROR;
534 set_up_tty(pty_slave, 1);
538 * Lock the device if we've been asked to.
540 status = EXIT_LOCK_FAILED;
541 if (lockflag && !privopen) {
542 if (lock(devnam) < 0)
548 * Open the serial device and set it up to be the ppp interface.
549 * First we open it in non-blocking mode so we can set the
550 * various termios flags appropriately. If we aren't dialling
551 * out and we want to use the modem lines, we reopen it later
552 * in order to wait for the carrier detect signal from the modem.
556 connector = doing_callback? callback_script: connect_script;
557 if (devnam[0] != 0) {
559 /* If the user specified the device name, become the
560 user before opening it. */
563 prio = privopen? OPRIO_ROOT: tty_options[0].priority;
564 if (prio < OPRIO_ROOT)
566 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
568 if (prio < OPRIO_ROOT)
574 error("Failed to open %s: %m", devnam);
575 status = EXIT_OPEN_FAILED;
577 if (!persist || err != EINTR)
581 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
582 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
583 warn("Couldn't reset non-blocking mode on device: %m");
587 * Linux 2.4 and above blocks normal writes to the tty
588 * when it is in PPP line discipline, so this isn't needed.
591 * Do the equivalent of `mesg n' to stop broadcast messages.
593 if (fstat(ttyfd, &statbuf) < 0
594 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
595 warn("Couldn't restrict write permissions to %s: %m", devnam);
597 tty_mode = statbuf.st_mode;
598 #endif /* __linux__ */
601 * Set line speed, flow control, etc.
602 * If we have a non-null connection or initializer script,
603 * on most systems we set CLOCAL for now so that we can talk
604 * to the modem before carrier comes up. But this has the
605 * side effect that we might miss it if CD drops before we
606 * get to clear CLOCAL below. On systems where we can talk
607 * successfully to the modem with CLOCAL clear and CD down,
608 * we could clear CLOCAL at this point.
610 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
611 || initializer != NULL));
615 * If the pty, socket, notty and/or record option was specified,
616 * start up the character shunt now.
618 status = EXIT_PTYCMD_FAILED;
619 if (ptycommand != NULL) {
620 if (record_file != NULL) {
621 int ipipe[2], opipe[2], ok;
623 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
624 fatal("Couldn't create pipes for record option: %m");
626 /* don't leak these to the ptycommand */
627 (void) fcntl(ipipe[0], F_SETFD, FD_CLOEXEC);
628 (void) fcntl(opipe[1], F_SETFD, FD_CLOEXEC);
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;
680 info("Serial port initialized.");
683 if (connector && connector[0]) {
684 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
685 error("Connect script failed");
686 status = EXIT_CONNECT_FAILED;
693 info("Serial connection established.");
696 /* set line speed, flow control, etc.;
697 clear CLOCAL if modem option */
698 if (real_ttyfd != -1)
699 set_up_tty(real_ttyfd, 0);
701 if (doing_callback == CALLBACK_DIALIN)
705 /* reopen tty if necessary to wait for carrier */
706 if (connector == NULL && modem && devnam[0] != 0) {
709 if ((i = open(devnam, O_RDWR)) >= 0)
711 if (errno != EINTR) {
712 error("Failed to reopen %s: %m", devnam);
713 status = EXIT_OPEN_FAILED;
715 if (!persist || errno != EINTR || hungup || kill_link)
721 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
722 script_setenv("SPEED", numbuf, 0);
724 /* run welcome script, if any */
725 if (welcomer && welcomer[0]) {
726 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
727 warn("Welcome script failed");
731 * If we are initiating this connection, wait for a short
732 * time for something from the peer. This can avoid bouncing
733 * our packets off his tty before he has it set up.
735 if (connector != NULL || ptycommand != NULL)
736 listen_time = connect_delay;
742 void disconnect_tty()
744 if (disconnect_script == NULL || hungup)
747 set_up_tty(real_ttyfd, 1);
748 if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
749 warn("disconnect script failed");
751 info("Serial link disconnected.");
761 if (real_ttyfd >= 0) {
765 /* N.B. ttyfd will == either pty_slave or real_ttyfd */
780 * tty_do_send_config - set transmit-side PPP configuration.
781 * We set the extended transmit ACCM here as well.
784 tty_do_send_config(mtu, accm, pcomp, accomp)
789 tty_set_xaccm(xmit_accm);
790 tty_send_config(mtu, accm, pcomp, accomp);
794 * finish_tty - restore the terminal device to its original settings
799 /* drop dtr to hang up */
800 if (!default_device && modem) {
801 setdtr(real_ttyfd, 0);
803 * This sleep is in case the serial port has CLOCAL set by default,
804 * and consequently will reassert DTR when we close the device.
809 restore_tty(real_ttyfd);
812 if (tty_mode != (mode_t) -1) {
813 if (fchmod(real_ttyfd, tty_mode) != 0)
814 error("Couldn't restore tty permissions");
816 #endif /* __linux__ */
823 * maybe_relock - our PID has changed, maybe update the lock file.
826 maybe_relock(arg, pid)
835 * open_socket - establish a stream socket connection to the nominated
842 char *sep, *endp = NULL;
845 struct hostent *hent;
846 struct sockaddr_in sad;
848 /* parse host:port and resolve host to an IP address */
849 sep = strchr(dest, ':');
851 port = strtol(sep+1, &endp, 10);
852 if (port < 0 || endp == sep+1 || sep == dest) {
853 error("Can't parse host:port for socket destination");
857 host = inet_addr(dest);
858 if (host == (u_int32_t) -1) {
859 hent = gethostbyname(dest);
861 error("%s: unknown host in socket option", dest);
865 host = *(u_int32_t *)(hent->h_addr_list[0]);
869 /* get a socket and connect it to the other end */
870 sock = socket(PF_INET, SOCK_STREAM, 0);
872 error("Can't create socket: %m");
875 memset(&sad, 0, sizeof(sad));
876 sad.sin_family = AF_INET;
877 sad.sin_port = htons(port);
878 sad.sin_addr.s_addr = host;
879 if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
880 error("Can't connect to %s: %m", dest);
890 * start_charshunt - create a child process to run the character shunt.
893 start_charshunt(ifd, ofd)
900 error("Can't fork process for character shunt: %m");
908 fatal("setuid failed");
912 charshunt(ifd, ofd, record_file);
915 charshunt_pid = cpid;
916 add_notifier(&sigreceived, stop_charshunt, 0);
920 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
932 stop_charshunt(arg, sig)
937 kill(charshunt_pid, (sig == SIGINT? sig: SIGTERM));
941 * charshunt - the character shunt, which passes characters between
942 * the pty master side and the serial port (or stdin/stdout).
943 * This runs as the user (not as root).
944 * (We assume ofd >= ifd which is true the way this gets called. :-).
947 charshunt(ifd, ofd, record_file)
952 fd_set ready, writey;
953 u_char *ibufp, *obufp;
956 int pty_readable, stdin_readable;
957 struct timeval lasttime;
958 FILE *recordf = NULL;
959 int ilevel, olevel, max_level;
960 struct timeval levelt, tout, *top;
961 extern u_char inpacket_buf[];
964 * Reset signal handlers.
966 signal(SIGHUP, SIG_IGN); /* Hangup */
967 signal(SIGINT, SIG_DFL); /* Interrupt */
968 signal(SIGTERM, SIG_DFL); /* Terminate */
969 signal(SIGCHLD, SIG_DFL);
970 signal(SIGUSR1, SIG_DFL);
971 signal(SIGUSR2, SIG_DFL);
972 signal(SIGABRT, SIG_DFL);
973 signal(SIGALRM, SIG_DFL);
974 signal(SIGFPE, SIG_DFL);
975 signal(SIGILL, SIG_DFL);
976 signal(SIGPIPE, SIG_DFL);
977 signal(SIGQUIT, SIG_DFL);
978 signal(SIGSEGV, SIG_DFL);
980 signal(SIGBUS, SIG_DFL);
983 signal(SIGEMT, SIG_DFL);
986 signal(SIGPOLL, SIG_DFL);
989 signal(SIGPROF, SIG_DFL);
992 signal(SIGSYS, SIG_DFL);
995 signal(SIGTRAP, SIG_DFL);
998 signal(SIGVTALRM, SIG_DFL);
1001 signal(SIGXCPU, SIG_DFL);
1004 signal(SIGXFSZ, SIG_DFL);
1008 * Check that the fds won't overrun the fd_sets
1010 if (ifd >= FD_SETSIZE || ofd >= FD_SETSIZE || pty_master >= FD_SETSIZE)
1011 fatal("internal error: file descriptor too large (%d, %d, %d)",
1012 ifd, ofd, pty_master);
1015 * Open the record file if required.
1017 if (record_file != NULL) {
1018 recordf = fopen(record_file, "a");
1019 if (recordf == NULL)
1020 error("Couldn't create record file %s: %m", record_file);
1023 /* set all the fds to non-blocking mode */
1024 flags = fcntl(pty_master, F_GETFL);
1026 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1027 warn("couldn't set pty master to nonblock: %m");
1028 flags = fcntl(ifd, F_GETFL);
1030 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1031 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1033 flags = fcntl(ofd, F_GETFL);
1035 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1036 warn("couldn't set stdout to nonblock: %m");
1040 ibufp = obufp = NULL;
1041 pty_readable = stdin_readable = 1;
1043 ilevel = olevel = 0;
1044 gettimeofday(&levelt, NULL);
1045 if (max_data_rate) {
1046 max_level = max_data_rate / 10;
1047 if (max_level < 100)
1050 max_level = PPP_MRU + PPP_HDRLEN + 1;
1052 nfds = (ofd > pty_master? ofd: pty_master) + 1;
1053 if (recordf != NULL) {
1054 gettimeofday(&lasttime, NULL);
1055 putc(7, recordf); /* put start marker */
1056 putc(lasttime.tv_sec >> 24, recordf);
1057 putc(lasttime.tv_sec >> 16, recordf);
1058 putc(lasttime.tv_sec >> 8, recordf);
1059 putc(lasttime.tv_sec, recordf);
1060 lasttime.tv_usec = 0;
1063 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1066 tout.tv_usec = 10000;
1070 if (ilevel >= max_level)
1073 FD_SET(pty_master, &writey);
1074 } else if (stdin_readable)
1075 FD_SET(ifd, &ready);
1077 if (olevel >= max_level)
1080 FD_SET(ofd, &writey);
1081 } else if (pty_readable)
1082 FD_SET(pty_master, &ready);
1083 if (select(nfds, &ready, &writey, NULL, top) < 0) {
1088 if (max_data_rate) {
1093 gettimeofday(&now, NULL);
1094 dt = (now.tv_sec - levelt.tv_sec
1095 + (now.tv_usec - levelt.tv_usec) / 1e6);
1096 nbt = (int)(dt * max_data_rate);
1097 ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
1098 olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
1101 ilevel = olevel = 0;
1102 if (FD_ISSET(ifd, &ready)) {
1103 ibufp = inpacket_buf;
1104 nibuf = read(ifd, ibufp, PPP_MRU + PPP_HDRLEN);
1105 if (nibuf < 0 && errno == EIO)
1108 if (!(errno == EINTR || errno == EAGAIN)) {
1109 error("Error reading standard input: %m");
1113 } else if (nibuf == 0) {
1114 /* end of file from stdin */
1116 /* do a 0-length write, hopefully this will generate
1117 an EOF (hangup) on the slave side. */
1118 write(pty_master, inpacket_buf, 0);
1120 if (!record_write(recordf, 4, NULL, 0, &lasttime))
1123 FD_SET(pty_master, &writey);
1125 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
1129 if (FD_ISSET(pty_master, &ready)) {
1130 obufp = outpacket_buf;
1131 nobuf = read(pty_master, obufp, PPP_MRU + PPP_HDRLEN);
1132 if (nobuf < 0 && errno == EIO)
1135 if (!(errno == EINTR || errno == EAGAIN)) {
1136 error("Error reading pseudo-tty master: %m");
1140 } else if (nobuf == 0) {
1141 /* end of file from the pty - slave side has closed */
1143 stdin_readable = 0; /* pty is not writable now */
1147 if (!record_write(recordf, 3, NULL, 0, &lasttime))
1150 FD_SET(ofd, &writey);
1152 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
1156 if (FD_ISSET(ofd, &writey)) {
1158 if (olevel + n > max_level)
1159 n = max_level - olevel;
1160 n = write(ofd, obufp, n);
1165 } else if (errno != EAGAIN && errno != EINTR) {
1166 error("Error writing standard output: %m");
1175 if (FD_ISSET(pty_master, &writey)) {
1177 if (ilevel + n > max_level)
1178 n = max_level - ilevel;
1179 n = write(pty_master, ibufp, n);
1184 } else if (errno != EAGAIN && errno != EINTR) {
1185 error("Error writing pseudo-tty master: %m");
1199 record_write(f, code, buf, nb, tp)
1209 gettimeofday(&now, NULL);
1210 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
1211 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
1215 putc(diff >> 24, f);
1216 putc(diff >> 16, f);
1229 fwrite(buf, nb, 1, f);
1233 error("Error writing record file: %m");