rp_pppoe: Copy acName and pppd_pppoe_service after option parsing
[mpls-ppp.git] / pppd / tty.c
blobd571b111d7e34755d9304104c075dcbcc16f4e44
1 /*
2 * tty.c - code for handling serial ports in pppd.
4 * Copyright (C) 2000-2004 Paul Mackerras. All rights reserved.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
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.
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>".
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.
30 * Portions derived from main.c, which is:
32 * Copyright (c) 1984-2000 Carnegie Mellon University. All rights reserved.
34 * Redistribution and use in source and binary forms, with or without
35 * modification, are permitted provided that the following conditions
36 * are met:
38 * 1. Redistributions of source code must retain the above copyright
39 * notice, this list of conditions and the following disclaimer.
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.
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
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/)."
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.
71 #define RCSID "$Id: tty.c,v 1.27 2008/07/01 12:27:56 paulus Exp $"
73 #include <stdio.h>
74 #include <ctype.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <termios.h>
78 #include <unistd.h>
79 #include <signal.h>
80 #include <errno.h>
81 #include <fcntl.h>
82 #include <syslog.h>
83 #include <netdb.h>
84 #include <utmp.h>
85 #include <pwd.h>
86 #include <setjmp.h>
87 #include <sys/param.h>
88 #include <sys/types.h>
89 #include <sys/wait.h>
90 #include <sys/time.h>
91 #include <sys/resource.h>
92 #include <sys/stat.h>
93 #include <sys/socket.h>
94 #include <netinet/in.h>
95 #include <arpa/inet.h>
97 #include "pppd.h"
98 #include "fsm.h"
99 #include "lcp.h"
101 void tty_process_extra_options __P((void));
102 void tty_check_options __P((void));
103 int connect_tty __P((void));
104 void disconnect_tty __P((void));
105 void tty_close_fds __P((void));
106 void cleanup_tty __P((void));
107 void tty_do_send_config __P((int, u_int32_t, int, int));
109 static int setdevname __P((char *, char **, int));
110 static int setspeed __P((char *, char **, int));
111 static int setxonxoff __P((char **));
112 static int setescape __P((char **));
113 static void printescape __P((option_t *, void (*)(void *, char *,...),void *));
114 static void finish_tty __P((void));
115 static int start_charshunt __P((int, int));
116 static void stop_charshunt __P((void *, int));
117 static void charshunt_done __P((void *));
118 static void charshunt __P((int, int, char *));
119 static int record_write __P((FILE *, int code, u_char *buf, int nb,
120 struct timeval *));
121 static int open_socket __P((char *));
122 static void maybe_relock __P((void *, int));
124 static int pty_master; /* fd for master side of pty */
125 static int pty_slave; /* fd for slave side of pty */
126 static int real_ttyfd; /* fd for actual serial port (not pty) */
127 static int ttyfd; /* Serial port file descriptor */
128 static char speed_str[16]; /* Serial port speed as string */
130 mode_t tty_mode = (mode_t)-1; /* Original access permissions to tty */
131 int baud_rate; /* Actual bits/second for serial device */
132 char *callback_script; /* script for doing callback */
133 int charshunt_pid; /* Process ID for charshunt */
134 int locked; /* lock() has succeeded */
135 struct stat devstat; /* result of stat() on devnam */
137 /* option variables */
138 int crtscts = 0; /* Use hardware flow control */
139 bool modem = 1; /* Use modem control lines */
140 int inspeed = 0; /* Input/Output speed requested */
141 bool lockflag = 0; /* Create lock file to lock the serial dev */
142 char *initializer = NULL; /* Script to initialize physical link */
143 char *connect_script = NULL; /* Script to establish physical link */
144 char *disconnect_script = NULL; /* Script to disestablish physical link */
145 char *welcomer = NULL; /* Script to run after phys link estab. */
146 char *ptycommand = NULL; /* Command to run on other side of pty */
147 bool notty = 0; /* Stdin/out is not a tty */
148 char *record_file = NULL; /* File to record chars sent/received */
149 int max_data_rate; /* max bytes/sec through charshunt */
150 bool sync_serial = 0; /* Device is synchronous serial device */
151 char *pty_socket = NULL; /* Socket to connect to pty */
152 int using_pty = 0; /* we're allocating a pty as the device */
154 extern uid_t uid;
155 extern int kill_link;
156 extern int asked_to_quit;
157 extern int got_sigterm;
159 /* XXX */
160 extern int privopen; /* don't lock, open device as root */
162 u_int32_t xmit_accm[8]; /* extended transmit ACCM */
164 /* option descriptors */
165 option_t tty_options[] = {
166 /* device name must be first, or change connect_tty() below! */
167 { "device name", o_wild, (void *) &setdevname,
168 "Serial port device name",
169 OPT_DEVNAM | OPT_PRIVFIX | OPT_NOARG | OPT_A2STRVAL | OPT_STATIC,
170 devnam},
172 { "tty speed", o_wild, (void *) &setspeed,
173 "Baud rate for serial port",
174 OPT_PRIO | OPT_NOARG | OPT_A2STRVAL | OPT_STATIC, speed_str },
176 { "lock", o_bool, &lockflag,
177 "Lock serial device with UUCP-style lock file", OPT_PRIO | 1 },
178 { "nolock", o_bool, &lockflag,
179 "Don't lock serial device", OPT_PRIOSUB | OPT_PRIV },
181 { "init", o_string, &initializer,
182 "A program to initialize the device", OPT_PRIO | OPT_PRIVFIX },
184 { "connect", o_string, &connect_script,
185 "A program to set up a connection", OPT_PRIO | OPT_PRIVFIX },
187 { "disconnect", o_string, &disconnect_script,
188 "Program to disconnect serial device", OPT_PRIO | OPT_PRIVFIX },
190 { "welcome", o_string, &welcomer,
191 "Script to welcome client", OPT_PRIO | OPT_PRIVFIX },
193 { "pty", o_string, &ptycommand,
194 "Script to run on pseudo-tty master side",
195 OPT_PRIO | OPT_PRIVFIX | OPT_DEVNAM },
197 { "notty", o_bool, &notty,
198 "Input/output is not a tty", OPT_DEVNAM | 1 },
200 { "socket", o_string, &pty_socket,
201 "Send and receive over socket, arg is host:port",
202 OPT_PRIO | OPT_DEVNAM },
204 { "record", o_string, &record_file,
205 "Record characters sent/received to file", OPT_PRIO },
207 { "crtscts", o_int, &crtscts,
208 "Set hardware (RTS/CTS) flow control",
209 OPT_PRIO | OPT_NOARG | OPT_VAL(1) },
210 { "cdtrcts", o_int, &crtscts,
211 "Set alternate hardware (DTR/CTS) flow control",
212 OPT_PRIOSUB | OPT_NOARG | OPT_VAL(2) },
213 { "nocrtscts", o_int, &crtscts,
214 "Disable hardware flow control",
215 OPT_PRIOSUB | OPT_NOARG | OPT_VAL(-1) },
216 { "-crtscts", o_int, &crtscts,
217 "Disable hardware flow control",
218 OPT_PRIOSUB | OPT_ALIAS | OPT_NOARG | OPT_VAL(-1) },
219 { "nocdtrcts", o_int, &crtscts,
220 "Disable hardware flow control",
221 OPT_PRIOSUB | OPT_ALIAS | OPT_NOARG | OPT_VAL(-1) },
222 { "xonxoff", o_special_noarg, (void *)setxonxoff,
223 "Set software (XON/XOFF) flow control", OPT_PRIOSUB },
225 { "modem", o_bool, &modem,
226 "Use modem control lines", OPT_PRIO | 1 },
227 { "local", o_bool, &modem,
228 "Don't use modem control lines", OPT_PRIOSUB | 0 },
230 { "sync", o_bool, &sync_serial,
231 "Use synchronous HDLC serial encoding", 1 },
233 { "datarate", o_int, &max_data_rate,
234 "Maximum data rate in bytes/sec (with pty, notty or record option)",
235 OPT_PRIO },
237 { "escape", o_special, (void *)setescape,
238 "List of character codes to escape on transmission",
239 OPT_A2PRINTER, (void *)printescape },
241 { NULL }
245 struct channel tty_channel = {
246 tty_options,
247 &tty_process_extra_options,
248 &tty_check_options,
249 &connect_tty,
250 &disconnect_tty,
251 &tty_establish_ppp,
252 &tty_disestablish_ppp,
253 &tty_do_send_config,
254 &tty_recv_config,
255 &cleanup_tty,
256 &tty_close_fds
260 * setspeed - Set the serial port baud rate.
261 * If doit is 0, the call is to check whether this option is
262 * potentially a speed value.
264 static int
265 setspeed(arg, argv, doit)
266 char *arg;
267 char **argv;
268 int doit;
270 char *ptr;
271 int spd;
273 spd = strtol(arg, &ptr, 0);
274 if (ptr == arg || *ptr != 0 || spd == 0)
275 return 0;
276 if (doit) {
277 inspeed = spd;
278 slprintf(speed_str, sizeof(speed_str), "%d", spd);
280 return 1;
285 * setdevname - Set the device name.
286 * If doit is 0, the call is to check whether this option is
287 * potentially a device name.
289 static int
290 setdevname(cp, argv, doit)
291 char *cp;
292 char **argv;
293 int doit;
295 struct stat statbuf;
296 char dev[MAXPATHLEN];
298 if (*cp == 0)
299 return 0;
301 if (*cp != '/') {
302 strlcpy(dev, "/dev/", sizeof(dev));
303 strlcat(dev, cp, sizeof(dev));
304 cp = dev;
308 * Check if there is a character device by this name.
310 if (stat(cp, &statbuf) < 0) {
311 if (!doit)
312 return errno != ENOENT;
313 option_error("Couldn't stat %s: %m", cp);
314 return 0;
316 if (!S_ISCHR(statbuf.st_mode)) {
317 if (doit)
318 option_error("%s is not a character device", cp);
319 return 0;
322 if (doit) {
323 strlcpy(devnam, cp, sizeof(devnam));
324 devstat = statbuf;
325 default_device = 0;
328 return 1;
331 static int
332 setxonxoff(argv)
333 char **argv;
335 lcp_wantoptions[0].asyncmap |= 0x000A0000; /* escape ^S and ^Q */
336 lcp_wantoptions[0].neg_asyncmap = 1;
338 crtscts = -2;
339 return 1;
343 * setescape - add chars to the set we escape on transmission.
345 static int
346 setescape(argv)
347 char **argv;
349 int n, ret;
350 char *p, *endp;
352 p = *argv;
353 ret = 1;
354 while (*p) {
355 n = strtol(p, &endp, 16);
356 if (p == endp) {
357 option_error("escape parameter contains invalid hex number '%s'",
359 return 0;
361 p = endp;
362 if (n < 0 || n == 0x5E || n > 0xFF) {
363 option_error("can't escape character 0x%x", n);
364 ret = 0;
365 } else
366 xmit_accm[n >> 5] |= 1 << (n & 0x1F);
367 while (*p == ',' || *p == ' ')
368 ++p;
370 lcp_allowoptions[0].asyncmap = xmit_accm[0];
371 return ret;
374 static void
375 printescape(opt, printer, arg)
376 option_t *opt;
377 void (*printer) __P((void *, char *, ...));
378 void *arg;
380 int n;
381 int first = 1;
383 for (n = 0; n < 256; ++n) {
384 if (n == 0x7d)
385 n += 2; /* skip 7d, 7e */
386 if (xmit_accm[n >> 5] & (1 << (n & 0x1f))) {
387 if (!first)
388 printer(arg, ",");
389 else
390 first = 0;
391 printer(arg, "%x", n);
394 if (first)
395 printer(arg, "oops # nothing escaped");
399 * tty_init - do various tty-related initializations.
401 void tty_init()
403 add_notifier(&pidchange, maybe_relock, 0);
404 the_channel = &tty_channel;
405 xmit_accm[3] = 0x60000000;
409 * tty_process_extra_options - work out which tty device we are using
410 * and read its options file.
412 void tty_process_extra_options()
414 using_pty = notty || ptycommand != NULL || pty_socket != NULL;
415 if (using_pty)
416 return;
417 if (default_device) {
418 char *p;
419 if (!isatty(0) || (p = ttyname(0)) == NULL) {
420 option_error("no device specified and stdin is not a tty");
421 exit(EXIT_OPTION_ERROR);
423 strlcpy(devnam, p, sizeof(devnam));
424 if (stat(devnam, &devstat) < 0)
425 fatal("Couldn't stat default device %s: %m", devnam);
430 * Parse the tty options file.
431 * The per-tty options file should not change
432 * ptycommand, pty_socket, notty or devnam.
433 * options_for_tty doesn't override options set on the command line,
434 * except for some privileged options.
436 if (!options_for_tty())
437 exit(EXIT_OPTION_ERROR);
441 * tty_check_options - do consistency checks on the options we were given.
443 void
444 tty_check_options()
446 struct stat statbuf;
447 int fdflags;
449 if (demand && notty) {
450 option_error("demand-dialling is incompatible with notty");
451 exit(EXIT_OPTION_ERROR);
453 if (demand && connect_script == 0 && ptycommand == NULL
454 && pty_socket == NULL) {
455 option_error("connect script is required for demand-dialling\n");
456 exit(EXIT_OPTION_ERROR);
458 /* default holdoff to 0 if no connect script has been given */
459 if (connect_script == 0 && !holdoff_specified)
460 holdoff = 0;
462 if (using_pty) {
463 if (!default_device) {
464 option_error("%s option precludes specifying device name",
465 pty_socket? "socket": notty? "notty": "pty");
466 exit(EXIT_OPTION_ERROR);
468 if (ptycommand != NULL && notty) {
469 option_error("pty option is incompatible with notty option");
470 exit(EXIT_OPTION_ERROR);
472 if (pty_socket != NULL && (ptycommand != NULL || notty)) {
473 option_error("socket option is incompatible with pty and notty");
474 exit(EXIT_OPTION_ERROR);
476 default_device = notty;
477 lockflag = 0;
478 modem = 0;
479 if (notty && log_to_fd <= 1)
480 log_to_fd = -1;
481 } else {
483 * If the user has specified a device which is the same as
484 * the one on stdin, pretend they didn't specify any.
485 * If the device is already open read/write on stdin,
486 * we assume we don't need to lock it, and we can open it
487 * as root.
489 if (fstat(0, &statbuf) >= 0 && S_ISCHR(statbuf.st_mode)
490 && statbuf.st_rdev == devstat.st_rdev) {
491 default_device = 1;
492 fdflags = fcntl(0, F_GETFL);
493 if (fdflags != -1 && (fdflags & O_ACCMODE) == O_RDWR)
494 privopen = 1;
497 if (default_device)
498 nodetach = 1;
501 * Don't send log messages to the serial port, it tends to
502 * confuse the peer. :-)
504 if (log_to_fd >= 0 && fstat(log_to_fd, &statbuf) >= 0
505 && S_ISCHR(statbuf.st_mode) && statbuf.st_rdev == devstat.st_rdev)
506 log_to_fd = -1;
510 * connect_tty - get the serial port ready to start doing PPP.
511 * That is, open the serial port, set its speed and mode, and run
512 * the connector and/or welcomer.
514 int connect_tty()
516 char *connector;
517 int fdflags;
518 #ifndef __linux__
519 struct stat statbuf;
520 #endif
521 char numbuf[16];
524 * Get a pty master/slave pair if the pty, notty, socket,
525 * or record options were specified.
527 strlcpy(ppp_devnam, devnam, sizeof(ppp_devnam));
528 pty_master = -1;
529 pty_slave = -1;
530 real_ttyfd = -1;
531 if (using_pty || record_file != NULL) {
532 if (!get_pty(&pty_master, &pty_slave, ppp_devnam, uid)) {
533 error("Couldn't allocate pseudo-tty");
534 status = EXIT_FATAL_ERROR;
535 return -1;
537 set_up_tty(pty_slave, 1);
541 * Lock the device if we've been asked to.
543 status = EXIT_LOCK_FAILED;
544 if (lockflag && !privopen) {
545 if (lock(devnam) < 0)
546 goto errret;
547 locked = 1;
551 * Open the serial device and set it up to be the ppp interface.
552 * First we open it in non-blocking mode so we can set the
553 * various termios flags appropriately. If we aren't dialling
554 * out and we want to use the modem lines, we reopen it later
555 * in order to wait for the carrier detect signal from the modem.
557 got_sigterm = 0;
558 connector = doing_callback? callback_script: connect_script;
559 if (devnam[0] != 0) {
560 for (;;) {
561 /* If the user specified the device name, become the
562 user before opening it. */
563 int err, prio;
565 prio = privopen? OPRIO_ROOT: tty_options[0].priority;
566 if (prio < OPRIO_ROOT && seteuid(uid) == -1) {
567 error("Unable to drop privileges before opening %s: %m\n",
568 devnam);
569 status = EXIT_OPEN_FAILED;
570 goto errret;
572 real_ttyfd = open(devnam, O_NONBLOCK | O_RDWR, 0);
573 err = errno;
574 if (prio < OPRIO_ROOT && seteuid(0) == -1)
575 fatal("Unable to regain privileges");
576 if (real_ttyfd >= 0)
577 break;
578 errno = err;
579 if (err != EINTR) {
580 error("Failed to open %s: %m", devnam);
581 status = EXIT_OPEN_FAILED;
583 if (!persist || err != EINTR)
584 goto errret;
586 ttyfd = real_ttyfd;
587 if ((fdflags = fcntl(ttyfd, F_GETFL)) == -1
588 || fcntl(ttyfd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
589 warn("Couldn't reset non-blocking mode on device: %m");
591 #ifndef __linux__
593 * Linux 2.4 and above blocks normal writes to the tty
594 * when it is in PPP line discipline, so this isn't needed.
597 * Do the equivalent of `mesg n' to stop broadcast messages.
599 if (fstat(ttyfd, &statbuf) < 0
600 || fchmod(ttyfd, statbuf.st_mode & ~(S_IWGRP | S_IWOTH)) < 0) {
601 warn("Couldn't restrict write permissions to %s: %m", devnam);
602 } else
603 tty_mode = statbuf.st_mode;
604 #endif /* __linux__ */
607 * Set line speed, flow control, etc.
608 * If we have a non-null connection or initializer script,
609 * on most systems we set CLOCAL for now so that we can talk
610 * to the modem before carrier comes up. But this has the
611 * side effect that we might miss it if CD drops before we
612 * get to clear CLOCAL below. On systems where we can talk
613 * successfully to the modem with CLOCAL clear and CD down,
614 * we could clear CLOCAL at this point.
616 set_up_tty(ttyfd, ((connector != NULL && connector[0] != 0)
617 || initializer != NULL));
621 * If the pty, socket, notty and/or record option was specified,
622 * start up the character shunt now.
624 status = EXIT_PTYCMD_FAILED;
625 if (ptycommand != NULL) {
626 if (record_file != NULL) {
627 int ipipe[2], opipe[2], ok;
629 if (pipe(ipipe) < 0 || pipe(opipe) < 0)
630 fatal("Couldn't create pipes for record option: %m");
632 /* don't leak these to the ptycommand */
633 (void) fcntl(ipipe[0], F_SETFD, FD_CLOEXEC);
634 (void) fcntl(opipe[1], F_SETFD, FD_CLOEXEC);
636 ok = device_script(ptycommand, opipe[0], ipipe[1], 1) == 0
637 && start_charshunt(ipipe[0], opipe[1]);
638 close(ipipe[0]);
639 close(ipipe[1]);
640 close(opipe[0]);
641 close(opipe[1]);
642 if (!ok)
643 goto errret;
644 } else {
645 if (device_script(ptycommand, pty_master, pty_master, 1) < 0)
646 goto errret;
648 } else if (pty_socket != NULL) {
649 int fd = open_socket(pty_socket);
650 if (fd < 0)
651 goto errret;
652 if (!start_charshunt(fd, fd))
653 goto errret;
654 close(fd);
655 } else if (notty) {
656 if (!start_charshunt(0, 1))
657 goto errret;
658 dup2(fd_devnull, 0);
659 dup2(fd_devnull, 1);
660 if (log_to_fd == 1)
661 log_to_fd = -1;
662 if (log_to_fd != 2)
663 dup2(fd_devnull, 2);
664 } else if (record_file != NULL) {
665 int fd = dup(ttyfd);
666 if (!start_charshunt(fd, fd))
667 goto errret;
670 if (using_pty || record_file != NULL) {
671 ttyfd = pty_slave;
672 close(pty_master);
673 pty_master = -1;
676 /* run connection script */
677 if ((connector && connector[0]) || initializer) {
678 if (real_ttyfd != -1) {
679 /* XXX do this if doing_callback == CALLBACK_DIALIN? */
680 if (!default_device && modem) {
681 setdtr(real_ttyfd, 0); /* in case modem is off hook */
682 sleep(1);
683 setdtr(real_ttyfd, 1);
687 if (initializer && initializer[0]) {
688 if (device_script(initializer, ttyfd, ttyfd, 0) < 0) {
689 error("Initializer script failed");
690 status = EXIT_INIT_FAILED;
691 goto errretf;
693 if (got_sigterm) {
694 disconnect_tty();
695 goto errretf;
697 info("Serial port initialized.");
700 if (connector && connector[0]) {
701 if (device_script(connector, ttyfd, ttyfd, 0) < 0) {
702 error("Connect script failed");
703 status = EXIT_CONNECT_FAILED;
704 goto errretf;
706 if (got_sigterm) {
707 disconnect_tty();
708 goto errretf;
710 info("Serial connection established.");
713 /* set line speed, flow control, etc.;
714 clear CLOCAL if modem option */
715 if (real_ttyfd != -1)
716 set_up_tty(real_ttyfd, 0);
718 if (doing_callback == CALLBACK_DIALIN)
719 connector = NULL;
722 /* reopen tty if necessary to wait for carrier */
723 if (connector == NULL && modem && devnam[0] != 0) {
724 int i;
725 for (;;) {
726 if ((i = open(devnam, O_RDWR)) >= 0)
727 break;
728 if (errno != EINTR) {
729 error("Failed to reopen %s: %m", devnam);
730 status = EXIT_OPEN_FAILED;
732 if (!persist || errno != EINTR || hungup || got_sigterm)
733 goto errret;
735 close(i);
738 slprintf(numbuf, sizeof(numbuf), "%d", baud_rate);
739 script_setenv("SPEED", numbuf, 0);
741 /* run welcome script, if any */
742 if (welcomer && welcomer[0]) {
743 if (device_script(welcomer, ttyfd, ttyfd, 0) < 0)
744 warn("Welcome script failed");
748 * If we are initiating this connection, wait for a short
749 * time for something from the peer. This can avoid bouncing
750 * our packets off his tty before he has it set up.
752 if (connector != NULL || ptycommand != NULL || pty_socket != NULL)
753 listen_time = connect_delay;
755 return ttyfd;
757 errretf:
758 if (real_ttyfd >= 0)
759 tcflush(real_ttyfd, TCIOFLUSH);
760 errret:
761 if (pty_master >= 0) {
762 close(pty_master);
763 pty_master = -1;
765 ttyfd = -1;
766 if (got_sigterm)
767 asked_to_quit = 1;
768 return -1;
772 void disconnect_tty()
774 if (disconnect_script == NULL || hungup)
775 return;
776 if (real_ttyfd >= 0)
777 set_up_tty(real_ttyfd, 1);
778 if (device_script(disconnect_script, ttyfd, ttyfd, 0) < 0) {
779 warn("disconnect script failed");
780 } else {
781 info("Serial link disconnected.");
783 stop_charshunt(NULL, 0);
786 void tty_close_fds()
788 if (pty_slave >= 0)
789 close(pty_slave);
790 if (real_ttyfd >= 0) {
791 close(real_ttyfd);
792 real_ttyfd = -1;
794 /* N.B. ttyfd will == either pty_slave or real_ttyfd */
797 void cleanup_tty()
799 if (real_ttyfd >= 0)
800 finish_tty();
801 tty_close_fds();
802 if (locked) {
803 unlock();
804 locked = 0;
809 * tty_do_send_config - set transmit-side PPP configuration.
810 * We set the extended transmit ACCM here as well.
812 void
813 tty_do_send_config(mtu, accm, pcomp, accomp)
814 int mtu;
815 u_int32_t accm;
816 int pcomp, accomp;
818 tty_set_xaccm(xmit_accm);
819 tty_send_config(mtu, accm, pcomp, accomp);
823 * finish_tty - restore the terminal device to its original settings
825 static void
826 finish_tty()
828 /* drop dtr to hang up */
829 if (!default_device && modem) {
830 setdtr(real_ttyfd, 0);
832 * This sleep is in case the serial port has CLOCAL set by default,
833 * and consequently will reassert DTR when we close the device.
835 sleep(1);
838 restore_tty(real_ttyfd);
840 #ifndef __linux__
841 if (tty_mode != (mode_t) -1) {
842 if (fchmod(real_ttyfd, tty_mode) != 0)
843 error("Couldn't restore tty permissions");
845 #endif /* __linux__ */
847 close(real_ttyfd);
848 real_ttyfd = -1;
852 * maybe_relock - our PID has changed, maybe update the lock file.
854 static void
855 maybe_relock(arg, pid)
856 void *arg;
857 int pid;
859 if (locked)
860 relock(pid);
864 * open_socket - establish a stream socket connection to the nominated
865 * host and port.
867 static int
868 open_socket(dest)
869 char *dest;
871 char *sep, *endp = NULL;
872 int sock, port = -1;
873 u_int32_t host;
874 struct hostent *hent;
875 struct sockaddr_in sad;
877 /* parse host:port and resolve host to an IP address */
878 sep = strchr(dest, ':');
879 if (sep != NULL)
880 port = strtol(sep+1, &endp, 10);
881 if (port < 0 || endp == sep+1 || sep == dest) {
882 error("Can't parse host:port for socket destination");
883 return -1;
885 *sep = 0;
886 host = inet_addr(dest);
887 if (host == (u_int32_t) -1) {
888 hent = gethostbyname(dest);
889 if (hent == NULL) {
890 error("%s: unknown host in socket option", dest);
891 *sep = ':';
892 return -1;
894 host = *(u_int32_t *)(hent->h_addr_list[0]);
896 *sep = ':';
898 /* get a socket and connect it to the other end */
899 sock = socket(PF_INET, SOCK_STREAM, 0);
900 if (sock < 0) {
901 error("Can't create socket: %m");
902 return -1;
904 memset(&sad, 0, sizeof(sad));
905 sad.sin_family = AF_INET;
906 sad.sin_port = htons(port);
907 sad.sin_addr.s_addr = host;
908 if (connect(sock, (struct sockaddr *)&sad, sizeof(sad)) < 0) {
909 error("Can't connect to %s: %m", dest);
910 close(sock);
911 return -1;
914 return sock;
919 * start_charshunt - create a child process to run the character shunt.
921 static int
922 start_charshunt(ifd, ofd)
923 int ifd, ofd;
925 int cpid;
927 cpid = safe_fork(ifd, ofd, (log_to_fd >= 0? log_to_fd: 2));
928 if (cpid == -1) {
929 error("Can't fork process for character shunt: %m");
930 return 0;
932 if (cpid == 0) {
933 /* child */
934 reopen_log();
935 if (!nodetach)
936 log_to_fd = -1;
937 else if (log_to_fd >= 0)
938 log_to_fd = 2;
939 setgid(getgid());
940 setuid(uid);
941 if (getuid() != uid)
942 fatal("setuid failed");
943 charshunt(0, 1, record_file);
944 exit(0);
946 charshunt_pid = cpid;
947 record_child(cpid, "pppd (charshunt)", charshunt_done, NULL, 1);
948 return 1;
951 static void
952 charshunt_done(arg)
953 void *arg;
955 charshunt_pid = 0;
958 static void
959 stop_charshunt(arg, sig)
960 void *arg;
961 int sig;
963 if (charshunt_pid)
964 kill(charshunt_pid, (sig == SIGINT? sig: SIGTERM));
968 * charshunt - the character shunt, which passes characters between
969 * the pty master side and the serial port (or stdin/stdout).
970 * This runs as the user (not as root).
971 * (We assume ofd >= ifd which is true the way this gets called. :-).
973 static void
974 charshunt(ifd, ofd, record_file)
975 int ifd, ofd;
976 char *record_file;
978 int n, nfds;
979 fd_set ready, writey;
980 u_char *ibufp, *obufp;
981 int nibuf, nobuf;
982 int flags;
983 int pty_readable, stdin_readable;
984 struct timeval lasttime;
985 FILE *recordf = NULL;
986 int ilevel, olevel, max_level;
987 struct timeval levelt, tout, *top;
988 extern u_char inpacket_buf[];
991 * Reset signal handlers.
993 signal(SIGHUP, SIG_IGN); /* Hangup */
994 signal(SIGINT, SIG_DFL); /* Interrupt */
995 signal(SIGTERM, SIG_DFL); /* Terminate */
996 signal(SIGCHLD, SIG_DFL);
997 signal(SIGUSR1, SIG_DFL);
998 signal(SIGUSR2, SIG_DFL);
999 signal(SIGABRT, SIG_DFL);
1000 signal(SIGALRM, SIG_DFL);
1001 signal(SIGFPE, SIG_DFL);
1002 signal(SIGILL, SIG_DFL);
1003 signal(SIGPIPE, SIG_DFL);
1004 signal(SIGQUIT, SIG_DFL);
1005 signal(SIGSEGV, SIG_DFL);
1006 #ifdef SIGBUS
1007 signal(SIGBUS, SIG_DFL);
1008 #endif
1009 #ifdef SIGEMT
1010 signal(SIGEMT, SIG_DFL);
1011 #endif
1012 #ifdef SIGPOLL
1013 signal(SIGPOLL, SIG_DFL);
1014 #endif
1015 #ifdef SIGPROF
1016 signal(SIGPROF, SIG_DFL);
1017 #endif
1018 #ifdef SIGSYS
1019 signal(SIGSYS, SIG_DFL);
1020 #endif
1021 #ifdef SIGTRAP
1022 signal(SIGTRAP, SIG_DFL);
1023 #endif
1024 #ifdef SIGVTALRM
1025 signal(SIGVTALRM, SIG_DFL);
1026 #endif
1027 #ifdef SIGXCPU
1028 signal(SIGXCPU, SIG_DFL);
1029 #endif
1030 #ifdef SIGXFSZ
1031 signal(SIGXFSZ, SIG_DFL);
1032 #endif
1035 * Check that the fds won't overrun the fd_sets
1037 if (ifd >= FD_SETSIZE || ofd >= FD_SETSIZE || pty_master >= FD_SETSIZE)
1038 fatal("internal error: file descriptor too large (%d, %d, %d)",
1039 ifd, ofd, pty_master);
1042 * Open the record file if required.
1044 if (record_file != NULL) {
1045 recordf = fopen(record_file, "a");
1046 if (recordf == NULL)
1047 error("Couldn't create record file %s: %m", record_file);
1050 /* set all the fds to non-blocking mode */
1051 flags = fcntl(pty_master, F_GETFL);
1052 if (flags == -1
1053 || fcntl(pty_master, F_SETFL, flags | O_NONBLOCK) == -1)
1054 warn("couldn't set pty master to nonblock: %m");
1055 flags = fcntl(ifd, F_GETFL);
1056 if (flags == -1
1057 || fcntl(ifd, F_SETFL, flags | O_NONBLOCK) == -1)
1058 warn("couldn't set %s to nonblock: %m", (ifd==0? "stdin": "tty"));
1059 if (ofd != ifd) {
1060 flags = fcntl(ofd, F_GETFL);
1061 if (flags == -1
1062 || fcntl(ofd, F_SETFL, flags | O_NONBLOCK) == -1)
1063 warn("couldn't set stdout to nonblock: %m");
1066 nibuf = nobuf = 0;
1067 ibufp = obufp = NULL;
1068 pty_readable = stdin_readable = 1;
1070 ilevel = olevel = 0;
1071 gettimeofday(&levelt, NULL);
1072 if (max_data_rate) {
1073 max_level = max_data_rate / 10;
1074 if (max_level < 100)
1075 max_level = 100;
1076 } else
1077 max_level = PPP_MRU + PPP_HDRLEN + 1;
1079 nfds = (ofd > pty_master? ofd: pty_master) + 1;
1080 if (recordf != NULL) {
1081 gettimeofday(&lasttime, NULL);
1082 putc(7, recordf); /* put start marker */
1083 putc(lasttime.tv_sec >> 24, recordf);
1084 putc(lasttime.tv_sec >> 16, recordf);
1085 putc(lasttime.tv_sec >> 8, recordf);
1086 putc(lasttime.tv_sec, recordf);
1087 lasttime.tv_usec = 0;
1090 while (nibuf != 0 || nobuf != 0 || pty_readable || stdin_readable) {
1091 top = 0;
1092 tout.tv_sec = 0;
1093 tout.tv_usec = 10000;
1094 FD_ZERO(&ready);
1095 FD_ZERO(&writey);
1096 if (nibuf != 0) {
1097 if (ilevel >= max_level)
1098 top = &tout;
1099 else
1100 FD_SET(pty_master, &writey);
1101 } else if (stdin_readable)
1102 FD_SET(ifd, &ready);
1103 if (nobuf != 0) {
1104 if (olevel >= max_level)
1105 top = &tout;
1106 else
1107 FD_SET(ofd, &writey);
1108 } else if (pty_readable)
1109 FD_SET(pty_master, &ready);
1110 if (select(nfds, &ready, &writey, NULL, top) < 0) {
1111 if (errno != EINTR)
1112 fatal("select");
1113 continue;
1115 if (max_data_rate) {
1116 double dt;
1117 int nbt;
1118 struct timeval now;
1120 gettimeofday(&now, NULL);
1121 dt = (now.tv_sec - levelt.tv_sec
1122 + (now.tv_usec - levelt.tv_usec) / 1e6);
1123 nbt = (int)(dt * max_data_rate);
1124 ilevel = (nbt < 0 || nbt > ilevel)? 0: ilevel - nbt;
1125 olevel = (nbt < 0 || nbt > olevel)? 0: olevel - nbt;
1126 levelt = now;
1127 } else
1128 ilevel = olevel = 0;
1129 if (FD_ISSET(ifd, &ready)) {
1130 ibufp = inpacket_buf;
1131 nibuf = read(ifd, ibufp, PPP_MRU + PPP_HDRLEN);
1132 if (nibuf < 0 && errno == EIO)
1133 nibuf = 0;
1134 if (nibuf < 0) {
1135 if (!(errno == EINTR || errno == EAGAIN)) {
1136 error("Error reading standard input: %m");
1137 break;
1139 nibuf = 0;
1140 } else if (nibuf == 0) {
1141 /* end of file from stdin */
1142 stdin_readable = 0;
1143 if (recordf)
1144 if (!record_write(recordf, 4, NULL, 0, &lasttime))
1145 recordf = NULL;
1146 } else {
1147 FD_SET(pty_master, &writey);
1148 if (recordf)
1149 if (!record_write(recordf, 2, ibufp, nibuf, &lasttime))
1150 recordf = NULL;
1153 if (FD_ISSET(pty_master, &ready)) {
1154 obufp = outpacket_buf;
1155 nobuf = read(pty_master, obufp, PPP_MRU + PPP_HDRLEN);
1156 if (nobuf < 0 && errno == EIO)
1157 nobuf = 0;
1158 if (nobuf < 0) {
1159 if (!(errno == EINTR || errno == EAGAIN)) {
1160 error("Error reading pseudo-tty master: %m");
1161 break;
1163 nobuf = 0;
1164 } else if (nobuf == 0) {
1165 /* end of file from the pty - slave side has closed */
1166 pty_readable = 0;
1167 stdin_readable = 0; /* pty is not writable now */
1168 nibuf = 0;
1169 close(ofd);
1170 if (recordf)
1171 if (!record_write(recordf, 3, NULL, 0, &lasttime))
1172 recordf = NULL;
1173 } else {
1174 FD_SET(ofd, &writey);
1175 if (recordf)
1176 if (!record_write(recordf, 1, obufp, nobuf, &lasttime))
1177 recordf = NULL;
1179 } else if (!stdin_readable)
1180 pty_readable = 0;
1181 if (FD_ISSET(ofd, &writey)) {
1182 n = nobuf;
1183 if (olevel + n > max_level)
1184 n = max_level - olevel;
1185 n = write(ofd, obufp, n);
1186 if (n < 0) {
1187 if (errno == EIO) {
1188 pty_readable = 0;
1189 nobuf = 0;
1190 } else if (errno != EAGAIN && errno != EINTR) {
1191 error("Error writing standard output: %m");
1192 break;
1194 } else {
1195 obufp += n;
1196 nobuf -= n;
1197 olevel += n;
1200 if (FD_ISSET(pty_master, &writey)) {
1201 n = nibuf;
1202 if (ilevel + n > max_level)
1203 n = max_level - ilevel;
1204 n = write(pty_master, ibufp, n);
1205 if (n < 0) {
1206 if (errno == EIO) {
1207 stdin_readable = 0;
1208 nibuf = 0;
1209 } else if (errno != EAGAIN && errno != EINTR) {
1210 error("Error writing pseudo-tty master: %m");
1211 break;
1213 } else {
1214 ibufp += n;
1215 nibuf -= n;
1216 ilevel += n;
1220 exit(0);
1223 static int
1224 record_write(f, code, buf, nb, tp)
1225 FILE *f;
1226 int code;
1227 u_char *buf;
1228 int nb;
1229 struct timeval *tp;
1231 struct timeval now;
1232 int diff;
1234 gettimeofday(&now, NULL);
1235 now.tv_usec /= 100000; /* actually 1/10 s, not usec now */
1236 diff = (now.tv_sec - tp->tv_sec) * 10 + (now.tv_usec - tp->tv_usec);
1237 if (diff > 0) {
1238 if (diff > 255) {
1239 putc(5, f);
1240 putc(diff >> 24, f);
1241 putc(diff >> 16, f);
1242 putc(diff >> 8, f);
1243 putc(diff, f);
1244 } else {
1245 putc(6, f);
1246 putc(diff, f);
1248 *tp = now;
1250 putc(code, f);
1251 if (buf != NULL) {
1252 putc(nb >> 8, f);
1253 putc(nb, f);
1254 fwrite(buf, nb, 1, f);
1256 fflush(f);
1257 if (ferror(f)) {
1258 error("Error writing record file: %m");
1259 return 0;
1261 return 1;