telnetd.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Simple telnet server
  4. * Bjorn Wesen, Axis Communications AB (bjornw@axis.com)
  5. *
  6. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  7. *
  8. * ---------------------------------------------------------------------------
  9. * (C) Copyright 2000, Axis Communications AB, LUND, SWEDEN
  10. ****************************************************************************
  11. *
  12. * The telnetd manpage says it all:
  13. *
  14. * Telnetd operates by allocating a pseudo-terminal device (see pty(4)) for
  15. * a client, then creating a login process which has the slave side of the
  16. * pseudo-terminal as stdin, stdout, and stderr. Telnetd manipulates the
  17. * master side of the pseudo-terminal, implementing the telnet protocol and
  18. * passing characters between the remote client and the login process.
  19. *
  20. * Vladimir Oleynik <dzo@simtreas.ru> 2001
  21. * Set process group corrections, initial busybox port
  22. */
  23. //config:config TELNETD
  24. //config: bool "telnetd (12 kb)"
  25. //config: default y
  26. //config: select FEATURE_SYSLOG
  27. //config: help
  28. //config: A daemon for the TELNET protocol, allowing you to log onto the host
  29. //config: running the daemon. Please keep in mind that the TELNET protocol
  30. //config: sends passwords in plain text. If you can't afford the space for an
  31. //config: SSH daemon and you trust your network, you may say 'y' here. As a
  32. //config: more secure alternative, you should seriously consider installing the
  33. //config: very small Dropbear SSH daemon instead:
  34. //config: http://matt.ucc.asn.au/dropbear/dropbear.html
  35. //config:
  36. //config: Note that for busybox telnetd to work you need several things:
  37. //config: First of all, your kernel needs:
  38. //config: CONFIG_UNIX98_PTYS=y
  39. //config:
  40. //config: Next, you need a /dev/pts directory on your root filesystem:
  41. //config:
  42. //config: $ ls -ld /dev/pts
  43. //config: drwxr-xr-x 2 root root 0 Sep 23 13:21 /dev/pts/
  44. //config:
  45. //config: Next you need the pseudo terminal master multiplexer /dev/ptmx:
  46. //config:
  47. //config: $ ls -la /dev/ptmx
  48. //config: crw-rw-rw- 1 root tty 5, 2 Sep 23 13:55 /dev/ptmx
  49. //config:
  50. //config: Any /dev/ttyp[0-9]* files you may have can be removed.
  51. //config: Next, you need to mount the devpts filesystem on /dev/pts using:
  52. //config:
  53. //config: mount -t devpts devpts /dev/pts
  54. //config:
  55. //config: You need to be sure that busybox has LOGIN and
  56. //config: FEATURE_SUID enabled. And finally, you should make
  57. //config: certain that busybox has been installed setuid root:
  58. //config:
  59. //config: chown root.root /bin/busybox
  60. //config: chmod 4755 /bin/busybox
  61. //config:
  62. //config: with all that done, telnetd _should_ work....
  63. //config:
  64. //config:config FEATURE_TELNETD_STANDALONE
  65. //config: bool "Support standalone telnetd (not inetd only)"
  66. //config: default y
  67. //config: depends on TELNETD
  68. //config: help
  69. //config: Selecting this will make telnetd able to run standalone.
  70. //config:
  71. //config:config FEATURE_TELNETD_INETD_WAIT
  72. //config: bool "Support -w SEC option (inetd wait mode)"
  73. //config: default y
  74. //config: depends on FEATURE_TELNETD_STANDALONE
  75. //config: help
  76. //config: This option allows you to run telnetd in "inet wait" mode.
  77. //config: Example inetd.conf line (note "wait", not usual "nowait"):
  78. //config:
  79. //config: telnet stream tcp wait root /bin/telnetd telnetd -w10
  80. //config:
  81. //config: In this example, inetd passes _listening_ socket_ as fd 0
  82. //config: to telnetd when connection appears.
  83. //config: telnetd will wait for connections until all existing
  84. //config: connections are closed, and no new connections
  85. //config: appear during 10 seconds. Then it exits, and inetd continues
  86. //config: to listen for new connections.
  87. //config:
  88. //config: This option is rarely used. "tcp nowait" is much more usual
  89. //config: way of running tcp services, including telnetd.
  90. //config: You most probably want to say N here.
  91. //applet:IF_TELNETD(APPLET(telnetd, BB_DIR_USR_SBIN, BB_SUID_DROP))
  92. //kbuild:lib-$(CONFIG_TELNETD) += telnetd.o
  93. //usage:#define telnetd_trivial_usage
  94. //usage: "[OPTIONS]"
  95. //usage:#define telnetd_full_usage "\n\n"
  96. //usage: "Handle incoming telnet connections"
  97. //usage: IF_NOT_FEATURE_TELNETD_STANDALONE(" via inetd") "\n"
  98. //usage: "\n -l LOGIN Exec LOGIN on connect"
  99. //usage: "\n -f ISSUE_FILE Display ISSUE_FILE instead of /etc/issue"
  100. //usage: "\n -K Close connection as soon as login exits"
  101. //usage: "\n (normally wait until all programs close slave pty)"
  102. //usage: IF_FEATURE_TELNETD_STANDALONE(
  103. //usage: "\n -p PORT Port to listen on"
  104. //usage: "\n -b ADDR[:PORT] Address to bind to"
  105. //usage: "\n -F Run in foreground"
  106. //usage: "\n -i Inetd mode"
  107. //usage: IF_FEATURE_TELNETD_INETD_WAIT(
  108. //usage: "\n -w SEC Inetd 'wait' mode, linger time SEC"
  109. //usage: "\n -S Log to syslog (implied by -i or without -F and -w)"
  110. //usage: )
  111. //usage: )
  112. #define DEBUG 0
  113. #include "libbb.h"
  114. #include "common_bufsiz.h"
  115. #include <syslog.h>
  116. #if DEBUG
  117. # define TELCMDS
  118. # define TELOPTS
  119. #endif
  120. #include <arpa/telnet.h>
  121. struct tsession {
  122. struct tsession *next;
  123. pid_t shell_pid;
  124. int sockfd_read;
  125. int sockfd_write;
  126. int ptyfd;
  127. smallint buffered_IAC_for_pty;
  128. /* two circular buffers */
  129. /*char *buf1, *buf2;*/
  130. /*#define TS_BUF1(ts) ts->buf1*/
  131. /*#define TS_BUF2(ts) TS_BUF2(ts)*/
  132. #define TS_BUF1(ts) ((unsigned char*)(ts + 1))
  133. #define TS_BUF2(ts) (((unsigned char*)(ts + 1)) + BUFSIZE)
  134. int rdidx1, wridx1, size1;
  135. int rdidx2, wridx2, size2;
  136. };
  137. /* Two buffers are directly after tsession in malloced memory.
  138. * Make whole thing fit in 4k */
  139. enum { BUFSIZE = (4 * 1024 - sizeof(struct tsession)) / 2 };
  140. /* Globals */
  141. struct globals {
  142. struct tsession *sessions;
  143. const char *loginpath;
  144. const char *issuefile;
  145. int maxfd;
  146. } FIX_ALIASING;
  147. #define G (*(struct globals*)bb_common_bufsiz1)
  148. #define INIT_G() do { \
  149. setup_common_bufsiz(); \
  150. G.loginpath = "/bin/login"; \
  151. G.issuefile = "/etc/issue.net"; \
  152. } while (0)
  153. /* Write some buf1 data to pty, processing IACs.
  154. * Update wridx1 and size1. Return < 0 on error.
  155. * Buggy if IAC is present but incomplete: skips them.
  156. */
  157. static ssize_t
  158. safe_write_to_pty_decode_iac(struct tsession *ts)
  159. {
  160. unsigned wr;
  161. ssize_t rc;
  162. unsigned char *buf;
  163. unsigned char *found;
  164. buf = TS_BUF1(ts) + ts->wridx1;
  165. wr = MIN(BUFSIZE - ts->wridx1, ts->size1);
  166. /* wr is at least 1 here */
  167. if (ts->buffered_IAC_for_pty) {
  168. /* Last time we stopped on a "dangling" IAC byte.
  169. * We removed it from the buffer back then.
  170. * Now pretend it's still there, and jump to IAC processing.
  171. */
  172. ts->buffered_IAC_for_pty = 0;
  173. wr++;
  174. ts->size1++;
  175. buf--; /* Yes, this can point before the buffer. It's ok */
  176. ts->wridx1--;
  177. goto handle_iac;
  178. }
  179. found = memchr(buf, IAC, wr);
  180. if (found != buf) {
  181. /* There is a "prefix" of non-IAC chars.
  182. * Write only them, and return.
  183. */
  184. if (found)
  185. wr = found - buf;
  186. /* We map \r\n ==> \r for pragmatic reasons:
  187. * many client implementations send \r\n when
  188. * the user hits the CarriageReturn key.
  189. * See RFC 1123 3.3.1 Telnet End-of-Line Convention.
  190. */
  191. rc = wr;
  192. found = memchr(buf, '\r', wr);
  193. if (found)
  194. rc = found - buf + 1;
  195. rc = safe_write(ts->ptyfd, buf, rc);
  196. if (rc <= 0)
  197. return rc;
  198. if (rc < wr /* don't look past available data */
  199. && buf[rc-1] == '\r' /* need this: imagine that write was _short_ */
  200. && (buf[rc] == '\n' || buf[rc] == '\0')
  201. ) {
  202. rc++;
  203. }
  204. goto update_and_return;
  205. }
  206. /* buf starts with IAC char. Process that sequence.
  207. * Example: we get this from our own (bbox) telnet client:
  208. * read(5, "\377\374\1""\377\373\37""\377\372\37\0\262\0@\377\360""\377\375\1""\377\375\3"):
  209. * IAC WONT ECHO, IAC WILL NAWS, IAC SB NAWS <cols> <rows> IAC SE, IAC DO SGA
  210. * Another example (telnet-0.17 from old-netkit):
  211. * read(4, "\377\375\3""\377\373\30""\377\373\37""\377\373 ""\377\373!""\377\373\"""\377\373'"
  212. * "\377\375\5""\377\373#""\377\374\1""\377\372\37\0\257\0I\377\360""\377\375\1"):
  213. * IAC DO SGA, IAC WILL TTYPE, IAC WILL NAWS, IAC WILL TSPEED, IAC WILL LFLOW, IAC WILL LINEMODE, IAC WILL NEW_ENVIRON,
  214. * IAC DO STATUS, IAC WILL XDISPLOC, IAC WONT ECHO, IAC SB NAWS <cols> <rows> IAC SE, IAC DO ECHO
  215. */
  216. if (wr <= 1) {
  217. /* Only the single IAC byte is in the buffer, eat it
  218. * and set a flag "process the rest of the sequence
  219. * next time we are here".
  220. */
  221. //bb_error_msg("dangling IAC!");
  222. ts->buffered_IAC_for_pty = 1;
  223. rc = 1;
  224. goto update_and_return;
  225. }
  226. handle_iac:
  227. /* 2-byte commands (240..250 and 255):
  228. * IAC IAC (255) Literal 255. Supported.
  229. * IAC SE (240) End of subnegotiation. Treated as NOP.
  230. * IAC NOP (241) NOP. Supported.
  231. * IAC BRK (243) Break. Like serial line break. TODO via tcsendbreak()?
  232. * IAC AYT (246) Are you there.
  233. * These don't look useful:
  234. * IAC DM (242) Data mark. What is this?
  235. * IAC IP (244) Suspend, interrupt or abort the process. (Ancient cousin of ^C).
  236. * IAC AO (245) Abort output. "You can continue running, but do not send me the output".
  237. * IAC EC (247) Erase character. The receiver should delete the last received char.
  238. * IAC EL (248) Erase line. The receiver should delete everything up tp last newline.
  239. * IAC GA (249) Go ahead. For half-duplex lines: "now you talk".
  240. * Implemented only as part of NAWS:
  241. * IAC SB (250) Subnegotiation of an option follows.
  242. */
  243. if (buf[1] == IAC) {
  244. /* Literal 255 (emacs M-DEL) */
  245. //bb_error_msg("255!");
  246. rc = safe_write(ts->ptyfd, &buf[1], 1);
  247. /*
  248. * If we went through buffered_IAC_for_pty==1 path,
  249. * bailing out on error like below messes up the buffer.
  250. * EAGAIN is highly unlikely here, other errors will be
  251. * repeated on next write, let's just skip error check.
  252. */
  253. #if 0
  254. if (rc <= 0)
  255. return rc;
  256. #endif
  257. rc = 2;
  258. goto update_and_return;
  259. }
  260. if (buf[1] == AYT) {
  261. if (ts->size2 == 0) { /* if nothing buffered yet... */
  262. /* Send back evidence that AYT was seen */
  263. unsigned char *buf2 = TS_BUF2(ts);
  264. buf2[0] = IAC;
  265. buf2[1] = NOP;
  266. ts->wridx2 = 0;
  267. ts->rdidx2 = ts->size2 = 2;
  268. }
  269. rc = 2;
  270. goto update_and_return;
  271. }
  272. if (buf[1] >= 240 && buf[1] <= 249) {
  273. /* NOP (241). Ignore (putty keepalive, etc) */
  274. /* All other 2-byte commands also treated as NOPs here */
  275. rc = 2;
  276. goto update_and_return;
  277. }
  278. if (wr <= 2) {
  279. /* BUG: only 2 bytes of the IAC is in the buffer, we just eat them.
  280. * This is not a practical problem since >2 byte IACs are seen only
  281. * in initial negotiation, when buffer is empty
  282. */
  283. rc = 2;
  284. goto update_and_return;
  285. }
  286. if (buf[1] == SB) {
  287. if (buf[2] == TELOPT_NAWS) {
  288. /* IAC SB, TELOPT_NAWS, 4-byte, IAC SE */
  289. struct winsize ws;
  290. if (wr <= 6) {
  291. /* BUG: incomplete, can't process */
  292. rc = wr;
  293. goto update_and_return;
  294. }
  295. memset(&ws, 0, sizeof(ws)); /* pixel sizes are set to 0 */
  296. ws.ws_col = (buf[3] << 8) | buf[4];
  297. ws.ws_row = (buf[5] << 8) | buf[6];
  298. ioctl(ts->ptyfd, TIOCSWINSZ, (char *)&ws);
  299. rc = 7;
  300. /* trailing IAC SE will be eaten separately, as 2-byte NOP */
  301. goto update_and_return;
  302. }
  303. /* else: other subnegs not supported yet */
  304. }
  305. /* Assume it is a 3-byte WILL/WONT/DO/DONT 251..254 command and skip it */
  306. #if DEBUG
  307. fprintf(stderr, "Ignoring IAC %s,%s\n",
  308. TELCMD(buf[1]), TELOPT(buf[2]));
  309. #endif
  310. rc = 3;
  311. update_and_return:
  312. ts->wridx1 += rc;
  313. if (ts->wridx1 >= BUFSIZE) /* actually == BUFSIZE */
  314. ts->wridx1 = 0;
  315. ts->size1 -= rc;
  316. /*
  317. * Hack. We cannot process IACs which wrap around buffer's end.
  318. * Since properly fixing it requires writing bigger code,
  319. * we rely instead on this code making it virtually impossible
  320. * to have wrapped IAC (people don't type at 2k/second).
  321. * It also allows for bigger reads in common case.
  322. */
  323. if (ts->size1 == 0) { /* very typical */
  324. //bb_error_msg("zero size1");
  325. ts->rdidx1 = 0;
  326. ts->wridx1 = 0;
  327. return rc;
  328. }
  329. wr = ts->wridx1;
  330. if (wr != 0 && wr < ts->rdidx1) {
  331. /* Buffer is not wrapped yet.
  332. * We can easily move it to the beginning.
  333. */
  334. //bb_error_msg("moved %d", wr);
  335. memmove(TS_BUF1(ts), TS_BUF1(ts) + wr, ts->size1);
  336. ts->rdidx1 -= wr;
  337. ts->wridx1 = 0;
  338. }
  339. return rc;
  340. }
  341. /*
  342. * Converting single IAC into double on output
  343. */
  344. static size_t safe_write_double_iac(int fd, const char *buf, size_t count)
  345. {
  346. const char *IACptr;
  347. size_t wr, rc, total;
  348. total = 0;
  349. while (1) {
  350. if (count == 0)
  351. return total;
  352. if (*buf == (char)IAC) {
  353. static const char IACIAC[] ALIGN1 = { IAC, IAC };
  354. rc = safe_write(fd, IACIAC, 2);
  355. /* BUG: if partial write was only 1 byte long, we end up emitting just one IAC */
  356. if (rc != 2)
  357. break;
  358. buf++;
  359. total++;
  360. count--;
  361. continue;
  362. }
  363. /* count != 0, *buf != IAC */
  364. IACptr = memchr(buf, IAC, count);
  365. wr = count;
  366. if (IACptr)
  367. wr = IACptr - buf;
  368. rc = safe_write(fd, buf, wr);
  369. if (rc != wr)
  370. break;
  371. buf += rc;
  372. total += rc;
  373. count -= rc;
  374. }
  375. /* here: rc - result of last short write */
  376. if ((ssize_t)rc < 0) { /* error? */
  377. if (total == 0)
  378. return rc;
  379. rc = 0;
  380. }
  381. return total + rc;
  382. }
  383. /* Must match getopt32 string */
  384. enum {
  385. OPT_WATCHCHILD = (1 << 2), /* -K */
  386. OPT_INETD = (1 << 3) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -i */
  387. OPT_PORT = (1 << 4) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -p PORT */
  388. OPT_FOREGROUND = (1 << 6) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -F */
  389. OPT_SYSLOG = (1 << 7) * ENABLE_FEATURE_TELNETD_INETD_WAIT, /* -S */
  390. OPT_WAIT = (1 << 8) * ENABLE_FEATURE_TELNETD_INETD_WAIT, /* -w SEC */
  391. };
  392. static struct tsession *
  393. make_new_session(
  394. IF_FEATURE_TELNETD_STANDALONE(int sock)
  395. IF_NOT_FEATURE_TELNETD_STANDALONE(void)
  396. ) {
  397. #if !ENABLE_FEATURE_TELNETD_STANDALONE
  398. enum { sock = 0 };
  399. #endif
  400. const char *login_argv[2];
  401. struct termios termbuf;
  402. int fd, pid;
  403. char tty_name[GETPTY_BUFSIZE];
  404. struct tsession *ts = xzalloc(sizeof(struct tsession) + BUFSIZE * 2);
  405. /*ts->buf1 = (char *)(ts + 1);*/
  406. /*ts->buf2 = ts->buf1 + BUFSIZE;*/
  407. /* Got a new connection, set up a tty */
  408. fd = xgetpty(tty_name);
  409. if (fd > G.maxfd)
  410. G.maxfd = fd;
  411. ts->ptyfd = fd;
  412. ndelay_on(fd);
  413. close_on_exec_on(fd);
  414. /* SO_KEEPALIVE by popular demand */
  415. setsockopt_keepalive(sock);
  416. #if ENABLE_FEATURE_TELNETD_STANDALONE
  417. ts->sockfd_read = sock;
  418. ndelay_on(sock);
  419. if (sock == 0) { /* We are called with fd 0 - we are in inetd mode */
  420. sock++; /* so use fd 1 for output */
  421. ndelay_on(sock);
  422. }
  423. ts->sockfd_write = sock;
  424. if (sock > G.maxfd)
  425. G.maxfd = sock;
  426. #else
  427. /* ts->sockfd_read = 0; - done by xzalloc */
  428. ts->sockfd_write = 1;
  429. ndelay_on(0);
  430. ndelay_on(1);
  431. #endif
  432. /* Make the telnet client understand we will echo characters so it
  433. * should not do it locally. We don't tell the client to run linemode,
  434. * because we want to handle line editing and tab completion and other
  435. * stuff that requires char-by-char support. */
  436. {
  437. static const char iacs_to_send[] ALIGN1 = {
  438. IAC, DO, TELOPT_ECHO,
  439. IAC, DO, TELOPT_NAWS,
  440. /* This requires telnetd.ctrlSQ.patch (incomplete) */
  441. /*IAC, DO, TELOPT_LFLOW,*/
  442. IAC, WILL, TELOPT_ECHO,
  443. IAC, WILL, TELOPT_SGA
  444. };
  445. /* This confuses safe_write_double_iac(), it will try to duplicate
  446. * each IAC... */
  447. //memcpy(TS_BUF2(ts), iacs_to_send, sizeof(iacs_to_send));
  448. //ts->rdidx2 = sizeof(iacs_to_send);
  449. //ts->size2 = sizeof(iacs_to_send);
  450. /* So just stuff it into TCP stream! (no error check...) */
  451. #if ENABLE_FEATURE_TELNETD_STANDALONE
  452. safe_write(sock, iacs_to_send, sizeof(iacs_to_send));
  453. #else
  454. safe_write(1, iacs_to_send, sizeof(iacs_to_send));
  455. #endif
  456. /*ts->rdidx2 = 0; - xzalloc did it */
  457. /*ts->size2 = 0;*/
  458. }
  459. fflush_all();
  460. pid = vfork(); /* NOMMU-friendly */
  461. if (pid < 0) {
  462. free(ts);
  463. close(fd);
  464. /* sock will be closed by caller */
  465. bb_simple_perror_msg("vfork");
  466. return NULL;
  467. }
  468. if (pid > 0) {
  469. /* Parent */
  470. ts->shell_pid = pid;
  471. return ts;
  472. }
  473. /* Child */
  474. /* Careful - we are after vfork! */
  475. /* Restore default signal handling ASAP */
  476. bb_signals((1 << SIGCHLD) + (1 << SIGPIPE), SIG_DFL);
  477. pid = getpid();
  478. if (ENABLE_FEATURE_UTMP) {
  479. len_and_sockaddr *lsa = get_peer_lsa(sock);
  480. char *hostname = NULL;
  481. if (lsa) {
  482. hostname = xmalloc_sockaddr2dotted(&lsa->u.sa);
  483. free(lsa);
  484. }
  485. write_new_utmp(pid, LOGIN_PROCESS, tty_name, /*username:*/ "LOGIN", hostname);
  486. free(hostname);
  487. }
  488. /* Make new session and process group */
  489. setsid();
  490. /* Open the child's side of the tty */
  491. /* NB: setsid() disconnects from any previous ctty's. Therefore
  492. * we must open child's side of the tty AFTER setsid! */
  493. close(0);
  494. xopen(tty_name, O_RDWR); /* becomes our ctty */
  495. xdup2(0, 1);
  496. xdup2(0, 2);
  497. tcsetpgrp(0, pid); /* switch this tty's process group to us */
  498. /* The pseudo-terminal allocated to the client is configured to operate
  499. * in cooked mode, and with XTABS CRMOD enabled (see tty(4)) */
  500. tcgetattr(0, &termbuf);
  501. termbuf.c_lflag |= ECHO; /* if we use readline we dont want this */
  502. termbuf.c_oflag |= ONLCR | XTABS;
  503. termbuf.c_iflag |= ICRNL;
  504. termbuf.c_iflag &= ~IXOFF;
  505. /*termbuf.c_lflag &= ~ICANON;*/
  506. tcsetattr_stdin_TCSANOW(&termbuf);
  507. /* Uses FILE-based I/O to stdout, but does fflush_all(),
  508. * so should be safe with vfork.
  509. * I fear, though, that some users will have ridiculously big
  510. * issue files, and they may block writing to fd 1,
  511. * (parent is supposed to read it, but parent waits
  512. * for vforked child to exec!) */
  513. print_login_issue(G.issuefile, tty_name);
  514. /* Exec shell / login / whatever */
  515. login_argv[0] = G.loginpath;
  516. login_argv[1] = NULL;
  517. /* exec busybox applet (if PREFER_APPLETS=y), if that fails,
  518. * exec external program.
  519. * NB: sock is either 0 or has CLOEXEC set on it.
  520. * fd has CLOEXEC set on it too. These two fds will be closed here.
  521. */
  522. BB_EXECVP(G.loginpath, (char **)login_argv);
  523. /* _exit is safer with vfork, and we shouldn't send message
  524. * to remote clients anyway */
  525. _exit(EXIT_FAILURE); /*bb_perror_msg_and_die("execv %s", G.loginpath);*/
  526. }
  527. #if ENABLE_FEATURE_TELNETD_STANDALONE
  528. static void
  529. free_session(struct tsession *ts)
  530. {
  531. struct tsession *t;
  532. if (option_mask32 & OPT_INETD)
  533. exit(EXIT_SUCCESS);
  534. /* Unlink this telnet session from the session list */
  535. t = G.sessions;
  536. if (t == ts)
  537. G.sessions = ts->next;
  538. else {
  539. while (t->next != ts)
  540. t = t->next;
  541. t->next = ts->next;
  542. }
  543. #if 0
  544. /* It was said that "normal" telnetd just closes ptyfd,
  545. * doesn't send SIGKILL. When we close ptyfd,
  546. * kernel sends SIGHUP to processes having slave side opened. */
  547. kill(ts->shell_pid, SIGKILL);
  548. waitpid(ts->shell_pid, NULL, 0);
  549. #endif
  550. close(ts->ptyfd);
  551. close(ts->sockfd_read);
  552. /* We do not need to close(ts->sockfd_write), it's the same
  553. * as sockfd_read unless we are in inetd mode. But in inetd mode
  554. * we do not reach this */
  555. free(ts);
  556. /* Scan all sessions and find new maxfd */
  557. G.maxfd = 0;
  558. ts = G.sessions;
  559. while (ts) {
  560. if (G.maxfd < ts->ptyfd)
  561. G.maxfd = ts->ptyfd;
  562. if (G.maxfd < ts->sockfd_read)
  563. G.maxfd = ts->sockfd_read;
  564. #if 0
  565. /* Again, sockfd_write == sockfd_read here */
  566. if (G.maxfd < ts->sockfd_write)
  567. G.maxfd = ts->sockfd_write;
  568. #endif
  569. ts = ts->next;
  570. }
  571. }
  572. #else /* !FEATURE_TELNETD_STANDALONE */
  573. /* Used in main() only, thus "return 0" actually is exit(EXIT_SUCCESS). */
  574. #define free_session(ts) return 0
  575. #endif
  576. static void handle_sigchld(int sig UNUSED_PARAM)
  577. {
  578. pid_t pid;
  579. struct tsession *ts;
  580. int save_errno = errno;
  581. /* Looping: more than one child may have exited */
  582. while (1) {
  583. pid = wait_any_nohang(NULL);
  584. if (pid <= 0)
  585. break;
  586. ts = G.sessions;
  587. while (ts) {
  588. if (ts->shell_pid == pid) {
  589. ts->shell_pid = -1;
  590. update_utmp_DEAD_PROCESS(pid);
  591. break;
  592. }
  593. ts = ts->next;
  594. }
  595. }
  596. errno = save_errno;
  597. }
  598. int telnetd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  599. int telnetd_main(int argc UNUSED_PARAM, char **argv)
  600. {
  601. fd_set rdfdset, wrfdset;
  602. unsigned opt;
  603. int count;
  604. struct tsession *ts;
  605. #if ENABLE_FEATURE_TELNETD_STANDALONE
  606. #define IS_INETD (opt & OPT_INETD)
  607. int master_fd = master_fd; /* for compiler */
  608. int sec_linger = sec_linger;
  609. char *opt_bindaddr = NULL;
  610. char *opt_portnbr;
  611. #else
  612. enum {
  613. IS_INETD = 1,
  614. master_fd = -1,
  615. };
  616. #endif
  617. INIT_G();
  618. /* Even if !STANDALONE, we accept (and ignore) -i, thus people
  619. * don't need to guess whether it's ok to pass -i to us */
  620. opt = getopt32(argv, "^"
  621. "f:l:Ki"
  622. IF_FEATURE_TELNETD_STANDALONE("p:b:F")
  623. IF_FEATURE_TELNETD_INETD_WAIT("Sw:+") /* -w NUM */
  624. "\0"
  625. /* -w implies -F. -w and -i don't mix */
  626. IF_FEATURE_TELNETD_INETD_WAIT("wF:i--w:w--i"),
  627. &G.issuefile, &G.loginpath
  628. IF_FEATURE_TELNETD_STANDALONE(, &opt_portnbr, &opt_bindaddr)
  629. IF_FEATURE_TELNETD_INETD_WAIT(, &sec_linger)
  630. );
  631. if (!IS_INETD /*&& !re_execed*/) {
  632. /* inform that we start in standalone mode?
  633. * May be useful when people forget to give -i */
  634. /*bb_error_msg("listening for connections");*/
  635. if (!(opt & OPT_FOREGROUND)) {
  636. /* DAEMON_CHDIR_ROOT was giving inconsistent
  637. * behavior with/without -F, -i */
  638. bb_daemonize_or_rexec(0 /*was DAEMON_CHDIR_ROOT*/, argv);
  639. }
  640. }
  641. /* Redirect log to syslog early, if needed */
  642. if (IS_INETD || (opt & OPT_SYSLOG) || !(opt & OPT_FOREGROUND)) {
  643. openlog(applet_name, LOG_PID, LOG_DAEMON);
  644. logmode = LOGMODE_SYSLOG;
  645. }
  646. #if ENABLE_FEATURE_TELNETD_STANDALONE
  647. if (IS_INETD) {
  648. G.sessions = make_new_session(0);
  649. if (!G.sessions) /* pty opening or vfork problem, exit */
  650. return 1; /* make_new_session printed error message */
  651. } else {
  652. master_fd = 0;
  653. if (!(opt & OPT_WAIT)) {
  654. unsigned portnbr = 23;
  655. if (opt & OPT_PORT)
  656. portnbr = xatou16(opt_portnbr);
  657. master_fd = create_and_bind_stream_or_die(opt_bindaddr, portnbr);
  658. xlisten(master_fd, 1);
  659. }
  660. close_on_exec_on(master_fd);
  661. }
  662. #else
  663. G.sessions = make_new_session();
  664. if (!G.sessions) /* pty opening or vfork problem, exit */
  665. return 1; /* make_new_session printed error message */
  666. #endif
  667. /* We don't want to die if just one session is broken */
  668. signal(SIGPIPE, SIG_IGN);
  669. if (opt & OPT_WATCHCHILD)
  670. signal(SIGCHLD, handle_sigchld);
  671. else /* prevent dead children from becoming zombies */
  672. signal(SIGCHLD, SIG_IGN);
  673. /*
  674. This is how the buffers are used. The arrows indicate data flow.
  675. +-------+ wridx1++ +------+ rdidx1++ +----------+
  676. | | <-------------- | buf1 | <-------------- | |
  677. | | size1-- +------+ size1++ | |
  678. | pty | | socket |
  679. | | rdidx2++ +------+ wridx2++ | |
  680. | | --------------> | buf2 | --------------> | |
  681. +-------+ size2++ +------+ size2-- +----------+
  682. size1: "how many bytes are buffered for pty between rdidx1 and wridx1?"
  683. size2: "how many bytes are buffered for socket between rdidx2 and wridx2?"
  684. Each session has got two buffers. Buffers are circular. If sizeN == 0,
  685. buffer is empty. If sizeN == BUFSIZE, buffer is full. In both these cases
  686. rdidxN == wridxN.
  687. */
  688. again:
  689. FD_ZERO(&rdfdset);
  690. FD_ZERO(&wrfdset);
  691. /* Select on the master socket, all telnet sockets and their
  692. * ptys if there is room in their session buffers.
  693. * NB: scalability problem: we recalculate entire bitmap
  694. * before each select. Can be a problem with 500+ connections. */
  695. ts = G.sessions;
  696. while (ts) {
  697. struct tsession *next = ts->next; /* in case we free ts */
  698. if (ts->shell_pid == -1) {
  699. /* Child died and we detected that */
  700. free_session(ts);
  701. } else {
  702. if (ts->size1 > 0) /* can write to pty */
  703. FD_SET(ts->ptyfd, &wrfdset);
  704. if (ts->size1 < BUFSIZE) /* can read from socket */
  705. FD_SET(ts->sockfd_read, &rdfdset);
  706. if (ts->size2 > 0) /* can write to socket */
  707. FD_SET(ts->sockfd_write, &wrfdset);
  708. if (ts->size2 < BUFSIZE) /* can read from pty */
  709. FD_SET(ts->ptyfd, &rdfdset);
  710. }
  711. ts = next;
  712. }
  713. if (!IS_INETD) {
  714. FD_SET(master_fd, &rdfdset);
  715. /* This is needed because free_session() does not
  716. * take master_fd into account when it finds new
  717. * maxfd among remaining fd's */
  718. if (master_fd > G.maxfd)
  719. G.maxfd = master_fd;
  720. }
  721. {
  722. struct timeval *tv_ptr = NULL;
  723. #if ENABLE_FEATURE_TELNETD_INETD_WAIT
  724. struct timeval tv;
  725. if ((opt & OPT_WAIT) && !G.sessions) {
  726. tv.tv_sec = sec_linger;
  727. tv.tv_usec = 0;
  728. tv_ptr = &tv;
  729. }
  730. #endif
  731. count = select(G.maxfd + 1, &rdfdset, &wrfdset, NULL, tv_ptr);
  732. }
  733. if (count == 0) /* "telnetd -w SEC" timed out */
  734. return 0;
  735. if (count < 0)
  736. goto again; /* EINTR or ENOMEM */
  737. #if ENABLE_FEATURE_TELNETD_STANDALONE
  738. /* Check for and accept new sessions */
  739. if (!IS_INETD && FD_ISSET(master_fd, &rdfdset)) {
  740. int fd;
  741. struct tsession *new_ts;
  742. fd = accept(master_fd, NULL, NULL);
  743. if (fd < 0)
  744. goto again;
  745. close_on_exec_on(fd);
  746. /* Create a new session and link it into active list */
  747. new_ts = make_new_session(fd);
  748. if (new_ts) {
  749. new_ts->next = G.sessions;
  750. G.sessions = new_ts;
  751. } else {
  752. close(fd);
  753. }
  754. }
  755. #endif
  756. /* Then check for data tunneling */
  757. ts = G.sessions;
  758. while (ts) { /* For all sessions... */
  759. struct tsession *next = ts->next; /* in case we free ts */
  760. if (/*ts->size1 &&*/ FD_ISSET(ts->ptyfd, &wrfdset)) {
  761. /* Write to pty from buffer 1 */
  762. count = safe_write_to_pty_decode_iac(ts);
  763. if (count < 0) {
  764. if (errno == EAGAIN)
  765. goto skip1;
  766. goto kill_session;
  767. }
  768. }
  769. skip1:
  770. if (/*ts->size2 &&*/ FD_ISSET(ts->sockfd_write, &wrfdset)) {
  771. /* Write to socket from buffer 2 */
  772. count = MIN(BUFSIZE - ts->wridx2, ts->size2);
  773. count = safe_write_double_iac(ts->sockfd_write, (void*)(TS_BUF2(ts) + ts->wridx2), count);
  774. if (count < 0) {
  775. if (errno == EAGAIN)
  776. goto skip2;
  777. goto kill_session;
  778. }
  779. ts->wridx2 += count;
  780. if (ts->wridx2 >= BUFSIZE) /* actually == BUFSIZE */
  781. ts->wridx2 = 0;
  782. ts->size2 -= count;
  783. if (ts->size2 == 0) {
  784. ts->rdidx2 = 0;
  785. ts->wridx2 = 0;
  786. }
  787. }
  788. skip2:
  789. if (/*ts->size1 < BUFSIZE &&*/ FD_ISSET(ts->sockfd_read, &rdfdset)) {
  790. /* Read from socket to buffer 1 */
  791. count = MIN(BUFSIZE - ts->rdidx1, BUFSIZE - ts->size1);
  792. count = safe_read(ts->sockfd_read, TS_BUF1(ts) + ts->rdidx1, count);
  793. if (count <= 0) {
  794. if (count < 0 && errno == EAGAIN)
  795. goto skip3;
  796. goto kill_session;
  797. }
  798. /* Ignore trailing NUL if it is there */
  799. if (!TS_BUF1(ts)[ts->rdidx1 + count - 1]) {
  800. --count;
  801. }
  802. ts->size1 += count;
  803. ts->rdidx1 += count;
  804. if (ts->rdidx1 >= BUFSIZE) /* actually == BUFSIZE */
  805. ts->rdidx1 = 0;
  806. }
  807. skip3:
  808. if (/*ts->size2 < BUFSIZE &&*/ FD_ISSET(ts->ptyfd, &rdfdset)) {
  809. /* Read from pty to buffer 2 */
  810. int eio = 0;
  811. read_pty:
  812. count = MIN(BUFSIZE - ts->rdidx2, BUFSIZE - ts->size2);
  813. count = safe_read(ts->ptyfd, TS_BUF2(ts) + ts->rdidx2, count);
  814. if (count <= 0) {
  815. if (count < 0) {
  816. if (errno == EAGAIN)
  817. goto skip4;
  818. /* login process might call vhangup(),
  819. * which causes intermittent EIOs on read above
  820. * (observed on kernel 4.12.0). Try up to 10 ms.
  821. */
  822. if (errno == EIO && eio < 10) {
  823. eio++;
  824. //bb_error_msg("EIO pty %u", eio);
  825. usleep(1000);
  826. goto read_pty;
  827. }
  828. }
  829. goto kill_session;
  830. }
  831. ts->size2 += count;
  832. ts->rdidx2 += count;
  833. if (ts->rdidx2 >= BUFSIZE) /* actually == BUFSIZE */
  834. ts->rdidx2 = 0;
  835. }
  836. skip4:
  837. ts = next;
  838. continue;
  839. kill_session:
  840. if (ts->shell_pid > 0)
  841. update_utmp_DEAD_PROCESS(ts->shell_pid);
  842. free_session(ts);
  843. ts = next;
  844. }
  845. goto again;
  846. }