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.4 2001/02/22 03:15:21 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 setdevname __P((char *, char **, int));
53 static int setspeed __P((char *, char **, int));
54 static int setxonxoff __P((char **));
55 static void finish_tty __P((void));
56 static int start_charshunt __P((int, int));
57 static void stop_charshunt __P((void *, int));
58 static void charshunt_done __P((void *));
59 static void charshunt __P((int, int, char *));
60 static int record_write __P((FILE *, int code, u_char *buf, int nb,
62 static int open_socket __P((char *));
63 static void maybe_relock __P((void *, int));
65 static int pty_master; /* fd for master side of pty */
66 static int pty_slave; /* fd for slave side of pty */
67 static int real_ttyfd; /* fd for actual serial port (not pty) */
68 static int ttyfd; /* Serial port file descriptor */
70 mode_t tty_mode = (mode_t)-1; /* Original access permissions to tty */
71 int baud_rate; /* Actual bits/second for serial device */
72 char *callback_script; /* script for doing callback */
73 int charshunt_pid; /* Process ID for charshunt */
74 int locked; /* lock() has succeeded */
75 struct stat devstat; /* result of stat() on devnam */
77 /* option variables */
78 int crtscts = 0; /* Use hardware flow control */
79 bool modem = 1; /* Use modem control lines */
80 int inspeed = 0; /* Input/Output speed requested */
81 bool lockflag = 0; /* Create lock file to lock the serial dev */
82 char *initializer = NULL; /* Script to initialize physical link */
83 char *connect_script = NULL; /* Script to establish physical link */
84 char *disconnect_script = NULL; /* Script to disestablish physical link */
85 char *welcomer = NULL; /* Script to run after phys link estab. */
86 char *ptycommand = NULL; /* Command to run on other side of pty */
87 bool notty = 0; /* Stdin/out is not a tty */
88 char *record_file = NULL; /* File to record chars sent/received */
89 int max_data_rate; /* max bytes/sec through charshunt */
90 bool sync_serial = 0; /* Device is synchronous serial device */
91 char *pty_socket = NULL; /* Socket to connect to pty */
92 int using_pty = 0; /* we're allocating a pty as the device */
98 extern int privopen; /* don't lock, open device as root */
100 /* option descriptors */
101 option_t tty_options[] = {
102 /* device name must be first, or change connect_tty() below! */
103 { "device name", o_wild, (void *) &setdevname,
104 "Serial port device name", OPT_DEVNAM | OPT_PRIVFIX | OPT_NOARG },
105 { "tty speed", o_wild, (void *) &setspeed,
106 "Baud rate for serial port", OPT_NOARG },
107 { "lock", o_bool, &lockflag,
108 "Lock serial device with UUCP-style lock file", 1 },
109 { "nolock", o_bool, &lockflag,
110 "Don't lock serial device", OPT_PRIV },
111 { "init", o_string, &initializer,
112 "A program to initialize the device", OPT_PRIVFIX },
113 { "connect", o_string, &connect_script,
114 "A program to set up a connection", OPT_PRIVFIX },
115 { "disconnect", o_string, &disconnect_script,
116 "Program to disconnect serial device", OPT_PRIVFIX },
117 { "welcome", o_string, &welcomer,
118 "Script to welcome client", OPT_PRIVFIX },
119 { "pty", o_string, &ptycommand,
120 "Script to run on pseudo-tty master side", OPT_PRIVFIX | OPT_DEVNAM },
121 { "notty", o_bool, ¬ty,
122 "Input/output is not a tty", OPT_DEVNAM | 1 },
123 { "socket", o_string, &pty_socket,
124 "Send and receive over socket, arg is host:port", OPT_DEVNAM },
125 { "record", o_string, &record_file,
126 "Record characters sent/received to file" },
127 { "crtscts", o_int, &crtscts,
128 "Set hardware (RTS/CTS) flow control", OPT_NOARG|OPT_VAL(1) },
129 { "nocrtscts", o_int, &crtscts,
130 "Disable hardware flow control", OPT_NOARG|OPT_VAL(-1) },
131 { "-crtscts", o_int, &crtscts,
132 "Disable hardware flow control", OPT_NOARG|OPT_VAL(-1) },
133 { "cdtrcts", o_int, &crtscts,
134 "Set alternate hardware (DTR/CTS) flow control", OPT_NOARG|OPT_VAL(2) },
135 { "nocdtrcts", o_int, &crtscts,
136 "Disable hardware flow control", OPT_NOARG|OPT_VAL(-1) },
137 { "xonxoff", o_special_noarg, (void *)setxonxoff,
138 "Set software (XON/XOFF) flow control" },
139 { "modem", o_bool, &modem,
140 "Use modem control lines", 1 },
141 { "local", o_bool, &modem,
142 "Don't use modem control lines" },
143 { "sync", o_bool, &sync_serial,
144 "Use synchronous HDLC serial encoding", 1 },
145 { "datarate", o_int, &max_data_rate,
146 "Maximum data rate in bytes/sec (with pty, notty or record option)" },
152 * setspeed - Set the serial port baud rate.
153 * If doit is 0, the call is to check whether this option is
154 * potentially a speed value.
157 setspeed(arg, argv, doit)
165 spd = strtol(arg, &ptr, 0);
166 if (ptr == arg || *ptr != 0 || spd == 0)
175 * setdevname - Set the device name.
176 * If doit is 0, the call is to check whether this option is
177 * potentially a device name.
180 setdevname(cp, argv, doit)
186 char dev[MAXPATHLEN];
191 if (strncmp("/dev/", cp, 5) != 0) {
192 strlcpy(dev, "/dev/", sizeof(dev));
193 strlcat(dev, cp, sizeof(dev));
198 * Check if there is a character device by this name.
200 if (stat(cp, &statbuf) < 0) {
202 return errno != ENOENT;
203 option_error("Couldn't stat %s: %m", cp);
206 if (!S_ISCHR(statbuf.st_mode)) {
208 option_error("%s is not a character device", cp);
213 strlcpy(devnam, cp, sizeof(devnam));
225 lcp_wantoptions[0].asyncmap |= 0x000A0000; /* escape ^S and ^Q */
226 lcp_wantoptions[0].neg_asyncmap = 1;
233 * tty_init - do various tty-related initializations.
237 add_notifier(&pidchange, maybe_relock, 0);
238 add_options(tty_options);
242 * tty_device_check - work out which tty device we are using
243 * and read its options file.
245 void tty_device_check()
247 using_pty = notty || ptycommand != NULL || pty_socket != NULL;
250 if (default_device) {
252 if (!isatty(0) || (p = ttyname(0)) == NULL) {
253 option_error("no device specified and stdin is not a tty");
254 exit(EXIT_OPTION_ERROR);
256 strlcpy(devnam, p, sizeof(devnam));
257 if (stat(devnam, &devstat) < 0)
258 fatal("Couldn't stat default device %s: %m", devnam);
263 * Parse the tty options file.
264 * The per-tty options file should not change
265 * ptycommand, pty_socket, notty or devnam.
266 * options_for_tty doesn't override options set on the command line,
267 * except for some privileged options.
269 if (!options_for_tty())
270 exit(EXIT_OPTION_ERROR);
274 * tty_check_options - do consistency checks on the options we were given.
282 if (demand && connect_script == 0) {
283 option_error("connect script is required for demand-dialling\n");
284 exit(EXIT_OPTION_ERROR);
286 /* default holdoff to 0 if no connect script has been given */
287 if (connect_script == 0 && !holdoff_specified)
291 if (!default_device) {
292 option_error("%s option precludes specifying device name",
293 notty? "notty": "pty");
294 exit(EXIT_OPTION_ERROR);
296 if (ptycommand != NULL && notty) {
297 option_error("pty option is incompatible with notty option");
298 exit(EXIT_OPTION_ERROR);
300 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
301 option_error("socket option is incompatible with pty and notty");
302 exit(EXIT_OPTION_ERROR);
304 default_device = notty;
307 if (notty && log_to_fd <= 1)
311 * If the user has specified a device which is the same as
312 * the one on stdin, pretend they didn't specify any.
313 * If the device is already open read/write on stdin,
314 * we assume we don't need to lock it, and we can open it
317 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
318 && statbuf.st_rdev == devstat.st_rdev) {
320 fdflags = fcntl(0, F_GETFL);
321 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
329 * Don't send log messages to the serial port, it tends to
330 * confuse the peer. :-)
332 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
333 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
338 * connect_tty - get the serial port ready to start doing PPP.
339 * That is, open the serial port, set its speed and mode, and run
340 * the connector and/or welcomer.
350 * Get a pty master/slave pair if the pty, notty, socket,
351 * or record options were specified.
353 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
357 if (using_pty || record_file != NULL) {
358 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
359 error("Couldn't allocate pseudo-tty");
360 status = EXIT_FATAL_ERROR;
363 set_up_tty(pty_slave, 1);
367 * Lock the device if we've been asked to.
369 status = EXIT_LOCK_FAILED;
370 if (lockflag && !privopen) {
371 if (lock(devnam) < 0)
377 * Open the serial device and set it up to be the ppp interface.
378 * First we open it in non-blocking mode so we can set the
379 * various termios flags appropriately. If we aren't dialling
380 * out and we want to use the modem lines, we reopen it later
381 * in order to wait for the carrier detect signal from the modem.
385 connector = doing_callback? callback_script: connect_script;
386 if (devnam[0] != 0) {
388 /* If the user specified the device name, become the
389 user before opening it. */
392 prio = privopen? OPRIO_ROOT: tty_options[0].priority;
393 if (prio < OPRIO_ROOT)
395 ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
397 if (prio < OPRIO_ROOT)
403 error("Failed to open %s: %m", devnam);
404 status = EXIT_OPEN_FAILED;
406 if (!persist || err != EINTR)
410 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
411 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
412 warn("Couldn't reset non-blocking mode on device: %m");
415 * Do the equivalent of `mesg n' to stop broadcast messages.
417 if (fstat(ttyfd, &statbuf) < 0
418 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
419 warn("Couldn't restrict write permissions to %s: %m", devnam);
421 tty_mode = statbuf.st_mode;
424 * Set line speed, flow control, etc.
425 * If we have a non-null connection or initializer script,
426 * on most systems we set CLOCAL for now so that we can talk
427 * to the modem before carrier comes up. But this has the
428 * side effect that we might miss it if CD drops before we
429 * get to clear CLOCAL below. On systems where we can talk
430 * successfully to the modem with CLOCAL clear and CD down,
431 * we could clear CLOCAL at this point.
433 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
434 || initializer != NULL));
438 * If the pty, socket, notty and/or record option was specified,
439 * start up the character shunt now.
441 status = EXIT_PTYCMD_FAILED;
442 if (ptycommand != NULL) {
443 if (record_file != NULL) {
444 int ipipe[2], opipe[2], ok;
446 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
447 fatal("Couldn't create pipes for record option: %m");
448 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
449 && start_charshunt(ipipe[0], opipe[1]);
457 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
463 } else if (pty_socket != NULL) {
464 int fd = open_socket(pty_socket);
467 if (!start_charshunt(fd, fd))
470 if (!start_charshunt(0, 1))
472 } else if (record_file != NULL) {
473 if (!start_charshunt(ttyfd, ttyfd))
477 /* run connection script */
478 if ((connector && connector[0]) || initializer) {
479 if (real_ttyfd != -1) {
480 /* XXX do this if doing_callback == CALLBACK_DIALIN? */
481 if (!default_device && modem) {
482 setdtr(real_ttyfd, 0); /* in case modem is off hook */
484 setdtr(real_ttyfd, 1);
488 if (initializer && initializer[0]) {
489 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
490 error("Initializer script failed");
491 status = EXIT_INIT_FAILED;
498 info("Serial port initialized.");
501 if (connector && connector[0]) {
502 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
503 error("Connect script failed");
504 status = EXIT_CONNECT_FAILED;
511 info("Serial connection established.");
514 /* set line speed, flow control, etc.;
515 clear CLOCAL if modem option */
516 if (real_ttyfd != -1)
517 set_up_tty(real_ttyfd, 0);
519 if (doing_callback == CALLBACK_DIALIN)
523 /* reopen tty if necessary to wait for carrier */
524 if (connector == NULL && modem && devnam[0] != 0) {
527 if ((i = open(devnam, O_RDWR)) >= 0)
529 if (errno != EINTR) {
530 error("Failed to reopen %s: %m", devnam);
531 status = EXIT_OPEN_FAILED;
533 if (!persist || errno != EINTR || hungup || kill_link)
539 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
540 script_setenv("SPEED", numbuf, 0);
542 /* run welcome script, if any */
543 if (welcomer && welcomer[0]) {
544 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
545 warn("Welcome script failed");
549 * If we are initiating this connection, wait for a short
550 * time for something from the peer. This can avoid bouncing
551 * our packets off his tty before he has it set up.
553 if (connector != NULL || ptycommand != NULL)
554 listen_time = connect_delay;
560 void disconnect_tty()
562 if (disconnect_script == NULL || hungup)
565 set_up_tty(real_ttyfd, 1);
566 if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
567 warn("disconnect script failed");
569 info("Serial link disconnected.");
579 if (real_ttyfd >= 0) {
583 /* N.B. ttyfd will == either pty_slave or real_ttyfd */
598 * finish_tty - restore the terminal device to its original settings
603 /* drop dtr to hang up */
604 if (!default_device && modem) {
605 setdtr(real_ttyfd, 0);
607 * This sleep is in case the serial port has CLOCAL set by default,
608 * and consequently will reassert DTR when we close the device.
613 restore_tty(real_ttyfd);
615 if (tty_mode != (mode_t) -1) {
616 if (fchmod(real_ttyfd, tty_mode) != 0) {
617 /* XXX if devnam is a symlink, this will change the link */
618 chmod(devnam, tty_mode);
627 * maybe_relock - our PID has changed, maybe update the lock file.
630 maybe_relock(arg, pid)
639 * open_socket - establish a stream socket connection to the nominated
646 char *sep, *endp = NULL;
649 struct hostent *hent;
650 struct sockaddr_in sad;
652 /* parse host:port and resolve host to an IP address */
653 sep = strchr(dest, ':');
655 port = strtol(sep+1, &endp, 10);
656 if (port < 0 || endp == sep+1 || sep == dest) {
657 error("Can't parse host:port for socket destination");
661 host = inet_addr(dest);
662 if (host == (u_int32_t) -1) {
663 hent = gethostbyname(dest);
665 error("%s: unknown host in socket option", dest);
669 host = *(u_int32_t *)(hent->h_addr_list[0]);
673 /* get a socket and connect it to the other end */
674 sock = socket(PF_INET, SOCK_STREAM, 0);
676 error("Can't create socket: %m");
679 memset(&sad, 0, sizeof(sad));
680 sad.sin_family = AF_INET;
681 sad.sin_port = htons(port);
682 sad.sin_addr.s_addr = host;
683 if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
684 error("Can't connect to %s: %m", dest);
694 * start_charshunt - create a child process to run the character shunt.
697 start_charshunt(ifd, ofd)
704 error("Can't fork process for character shunt: %m");
712 fatal("setuid failed");
716 charshunt(ifd, ofd, record_file);
719 charshunt_pid = cpid;
720 add_notifier(&sigreceived, stop_charshunt, 0);
724 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
736 stop_charshunt(arg, sig)
741 kill(charshunt_pid, (sig == SIGINT? sig: SIGTERM));
745 * charshunt - the character shunt, which passes characters between
746 * the pty master side and the serial port (or stdin/stdout).
747 * This runs as the user (not as root).
748 * (We assume ofd >= ifd which is true the way this gets called. :-).
751 charshunt(ifd, ofd, record_file)
756 fd_set ready, writey;
757 u_char *ibufp, *obufp;
760 int pty_readable, stdin_readable;
761 struct timeval lasttime;
762 FILE *recordf = NULL;
763 int ilevel, olevel, max_level;
764 struct timeval levelt, tout, *top;
765 extern u_char inpacket_buf[];
768 * Reset signal handlers.
770 signal(SIGHUP, SIG_IGN); /* Hangup */
771 signal(SIGINT, SIG_DFL); /* Interrupt */
772 signal(SIGTERM, SIG_DFL); /* Terminate */
773 signal(SIGCHLD, SIG_DFL);
774 signal(SIGUSR1, SIG_DFL);
775 signal(SIGUSR2, SIG_DFL);
776 signal(SIGABRT, SIG_DFL);
777 signal(SIGALRM, SIG_DFL);
778 signal(SIGFPE, SIG_DFL);
779 signal(SIGILL, SIG_DFL);
780 signal(SIGPIPE, SIG_DFL);
781 signal(SIGQUIT, SIG_DFL);
782 signal(SIGSEGV, SIG_DFL);
784 signal(SIGBUS, SIG_DFL);
787 signal(SIGEMT, SIG_DFL);
790 signal(SIGPOLL, SIG_DFL);
793 signal(SIGPROF, SIG_DFL);
796 signal(SIGSYS, SIG_DFL);
799 signal(SIGTRAP, SIG_DFL);
802 signal(SIGVTALRM, SIG_DFL);
805 signal(SIGXCPU, SIG_DFL);
808 signal(SIGXFSZ, SIG_DFL);
812 * Open the record file if required.
814 if (record_file != NULL) {
815 recordf = fopen(record_file, "a");
817 error("Couldn't create record file %s: %m", record_file);
820 /* set all the fds to non-blocking mode */
821 flags = fcntl(pty_master, F_GETFL);
823 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
824 warn("couldn't set pty master to nonblock: %m");
825 flags = fcntl(ifd, F_GETFL);
827 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
828 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
830 flags = fcntl(ofd, F_GETFL);
832 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
833 warn("couldn't set stdout to nonblock: %m");
837 ibufp = obufp = NULL;
838 pty_readable = stdin_readable = 1;
841 gettimeofday(&levelt, NULL);
843 max_level = max_data_rate / 10;
847 max_level = PPP_MRU + PPP_HDRLEN + 1;
849 nfds = (ofd > pty_master? ofd: pty_master) + 1;
850 if (recordf != NULL) {
851 gettimeofday(&lasttime, NULL);
852 putc(7, recordf); /* put start marker */
853 putc(lasttime.tv_sec >> 24, recordf);
854 putc(lasttime.tv_sec >> 16, recordf);
855 putc(lasttime.tv_sec >> 8, recordf);
856 putc(lasttime.tv_sec, recordf);
857 lasttime.tv_usec = 0;
860 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
863 tout.tv_usec = 10000;
867 if (ilevel >= max_level)
870 FD_SET(pty_master, &writey);
871 } else if (stdin_readable)
874 if (olevel >= max_level)
877 FD_SET(ofd, &writey);
878 } else if (pty_readable)
879 FD_SET(pty_master, &ready);
880 if (select(nfds, &ready, &writey, NULL, top) < 0) {
890 gettimeofday(&now, NULL);
891 dt = (now.tv_sec - levelt.tv_sec
892 + (now.tv_usec - levelt.tv_usec) / 1e6);
893 nbt = (int)(dt * max_data_rate);
894 ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
895 olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
899 if (FD_ISSET(ifd, &ready)) {
900 ibufp = inpacket_buf;
901 nibuf = read(ifd, ibufp, PPP_MRU + PPP_HDRLEN);
902 if (nibuf < 0 && errno == EIO)
905 if (!(errno == EINTR || errno == EAGAIN)) {
906 error("Error reading standard input: %m");
910 } else if (nibuf == 0) {
911 /* end of file from stdin */
913 /* do a 0-length write, hopefully this will generate
914 an EOF (hangup) on the slave side. */
915 write(pty_master, inpacket_buf, 0);
917 if (!record_write(recordf, 4, NULL, 0, &lasttime))
920 FD_SET(pty_master, &writey);
922 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
926 if (FD_ISSET(pty_master, &ready)) {
927 obufp = outpacket_buf;
928 nobuf = read(pty_master, obufp, PPP_MRU + PPP_HDRLEN);
929 if (nobuf < 0 && errno == EIO)
932 if (!(errno == EINTR || errno == EAGAIN)) {
933 error("Error reading pseudo-tty master: %m");
937 } else if (nobuf == 0) {
938 /* end of file from the pty - slave side has closed */
940 stdin_readable = 0; /* pty is not writable now */
944 if (!record_write(recordf, 3, NULL, 0, &lasttime))
947 FD_SET(ofd, &writey);
949 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
953 if (FD_ISSET(ofd, &writey)) {
955 if (olevel + n > max_level)
956 n = max_level - olevel;
957 n = write(ofd, obufp, n);
962 } else if (errno != EAGAIN && errno != EINTR) {
963 error("Error writing standard output: %m");
972 if (FD_ISSET(pty_master, &writey)) {
974 if (ilevel + n > max_level)
975 n = max_level - ilevel;
976 n = write(pty_master, ibufp, n);
981 } else if (errno != EAGAIN && errno != EINTR) {
982 error("Error writing pseudo-tty master: %m");
996 record_write(f, code, buf, nb, tp)
1006 gettimeofday(&now, NULL);
1007 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
1008 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
1012 putc(diff >> 24, f);
1013 putc(diff >> 16, f);
1026 fwrite(buf, nb, 1, f);
1030 error("Error writing record file: %m");