tty.c 32 KB

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