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