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