2 * tty.c - code for handling serial ports in pppd.
4 * Copyright (C) 2000 Paul Mackerras.
7 * Portions Copyright (c) 1989 Carnegie Mellon University.
10 * Redistribution and use in source and binary forms are permitted
11 * provided that the above copyright notice and this paragraph are
12 * duplicated in all such forms and that any documentation,
13 * advertising materials, and other materials related to such
14 * distribution and use acknowledge that the software was developed
15 * by Carnegie Mellon University. The name of the
16 * University may not be used to endorse or promote products derived
17 * from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
20 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
23 #define RCSID "$Id: tty.c,v 1.2 2000/07/06 11:17:03 paulus Exp $"
38 #include <sys/param.h>
39 #include <sys/types.h>
42 #include <sys/resource.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
52 static int setxonxoff __P((char **));
53 static void finish_tty __P((void));
54 static int start_charshunt __P((int, int));
55 static void stop_charshunt __P((void *, int));
56 static void charshunt_done __P((void *));
57 static void charshunt __P((int, int, char *));
58 static int record_write __P((FILE *, int code, u_char *buf, int nb,
60 static int open_socket __P((char *));
61 static void maybe_relock __P((void *, int));
63 static int pty_master; /* fd for master side of pty */
64 static int pty_slave; /* fd for slave side of pty */
65 static int real_ttyfd; /* fd for actual serial port (not pty) */
66 static int ttyfd; /* Serial port file descriptor */
68 mode_t tty_mode = (mode_t)-1; /* Original access permissions to tty */
69 int baud_rate; /* Actual bits/second for serial device */
70 char *callback_script; /* script for doing callback */
71 int charshunt_pid; /* Process ID for charshunt */
72 int locked; /* lock() has succeeded */
73 struct stat devstat; /* result of stat() on devnam */
75 /* option variables */
76 int crtscts = 0; /* Use hardware flow control */
77 bool modem = 1; /* Use modem control lines */
78 int inspeed = 0; /* Input/Output speed requested */
79 bool lockflag = 0; /* Create lock file to lock the serial dev */
80 char *initializer = NULL; /* Script to initialize physical link */
81 char *connect_script = NULL; /* Script to establish physical link */
82 char *disconnect_script = NULL; /* Script to disestablish physical link */
83 char *welcomer = NULL; /* Script to run after phys link estab. */
84 char *ptycommand = NULL; /* Command to run on other side of pty */
85 bool notty = 0; /* Stdin/out is not a tty */
86 char *record_file = NULL; /* File to record chars sent/received */
87 int max_data_rate; /* max bytes/sec through charshunt */
88 bool sync_serial = 0; /* Device is synchronous serial device */
89 char *pty_socket = NULL; /* Socket to connect to pty */
90 int using_pty = 0; /* we're allocating a pty as the device */
96 extern int privopen; /* don't lock, open device as root */
98 /* option descriptors */
99 option_t tty_options[] = {
100 { "lock", o_bool, &lockflag,
101 "Lock serial device with UUCP-style lock file", 1 },
102 { "nolock", o_bool, &lockflag,
103 "Don't lock serial device", OPT_PRIV },
104 { "init", o_string, &initializer,
105 "A program to initialize the device",
106 OPT_A2INFO | OPT_PRIVFIX, &initializer_info },
107 { "connect", o_string, &connect_script,
108 "A program to set up a connection",
109 OPT_A2INFO | OPT_PRIVFIX, &connect_script_info },
110 { "disconnect", o_string, &disconnect_script,
111 "Program to disconnect serial device",
112 OPT_A2INFO | OPT_PRIVFIX, &disconnect_script_info },
113 { "welcome", o_string, &welcomer,
114 "Script to welcome client",
115 OPT_A2INFO | OPT_PRIVFIX, &welcomer_info },
116 { "pty", o_string, &ptycommand,
117 "Script to run on pseudo-tty master side",
118 OPT_A2INFO | OPT_PRIVFIX | OPT_DEVNAM, &ptycommand_info },
119 { "notty", o_bool, ¬ty,
120 "Input/output is not a tty", OPT_DEVNAM | 1 },
121 { "socket", o_string, &pty_socket,
122 "Send and receive over socket, arg is host:port", OPT_DEVNAM },
123 { "record", o_string, &record_file,
124 "Record characters sent/received to file" },
125 { "crtscts", o_int, &crtscts,
126 "Set hardware (RTS/CTS) flow control", OPT_NOARG|OPT_VAL(1) },
127 { "nocrtscts", o_int, &crtscts,
128 "Disable hardware flow control", OPT_NOARG|OPT_VAL(-1) },
129 { "-crtscts", o_int, &crtscts,
130 "Disable hardware flow control", OPT_NOARG|OPT_VAL(-1) },
131 { "cdtrcts", o_int, &crtscts,
132 "Set alternate hardware (DTR/CTS) flow control", OPT_NOARG|OPT_VAL(2) },
133 { "nocdtrcts", o_int, &crtscts,
134 "Disable hardware flow control", OPT_NOARG|OPT_VAL(-1) },
135 { "xonxoff", o_special_noarg, (void *)setxonxoff,
136 "Set software (XON/XOFF) flow control" },
137 { "modem", o_bool, &modem,
138 "Use modem control lines", 1 },
139 { "local", o_bool, &modem,
140 "Don't use modem control lines" },
141 { "sync", o_bool, &sync_serial,
142 "Use synchronous HDLC serial encoding", 1 },
143 { "datarate", o_int, &max_data_rate,
144 "Maximum data rate in bytes/sec (with pty, notty or record option)" },
152 lcp_wantoptions[0].asyncmap |= 0x000A0000; /* escape ^S and ^Q */
153 lcp_wantoptions[0].neg_asyncmap = 1;
160 * tty_init - do various tty-related initializations.
164 add_notifier(&pidchange, maybe_relock, 0);
165 add_options(tty_options);
169 * tty_device_check - work out which tty device we are using
170 * and read its options file.
172 void tty_device_check()
174 using_pty = notty || ptycommand != NULL || pty_socket != NULL;
177 if (default_device) {
179 if (!isatty(0) || (p = ttyname(0)) == NULL) {
180 option_error("no device specified and stdin is not a tty");
181 exit(EXIT_OPTION_ERROR);
183 strlcpy(devnam, p, sizeof(devnam));
184 if (stat(devnam, &devstat) < 0)
185 fatal("Couldn't stat default device %s: %m", devnam);
190 * Parse the tty options file.
191 * The per-tty options file should not change
192 * ptycommand, pty_socket, notty or devnam.
193 * options_for_tty doesn't override options set on the command line,
194 * except for some privileged options.
196 if (!options_for_tty())
197 exit(EXIT_OPTION_ERROR);
201 * tty_check_options - do consistency checks on the options we were given.
209 if (demand && connect_script == 0) {
210 option_error("connect script is required for demand-dialling\n");
211 exit(EXIT_OPTION_ERROR);
213 /* default holdoff to 0 if no connect script has been given */
214 if (connect_script == 0 && !holdoff_specified)
218 if (!default_device) {
219 option_error("%s option precludes specifying device name",
220 notty? "notty": "pty");
221 exit(EXIT_OPTION_ERROR);
223 if (ptycommand != NULL && notty) {
224 option_error("pty option is incompatible with notty option");
225 exit(EXIT_OPTION_ERROR);
227 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
228 option_error("socket option is incompatible with pty and notty");
229 exit(EXIT_OPTION_ERROR);
231 default_device = notty;
234 if (notty && log_to_fd <= 1)
238 * If the user has specified a device which is the same as
239 * the one on stdin, pretend they didn't specify any.
240 * If the device is already open read/write on stdin,
241 * we assume we don't need to lock it, and we can open it
244 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
245 && statbuf.st_rdev == devstat.st_rdev) {
247 fdflags = fcntl(0, F_GETFL);
248 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
256 * Don't send log messages to the serial port, it tends to
257 * confuse the peer. :-)
259 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
260 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
265 * connect_tty - get the serial port ready to start doing PPP.
266 * That is, open the serial port, set its speed and mode, and run
267 * the connector and/or welcomer.
277 * Get a pty master/slave pair if the pty, notty, socket,
278 * or record options were specified.
280 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
284 if (using_pty || record_file != NULL) {
285 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
286 error("Couldn't allocate pseudo-tty");
287 status = EXIT_FATAL_ERROR;
290 set_up_tty(pty_slave, 1);
294 * Lock the device if we've been asked to.
296 status = EXIT_LOCK_FAILED;
297 if (lockflag && !privopen) {
298 if (lock(devnam) < 0)
304 * Open the serial device and set it up to be the ppp interface.
305 * First we open it in non-blocking mode so we can set the
306 * various termios flags appropriately. If we aren't dialling
307 * out and we want to use the modem lines, we reopen it later
308 * in order to wait for the carrier detect signal from the modem.
312 connector = doing_callback? callback_script: connect_script;
313 if (devnam[0] != 0) {
315 /* If the user specified the device name, become the
316 user before opening it. */
318 if (!devnam_info.priv && !privopen)
320 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
322 if (!devnam_info.priv && !privopen)
328 error("Failed to open %s: %m", devnam);
329 status = EXIT_OPEN_FAILED;
331 if (!persist || err != EINTR)
334 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
335 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
336 warn("Couldn't reset non-blocking mode on device: %m");
339 * Do the equivalent of `mesg n' to stop broadcast messages.
341 if (fstat(ttyfd, &statbuf) < 0
342 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
343 warn("Couldn't restrict write permissions to %s: %m", devnam);
345 tty_mode = statbuf.st_mode;
348 * Set line speed, flow control, etc.
349 * If we have a non-null connection or initializer script,
350 * on most systems we set CLOCAL for now so that we can talk
351 * to the modem before carrier comes up. But this has the
352 * side effect that we might miss it if CD drops before we
353 * get to clear CLOCAL below. On systems where we can talk
354 * successfully to the modem with CLOCAL clear and CD down,
355 * we could clear CLOCAL at this point.
357 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
358 || initializer != NULL));
363 * If the pty, socket, notty and/or record option was specified,
364 * start up the character shunt now.
366 status = EXIT_PTYCMD_FAILED;
367 if (ptycommand != NULL) {
368 if (record_file != NULL) {
369 int ipipe[2], opipe[2], ok;
371 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
372 fatal("Couldn't create pipes for record option: %m");
373 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
374 && start_charshunt(ipipe[0], opipe[1]);
382 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
388 } else if (pty_socket != NULL) {
389 int fd = open_socket(pty_socket);
392 if (!start_charshunt(fd, fd))
395 if (!start_charshunt(0, 1))
397 } else if (record_file != NULL) {
398 if (!start_charshunt(ttyfd, ttyfd))
402 /* run connection script */
403 if ((connector && connector[0]) || initializer) {
404 if (real_ttyfd != -1) {
405 /* XXX do this if doing_callback == CALLBACK_DIALIN? */
406 if (!default_device && modem) {
407 setdtr(real_ttyfd, 0); /* in case modem is off hook */
409 setdtr(real_ttyfd, 1);
413 if (initializer && initializer[0]) {
414 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
415 error("Initializer script failed");
416 status = EXIT_INIT_FAILED;
423 info("Serial port initialized.");
426 if (connector && connector[0]) {
427 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
428 error("Connect script failed");
429 status = EXIT_CONNECT_FAILED;
436 info("Serial connection established.");
439 /* set line speed, flow control, etc.;
440 clear CLOCAL if modem option */
441 if (real_ttyfd != -1)
442 set_up_tty(real_ttyfd, 0);
444 if (doing_callback == CALLBACK_DIALIN)
448 /* reopen tty if necessary to wait for carrier */
449 if (connector == NULL && modem && devnam[0] != 0) {
452 if ((i = open(devnam, O_RDWR)) >= 0)
454 if (errno != EINTR) {
455 error("Failed to reopen %s: %m", devnam);
456 status = EXIT_OPEN_FAILED;
458 if (!persist || errno != EINTR || hungup || kill_link)
464 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
465 script_setenv("SPEED", numbuf, 0);
467 /* run welcome script, if any */
468 if (welcomer && welcomer[0]) {
469 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
470 warn("Welcome script failed");
473 if (connector != NULL || ptycommand != NULL)
474 listen_time = connect_delay;
480 void disconnect_tty()
482 if (disconnect_script == NULL || hungup)
485 set_up_tty(real_ttyfd, 1);
486 if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
487 warn("disconnect script failed");
489 info("Serial link disconnected.");
499 if (real_ttyfd >= 0) {
503 /* N.B. ttyfd will == either pty_slave or real_ttyfd */
518 * finish_tty - restore the terminal device to its original settings
523 /* drop dtr to hang up */
524 if (!default_device && modem) {
525 setdtr(real_ttyfd, 0);
527 * This sleep is in case the serial port has CLOCAL set by default,
528 * and consequently will reassert DTR when we close the device.
533 restore_tty(real_ttyfd);
535 if (tty_mode != (mode_t) -1) {
536 if (fchmod(real_ttyfd, tty_mode) != 0) {
537 /* XXX if devnam is a symlink, this will change the link */
538 chmod(devnam, tty_mode);
547 * maybe_relock - our PID has changed, maybe update the lock file.
550 maybe_relock(arg, pid)
559 * open_socket - establish a stream socket connection to the nominated
566 char *sep, *endp = NULL;
569 struct hostent *hent;
570 struct sockaddr_in sad;
572 /* parse host:port and resolve host to an IP address */
573 sep = strchr(dest, ':');
575 port = strtol(sep+1, &endp, 10);
576 if (port < 0 || endp == sep+1 || sep == dest) {
577 error("Can't parse host:port for socket destination");
581 host = inet_addr(dest);
582 if (host == (u_int32_t) -1) {
583 hent = gethostbyname(dest);
585 error("%s: unknown host in socket option", dest);
589 host = *(u_int32_t *)(hent->h_addr_list[0]);
593 /* get a socket and connect it to the other end */
594 sock = socket(PF_INET, SOCK_STREAM, 0);
596 error("Can't create socket: %m");
599 memset(&sad, 0, sizeof(sad));
600 sad.sin_family = AF_INET;
601 sad.sin_port = htons(port);
602 sad.sin_addr.s_addr = host;
603 if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
604 error("Can't connect to %s: %m", dest);
614 * start_charshunt - create a child process to run the character shunt.
617 start_charshunt(ifd, ofd)
624 error("Can't fork process for character shunt: %m");
632 fatal("setuid failed");
636 charshunt(ifd, ofd, record_file);
639 charshunt_pid = cpid;
640 add_notifier(&sigreceived, stop_charshunt, 0);
644 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
656 stop_charshunt(arg, sig)
661 kill(charshunt_pid, (sig == SIGINT? sig: SIGTERM));
665 * charshunt - the character shunt, which passes characters between
666 * the pty master side and the serial port (or stdin/stdout).
667 * This runs as the user (not as root).
668 * (We assume ofd >= ifd which is true the way this gets called. :-).
671 charshunt(ifd, ofd, record_file)
676 fd_set ready, writey;
677 u_char *ibufp, *obufp;
680 int pty_readable, stdin_readable;
681 struct timeval lasttime;
682 FILE *recordf = NULL;
683 int ilevel, olevel, max_level;
684 struct timeval levelt, tout, *top;
685 extern u_char inpacket_buf[];
688 * Reset signal handlers.
690 signal(SIGHUP, SIG_IGN); /* Hangup */
691 signal(SIGINT, SIG_DFL); /* Interrupt */
692 signal(SIGTERM, SIG_DFL); /* Terminate */
693 signal(SIGCHLD, SIG_DFL);
694 signal(SIGUSR1, SIG_DFL);
695 signal(SIGUSR2, SIG_DFL);
696 signal(SIGABRT, SIG_DFL);
697 signal(SIGALRM, SIG_DFL);
698 signal(SIGFPE, SIG_DFL);
699 signal(SIGILL, SIG_DFL);
700 signal(SIGPIPE, SIG_DFL);
701 signal(SIGQUIT, SIG_DFL);
702 signal(SIGSEGV, SIG_DFL);
704 signal(SIGBUS, SIG_DFL);
707 signal(SIGEMT, SIG_DFL);
710 signal(SIGPOLL, SIG_DFL);
713 signal(SIGPROF, SIG_DFL);
716 signal(SIGSYS, SIG_DFL);
719 signal(SIGTRAP, SIG_DFL);
722 signal(SIGVTALRM, SIG_DFL);
725 signal(SIGXCPU, SIG_DFL);
728 signal(SIGXFSZ, SIG_DFL);
732 * Open the record file if required.
734 if (record_file != NULL) {
735 recordf = fopen(record_file, "a");
737 error("Couldn't create record file %s: %m", record_file);
740 /* set all the fds to non-blocking mode */
741 flags = fcntl(pty_master, F_GETFL);
743 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
744 warn("couldn't set pty master to nonblock: %m");
745 flags = fcntl(ifd, F_GETFL);
747 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
748 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
750 flags = fcntl(ofd, F_GETFL);
752 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
753 warn("couldn't set stdout to nonblock: %m");
757 ibufp = obufp = NULL;
758 pty_readable = stdin_readable = 1;
761 gettimeofday(&levelt, NULL);
763 max_level = max_data_rate / 10;
767 max_level = PPP_MRU + PPP_HDRLEN + 1;
769 nfds = (ofd > pty_master? ofd: pty_master) + 1;
770 if (recordf != NULL) {
771 gettimeofday(&lasttime, NULL);
772 putc(7, recordf); /* put start marker */
773 putc(lasttime.tv_sec >> 24, recordf);
774 putc(lasttime.tv_sec >> 16, recordf);
775 putc(lasttime.tv_sec >> 8, recordf);
776 putc(lasttime.tv_sec, recordf);
777 lasttime.tv_usec = 0;
780 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
783 tout.tv_usec = 10000;
787 if (ilevel >= max_level)
790 FD_SET(pty_master, &writey);
791 } else if (stdin_readable)
794 if (olevel >= max_level)
797 FD_SET(ofd, &writey);
798 } else if (pty_readable)
799 FD_SET(pty_master, &ready);
800 if (select(nfds, &ready, &writey, NULL, top) < 0) {
810 gettimeofday(&now, NULL);
811 dt = (now.tv_sec - levelt.tv_sec
812 + (now.tv_usec - levelt.tv_usec) / 1e6);
813 nbt = (int)(dt * max_data_rate);
814 ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
815 olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
819 if (FD_ISSET(ifd, &ready)) {
820 ibufp = inpacket_buf;
821 nibuf = read(ifd, ibufp, PPP_MRU + PPP_HDRLEN);
822 if (nibuf < 0 && errno == EIO)
825 if (!(errno == EINTR || errno == EAGAIN)) {
826 error("Error reading standard input: %m");
830 } else if (nibuf == 0) {
831 /* end of file from stdin */
833 /* do a 0-length write, hopefully this will generate
834 an EOF (hangup) on the slave side. */
835 write(pty_master, inpacket_buf, 0);
837 if (!record_write(recordf, 4, NULL, 0, &lasttime))
840 FD_SET(pty_master, &writey);
842 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
846 if (FD_ISSET(pty_master, &ready)) {
847 obufp = outpacket_buf;
848 nobuf = read(pty_master, obufp, PPP_MRU + PPP_HDRLEN);
849 if (nobuf < 0 && errno == EIO)
852 if (!(errno == EINTR || errno == EAGAIN)) {
853 error("Error reading pseudo-tty master: %m");
857 } else if (nobuf == 0) {
858 /* end of file from the pty - slave side has closed */
860 stdin_readable = 0; /* pty is not writable now */
864 if (!record_write(recordf, 3, NULL, 0, &lasttime))
867 FD_SET(ofd, &writey);
869 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
873 if (FD_ISSET(ofd, &writey)) {
875 if (olevel + n > max_level)
876 n = max_level - olevel;
877 n = write(ofd, obufp, n);
882 } else if (errno != EAGAIN && errno != EINTR) {
883 error("Error writing standard output: %m");
892 if (FD_ISSET(pty_master, &writey)) {
894 if (ilevel + n > max_level)
895 n = max_level - ilevel;
896 n = write(pty_master, ibufp, n);
901 } else if (errno != EAGAIN && errno != EINTR) {
902 error("Error writing pseudo-tty master: %m");
916 record_write(f, code, buf, nb, tp)
926 gettimeofday(&now, NULL);
927 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
928 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
946 fwrite(buf, nb, 1, f);
950 error("Error writing record file: %m");