telnetd.c 27 KB

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