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