Debian Codegraph @

pppd/tty.c

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