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