]> git.ozlabs.org Git - ppp.git/blob - pppd/tty.c
b7e61650d48357f692d3353a77ea2db71ef7fcee
[ppp.git] / pppd / tty.c
1 /*
2  * tty.c - code for handling serial ports in pppd.
3  *
4  * Copyright (C) 2000 Paul Mackerras.
5  * All rights reserved.
6  *
7  * Portions Copyright (c) 1989 Carnegie Mellon University.
8  * All rights reserved.
9  *
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.
21  */
22
23 #define RCSID   "$Id: tty.c,v 1.4 2001/02/22 03:15:21 paulus Exp $"
24
25 #include <stdio.h>
26 #include <ctype.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30 #include <signal.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <syslog.h>
34 #include <netdb.h>
35 #include <utmp.h>
36 #include <pwd.h>
37 #include <setjmp.h>
38 #include <sys/param.h>
39 #include <sys/types.h>
40 #include <sys/wait.h>
41 #include <sys/time.h>
42 #include <sys/resource.h>
43 #include <sys/stat.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <arpa/inet.h>
47
48 #include "pppd.h"
49 #include "fsm.h"
50 #include "lcp.h"
51
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,
61                              struct timeval *));
62 static int open_socket __P((char *));
63 static void maybe_relock __P((void *, int));
64
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 */
69
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 */
76
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 */
93
94 extern uid_t uid;
95 extern int kill_link;
96
97 /* XXX */
98 extern int privopen;            /* don't lock, open device as root */
99
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, &notty,
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)" },
147     { NULL }
148 };
149
150
151 /*
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.
155  */
156 static int
157 setspeed(arg, argv, doit)
158     char *arg;
159     char **argv;
160     int doit;
161 {
162         char *ptr;
163         int spd;
164
165         spd = strtol(arg, &ptr, 0);
166         if (ptr == arg || *ptr != 0 || spd == 0)
167                 return 0;
168         if (doit)
169                 inspeed = spd;
170         return 1;
171 }
172
173
174 /*
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.
178  */
179 static int
180 setdevname(cp, argv, doit)
181     char *cp;
182     char **argv;
183     int doit;
184 {
185         struct stat statbuf;
186         char dev[MAXPATHLEN];
187
188         if (*cp == 0)
189                 return 0;
190
191         if (strncmp("/dev/", cp, 5) != 0) {
192                 strlcpy(dev, "/dev/", sizeof(dev));
193                 strlcat(dev, cp, sizeof(dev));
194                 cp = dev;
195         }
196
197         /*
198          * Check if there is a character device by this name.
199          */
200         if (stat(cp, &statbuf) < 0) {
201                 if (!doit)
202                         return errno != ENOENT;
203                 option_error("Couldn't stat %s: %m", cp);
204                 return 0;
205         }
206         if (!S_ISCHR(statbuf.st_mode)) {
207                 if (doit)
208                         option_error("%s is not a character device", cp);
209                 return 0;
210         }
211
212         if (doit) {
213                 strlcpy(devnam, cp, sizeof(devnam));
214                 devstat = statbuf;
215                 default_device = 0;
216         }
217   
218         return 1;
219 }
220
221 static int
222 setxonxoff(argv)
223     char **argv;
224 {
225         lcp_wantoptions[0].asyncmap |= 0x000A0000;      /* escape ^S and ^Q */
226         lcp_wantoptions[0].neg_asyncmap = 1;
227
228         crtscts = -2;
229         return 1;
230 }
231
232 /*
233  * tty_init - do various tty-related initializations.
234  */
235 void tty_init()
236 {
237     add_notifier(&pidchange, maybe_relock, 0);
238     add_options(tty_options);
239 }
240
241 /*
242  * tty_device_check - work out which tty device we are using
243  * and read its options file.
244  */
245 void tty_device_check()
246 {
247         using_pty = notty || ptycommand != NULL || pty_socket != NULL;
248         if (using_pty)
249                 return;
250         if (default_device) {
251                 char *p;
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);
255                 }
256                 strlcpy(devnam, p, sizeof(devnam));
257                 if (stat(devnam, &devstat) < 0)
258                         fatal("Couldn't stat default device %s: %m", devnam);
259         }
260
261
262         /*
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.
268          */
269         if (!options_for_tty())
270                 exit(EXIT_OPTION_ERROR);
271 }
272
273 /*
274  * tty_check_options - do consistency checks on the options we were given.
275  */
276 void
277 tty_check_options()
278 {
279         struct stat statbuf;
280         int fdflags;
281
282         if (demand && connect_script == 0) {
283                 option_error("connect script is required for demand-dialling\n");
284                 exit(EXIT_OPTION_ERROR);
285         }
286         /* default holdoff to 0 if no connect script has been given */
287         if (connect_script == 0 && !holdoff_specified)
288                 holdoff = 0;
289
290         if (using_pty) {
291                 if (!default_device) {
292                         option_error("%s option precludes specifying device name",
293                                      notty? "notty": "pty");
294                         exit(EXIT_OPTION_ERROR);
295                 }
296                 if (ptycommand != NULL && notty) {
297                         option_error("pty option is incompatible with notty option");
298                         exit(EXIT_OPTION_ERROR);
299                 }
300                 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
301                         option_error("socket option is incompatible with pty and notty");
302                         exit(EXIT_OPTION_ERROR);
303                 }
304                 default_device = notty;
305                 lockflag = 0;
306                 modem = 0;
307                 if (notty && log_to_fd <= 1)
308                         log_to_fd = -1;
309         } else {
310                 /*
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
315                  * as root.
316                  */
317                 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
318                     && statbuf.st_rdev == devstat.st_rdev) {
319                         default_device = 1;
320                         fdflags = fcntl(0, F_GETFL);
321                         if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
322                                 privopen = 1;
323                 }
324         }
325         if (default_device)
326                 nodetach = 1;
327
328         /*
329          * Don't send log messages to the serial port, it tends to
330          * confuse the peer. :-)
331          */
332         if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
333             && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
334                 log_to_fd = -1;
335 }
336
337 /*
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.
341  */
342 int connect_tty()
343 {
344         char *connector;
345         int fdflags;
346         struct stat statbuf;
347         char numbuf[16];
348
349         /*
350          * Get a pty master/slave pair if the pty, notty, socket,
351          * or record options were specified.
352          */
353         strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
354         pty_master = -1;
355         pty_slave = -1;
356         real_ttyfd = -1;
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;
361                         return -1;
362                 }
363                 set_up_tty(pty_slave, 1);
364         }
365
366         /*
367          * Lock the device if we've been asked to.
368          */
369         status = EXIT_LOCK_FAILED;
370         if (lockflag && !privopen) {
371                 if (lock(devnam) < 0)
372                         return -1;
373                 locked = 1;
374         }
375
376         /*
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.
382          */
383         hungup = 0;
384         kill_link = 0;
385         connector = doing_callback? callback_script: connect_script;
386         if (devnam[0] != 0) {
387                 for (;;) {
388                         /* If the user specified the device name, become the
389                            user before opening it. */
390                         int err, prio;
391
392                         prio = privopen? OPRIO_ROOT: tty_options[0].priority;
393                         if (prio < OPRIO_ROOT)
394                                 seteuid(uid);
395                         ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
396                         err = errno;
397                         if (prio < OPRIO_ROOT)
398                                 seteuid(0);
399                         if (ttyfd >= 0)
400                                 break;
401                         errno = err;
402                         if (err != EINTR) {
403                                 error("Failed to open %s: %m", devnam);
404                                 status = EXIT_OPEN_FAILED;
405                         }
406                         if (!persist || err != EINTR)
407                                 return -1;
408                 }
409                 real_ttyfd = ttyfd;
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");
413
414                 /*
415                  * Do the equivalent of `mesg n' to stop broadcast messages.
416                  */
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);
420                 } else
421                         tty_mode = statbuf.st_mode;
422
423                 /*
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.
432                  */
433                 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
434                                    || initializer != NULL));
435         }
436
437         /*
438          * If the pty, socket, notty and/or record option was specified,
439          * start up the character shunt now.
440          */
441         status = EXIT_PTYCMD_FAILED;
442         if (ptycommand != NULL) {
443                 if (record_file != NULL) {
444                         int ipipe[2], opipe[2], ok;
445
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]);
450                         close(ipipe[0]);
451                         close(ipipe[1]);
452                         close(opipe[0]);
453                         close(opipe[1]);
454                         if (!ok)
455                                 return -1;
456                 } else {
457                         if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
458                                 return -1;
459                         ttyfd = pty_slave;
460                         close(pty_master);
461                         pty_master = -1;
462                 }
463         } else if (pty_socket != NULL) {
464                 int fd = open_socket(pty_socket);
465                 if (fd < 0)
466                         return -1;
467                 if (!start_charshunt(fd, fd))
468                         return -1;
469         } else if (notty) {
470                 if (!start_charshunt(0, 1))
471                         return -1;
472         } else if (record_file != NULL) {
473                 if (!start_charshunt(ttyfd, ttyfd))
474                         return -1;
475         }
476
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 */
483                                 sleep(1);
484                                 setdtr(real_ttyfd, 1);
485                         }
486                 }
487
488                 if (initializer && initializer[0]) {
489                         if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
490                                 error("Initializer script failed");
491                                 status = EXIT_INIT_FAILED;
492                                 return -1;
493                         }
494                         if (kill_link) {
495                                 disconnect_tty();
496                                 return -1;
497                         }
498                         info("Serial port initialized.");
499                 }
500
501                 if (connector && connector[0]) {
502                         if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
503                                 error("Connect script failed");
504                                 status = EXIT_CONNECT_FAILED;
505                                 return -1;
506                         }
507                         if (kill_link) {
508                                 disconnect_tty();
509                                 return -1;
510                         }
511                         info("Serial connection established.");
512                 }
513
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);
518
519                 if (doing_callback == CALLBACK_DIALIN)
520                         connector = NULL;
521         }
522
523         /* reopen tty if necessary to wait for carrier */
524         if (connector == NULL && modem && devnam[0] != 0) {
525                 int i;
526                 for (;;) {
527                         if ((i = open(devnam, O_RDWR)) >= 0)
528                                 break;
529                         if (errno != EINTR) {
530                                 error("Failed to reopen %s: %m", devnam);
531                                 status = EXIT_OPEN_FAILED;
532                         }
533                         if (!persist || errno != EINTR || hungup || kill_link)
534                                 return -1;
535                 }
536                 close(i);
537         }
538
539         slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
540         script_setenv("SPEED", numbuf, 0);
541
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");
546         }
547
548         /*
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.
552          */
553         if (connector != NULL || ptycommand != NULL)
554                 listen_time = connect_delay;
555
556         return ttyfd;
557 }
558
559
560 void disconnect_tty()
561 {
562         if (disconnect_script == NULL || hungup)
563                 return;
564         if (real_ttyfd >= 0)
565                 set_up_tty(real_ttyfd, 1);
566         if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
567                 warn("disconnect script failed");
568         } else {
569                 info("Serial link disconnected.");
570         }
571 }
572
573 void tty_close_fds()
574 {
575         if (pty_master >= 0)
576                 close(pty_master);
577         if (pty_slave >= 0)
578                 close(pty_slave);
579         if (real_ttyfd >= 0) {
580                 close(real_ttyfd);
581                 real_ttyfd = -1;
582         }
583         /* N.B. ttyfd will == either pty_slave or real_ttyfd */
584 }
585
586 void cleanup_tty()
587 {
588         if (real_ttyfd >= 0)
589                 finish_tty();
590         tty_close_fds();
591         if (locked) {
592                 unlock();
593                 locked = 0;
594         }
595 }
596
597 /*
598  * finish_tty - restore the terminal device to its original settings
599  */
600 static void
601 finish_tty()
602 {
603         /* drop dtr to hang up */
604         if (!default_device && modem) {
605                 setdtr(real_ttyfd, 0);
606                 /*
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.
609                  */
610                 sleep(1);
611         }
612
613         restore_tty(real_ttyfd);
614
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);
619                 }
620         }
621
622         close(real_ttyfd);
623         real_ttyfd = -1;
624 }
625
626 /*
627  * maybe_relock - our PID has changed, maybe update the lock file.
628  */
629 static void
630 maybe_relock(arg, pid)
631     void *arg;
632     int pid;
633 {
634     if (locked)
635         relock(pid);
636 }
637
638 /*
639  * open_socket - establish a stream socket connection to the nominated
640  * host and port.
641  */
642 static int
643 open_socket(dest)
644     char *dest;
645 {
646     char *sep, *endp = NULL;
647     int sock, port = -1;
648     u_int32_t host;
649     struct hostent *hent;
650     struct sockaddr_in sad;
651
652     /* parse host:port and resolve host to an IP address */
653     sep = strchr(dest, ':');
654     if (sep != NULL)
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");
658         return -1;
659     }
660     *sep = 0;
661     host = inet_addr(dest);
662     if (host == (u_int32_t) -1) {
663         hent = gethostbyname(dest);
664         if (hent == NULL) {
665             error("%s: unknown host in socket option", dest);
666             *sep = ':';
667             return -1;
668         }
669         host = *(u_int32_t *)(hent->h_addr_list[0]);
670     }
671     *sep = ':';
672
673     /* get a socket and connect it to the other end */
674     sock = socket(PF_INET, SOCK_STREAM, 0);
675     if (sock < 0) {
676         error("Can't create socket: %m");
677         return -1;
678     }
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);
685         close(sock);
686         return -1;
687     }
688
689     return sock;
690 }
691
692
693 /*
694  * start_charshunt - create a child process to run the character shunt.
695  */
696 static int
697 start_charshunt(ifd, ofd)
698     int ifd, ofd;
699 {
700     int cpid;
701
702     cpid = fork();
703     if (cpid == -1) {
704         error("Can't fork process for character shunt: %m");
705         return 0;
706     }
707     if (cpid == 0) {
708         /* child */
709         close(pty_slave);
710         setuid(uid);
711         if (getuid() != uid)
712             fatal("setuid failed");
713         setgid(getgid());
714         if (!nodetach)
715             log_to_fd = -1;
716         charshunt(ifd, ofd, record_file);
717         exit(0);
718     }
719     charshunt_pid = cpid;
720     add_notifier(&sigreceived, stop_charshunt, 0);
721     close(pty_master);
722     pty_master = -1;
723     ttyfd = pty_slave;
724     record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
725     return 1;
726 }
727
728 static void
729 charshunt_done(arg)
730     void *arg;
731 {
732         charshunt_pid = 0;
733 }
734
735 static void
736 stop_charshunt(arg, sig)
737     void *arg;
738     int sig;
739 {
740         if (charshunt_pid)
741                 kill(charshunt_pid, (sig == SIGINT? sig: SIGTERM));
742 }
743
744 /*
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. :-).
749  */
750 static void
751 charshunt(ifd, ofd, record_file)
752     int ifd, ofd;
753     char *record_file;
754 {
755     int n, nfds;
756     fd_set ready, writey;
757     u_char *ibufp, *obufp;
758     int nibuf, nobuf;
759     int flags;
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[];
766
767     /*
768      * Reset signal handlers.
769      */
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);
783 #ifdef SIGBUS
784     signal(SIGBUS, SIG_DFL);
785 #endif
786 #ifdef SIGEMT
787     signal(SIGEMT, SIG_DFL);
788 #endif
789 #ifdef SIGPOLL
790     signal(SIGPOLL, SIG_DFL);
791 #endif
792 #ifdef SIGPROF
793     signal(SIGPROF, SIG_DFL);
794 #endif
795 #ifdef SIGSYS
796     signal(SIGSYS, SIG_DFL);
797 #endif
798 #ifdef SIGTRAP
799     signal(SIGTRAP, SIG_DFL);
800 #endif
801 #ifdef SIGVTALRM
802     signal(SIGVTALRM, SIG_DFL);
803 #endif
804 #ifdef SIGXCPU
805     signal(SIGXCPU, SIG_DFL);
806 #endif
807 #ifdef SIGXFSZ
808     signal(SIGXFSZ, SIG_DFL);
809 #endif
810
811     /*
812      * Open the record file if required.
813      */
814     if (record_file != NULL) {
815         recordf = fopen(record_file, "a");
816         if (recordf == NULL)
817             error("Couldn't create record file %s: %m", record_file);
818     }
819
820     /* set all the fds to non-blocking mode */
821     flags = fcntl(pty_master, F_GETFL);
822     if (flags == -1
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);
826     if (flags == -1
827         || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
828         warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
829     if (ofd != ifd) {
830         flags = fcntl(ofd, F_GETFL);
831         if (flags == -1
832             || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
833             warn("couldn't set stdout to nonblock: %m");
834     }
835
836     nibuf = nobuf = 0;
837     ibufp = obufp = NULL;
838     pty_readable = stdin_readable = 1;
839
840     ilevel = olevel = 0;
841     gettimeofday(&levelt, NULL);
842     if (max_data_rate) {
843         max_level = max_data_rate / 10;
844         if (max_level < 100)
845             max_level = 100;
846     } else
847         max_level = PPP_MRU + PPP_HDRLEN + 1;
848
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;
858     }
859
860     while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
861         top = 0;
862         tout.tv_sec = 0;
863         tout.tv_usec = 10000;
864         FD_ZERO(&ready);
865         FD_ZERO(&writey);
866         if (nibuf != 0) {
867             if (ilevel >= max_level)
868                 top = &tout;
869             else
870                 FD_SET(pty_master, &writey);
871         } else if (stdin_readable)
872             FD_SET(ifd, &ready);
873         if (nobuf != 0) {
874             if (olevel >= max_level)
875                 top = &tout;
876             else
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) {
881             if (errno != EINTR)
882                 fatal("select");
883             continue;
884         }
885         if (max_data_rate) {
886             double dt;
887             int nbt;
888             struct timeval now;
889
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;
896             levelt = now;
897         } else
898             ilevel = olevel = 0;
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)
903                 nibuf = 0;
904             if (nibuf < 0) {
905                 if (!(errno == EINTR || errno == EAGAIN)) {
906                     error("Error reading standard input: %m");
907                     break;
908                 }
909                 nibuf = 0;
910             } else if (nibuf == 0) {
911                 /* end of file from stdin */
912                 stdin_readable = 0;
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);
916                 if (recordf)
917                     if (!record_write(recordf, 4, NULL, 0, &lasttime))
918                         recordf = NULL;
919             } else {
920                 FD_SET(pty_master, &writey);
921                 if (recordf)
922                     if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
923                         recordf = NULL;
924             }
925         }
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)
930                 nobuf = 0;
931             if (nobuf < 0) {
932                 if (!(errno == EINTR || errno == EAGAIN)) {
933                     error("Error reading pseudo-tty master: %m");
934                     break;
935                 }
936                 nobuf = 0;
937             } else if (nobuf == 0) {
938                 /* end of file from the pty - slave side has closed */
939                 pty_readable = 0;
940                 stdin_readable = 0;     /* pty is not writable now */
941                 nibuf = 0;
942                 close(ofd);
943                 if (recordf)
944                     if (!record_write(recordf, 3, NULL, 0, &lasttime))
945                         recordf = NULL;
946             } else {
947                 FD_SET(ofd, &writey);
948                 if (recordf)
949                     if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
950                         recordf = NULL;
951             }
952         }
953         if (FD_ISSET(ofd, &writey)) {
954             n = nobuf;
955             if (olevel + n > max_level)
956                 n = max_level - olevel;
957             n = write(ofd, obufp, n);
958             if (n < 0) {
959                 if (errno == EIO) {
960                     pty_readable = 0;
961                     nobuf = 0;
962                 } else if (errno != EAGAIN && errno != EINTR) {
963                     error("Error writing standard output: %m");
964                     break;
965                 }
966             } else {
967                 obufp += n;
968                 nobuf -= n;
969                 olevel += n;
970             }
971         }
972         if (FD_ISSET(pty_master, &writey)) {
973             n = nibuf;
974             if (ilevel + n > max_level)
975                 n = max_level - ilevel;
976             n = write(pty_master, ibufp, n);
977             if (n < 0) {
978                 if (errno == EIO) {
979                     stdin_readable = 0;
980                     nibuf = 0;
981                 } else if (errno != EAGAIN && errno != EINTR) {
982                     error("Error writing pseudo-tty master: %m");
983                     break;
984                 }
985             } else {
986                 ibufp += n;
987                 nibuf -= n;
988                 ilevel += n;
989             }
990         }
991     }
992     exit(0);
993 }
994
995 static int
996 record_write(f, code, buf, nb, tp)
997     FILE *f;
998     int code;
999     u_char *buf;
1000     int nb;
1001     struct timeval *tp;
1002 {
1003     struct timeval now;
1004     int diff;
1005
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);
1009     if (diff > 0) {
1010         if (diff > 255) {
1011             putc(5, f);
1012             putc(diff >> 24, f);
1013             putc(diff >> 16, f);
1014             putc(diff >> 8, f);
1015             putc(diff, f);
1016         } else {
1017             putc(6, f);
1018             putc(diff, f);
1019         }
1020         *tp = now;
1021     }
1022     putc(code, f);
1023     if (buf != NULL) {
1024         putc(nb >> 8, f);
1025         putc(nb, f);
1026         fwrite(buf, nb, 1, f);
1027     }
1028     fflush(f);
1029     if (ferror(f)) {
1030         error("Error writing record file: %m");
1031         return 0;
1032     }
1033     return 1;
1034 }