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