]> git.ozlabs.org Git - ppp.git/blob - pppd/tty.c
pppd: Use a compile test to detect crypt.h (#198)
[ppp.git] / pppd / tty.c
1 /*
2  * tty.c - code for handling serial ports in pppd.
3  *
4  * Copyright (C) 2000-2004 Paul Mackerras. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  *
13  * 2. The name(s) of the authors of this software must not be used to
14  *    endorse or promote products derived from this software without
15  *    prior written permission.
16  *
17  * 3. Redistributions of any form whatsoever must retain the following
18  *    acknowledgment:
19  *    "This product includes software developed by Paul Mackerras
20  *     <paulus@samba.org>".
21  *
22  * THE AUTHORS OF THIS SOFTWARE DISCLAIM ALL WARRANTIES WITH REGARD TO
23  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
24  * AND FITNESS, IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
25  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
26  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
27  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
28  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
29  *
30  * Portions derived from main.c, which is:
31  *
32  * Copyright (c) 1984-2000 Carnegie Mellon University. All rights reserved.
33  *
34  * Redistribution and use in source and binary forms, with or without
35  * modification, are permitted provided that the following conditions
36  * are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  *
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in
43  *    the documentation and/or other materials provided with the
44  *    distribution.
45  *
46  * 3. The name "Carnegie Mellon University" must not be used to
47  *    endorse or promote products derived from this software without
48  *    prior written permission. For permission or any legal
49  *    details, please contact
50  *      Office of Technology Transfer
51  *      Carnegie Mellon University
52  *      5000 Forbes Avenue
53  *      Pittsburgh, PA  15213-3890
54  *      (412) 268-4387, fax: (412) 268-7395
55  *      tech-transfer@andrew.cmu.edu
56  *
57  * 4. Redistributions of any form whatsoever must retain the following
58  *    acknowledgment:
59  *    "This product includes software developed by Computing Services
60  *     at Carnegie Mellon University (http://www.cmu.edu/computing/)."
61  *
62  * CARNEGIE MELLON UNIVERSITY DISCLAIMS ALL WARRANTIES WITH REGARD TO
63  * THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
64  * AND FITNESS, IN NO EVENT SHALL CARNEGIE MELLON UNIVERSITY BE LIABLE
65  * FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
66  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN
67  * AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
68  * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
69  */
70
71 #include <stdio.h>
72 #include <ctype.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <termios.h>
76 #include <unistd.h>
77 #include <signal.h>
78 #include <errno.h>
79 #include <fcntl.h>
80 #include <syslog.h>
81 #include <netdb.h>
82 #include <utmp.h>
83 #include <pwd.h>
84 #include <sys/param.h>
85 #include <sys/types.h>
86 #include <sys/wait.h>
87 #include <sys/time.h>
88 #include <sys/resource.h>
89 #include <sys/stat.h>
90 #include <sys/socket.h>
91 #include <netinet/in.h>
92 #include <arpa/inet.h>
93
94 #include "pppd.h"
95 #include "fsm.h"
96 #include "lcp.h"
97
98 void tty_process_extra_options(void);
99 void tty_check_options(void);
100 int  connect_tty(void);
101 void disconnect_tty(void);
102 void tty_close_fds(void);
103 void cleanup_tty(void);
104 void tty_do_send_config(int, u_int32_t, int, int);
105
106 static int setdevname(char *, char **, int);
107 static int setspeed(char *, char **, int);
108 static int setxonxoff(char **);
109 static int setescape(char **);
110 static void printescape(option_t *, void (*)(void *, char *,...),void *);
111 static void finish_tty(void);
112 static int start_charshunt(int, int);
113 static void stop_charshunt(void *, int);
114 static void charshunt_done(void *);
115 static void charshunt(int, int, char *);
116 static int record_write(FILE *, int code, u_char *buf, int nb,
117                         struct timeval *);
118 static int open_socket(char *);
119 static void maybe_relock(void *, int);
120
121 static int pty_master;          /* fd for master side of pty */
122 static int pty_slave;           /* fd for slave side of pty */
123 static int real_ttyfd;          /* fd for actual serial port (not pty) */
124 static int ttyfd;               /* Serial port file descriptor */
125 static char speed_str[16];      /* Serial port speed as string */
126
127 mode_t tty_mode = (mode_t)-1;   /* Original access permissions to tty */
128 int baud_rate;                  /* Actual bits/second for serial device */
129 char *callback_script;          /* script for doing callback */
130 int charshunt_pid;              /* Process ID for charshunt */
131 int locked;                     /* lock() has succeeded */
132 struct stat devstat;            /* result of stat() on devnam */
133
134 /* option variables */
135 int     crtscts = 0;            /* Use hardware flow control */
136 int     stop_bits = 1;          /* Number of serial port stop bits */
137 bool    modem = 1;              /* Use modem control lines */
138 int     inspeed = 0;            /* Input/Output speed requested */
139 bool    lockflag = 0;           /* Create lock file to lock the serial dev */
140 char    *initializer = NULL;    /* Script to initialize physical link */
141 char    *connect_script = NULL; /* Script to establish physical link */
142 char    *disconnect_script = NULL; /* Script to disestablish physical link */
143 char    *welcomer = NULL;       /* Script to run after phys link estab. */
144 char    *ptycommand = NULL;     /* Command to run on other side of pty */
145 bool    notty = 0;              /* Stdin/out is not a tty */
146 char    *record_file = NULL;    /* File to record chars sent/received */
147 int     max_data_rate;          /* max bytes/sec through charshunt */
148 bool    sync_serial = 0;        /* Device is synchronous serial device */
149 char    *pty_socket = NULL;     /* Socket to connect to pty */
150 int     using_pty = 0;          /* we're allocating a pty as the device */
151
152 extern uid_t uid;
153 extern int kill_link;
154 extern int asked_to_quit;
155 extern int got_sigterm;
156
157 /* XXX */
158 extern int privopen;            /* don't lock, open device as root */
159
160 u_int32_t xmit_accm[8];         /* extended transmit ACCM */
161
162 /* option descriptors */
163 option_t tty_options[] = {
164     /* device name must be first, or change connect_tty() below! */
165     { "device name", o_wild, (void *) &setdevname,
166       "Serial port device name",
167       OPT_DEVNAM | OPT_PRIVFIX | OPT_NOARG  | OPT_A2STRVAL | OPT_STATIC,
168       devnam},
169
170     { "tty speed", o_wild, (void *) &setspeed,
171       "Baud rate for serial port",
172       OPT_PRIO | OPT_NOARG | OPT_A2STRVAL | OPT_STATIC, speed_str },
173
174     { "lock", o_bool, &lockflag,
175       "Lock serial device with UUCP-style lock file", OPT_PRIO | 1 },
176     { "nolock", o_bool, &lockflag,
177       "Don't lock serial device", OPT_PRIOSUB | OPT_PRIV },
178
179     { "init", o_string, &initializer,
180       "A program to initialize the device", OPT_PRIO | OPT_PRIVFIX },
181
182     { "connect", o_string, &connect_script,
183       "A program to set up a connection", OPT_PRIO | OPT_PRIVFIX },
184
185     { "disconnect", o_string, &disconnect_script,
186       "Program to disconnect serial device", OPT_PRIO | OPT_PRIVFIX },
187
188     { "welcome", o_string, &welcomer,
189       "Script to welcome client", OPT_PRIO | OPT_PRIVFIX },
190
191     { "pty", o_string, &ptycommand,
192       "Script to run on pseudo-tty master side",
193       OPT_PRIO | OPT_PRIVFIX | OPT_DEVNAM },
194
195     { "notty", o_bool, &notty,
196       "Input/output is not a tty", OPT_DEVNAM | 1 },
197
198     { "socket", o_string, &pty_socket,
199       "Send and receive over socket, arg is host:port",
200       OPT_PRIO | OPT_DEVNAM },
201
202     { "record", o_string, &record_file,
203       "Record characters sent/received to file", OPT_PRIO },
204
205     { "crtscts", o_int, &crtscts,
206       "Set hardware (RTS/CTS) flow control",
207       OPT_PRIO | OPT_NOARG | OPT_VAL(1) },
208     { "cdtrcts", o_int, &crtscts,
209       "Set alternate hardware (DTR/CTS) flow control",
210       OPT_PRIOSUB | OPT_NOARG | OPT_VAL(2) },
211     { "nocrtscts", o_int, &crtscts,
212       "Disable hardware flow control",
213       OPT_PRIOSUB | OPT_NOARG | OPT_VAL(-1) },
214     { "-crtscts", o_int, &crtscts,
215       "Disable hardware flow control",
216       OPT_PRIOSUB | OPT_ALIAS | OPT_NOARG | OPT_VAL(-1) },
217     { "nocdtrcts", o_int, &crtscts,
218       "Disable hardware flow control",
219       OPT_PRIOSUB | OPT_ALIAS | OPT_NOARG | OPT_VAL(-1) },
220     { "xonxoff", o_special_noarg, (void *)setxonxoff,
221       "Set software (XON/XOFF) flow control", OPT_PRIOSUB },
222     { "stop-bits", o_int, &stop_bits,
223       "Number of stop bits in serial port",
224       OPT_PRIO | OPT_PRIVFIX | OPT_LIMITS, NULL, 2, 1 },
225
226     { "modem", o_bool, &modem,
227       "Use modem control lines", OPT_PRIO | 1 },
228     { "local", o_bool, &modem,
229       "Don't use modem control lines", OPT_PRIOSUB | 0 },
230
231     { "sync", o_bool, &sync_serial,
232       "Use synchronous HDLC serial encoding", 1 },
233
234     { "datarate", o_int, &max_data_rate,
235       "Maximum data rate in bytes/sec (with pty, notty or record option)",
236       OPT_PRIO },
237
238     { "escape", o_special, (void *)setescape,
239       "List of character codes to escape on transmission",
240       OPT_A2PRINTER, (void *)printescape },
241
242     { NULL }
243 };
244
245
246 struct channel tty_channel = {
247         tty_options,
248         &tty_process_extra_options,
249         &tty_check_options,
250         &connect_tty,
251         &disconnect_tty,
252         &tty_establish_ppp,
253         &tty_disestablish_ppp,
254         &tty_do_send_config,
255         &tty_recv_config,
256         &cleanup_tty,
257         &tty_close_fds
258 };
259
260 /*
261  * setspeed - Set the serial port baud rate.
262  * If doit is 0, the call is to check whether this option is
263  * potentially a speed value.
264  */
265 static int
266 setspeed(char *arg, char **argv, int doit)
267 {
268         char *ptr;
269         int spd;
270
271         spd = strtol(arg, &ptr, 0);
272         if (ptr == arg || *ptr != 0 || spd == 0)
273                 return 0;
274         if (doit) {
275                 inspeed = spd;
276                 slprintf(speed_str, sizeof(speed_str), "%d", spd);
277         }
278         return 1;
279 }
280
281
282 /*
283  * setdevname - Set the device name.
284  * If doit is 0, the call is to check whether this option is
285  * potentially a device name.
286  */
287 static int
288 setdevname(char *cp, char **argv, int doit)
289 {
290         struct stat statbuf;
291         char dev[MAXPATHLEN];
292
293         if (*cp == 0)
294                 return 0;
295
296         if (*cp != '/') {
297                 strlcpy(dev, "/dev/", sizeof(dev));
298                 strlcat(dev, cp, sizeof(dev));
299                 cp = dev;
300         }
301
302         /*
303          * Check if there is a character device by this name.
304          */
305         if (stat(cp, &statbuf) < 0) {
306                 if (!doit)
307                         return errno != ENOENT;
308                 option_error("Couldn't stat %s: %m", cp);
309                 return 0;
310         }
311         if (!S_ISCHR(statbuf.st_mode)) {
312                 if (doit)
313                         option_error("%s is not a character device", cp);
314                 return 0;
315         }
316
317         if (doit) {
318                 strlcpy(devnam, cp, sizeof(devnam));
319                 devstat = statbuf;
320                 default_device = 0;
321         }
322   
323         return 1;
324 }
325
326 static int
327 setxonxoff(char **argv)
328 {
329         lcp_wantoptions[0].asyncmap |= 0x000A0000;      /* escape ^S and ^Q */
330         lcp_wantoptions[0].neg_asyncmap = 1;
331
332         crtscts = -2;
333         return 1;
334 }
335
336 /*
337  * setescape - add chars to the set we escape on transmission.
338  */
339 static int
340 setescape(char **argv)
341 {
342     int n, ret;
343     char *p, *endp;
344
345     p = *argv;
346     ret = 1;
347     while (*p) {
348         n = strtol(p, &endp, 16);
349         if (p == endp) {
350             option_error("escape parameter contains invalid hex number '%s'",
351                          p);
352             return 0;
353         }
354         p = endp;
355         if (n < 0 || n == 0x5E || n > 0xFF) {
356             option_error("can't escape character 0x%x", n);
357             ret = 0;
358         } else
359             xmit_accm[n >> 5] |= 1 << (n & 0x1F);
360         while (*p == ',' || *p == ' ')
361             ++p;
362     }
363     lcp_allowoptions[0].asyncmap = xmit_accm[0];
364     return ret;
365 }
366
367 static void
368 printescape(option_t *opt, void (*printer)(void *, char *, ...), void *arg)
369 {
370         int n;
371         int first = 1;
372
373         for (n = 0; n < 256; ++n) {
374                 if (n == 0x7d)
375                         n += 2;         /* skip 7d, 7e */
376                 if (xmit_accm[n >> 5] & (1 << (n & 0x1f))) {
377                         if (!first)
378                                 printer(arg, ",");
379                         else
380                                 first = 0;
381                         printer(arg, "%x", n);
382                 }
383         }
384         if (first)
385                 printer(arg, "oops # nothing escaped");
386 }
387
388 /*
389  * tty_init - do various tty-related initializations.
390  */
391 void tty_init(void)
392 {
393     add_notifier(&pidchange, maybe_relock, 0);
394     the_channel = &tty_channel;
395     xmit_accm[3] = 0x60000000;
396 }
397
398 /*
399  * tty_process_extra_options - work out which tty device we are using
400  * and read its options file.
401  */
402 void tty_process_extra_options(void)
403 {
404         using_pty = notty || ptycommand != NULL || pty_socket != NULL;
405         if (using_pty)
406                 return;
407         if (default_device) {
408                 char *p;
409                 if (!isatty(0) || (p = ttyname(0)) == NULL) {
410                         option_error("no device specified and stdin is not a tty");
411                         exit(EXIT_OPTION_ERROR);
412                 }
413                 strlcpy(devnam, p, sizeof(devnam));
414                 if (stat(devnam, &devstat) < 0)
415                         fatal("Couldn't stat default device %s: %m", devnam);
416         }
417
418
419         /*
420          * Parse the tty options file.
421          * The per-tty options file should not change
422          * ptycommand, pty_socket, notty or devnam.
423          * options_for_tty doesn't override options set on the command line,
424          * except for some privileged options.
425          */
426         if (!options_for_tty())
427                 exit(EXIT_OPTION_ERROR);
428 }
429
430 /*
431  * tty_check_options - do consistency checks on the options we were given.
432  */
433 void
434 tty_check_options(void)
435 {
436         struct stat statbuf;
437         int fdflags;
438
439         if (demand && notty) {
440                 option_error("demand-dialling is incompatible with notty");
441                 exit(EXIT_OPTION_ERROR);
442         }
443         if (demand && connect_script == 0 && ptycommand == NULL
444             && pty_socket == NULL) {
445                 option_error("connect script is required for demand-dialling\n");
446                 exit(EXIT_OPTION_ERROR);
447         }
448         /* default holdoff to 0 if no connect script has been given */
449         if (connect_script == 0 && !holdoff_specified)
450                 holdoff = 0;
451
452         if (using_pty) {
453                 if (!default_device) {
454                         option_error("%s option precludes specifying device name",
455                                      pty_socket? "socket": notty? "notty": "pty");
456                         exit(EXIT_OPTION_ERROR);
457                 }
458                 if (ptycommand != NULL && notty) {
459                         option_error("pty option is incompatible with notty option");
460                         exit(EXIT_OPTION_ERROR);
461                 }
462                 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
463                         option_error("socket option is incompatible with pty and notty");
464                         exit(EXIT_OPTION_ERROR);
465                 }
466                 default_device = notty;
467                 lockflag = 0;
468                 modem = 0;
469                 if (notty && log_to_fd <= 1)
470                         log_to_fd = -1;
471         } else {
472                 /*
473                  * If the user has specified a device which is the same as
474                  * the one on stdin, pretend they didn't specify any.
475                  * If the device is already open read/write on stdin,
476                  * we assume we don't need to lock it, and we can open it
477                  * as root.
478                  */
479                 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
480                     && statbuf.st_rdev == devstat.st_rdev) {
481                         default_device = 1;
482                         fdflags = fcntl(0, F_GETFL);
483                         if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
484                                 privopen = 1;
485                 }
486         }
487         if (default_device)
488                 nodetach = 1;
489
490         /*
491          * Don't send log messages to the serial port, it tends to
492          * confuse the peer. :-)
493          */
494         if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
495             && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
496                 log_to_fd = -1;
497 }
498
499 /*
500  * connect_tty - get the serial port ready to start doing PPP.
501  * That is, open the serial port, set its speed and mode, and run
502  * the connector and/or welcomer.
503  */
504 int connect_tty(void)
505 {
506         char *connector;
507         int fdflags;
508 #ifndef __linux__
509         struct stat statbuf;
510 #endif
511         char numbuf[16];
512
513         /*
514          * Get a pty master/slave pair if the pty, notty, socket,
515          * or record options were specified.
516          */
517         strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
518         pty_master = -1;
519         pty_slave = -1;
520         real_ttyfd = -1;
521         if (using_pty || record_file != NULL) {
522                 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
523                         error("Couldn't allocate pseudo-tty");
524                         status = EXIT_FATAL_ERROR;
525                         return -1;
526                 }
527                 set_up_tty(pty_slave, 1);
528         }
529
530         /*
531          * Lock the device if we've been asked to.
532          */
533         status = EXIT_LOCK_FAILED;
534         if (lockflag && !privopen) {
535                 if (lock(devnam) < 0)
536                         goto errret;
537                 locked = 1;
538         }
539
540         /*
541          * Open the serial device and set it up to be the ppp interface.
542          * First we open it in non-blocking mode so we can set the
543          * various termios flags appropriately.  If we aren't dialling
544          * out and we want to use the modem lines, we reopen it later
545          * in order to wait for the carrier detect signal from the modem.
546          */
547         got_sigterm = 0;
548         connector = doing_callback? callback_script: connect_script;
549         if (devnam[0] != 0) {
550                 for (;;) {
551                         /* If the user specified the device name, become the
552                            user before opening it. */
553                         int err, prio;
554
555                         prio = privopen? OPRIO_ROOT: tty_options[0].priority;
556                         if (prio < OPRIO_ROOT && seteuid(uid) == -1) {
557                                 error("Unable to drop privileges before opening %s: %m\n",
558                                       devnam);
559                                 status = EXIT_OPEN_FAILED;
560                                 goto errret;
561                         }
562                         real_ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
563                         err = errno;
564                         if (prio < OPRIO_ROOT && seteuid(0) == -1)
565                                 fatal("Unable to regain privileges");
566                         if (real_ttyfd >= 0)
567                                 break;
568                         errno = err;
569                         if (err != EINTR) {
570                                 error("Failed to open %s: %m", devnam);
571                                 status = EXIT_OPEN_FAILED;
572                         }
573                         if (!persist || err != EINTR)
574                                 goto errret;
575                 }
576                 ttyfd = real_ttyfd;
577                 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
578                     || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
579                         warn("Couldn't reset non-blocking mode on device: %m");
580
581 #ifndef __linux__
582                 /*
583                  * Linux 2.4 and above blocks normal writes to the tty
584                  * when it is in PPP line discipline, so this isn't needed.
585                  */
586                 /*
587                  * Do the equivalent of `mesg n' to stop broadcast messages.
588                  */
589                 if (fstat(ttyfd, &statbuf) < 0
590                     || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
591                         warn("Couldn't restrict write permissions to %s: %m", devnam);
592                 } else
593                         tty_mode = statbuf.st_mode;
594 #endif /* __linux__ */
595
596                 /*
597                  * Set line speed, flow control, etc.
598                  * If we have a non-null connection or initializer script,
599                  * on most systems we set CLOCAL for now so that we can talk
600                  * to the modem before carrier comes up.  But this has the
601                  * side effect that we might miss it if CD drops before we
602                  * get to clear CLOCAL below.  On systems where we can talk
603                  * successfully to the modem with CLOCAL clear and CD down,
604                  * we could clear CLOCAL at this point.
605                  */
606                 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
607                                    || initializer != NULL));
608         }
609
610         /*
611          * If the pty, socket, notty and/or record option was specified,
612          * start up the character shunt now.
613          */
614         status = EXIT_PTYCMD_FAILED;
615         if (ptycommand != NULL) {
616                 if (record_file != NULL) {
617                         int ipipe[2], opipe[2], ok;
618
619                         if (pipe(ipipe) < 0 || pipe(opipe) < 0)
620                                 fatal("Couldn't create pipes for record option: %m");
621
622                         /* don't leak these to the ptycommand */
623                         (void) fcntl(ipipe[0], F_SETFD, FD_CLOEXEC);
624                         (void) fcntl(opipe[1], F_SETFD, FD_CLOEXEC);
625
626                         ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
627                                 && start_charshunt(ipipe[0], opipe[1]);
628                         close(ipipe[0]);
629                         close(ipipe[1]);
630                         close(opipe[0]);
631                         close(opipe[1]);
632                         if (!ok)
633                                 goto errret;
634                 } else {
635                         if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
636                                 goto errret;
637                 }
638         } else if (pty_socket != NULL) {
639                 int fd = open_socket(pty_socket);
640                 if (fd < 0)
641                         goto errret;
642                 if (!start_charshunt(fd, fd))
643                         goto errret;
644                 close(fd);
645         } else if (notty) {
646                 if (!start_charshunt(0, 1))
647                         goto errret;
648                 dup2(fd_devnull, 0);
649                 dup2(fd_devnull, 1);
650                 if (log_to_fd == 1)
651                         log_to_fd = -1;
652                 if (log_to_fd != 2)
653                         dup2(fd_devnull, 2);
654         } else if (record_file != NULL) {
655                 int fd = dup(ttyfd);
656                 if (!start_charshunt(fd, fd))
657                         goto errret;
658         }
659
660         if (using_pty || record_file != NULL) {
661                 ttyfd = pty_slave;
662                 close(pty_master);
663                 pty_master = -1;
664         }
665
666         /* run connection script */
667         if ((connector && connector[0]) || initializer) {
668                 if (real_ttyfd != -1) {
669                         /* XXX do this if doing_callback == CALLBACK_DIALIN? */
670                         if (!default_device && modem) {
671                                 setdtr(real_ttyfd, 0);  /* in case modem is off hook */
672                                 sleep(1);
673                                 setdtr(real_ttyfd, 1);
674                         }
675                 }
676
677                 if (initializer && initializer[0]) {
678                         if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
679                                 error("Initializer script failed");
680                                 status = EXIT_INIT_FAILED;
681                                 goto errretf;
682                         }
683                         if (got_sigterm) {
684                                 disconnect_tty();
685                                 goto errretf;
686                         }
687                         info("Serial port initialized.");
688                 }
689
690                 if (connector && connector[0]) {
691                         if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
692                                 error("Connect script failed");
693                                 status = EXIT_CONNECT_FAILED;
694                                 goto errretf;
695                         }
696                         if (got_sigterm) {
697                                 disconnect_tty();
698                                 goto errretf;
699                         }
700                         info("Serial connection established.");
701                 }
702
703                 /* set line speed, flow control, etc.;
704                    clear CLOCAL if modem option */
705                 if (real_ttyfd != -1)
706                         set_up_tty(real_ttyfd, 0);
707
708                 if (doing_callback == CALLBACK_DIALIN)
709                         connector = NULL;
710         }
711
712         /* reopen tty if necessary to wait for carrier */
713         if (connector == NULL && modem && devnam[0] != 0) {
714                 int i;
715                 for (;;) {
716                         if ((i = open(devnam, O_RDWR)) >= 0)
717                                 break;
718                         if (errno != EINTR) {
719                                 error("Failed to reopen %s: %m", devnam);
720                                 status = EXIT_OPEN_FAILED;
721                         }
722                         if (!persist || errno != EINTR || hungup || got_sigterm)
723                                 goto errret;
724                 }
725                 close(i);
726         }
727
728         slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
729         script_setenv("SPEED", numbuf, 0);
730
731         /* run welcome script, if any */
732         if (welcomer && welcomer[0]) {
733                 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
734                         warn("Welcome script failed");
735         }
736
737         /*
738          * If we are initiating this connection, wait for a short
739          * time for something from the peer.  This can avoid bouncing
740          * our packets off his tty before he has it set up.
741          */
742         if (connector != NULL || ptycommand != NULL || pty_socket != NULL)
743                 listen_time = connect_delay;
744
745         return ttyfd;
746
747  errretf:
748         if (real_ttyfd >= 0)
749                 tcflush(real_ttyfd, TCIOFLUSH);
750  errret:
751         if (pty_master >= 0) {
752                 close(pty_master);
753                 pty_master = -1;
754         }
755         ttyfd = -1;
756         if (got_sigterm)
757                 asked_to_quit = 1;
758         return -1;
759 }
760
761
762 void disconnect_tty(void)
763 {
764         if (disconnect_script == NULL || hungup)
765                 return;
766         if (real_ttyfd >= 0)
767                 set_up_tty(real_ttyfd, 1);
768         if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
769                 warn("disconnect script failed");
770         } else {
771                 info("Serial link disconnected.");
772         }
773         stop_charshunt(NULL, 0);
774 }
775
776 void tty_close_fds(void)
777 {
778         if (pty_slave >= 0)
779                 close(pty_slave);
780         if (real_ttyfd >= 0) {
781                 close(real_ttyfd);
782                 real_ttyfd = -1;
783         }
784         /* N.B. ttyfd will == either pty_slave or real_ttyfd */
785 }
786
787 void cleanup_tty(void)
788 {
789         if (real_ttyfd >= 0)
790                 finish_tty();
791         tty_close_fds();
792         if (locked) {
793                 unlock();
794                 locked = 0;
795         }
796 }
797
798 /*
799  * tty_do_send_config - set transmit-side PPP configuration.
800  * We set the extended transmit ACCM here as well.
801  */
802 void
803 tty_do_send_config(int mtu, u_int32_t accm, int pcomp, int accomp)
804 {
805         tty_set_xaccm(xmit_accm);
806         tty_send_config(mtu, accm, pcomp, accomp);
807 }
808
809 /*
810  * finish_tty - restore the terminal device to its original settings
811  */
812 static void
813 finish_tty(void)
814 {
815         /* drop dtr to hang up */
816         if (!default_device && modem) {
817                 setdtr(real_ttyfd, 0);
818                 /*
819                  * This sleep is in case the serial port has CLOCAL set by default,
820                  * and consequently will reassert DTR when we close the device.
821                  */
822                 sleep(1);
823         }
824
825         restore_tty(real_ttyfd);
826
827 #ifndef __linux__
828         if (tty_mode != (mode_t) -1) {
829                 if (fchmod(real_ttyfd, tty_mode) != 0)
830                         error("Couldn't restore tty permissions");
831         }
832 #endif /* __linux__ */
833
834         close(real_ttyfd);
835         real_ttyfd = -1;
836 }
837
838 /*
839  * maybe_relock - our PID has changed, maybe update the lock file.
840  */
841 static void
842 maybe_relock(void *arg, int pid)
843 {
844     if (locked)
845         relock(pid);
846 }
847
848 /*
849  * open_socket - establish a stream socket connection to the nominated
850  * host and port.
851  */
852 static int
853 open_socket(char *dest)
854 {
855     char *sep, *endp = NULL;
856     int sock, port = -1;
857     u_int32_t host;
858     struct hostent *hent;
859     struct sockaddr_in sad;
860
861     /* parse host:port and resolve host to an IP address */
862     sep = strchr(dest, ':');
863     if (sep != NULL)
864         port = strtol(sep+1, &endp, 10);
865     if (port < 0 || endp == sep+1 || sep == dest) {
866         error("Can't parse host:port for socket destination");
867         return -1;
868     }
869     *sep = 0;
870     host = inet_addr(dest);
871     if (host == (u_int32_t) -1) {
872         hent = gethostbyname(dest);
873         if (hent == NULL) {
874             error("%s: unknown host in socket option", dest);
875             *sep = ':';
876             return -1;
877         }
878         host = *(u_int32_t *)(hent->h_addr_list[0]);
879     }
880     *sep = ':';
881
882     /* get a socket and connect it to the other end */
883     sock = socket(PF_INET, SOCK_STREAM, 0);
884     if (sock < 0) {
885         error("Can't create socket: %m");
886         return -1;
887     }
888     memset(&sad, 0, sizeof(sad));
889     sad.sin_family = AF_INET;
890     sad.sin_port = htons(port);
891     sad.sin_addr.s_addr = host;
892     if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
893         error("Can't connect to %s: %m", dest);
894         close(sock);
895         return -1;
896     }
897
898     return sock;
899 }
900
901
902 /*
903  * start_charshunt - create a child process to run the character shunt.
904  */
905 static int
906 start_charshunt(int ifd, int ofd)
907 {
908     int cpid;
909
910     cpid = safe_fork(ifd, ofd, (log_to_fd >= 0? log_to_fd: 2));
911     if (cpid == -1) {
912         error("Can't fork process for character shunt: %m");
913         return 0;
914     }
915     if (cpid == 0) {
916         /* child */
917         reopen_log();
918         if (!nodetach)
919             log_to_fd = -1;
920         else if (log_to_fd >= 0)
921             log_to_fd = 2;
922         setgid(getgid());
923         setuid(uid);
924         if (getuid() != uid)
925             fatal("setuid failed");
926         charshunt(0, 1, record_file);
927         exit(0);
928     }
929     charshunt_pid = cpid;
930     record_child(cpid, "pppd (charshunt)", charshunt_done, NULL, 1);
931     return 1;
932 }
933
934 static void
935 charshunt_done(void *arg)
936 {
937         charshunt_pid = 0;
938 }
939
940 static void
941 stop_charshunt(void *arg, int sig)
942 {
943         if (charshunt_pid)
944                 kill(charshunt_pid, (sig == SIGINT? sig: SIGTERM));
945 }
946
947 /*
948  * charshunt - the character shunt, which passes characters between
949  * the pty master side and the serial port (or stdin/stdout).
950  * This runs as the user (not as root).
951  * (We assume ofd >= ifd which is true the way this gets called. :-).
952  */
953 static void
954 charshunt(int ifd, int ofd, char *record_file)
955 {
956     int n, nfds;
957     fd_set ready, writey;
958     u_char *ibufp, *obufp;
959     int nibuf, nobuf;
960     int flags;
961     int pty_readable, stdin_readable;
962     struct timeval lasttime;
963     FILE *recordf = NULL;
964     int ilevel, olevel, max_level;
965     struct timeval levelt, tout, *top;
966     extern u_char inpacket_buf[];
967
968     /*
969      * Reset signal handlers.
970      */
971     signal(SIGHUP, SIG_IGN);            /* Hangup */
972     signal(SIGINT, SIG_DFL);            /* Interrupt */
973     signal(SIGTERM, SIG_DFL);           /* Terminate */
974     signal(SIGCHLD, SIG_DFL);
975     signal(SIGUSR1, SIG_DFL);
976     signal(SIGUSR2, SIG_DFL);
977     signal(SIGABRT, SIG_DFL);
978     signal(SIGALRM, SIG_DFL);
979     signal(SIGFPE, SIG_DFL);
980     signal(SIGILL, SIG_DFL);
981     signal(SIGPIPE, SIG_DFL);
982     signal(SIGQUIT, SIG_DFL);
983     signal(SIGSEGV, SIG_DFL);
984 #ifdef SIGBUS
985     signal(SIGBUS, SIG_DFL);
986 #endif
987 #ifdef SIGEMT
988     signal(SIGEMT, SIG_DFL);
989 #endif
990 #ifdef SIGPOLL
991     signal(SIGPOLL, SIG_DFL);
992 #endif
993 #ifdef SIGPROF
994     signal(SIGPROF, SIG_DFL);
995 #endif
996 #ifdef SIGSYS
997     signal(SIGSYS, SIG_DFL);
998 #endif
999 #ifdef SIGTRAP
1000     signal(SIGTRAP, SIG_DFL);
1001 #endif
1002 #ifdef SIGVTALRM
1003     signal(SIGVTALRM, SIG_DFL);
1004 #endif
1005 #ifdef SIGXCPU
1006     signal(SIGXCPU, SIG_DFL);
1007 #endif
1008 #ifdef SIGXFSZ
1009     signal(SIGXFSZ, SIG_DFL);
1010 #endif
1011
1012     /*
1013      * Check that the fds won't overrun the fd_sets
1014      */
1015     if (ifd >= FD_SETSIZE || ofd >= FD_SETSIZE || pty_master >= FD_SETSIZE)
1016         fatal("internal error: file descriptor too large (%d, %d, %d)",
1017               ifd, ofd, pty_master);
1018
1019     /*
1020      * Open the record file if required.
1021      */
1022     if (record_file != NULL) {
1023         recordf = fopen(record_file, "a");
1024         if (recordf == NULL)
1025             error("Couldn't create record file %s: %m", record_file);
1026     }
1027
1028     /* set all the fds to non-blocking mode */
1029     flags = fcntl(pty_master, F_GETFL);
1030     if (flags == -1
1031         || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1032         warn("couldn't set pty master to nonblock: %m");
1033     flags = fcntl(ifd, F_GETFL);
1034     if (flags == -1
1035         || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1036         warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1037     if (ofd != ifd) {
1038         flags = fcntl(ofd, F_GETFL);
1039         if (flags == -1
1040             || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1041             warn("couldn't set stdout to nonblock: %m");
1042     }
1043
1044     nibuf = nobuf = 0;
1045     ibufp = obufp = NULL;
1046     pty_readable = stdin_readable = 1;
1047
1048     ilevel = olevel = 0;
1049     get_time(&levelt);
1050     if (max_data_rate) {
1051         max_level = max_data_rate / 10;
1052         if (max_level < 100)
1053             max_level = 100;
1054     } else
1055         max_level = PPP_MRU + PPP_HDRLEN + 1;
1056
1057     nfds = (ofd > pty_master? ofd: pty_master) + 1;
1058     if (recordf != NULL) {
1059         gettimeofday(&lasttime, NULL);
1060         putc(7, recordf);       /* put start marker */
1061         putc(lasttime.tv_sec >> 24, recordf);
1062         putc(lasttime.tv_sec >> 16, recordf);
1063         putc(lasttime.tv_sec >> 8, recordf);
1064         putc(lasttime.tv_sec, recordf);
1065         lasttime.tv_usec = 0;
1066     }
1067
1068     while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1069         top = 0;
1070         tout.tv_sec = 0;
1071         tout.tv_usec = 10000;
1072         FD_ZERO(&ready);
1073         FD_ZERO(&writey);
1074         if (nibuf != 0) {
1075             if (ilevel >= max_level)
1076                 top = &tout;
1077             else
1078                 FD_SET(pty_master, &writey);
1079         } else if (stdin_readable)
1080             FD_SET(ifd, &ready);
1081         if (nobuf != 0) {
1082             if (olevel >= max_level)
1083                 top = &tout;
1084             else
1085                 FD_SET(ofd, &writey);
1086         } else if (pty_readable)
1087             FD_SET(pty_master, &ready);
1088         if (select(nfds, &ready, &writey, NULL, top) < 0) {
1089             if (errno != EINTR)
1090                 fatal("select");
1091             continue;
1092         }
1093         if (max_data_rate) {
1094             double dt;
1095             int nbt;
1096             struct timeval now;
1097
1098             get_time(&now);
1099             dt = (now.tv_sec - levelt.tv_sec
1100                   + (now.tv_usec - levelt.tv_usec) / 1e6);
1101             nbt = (int)(dt * max_data_rate);
1102             ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
1103             olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
1104             levelt = now;
1105         } else
1106             ilevel = olevel = 0;
1107         if (FD_ISSET(ifd, &ready)) {
1108             ibufp = inpacket_buf;
1109             nibuf = read(ifd, ibufp, PPP_MRU + PPP_HDRLEN);
1110             if (nibuf < 0 && errno == EIO)
1111                 nibuf = 0;
1112             if (nibuf < 0) {
1113                 if (!(errno == EINTR || errno == EAGAIN)) {
1114                     error("Error reading standard input: %m");
1115                     break;
1116                 }
1117                 nibuf = 0;
1118             } else if (nibuf == 0) {
1119                 /* end of file from stdin */
1120                 stdin_readable = 0;
1121                 if (recordf)
1122                     if (!record_write(recordf, 4, NULL, 0, &lasttime))
1123                         recordf = NULL;
1124             } else {
1125                 FD_SET(pty_master, &writey);
1126                 if (recordf)
1127                     if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
1128                         recordf = NULL;
1129             }
1130         }
1131         if (FD_ISSET(pty_master, &ready)) {
1132             obufp = outpacket_buf;
1133             nobuf = read(pty_master, obufp, PPP_MRU + PPP_HDRLEN);
1134             if (nobuf < 0 && errno == EIO)
1135                 nobuf = 0;
1136             if (nobuf < 0) {
1137                 if (!(errno == EINTR || errno == EAGAIN)) {
1138                     error("Error reading pseudo-tty master: %m");
1139                     break;
1140                 }
1141                 nobuf = 0;
1142             } else if (nobuf == 0) {
1143                 /* end of file from the pty - slave side has closed */
1144                 pty_readable = 0;
1145                 stdin_readable = 0;     /* pty is not writable now */
1146                 nibuf = 0;
1147                 close(ofd);
1148                 if (recordf)
1149                     if (!record_write(recordf, 3, NULL, 0, &lasttime))
1150                         recordf = NULL;
1151             } else {
1152                 FD_SET(ofd, &writey);
1153                 if (recordf)
1154                     if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
1155                         recordf = NULL;
1156             }
1157         } else if (!stdin_readable)
1158             pty_readable = 0;
1159         if (FD_ISSET(ofd, &writey)) {
1160             n = nobuf;
1161             if (olevel + n > max_level)
1162                 n = max_level - olevel;
1163             n = write(ofd, obufp, n);
1164             if (n < 0) {
1165                 if (errno == EIO) {
1166                     pty_readable = 0;
1167                     nobuf = 0;
1168                 } else if (errno != EAGAIN && errno != EINTR) {
1169                     error("Error writing standard output: %m");
1170                     break;
1171                 }
1172             } else {
1173                 obufp += n;
1174                 nobuf -= n;
1175                 olevel += n;
1176             }
1177         }
1178         if (FD_ISSET(pty_master, &writey)) {
1179             n = nibuf;
1180             if (ilevel + n > max_level)
1181                 n = max_level - ilevel;
1182             n = write(pty_master, ibufp, n);
1183             if (n < 0) {
1184                 if (errno == EIO) {
1185                     stdin_readable = 0;
1186                     nibuf = 0;
1187                 } else if (errno != EAGAIN && errno != EINTR) {
1188                     error("Error writing pseudo-tty master: %m");
1189                     break;
1190                 }
1191             } else {
1192                 ibufp += n;
1193                 nibuf -= n;
1194                 ilevel += n;
1195             }
1196         }
1197     }
1198     exit(0);
1199 }
1200
1201 static int
1202 record_write(FILE *f, int code, u_char *buf, int nb, struct timeval *tp)
1203 {
1204     struct timeval now;
1205     int diff;
1206
1207     gettimeofday(&now, NULL);
1208     now.tv_usec /= 100000;      /* actually 1/10 s, not usec now */
1209     diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
1210     if (diff > 0) {
1211         if (diff > 255) {
1212             putc(5, f);
1213             putc(diff >> 24, f);
1214             putc(diff >> 16, f);
1215             putc(diff >> 8, f);
1216             putc(diff, f);
1217         } else {
1218             putc(6, f);
1219             putc(diff, f);
1220         }
1221         *tp = now;
1222     }
1223     putc(code, f);
1224     if (buf != NULL) {
1225         putc(nb >> 8, f);
1226         putc(nb, f);
1227         fwrite(buf, nb, 1, f);
1228     }
1229     fflush(f);
1230     if (ferror(f)) {
1231         error("Error writing record file: %m");
1232         return 0;
1233     }
1234     return 1;
1235 }