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