]> git.ozlabs.org Git - ppp.git/blob - pppd/tty.c
751bfadb5a5261fc220f480d8cf7fa398708d07e
[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.2 2000/07/06 11:17:03 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 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,
59                              struct timeval *));
60 static int open_socket __P((char *));
61 static void maybe_relock __P((void *, int));
62
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 */
67
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 */
74
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 */
91
92 extern uid_t uid;
93 extern int kill_link;
94
95 /* XXX */
96 extern int privopen;            /* don't lock, open device as root */
97
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, &notty,
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)" },
145     { NULL }
146 };
147
148 static int
149 setxonxoff(argv)
150     char **argv;
151 {
152         lcp_wantoptions[0].asyncmap |= 0x000A0000;      /* escape ^S and ^Q */
153         lcp_wantoptions[0].neg_asyncmap = 1;
154
155         crtscts = -2;
156         return 1;
157 }
158
159 /*
160  * tty_init - do various tty-related initializations.
161  */
162 void tty_init()
163 {
164     add_notifier(&pidchange, maybe_relock, 0);
165     add_options(tty_options);
166 }
167
168 /*
169  * tty_device_check - work out which tty device we are using
170  * and read its options file.
171  */
172 void tty_device_check()
173 {
174         using_pty = notty || ptycommand != NULL || pty_socket != NULL;
175         if (using_pty)
176                 return;
177         if (default_device) {
178                 char *p;
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);
182                 }
183                 strlcpy(devnam, p, sizeof(devnam));
184                 if (stat(devnam, &devstat) < 0)
185                         fatal("Couldn't stat default device %s: %m", devnam);
186         }
187
188
189         /*
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.
195          */
196         if (!options_for_tty())
197                 exit(EXIT_OPTION_ERROR);
198 }
199
200 /*
201  * tty_check_options - do consistency checks on the options we were given.
202  */
203 void
204 tty_check_options()
205 {
206         struct stat statbuf;
207         int fdflags;
208
209         if (demand && connect_script == 0) {
210                 option_error("connect script is required for demand-dialling\n");
211                 exit(EXIT_OPTION_ERROR);
212         }
213         /* default holdoff to 0 if no connect script has been given */
214         if (connect_script == 0 && !holdoff_specified)
215                 holdoff = 0;
216
217         if (using_pty) {
218                 if (!default_device) {
219                         option_error("%s option precludes specifying device name",
220                                      notty? "notty": "pty");
221                         exit(EXIT_OPTION_ERROR);
222                 }
223                 if (ptycommand != NULL && notty) {
224                         option_error("pty option is incompatible with notty option");
225                         exit(EXIT_OPTION_ERROR);
226                 }
227                 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
228                         option_error("socket option is incompatible with pty and notty");
229                         exit(EXIT_OPTION_ERROR);
230                 }
231                 default_device = notty;
232                 lockflag = 0;
233                 modem = 0;
234                 if (notty && log_to_fd <= 1)
235                         log_to_fd = -1;
236         } else {
237                 /*
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
242                  * as root.
243                  */
244                 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
245                     && statbuf.st_rdev == devstat.st_rdev) {
246                         default_device = 1;
247                         fdflags = fcntl(0, F_GETFL);
248                         if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
249                                 privopen = 1;
250                 }
251         }
252         if (default_device)
253                 nodetach = 1;
254
255         /*
256          * Don't send log messages to the serial port, it tends to
257          * confuse the peer. :-)
258          */
259         if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
260             && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
261                 log_to_fd = -1;
262 }
263
264 /*
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.
268  */
269 int connect_tty()
270 {
271         char *connector;
272         int fdflags;
273         struct stat statbuf;
274         char numbuf[16];
275
276         /*
277          * Get a pty master/slave pair if the pty, notty, socket,
278          * or record options were specified.
279          */
280         strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
281         pty_master = -1;
282         pty_slave = -1;
283         real_ttyfd = -1;
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;
288                         return -1;
289                 }
290                 set_up_tty(pty_slave, 1);
291         }
292
293         /*
294          * Lock the device if we've been asked to.
295          */
296         status = EXIT_LOCK_FAILED;
297         if (lockflag && !privopen) {
298                 if (lock(devnam) < 0)
299                         return -1;
300                 locked = 1;
301         }
302
303         /*
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.
309          */
310         hungup = 0;
311         kill_link = 0;
312         connector = doing_callback? callback_script: connect_script;
313         if (devnam[0] != 0) {
314                 for (;;) {
315                         /* If the user specified the device name, become the
316                            user before opening it. */
317                         int err;
318                         if (!devnam_info.priv && !privopen)
319                                 seteuid(uid);
320                         ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
321                         err = errno;
322                         if (!devnam_info.priv && !privopen)
323                                 seteuid(0);
324                         if (ttyfd >= 0)
325                                 break;
326                         errno = err;
327                         if (err != EINTR) {
328                                 error("Failed to open %s: %m", devnam);
329                                 status = EXIT_OPEN_FAILED;
330                         }
331                         if (!persist || err != EINTR)
332                                 return -1;
333                 }
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");
337
338                 /*
339                  * Do the equivalent of `mesg n' to stop broadcast messages.
340                  */
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);
344                 } else
345                         tty_mode = statbuf.st_mode;
346
347                 /*
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.
356                  */
357                 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
358                                    || initializer != NULL));
359                 real_ttyfd = ttyfd;
360         }
361
362         /*
363          * If the pty, socket, notty and/or record option was specified,
364          * start up the character shunt now.
365          */
366         status = EXIT_PTYCMD_FAILED;
367         if (ptycommand != NULL) {
368                 if (record_file != NULL) {
369                         int ipipe[2], opipe[2], ok;
370
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]);
375                         close(ipipe[0]);
376                         close(ipipe[1]);
377                         close(opipe[0]);
378                         close(opipe[1]);
379                         if (!ok)
380                                 return -1;
381                 } else {
382                         if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
383                                 return -1;
384                         ttyfd = pty_slave;
385                         close(pty_master);
386                         pty_master = -1;
387                 }
388         } else if (pty_socket != NULL) {
389                 int fd = open_socket(pty_socket);
390                 if (fd < 0)
391                         return -1;
392                 if (!start_charshunt(fd, fd))
393                         return -1;
394         } else if (notty) {
395                 if (!start_charshunt(0, 1))
396                         return -1;
397         } else if (record_file != NULL) {
398                 if (!start_charshunt(ttyfd, ttyfd))
399                         return -1;
400         }
401
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 */
408                                 sleep(1);
409                                 setdtr(real_ttyfd, 1);
410                         }
411                 }
412
413                 if (initializer && initializer[0]) {
414                         if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
415                                 error("Initializer script failed");
416                                 status = EXIT_INIT_FAILED;
417                                 return -1;
418                         }
419                         if (kill_link) {
420                                 disconnect_tty();
421                                 return -1;
422                         }
423                         info("Serial port initialized.");
424                 }
425
426                 if (connector && connector[0]) {
427                         if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
428                                 error("Connect script failed");
429                                 status = EXIT_CONNECT_FAILED;
430                                 return -1;
431                         }
432                         if (kill_link) {
433                                 disconnect_tty();
434                                 return -1;
435                         }
436                         info("Serial connection established.");
437                 }
438
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);
443
444                 if (doing_callback == CALLBACK_DIALIN)
445                         connector = NULL;
446         }
447
448         /* reopen tty if necessary to wait for carrier */
449         if (connector == NULL && modem && devnam[0] != 0) {
450                 int i;
451                 for (;;) {
452                         if ((i = open(devnam, O_RDWR)) >= 0)
453                                 break;
454                         if (errno != EINTR) {
455                                 error("Failed to reopen %s: %m", devnam);
456                                 status = EXIT_OPEN_FAILED;
457                         }
458                         if (!persist || errno != EINTR || hungup || kill_link)
459                                 return -1;
460                 }
461                 close(i);
462         }
463
464         slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
465         script_setenv("SPEED", numbuf, 0);
466
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");
471         }
472
473         if (connector != NULL || ptycommand != NULL)
474                 listen_time = connect_delay;
475
476         return ttyfd;
477 }
478
479
480 void disconnect_tty()
481 {
482         if (disconnect_script == NULL || hungup)
483                 return;
484         if (real_ttyfd >= 0)
485                 set_up_tty(real_ttyfd, 1);
486         if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
487                 warn("disconnect script failed");
488         } else {
489                 info("Serial link disconnected.");
490         }
491 }
492
493 void tty_close_fds()
494 {
495         if (pty_master >= 0)
496                 close(pty_master);
497         if (pty_slave >= 0)
498                 close(pty_slave);
499         if (real_ttyfd >= 0) {
500                 close(real_ttyfd);
501                 real_ttyfd = -1;
502         }
503         /* N.B. ttyfd will == either pty_slave or real_ttyfd */
504 }
505
506 void cleanup_tty()
507 {
508         if (real_ttyfd >= 0)
509                 finish_tty();
510         tty_close_fds();
511         if (locked) {
512                 unlock();
513                 locked = 0;
514         }
515 }
516
517 /*
518  * finish_tty - restore the terminal device to its original settings
519  */
520 static void
521 finish_tty()
522 {
523         /* drop dtr to hang up */
524         if (!default_device && modem) {
525                 setdtr(real_ttyfd, 0);
526                 /*
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.
529                  */
530                 sleep(1);
531         }
532
533         restore_tty(real_ttyfd);
534
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);
539                 }
540         }
541
542         close(real_ttyfd);
543         real_ttyfd = -1;
544 }
545
546 /*
547  * maybe_relock - our PID has changed, maybe update the lock file.
548  */
549 static void
550 maybe_relock(arg, pid)
551     void *arg;
552     int pid;
553 {
554     if (locked)
555         relock(pid);
556 }
557
558 /*
559  * open_socket - establish a stream socket connection to the nominated
560  * host and port.
561  */
562 static int
563 open_socket(dest)
564     char *dest;
565 {
566     char *sep, *endp = NULL;
567     int sock, port = -1;
568     u_int32_t host;
569     struct hostent *hent;
570     struct sockaddr_in sad;
571
572     /* parse host:port and resolve host to an IP address */
573     sep = strchr(dest, ':');
574     if (sep != NULL)
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");
578         return -1;
579     }
580     *sep = 0;
581     host = inet_addr(dest);
582     if (host == (u_int32_t) -1) {
583         hent = gethostbyname(dest);
584         if (hent == NULL) {
585             error("%s: unknown host in socket option", dest);
586             *sep = ':';
587             return -1;
588         }
589         host = *(u_int32_t *)(hent->h_addr_list[0]);
590     }
591     *sep = ':';
592
593     /* get a socket and connect it to the other end */
594     sock = socket(PF_INET, SOCK_STREAM, 0);
595     if (sock < 0) {
596         error("Can't create socket: %m");
597         return -1;
598     }
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);
605         close(sock);
606         return -1;
607     }
608
609     return sock;
610 }
611
612
613 /*
614  * start_charshunt - create a child process to run the character shunt.
615  */
616 static int
617 start_charshunt(ifd, ofd)
618     int ifd, ofd;
619 {
620     int cpid;
621
622     cpid = fork();
623     if (cpid == -1) {
624         error("Can't fork process for character shunt: %m");
625         return 0;
626     }
627     if (cpid == 0) {
628         /* child */
629         close(pty_slave);
630         setuid(uid);
631         if (getuid() != uid)
632             fatal("setuid failed");
633         setgid(getgid());
634         if (!nodetach)
635             log_to_fd = -1;
636         charshunt(ifd, ofd, record_file);
637         exit(0);
638     }
639     charshunt_pid = cpid;
640     add_notifier(&sigreceived, stop_charshunt, 0);
641     close(pty_master);
642     pty_master = -1;
643     ttyfd = pty_slave;
644     record_child(cpid, "pppd (charshunt)", charshunt_done, NULL);
645     return 1;
646 }
647
648 static void
649 charshunt_done(arg)
650     void *arg;
651 {
652         charshunt_pid = 0;
653 }
654
655 static void
656 stop_charshunt(arg, sig)
657     void *arg;
658     int sig;
659 {
660         if (charshunt_pid)
661                 kill(charshunt_pid, (sig == SIGINT? sig: SIGTERM));
662 }
663
664 /*
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. :-).
669  */
670 static void
671 charshunt(ifd, ofd, record_file)
672     int ifd, ofd;
673     char *record_file;
674 {
675     int n, nfds;
676     fd_set ready, writey;
677     u_char *ibufp, *obufp;
678     int nibuf, nobuf;
679     int flags;
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[];
686
687     /*
688      * Reset signal handlers.
689      */
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);
703 #ifdef SIGBUS
704     signal(SIGBUS, SIG_DFL);
705 #endif
706 #ifdef SIGEMT
707     signal(SIGEMT, SIG_DFL);
708 #endif
709 #ifdef SIGPOLL
710     signal(SIGPOLL, SIG_DFL);
711 #endif
712 #ifdef SIGPROF
713     signal(SIGPROF, SIG_DFL);
714 #endif
715 #ifdef SIGSYS
716     signal(SIGSYS, SIG_DFL);
717 #endif
718 #ifdef SIGTRAP
719     signal(SIGTRAP, SIG_DFL);
720 #endif
721 #ifdef SIGVTALRM
722     signal(SIGVTALRM, SIG_DFL);
723 #endif
724 #ifdef SIGXCPU
725     signal(SIGXCPU, SIG_DFL);
726 #endif
727 #ifdef SIGXFSZ
728     signal(SIGXFSZ, SIG_DFL);
729 #endif
730
731     /*
732      * Open the record file if required.
733      */
734     if (record_file != NULL) {
735         recordf = fopen(record_file, "a");
736         if (recordf == NULL)
737             error("Couldn't create record file %s: %m", record_file);
738     }
739
740     /* set all the fds to non-blocking mode */
741     flags = fcntl(pty_master, F_GETFL);
742     if (flags == -1
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);
746     if (flags == -1
747         || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
748         warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
749     if (ofd != ifd) {
750         flags = fcntl(ofd, F_GETFL);
751         if (flags == -1
752             || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
753             warn("couldn't set stdout to nonblock: %m");
754     }
755
756     nibuf = nobuf = 0;
757     ibufp = obufp = NULL;
758     pty_readable = stdin_readable = 1;
759
760     ilevel = olevel = 0;
761     gettimeofday(&levelt, NULL);
762     if (max_data_rate) {
763         max_level = max_data_rate / 10;
764         if (max_level < 100)
765             max_level = 100;
766     } else
767         max_level = PPP_MRU + PPP_HDRLEN + 1;
768
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;
778     }
779
780     while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
781         top = 0;
782         tout.tv_sec = 0;
783         tout.tv_usec = 10000;
784         FD_ZERO(&ready);
785         FD_ZERO(&writey);
786         if (nibuf != 0) {
787             if (ilevel >= max_level)
788                 top = &tout;
789             else
790                 FD_SET(pty_master, &writey);
791         } else if (stdin_readable)
792             FD_SET(ifd, &ready);
793         if (nobuf != 0) {
794             if (olevel >= max_level)
795                 top = &tout;
796             else
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) {
801             if (errno != EINTR)
802                 fatal("select");
803             continue;
804         }
805         if (max_data_rate) {
806             double dt;
807             int nbt;
808             struct timeval now;
809
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;
816             levelt = now;
817         } else
818             ilevel = olevel = 0;
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)
823                 nibuf = 0;
824             if (nibuf < 0) {
825                 if (!(errno == EINTR || errno == EAGAIN)) {
826                     error("Error reading standard input: %m");
827                     break;
828                 }
829                 nibuf = 0;
830             } else if (nibuf == 0) {
831                 /* end of file from stdin */
832                 stdin_readable = 0;
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);
836                 if (recordf)
837                     if (!record_write(recordf, 4, NULL, 0, &lasttime))
838                         recordf = NULL;
839             } else {
840                 FD_SET(pty_master, &writey);
841                 if (recordf)
842                     if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
843                         recordf = NULL;
844             }
845         }
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)
850                 nobuf = 0;
851             if (nobuf < 0) {
852                 if (!(errno == EINTR || errno == EAGAIN)) {
853                     error("Error reading pseudo-tty master: %m");
854                     break;
855                 }
856                 nobuf = 0;
857             } else if (nobuf == 0) {
858                 /* end of file from the pty - slave side has closed */
859                 pty_readable = 0;
860                 stdin_readable = 0;     /* pty is not writable now */
861                 nibuf = 0;
862                 close(ofd);
863                 if (recordf)
864                     if (!record_write(recordf, 3, NULL, 0, &lasttime))
865                         recordf = NULL;
866             } else {
867                 FD_SET(ofd, &writey);
868                 if (recordf)
869                     if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
870                         recordf = NULL;
871             }
872         }
873         if (FD_ISSET(ofd, &writey)) {
874             n = nobuf;
875             if (olevel + n > max_level)
876                 n = max_level - olevel;
877             n = write(ofd, obufp, n);
878             if (n < 0) {
879                 if (errno == EIO) {
880                     pty_readable = 0;
881                     nobuf = 0;
882                 } else if (errno != EAGAIN && errno != EINTR) {
883                     error("Error writing standard output: %m");
884                     break;
885                 }
886             } else {
887                 obufp += n;
888                 nobuf -= n;
889                 olevel += n;
890             }
891         }
892         if (FD_ISSET(pty_master, &writey)) {
893             n = nibuf;
894             if (ilevel + n > max_level)
895                 n = max_level - ilevel;
896             n = write(pty_master, ibufp, n);
897             if (n < 0) {
898                 if (errno == EIO) {
899                     stdin_readable = 0;
900                     nibuf = 0;
901                 } else if (errno != EAGAIN && errno != EINTR) {
902                     error("Error writing pseudo-tty master: %m");
903                     break;
904                 }
905             } else {
906                 ibufp += n;
907                 nibuf -= n;
908                 ilevel += n;
909             }
910         }
911     }
912     exit(0);
913 }
914
915 static int
916 record_write(f, code, buf, nb, tp)
917     FILE *f;
918     int code;
919     u_char *buf;
920     int nb;
921     struct timeval *tp;
922 {
923     struct timeval now;
924     int diff;
925
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);
929     if (diff > 0) {
930         if (diff > 255) {
931             putc(5, f);
932             putc(diff >> 24, f);
933             putc(diff >> 16, f);
934             putc(diff >> 8, f);
935             putc(diff, f);
936         } else {
937             putc(6, f);
938             putc(diff, f);
939         }
940         *tp = now;
941     }
942     putc(code, f);
943     if (buf != NULL) {
944         putc(nb >> 8, f);
945         putc(nb, f);
946         fwrite(buf, nb, 1, f);
947     }
948     fflush(f);
949     if (ferror(f)) {
950         error("Error writing record file: %m");
951         return 0;
952     }
953     return 1;
954 }