telnetd.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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. Send back evidence that AYT was seen. TODO (send NOP back)?
  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] >= 240 && buf[1] <= 249) {
  261. /* NOP (241). Ignore (putty keepalive, etc) */
  262. /* All other 2-byte commands also treated as NOPs here */
  263. rc = 2;
  264. goto update_and_return;
  265. }
  266. if (wr <= 2) {
  267. /* BUG: only 2 bytes of the IAC is in the buffer, we just eat them.
  268. * This is not a practical problem since >2 byte IACs are seen only
  269. * in initial negotiation, when buffer is empty
  270. */
  271. rc = 2;
  272. goto update_and_return;
  273. }
  274. if (buf[1] == SB) {
  275. if (buf[2] == TELOPT_NAWS) {
  276. /* IAC SB, TELOPT_NAWS, 4-byte, IAC SE */
  277. struct winsize ws;
  278. if (wr <= 6) {
  279. /* BUG: incomplete, can't process */
  280. rc = wr;
  281. goto update_and_return;
  282. }
  283. memset(&ws, 0, sizeof(ws)); /* pixel sizes are set to 0 */
  284. ws.ws_col = (buf[3] << 8) | buf[4];
  285. ws.ws_row = (buf[5] << 8) | buf[6];
  286. ioctl(ts->ptyfd, TIOCSWINSZ, (char *)&ws);
  287. rc = 7;
  288. /* trailing IAC SE will be eaten separately, as 2-byte NOP */
  289. goto update_and_return;
  290. }
  291. /* else: other subnegs not supported yet */
  292. }
  293. /* Assume it is a 3-byte WILL/WONT/DO/DONT 251..254 command and skip it */
  294. #if DEBUG
  295. fprintf(stderr, "Ignoring IAC %s,%s\n",
  296. TELCMD(buf[1]), TELOPT(buf[2]));
  297. #endif
  298. rc = 3;
  299. update_and_return:
  300. ts->wridx1 += rc;
  301. if (ts->wridx1 >= BUFSIZE) /* actually == BUFSIZE */
  302. ts->wridx1 = 0;
  303. ts->size1 -= rc;
  304. /*
  305. * Hack. We cannot process IACs which wrap around buffer's end.
  306. * Since properly fixing it requires writing bigger code,
  307. * we rely instead on this code making it virtually impossible
  308. * to have wrapped IAC (people don't type at 2k/second).
  309. * It also allows for bigger reads in common case.
  310. */
  311. if (ts->size1 == 0) { /* very typical */
  312. //bb_error_msg("zero size1");
  313. ts->rdidx1 = 0;
  314. ts->wridx1 = 0;
  315. return rc;
  316. }
  317. wr = ts->wridx1;
  318. if (wr != 0 && wr < ts->rdidx1) {
  319. /* Buffer is not wrapped yet.
  320. * We can easily move it to the beginning.
  321. */
  322. //bb_error_msg("moved %d", wr);
  323. memmove(TS_BUF1(ts), TS_BUF1(ts) + wr, ts->size1);
  324. ts->rdidx1 -= wr;
  325. ts->wridx1 = 0;
  326. }
  327. return rc;
  328. }
  329. /*
  330. * Converting single IAC into double on output
  331. */
  332. static size_t safe_write_double_iac(int fd, const char *buf, size_t count)
  333. {
  334. const char *IACptr;
  335. size_t wr, rc, total;
  336. total = 0;
  337. while (1) {
  338. if (count == 0)
  339. return total;
  340. if (*buf == (char)IAC) {
  341. static const char IACIAC[] ALIGN1 = { IAC, IAC };
  342. rc = safe_write(fd, IACIAC, 2);
  343. /* BUG: if partial write was only 1 byte long, we end up emitting just one IAC */
  344. if (rc != 2)
  345. break;
  346. buf++;
  347. total++;
  348. count--;
  349. continue;
  350. }
  351. /* count != 0, *buf != IAC */
  352. IACptr = memchr(buf, IAC, count);
  353. wr = count;
  354. if (IACptr)
  355. wr = IACptr - buf;
  356. rc = safe_write(fd, buf, wr);
  357. if (rc != wr)
  358. break;
  359. buf += rc;
  360. total += rc;
  361. count -= rc;
  362. }
  363. /* here: rc - result of last short write */
  364. if ((ssize_t)rc < 0) { /* error? */
  365. if (total == 0)
  366. return rc;
  367. rc = 0;
  368. }
  369. return total + rc;
  370. }
  371. /* Must match getopt32 string */
  372. enum {
  373. OPT_WATCHCHILD = (1 << 2), /* -K */
  374. OPT_INETD = (1 << 3) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -i */
  375. OPT_PORT = (1 << 4) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -p PORT */
  376. OPT_FOREGROUND = (1 << 6) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -F */
  377. OPT_SYSLOG = (1 << 7) * ENABLE_FEATURE_TELNETD_INETD_WAIT, /* -S */
  378. OPT_WAIT = (1 << 8) * ENABLE_FEATURE_TELNETD_INETD_WAIT, /* -w SEC */
  379. };
  380. static struct tsession *
  381. make_new_session(
  382. IF_FEATURE_TELNETD_STANDALONE(int sock)
  383. IF_NOT_FEATURE_TELNETD_STANDALONE(void)
  384. ) {
  385. #if !ENABLE_FEATURE_TELNETD_STANDALONE
  386. enum { sock = 0 };
  387. #endif
  388. const char *login_argv[2];
  389. struct termios termbuf;
  390. int fd, pid;
  391. char tty_name[GETPTY_BUFSIZE];
  392. struct tsession *ts = xzalloc(sizeof(struct tsession) + BUFSIZE * 2);
  393. /*ts->buf1 = (char *)(ts + 1);*/
  394. /*ts->buf2 = ts->buf1 + BUFSIZE;*/
  395. /* Got a new connection, set up a tty */
  396. fd = xgetpty(tty_name);
  397. if (fd > G.maxfd)
  398. G.maxfd = fd;
  399. ts->ptyfd = fd;
  400. ndelay_on(fd);
  401. close_on_exec_on(fd);
  402. /* SO_KEEPALIVE by popular demand */
  403. setsockopt_keepalive(sock);
  404. #if ENABLE_FEATURE_TELNETD_STANDALONE
  405. ts->sockfd_read = sock;
  406. ndelay_on(sock);
  407. if (sock == 0) { /* We are called with fd 0 - we are in inetd mode */
  408. sock++; /* so use fd 1 for output */
  409. ndelay_on(sock);
  410. }
  411. ts->sockfd_write = sock;
  412. if (sock > G.maxfd)
  413. G.maxfd = sock;
  414. #else
  415. /* ts->sockfd_read = 0; - done by xzalloc */
  416. ts->sockfd_write = 1;
  417. ndelay_on(0);
  418. ndelay_on(1);
  419. #endif
  420. /* Make the telnet client understand we will echo characters so it
  421. * should not do it locally. We don't tell the client to run linemode,
  422. * because we want to handle line editing and tab completion and other
  423. * stuff that requires char-by-char support. */
  424. {
  425. static const char iacs_to_send[] ALIGN1 = {
  426. IAC, DO, TELOPT_ECHO,
  427. IAC, DO, TELOPT_NAWS,
  428. /* This requires telnetd.ctrlSQ.patch (incomplete) */
  429. /*IAC, DO, TELOPT_LFLOW,*/
  430. IAC, WILL, TELOPT_ECHO,
  431. IAC, WILL, TELOPT_SGA
  432. };
  433. /* This confuses safe_write_double_iac(), it will try to duplicate
  434. * each IAC... */
  435. //memcpy(TS_BUF2(ts), iacs_to_send, sizeof(iacs_to_send));
  436. //ts->rdidx2 = sizeof(iacs_to_send);
  437. //ts->size2 = sizeof(iacs_to_send);
  438. /* So just stuff it into TCP stream! (no error check...) */
  439. #if ENABLE_FEATURE_TELNETD_STANDALONE
  440. safe_write(sock, iacs_to_send, sizeof(iacs_to_send));
  441. #else
  442. safe_write(1, iacs_to_send, sizeof(iacs_to_send));
  443. #endif
  444. /*ts->rdidx2 = 0; - xzalloc did it */
  445. /*ts->size2 = 0;*/
  446. }
  447. fflush_all();
  448. pid = vfork(); /* NOMMU-friendly */
  449. if (pid < 0) {
  450. free(ts);
  451. close(fd);
  452. /* sock will be closed by caller */
  453. bb_perror_msg("vfork");
  454. return NULL;
  455. }
  456. if (pid > 0) {
  457. /* Parent */
  458. ts->shell_pid = pid;
  459. return ts;
  460. }
  461. /* Child */
  462. /* Careful - we are after vfork! */
  463. /* Restore default signal handling ASAP */
  464. bb_signals((1 << SIGCHLD) + (1 << SIGPIPE), SIG_DFL);
  465. pid = getpid();
  466. if (ENABLE_FEATURE_UTMP) {
  467. len_and_sockaddr *lsa = get_peer_lsa(sock);
  468. char *hostname = NULL;
  469. if (lsa) {
  470. hostname = xmalloc_sockaddr2dotted(&lsa->u.sa);
  471. free(lsa);
  472. }
  473. write_new_utmp(pid, LOGIN_PROCESS, tty_name, /*username:*/ "LOGIN", hostname);
  474. free(hostname);
  475. }
  476. /* Make new session and process group */
  477. setsid();
  478. /* Open the child's side of the tty */
  479. /* NB: setsid() disconnects from any previous ctty's. Therefore
  480. * we must open child's side of the tty AFTER setsid! */
  481. close(0);
  482. xopen(tty_name, O_RDWR); /* becomes our ctty */
  483. xdup2(0, 1);
  484. xdup2(0, 2);
  485. tcsetpgrp(0, pid); /* switch this tty's process group to us */
  486. /* The pseudo-terminal allocated to the client is configured to operate
  487. * in cooked mode, and with XTABS CRMOD enabled (see tty(4)) */
  488. tcgetattr(0, &termbuf);
  489. termbuf.c_lflag |= ECHO; /* if we use readline we dont want this */
  490. termbuf.c_oflag |= ONLCR | XTABS;
  491. termbuf.c_iflag |= ICRNL;
  492. termbuf.c_iflag &= ~IXOFF;
  493. /*termbuf.c_lflag &= ~ICANON;*/
  494. tcsetattr_stdin_TCSANOW(&termbuf);
  495. /* Uses FILE-based I/O to stdout, but does fflush_all(),
  496. * so should be safe with vfork.
  497. * I fear, though, that some users will have ridiculously big
  498. * issue files, and they may block writing to fd 1,
  499. * (parent is supposed to read it, but parent waits
  500. * for vforked child to exec!) */
  501. print_login_issue(G.issuefile, tty_name);
  502. /* Exec shell / login / whatever */
  503. login_argv[0] = G.loginpath;
  504. login_argv[1] = NULL;
  505. /* exec busybox applet (if PREFER_APPLETS=y), if that fails,
  506. * exec external program.
  507. * NB: sock is either 0 or has CLOEXEC set on it.
  508. * fd has CLOEXEC set on it too. These two fds will be closed here.
  509. */
  510. BB_EXECVP(G.loginpath, (char **)login_argv);
  511. /* _exit is safer with vfork, and we shouldn't send message
  512. * to remote clients anyway */
  513. _exit(EXIT_FAILURE); /*bb_perror_msg_and_die("execv %s", G.loginpath);*/
  514. }
  515. #if ENABLE_FEATURE_TELNETD_STANDALONE
  516. static void
  517. free_session(struct tsession *ts)
  518. {
  519. struct tsession *t;
  520. if (option_mask32 & OPT_INETD)
  521. exit(EXIT_SUCCESS);
  522. /* Unlink this telnet session from the session list */
  523. t = G.sessions;
  524. if (t == ts)
  525. G.sessions = ts->next;
  526. else {
  527. while (t->next != ts)
  528. t = t->next;
  529. t->next = ts->next;
  530. }
  531. #if 0
  532. /* It was said that "normal" telnetd just closes ptyfd,
  533. * doesn't send SIGKILL. When we close ptyfd,
  534. * kernel sends SIGHUP to processes having slave side opened. */
  535. kill(ts->shell_pid, SIGKILL);
  536. waitpid(ts->shell_pid, NULL, 0);
  537. #endif
  538. close(ts->ptyfd);
  539. close(ts->sockfd_read);
  540. /* We do not need to close(ts->sockfd_write), it's the same
  541. * as sockfd_read unless we are in inetd mode. But in inetd mode
  542. * we do not reach this */
  543. free(ts);
  544. /* Scan all sessions and find new maxfd */
  545. G.maxfd = 0;
  546. ts = G.sessions;
  547. while (ts) {
  548. if (G.maxfd < ts->ptyfd)
  549. G.maxfd = ts->ptyfd;
  550. if (G.maxfd < ts->sockfd_read)
  551. G.maxfd = ts->sockfd_read;
  552. #if 0
  553. /* Again, sockfd_write == sockfd_read here */
  554. if (G.maxfd < ts->sockfd_write)
  555. G.maxfd = ts->sockfd_write;
  556. #endif
  557. ts = ts->next;
  558. }
  559. }
  560. #else /* !FEATURE_TELNETD_STANDALONE */
  561. /* Used in main() only, thus "return 0" actually is exit(EXIT_SUCCESS). */
  562. #define free_session(ts) return 0
  563. #endif
  564. static void handle_sigchld(int sig UNUSED_PARAM)
  565. {
  566. pid_t pid;
  567. struct tsession *ts;
  568. int save_errno = errno;
  569. /* Looping: more than one child may have exited */
  570. while (1) {
  571. pid = wait_any_nohang(NULL);
  572. if (pid <= 0)
  573. break;
  574. ts = G.sessions;
  575. while (ts) {
  576. if (ts->shell_pid == pid) {
  577. ts->shell_pid = -1;
  578. update_utmp_DEAD_PROCESS(pid);
  579. break;
  580. }
  581. ts = ts->next;
  582. }
  583. }
  584. errno = save_errno;
  585. }
  586. int telnetd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  587. int telnetd_main(int argc UNUSED_PARAM, char **argv)
  588. {
  589. fd_set rdfdset, wrfdset;
  590. unsigned opt;
  591. int count;
  592. struct tsession *ts;
  593. #if ENABLE_FEATURE_TELNETD_STANDALONE
  594. #define IS_INETD (opt & OPT_INETD)
  595. int master_fd = master_fd; /* for compiler */
  596. int sec_linger = sec_linger;
  597. char *opt_bindaddr = NULL;
  598. char *opt_portnbr;
  599. #else
  600. enum {
  601. IS_INETD = 1,
  602. master_fd = -1,
  603. };
  604. #endif
  605. INIT_G();
  606. /* Even if !STANDALONE, we accept (and ignore) -i, thus people
  607. * don't need to guess whether it's ok to pass -i to us */
  608. opt = getopt32(argv, "^"
  609. "f:l:Ki"
  610. IF_FEATURE_TELNETD_STANDALONE("p:b:F")
  611. IF_FEATURE_TELNETD_INETD_WAIT("Sw:+") /* -w NUM */
  612. "\0"
  613. /* -w implies -F. -w and -i don't mix */
  614. IF_FEATURE_TELNETD_INETD_WAIT("wF:i--w:w--i"),
  615. &G.issuefile, &G.loginpath
  616. IF_FEATURE_TELNETD_STANDALONE(, &opt_portnbr, &opt_bindaddr)
  617. IF_FEATURE_TELNETD_INETD_WAIT(, &sec_linger)
  618. );
  619. if (!IS_INETD /*&& !re_execed*/) {
  620. /* inform that we start in standalone mode?
  621. * May be useful when people forget to give -i */
  622. /*bb_error_msg("listening for connections");*/
  623. if (!(opt & OPT_FOREGROUND)) {
  624. /* DAEMON_CHDIR_ROOT was giving inconsistent
  625. * behavior with/without -F, -i */
  626. bb_daemonize_or_rexec(0 /*was DAEMON_CHDIR_ROOT*/, argv);
  627. }
  628. }
  629. /* Redirect log to syslog early, if needed */
  630. if (IS_INETD || (opt & OPT_SYSLOG) || !(opt & OPT_FOREGROUND)) {
  631. openlog(applet_name, LOG_PID, LOG_DAEMON);
  632. logmode = LOGMODE_SYSLOG;
  633. }
  634. #if ENABLE_FEATURE_TELNETD_STANDALONE
  635. if (IS_INETD) {
  636. G.sessions = make_new_session(0);
  637. if (!G.sessions) /* pty opening or vfork problem, exit */
  638. return 1; /* make_new_session printed error message */
  639. } else {
  640. master_fd = 0;
  641. if (!(opt & OPT_WAIT)) {
  642. unsigned portnbr = 23;
  643. if (opt & OPT_PORT)
  644. portnbr = xatou16(opt_portnbr);
  645. master_fd = create_and_bind_stream_or_die(opt_bindaddr, portnbr);
  646. xlisten(master_fd, 1);
  647. }
  648. close_on_exec_on(master_fd);
  649. }
  650. #else
  651. G.sessions = make_new_session();
  652. if (!G.sessions) /* pty opening or vfork problem, exit */
  653. return 1; /* make_new_session printed error message */
  654. #endif
  655. /* We don't want to die if just one session is broken */
  656. signal(SIGPIPE, SIG_IGN);
  657. if (opt & OPT_WATCHCHILD)
  658. signal(SIGCHLD, handle_sigchld);
  659. else /* prevent dead children from becoming zombies */
  660. signal(SIGCHLD, SIG_IGN);
  661. /*
  662. This is how the buffers are used. The arrows indicate data flow.
  663. +-------+ wridx1++ +------+ rdidx1++ +----------+
  664. | | <-------------- | buf1 | <-------------- | |
  665. | | size1-- +------+ size1++ | |
  666. | pty | | socket |
  667. | | rdidx2++ +------+ wridx2++ | |
  668. | | --------------> | buf2 | --------------> | |
  669. +-------+ size2++ +------+ size2-- +----------+
  670. size1: "how many bytes are buffered for pty between rdidx1 and wridx1?"
  671. size2: "how many bytes are buffered for socket between rdidx2 and wridx2?"
  672. Each session has got two buffers. Buffers are circular. If sizeN == 0,
  673. buffer is empty. If sizeN == BUFSIZE, buffer is full. In both these cases
  674. rdidxN == wridxN.
  675. */
  676. again:
  677. FD_ZERO(&rdfdset);
  678. FD_ZERO(&wrfdset);
  679. /* Select on the master socket, all telnet sockets and their
  680. * ptys if there is room in their session buffers.
  681. * NB: scalability problem: we recalculate entire bitmap
  682. * before each select. Can be a problem with 500+ connections. */
  683. ts = G.sessions;
  684. while (ts) {
  685. struct tsession *next = ts->next; /* in case we free ts */
  686. if (ts->shell_pid == -1) {
  687. /* Child died and we detected that */
  688. free_session(ts);
  689. } else {
  690. if (ts->size1 > 0) /* can write to pty */
  691. FD_SET(ts->ptyfd, &wrfdset);
  692. if (ts->size1 < BUFSIZE) /* can read from socket */
  693. FD_SET(ts->sockfd_read, &rdfdset);
  694. if (ts->size2 > 0) /* can write to socket */
  695. FD_SET(ts->sockfd_write, &wrfdset);
  696. if (ts->size2 < BUFSIZE) /* can read from pty */
  697. FD_SET(ts->ptyfd, &rdfdset);
  698. }
  699. ts = next;
  700. }
  701. if (!IS_INETD) {
  702. FD_SET(master_fd, &rdfdset);
  703. /* This is needed because free_session() does not
  704. * take master_fd into account when it finds new
  705. * maxfd among remaining fd's */
  706. if (master_fd > G.maxfd)
  707. G.maxfd = master_fd;
  708. }
  709. {
  710. struct timeval *tv_ptr = NULL;
  711. #if ENABLE_FEATURE_TELNETD_INETD_WAIT
  712. struct timeval tv;
  713. if ((opt & OPT_WAIT) && !G.sessions) {
  714. tv.tv_sec = sec_linger;
  715. tv.tv_usec = 0;
  716. tv_ptr = &tv;
  717. }
  718. #endif
  719. count = select(G.maxfd + 1, &rdfdset, &wrfdset, NULL, tv_ptr);
  720. }
  721. if (count == 0) /* "telnetd -w SEC" timed out */
  722. return 0;
  723. if (count < 0)
  724. goto again; /* EINTR or ENOMEM */
  725. #if ENABLE_FEATURE_TELNETD_STANDALONE
  726. /* Check for and accept new sessions */
  727. if (!IS_INETD && FD_ISSET(master_fd, &rdfdset)) {
  728. int fd;
  729. struct tsession *new_ts;
  730. fd = accept(master_fd, NULL, NULL);
  731. if (fd < 0)
  732. goto again;
  733. close_on_exec_on(fd);
  734. /* Create a new session and link it into active list */
  735. new_ts = make_new_session(fd);
  736. if (new_ts) {
  737. new_ts->next = G.sessions;
  738. G.sessions = new_ts;
  739. } else {
  740. close(fd);
  741. }
  742. }
  743. #endif
  744. /* Then check for data tunneling */
  745. ts = G.sessions;
  746. while (ts) { /* For all sessions... */
  747. struct tsession *next = ts->next; /* in case we free ts */
  748. if (/*ts->size1 &&*/ FD_ISSET(ts->ptyfd, &wrfdset)) {
  749. /* Write to pty from buffer 1 */
  750. count = safe_write_to_pty_decode_iac(ts);
  751. if (count < 0) {
  752. if (errno == EAGAIN)
  753. goto skip1;
  754. goto kill_session;
  755. }
  756. }
  757. skip1:
  758. if (/*ts->size2 &&*/ FD_ISSET(ts->sockfd_write, &wrfdset)) {
  759. /* Write to socket from buffer 2 */
  760. count = MIN(BUFSIZE - ts->wridx2, ts->size2);
  761. count = safe_write_double_iac(ts->sockfd_write, (void*)(TS_BUF2(ts) + ts->wridx2), count);
  762. if (count < 0) {
  763. if (errno == EAGAIN)
  764. goto skip2;
  765. goto kill_session;
  766. }
  767. ts->wridx2 += count;
  768. if (ts->wridx2 >= BUFSIZE) /* actually == BUFSIZE */
  769. ts->wridx2 = 0;
  770. ts->size2 -= count;
  771. if (ts->size2 == 0) {
  772. ts->rdidx2 = 0;
  773. ts->wridx2 = 0;
  774. }
  775. }
  776. skip2:
  777. if (/*ts->size1 < BUFSIZE &&*/ FD_ISSET(ts->sockfd_read, &rdfdset)) {
  778. /* Read from socket to buffer 1 */
  779. count = MIN(BUFSIZE - ts->rdidx1, BUFSIZE - ts->size1);
  780. count = safe_read(ts->sockfd_read, TS_BUF1(ts) + ts->rdidx1, count);
  781. if (count <= 0) {
  782. if (count < 0 && errno == EAGAIN)
  783. goto skip3;
  784. goto kill_session;
  785. }
  786. /* Ignore trailing NUL if it is there */
  787. if (!TS_BUF1(ts)[ts->rdidx1 + count - 1]) {
  788. --count;
  789. }
  790. ts->size1 += count;
  791. ts->rdidx1 += count;
  792. if (ts->rdidx1 >= BUFSIZE) /* actually == BUFSIZE */
  793. ts->rdidx1 = 0;
  794. }
  795. skip3:
  796. if (/*ts->size2 < BUFSIZE &&*/ FD_ISSET(ts->ptyfd, &rdfdset)) {
  797. /* Read from pty to buffer 2 */
  798. count = MIN(BUFSIZE - ts->rdidx2, BUFSIZE - ts->size2);
  799. count = safe_read(ts->ptyfd, TS_BUF2(ts) + ts->rdidx2, count);
  800. if (count <= 0) {
  801. if (count < 0 && errno == EAGAIN)
  802. goto skip4;
  803. goto kill_session;
  804. }
  805. ts->size2 += count;
  806. ts->rdidx2 += count;
  807. if (ts->rdidx2 >= BUFSIZE) /* actually == BUFSIZE */
  808. ts->rdidx2 = 0;
  809. }
  810. skip4:
  811. ts = next;
  812. continue;
  813. kill_session:
  814. if (ts->shell_pid > 0)
  815. update_utmp_DEAD_PROCESS(ts->shell_pid);
  816. free_session(ts);
  817. ts = next;
  818. }
  819. goto again;
  820. }