3
0

telnetd.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. //usage:#define telnetd_trivial_usage
  24. //usage: "[OPTIONS]"
  25. //usage:#define telnetd_full_usage "\n\n"
  26. //usage: "Handle incoming telnet connections"
  27. //usage: IF_NOT_FEATURE_TELNETD_STANDALONE(" via inetd") "\n"
  28. //usage: "\n -l LOGIN Exec LOGIN on connect"
  29. //usage: "\n -f ISSUE_FILE Display ISSUE_FILE instead of /etc/issue"
  30. //usage: "\n -K Close connection as soon as login exits"
  31. //usage: "\n (normally wait until all programs close slave pty)"
  32. //usage: IF_FEATURE_TELNETD_STANDALONE(
  33. //usage: "\n -p PORT Port to listen on"
  34. //usage: "\n -b ADDR[:PORT] Address to bind to"
  35. //usage: "\n -F Run in foreground"
  36. //usage: "\n -i Inetd mode"
  37. //usage: IF_FEATURE_TELNETD_INETD_WAIT(
  38. //usage: "\n -w SEC Inetd 'wait' mode, linger time SEC"
  39. //usage: "\n -S Log to syslog (implied by -i or without -F and -w)"
  40. //usage: )
  41. //usage: )
  42. #define DEBUG 0
  43. #include "libbb.h"
  44. #include <syslog.h>
  45. #if DEBUG
  46. # define TELCMDS
  47. # define TELOPTS
  48. #endif
  49. #include <arpa/telnet.h>
  50. struct tsession {
  51. struct tsession *next;
  52. pid_t shell_pid;
  53. int sockfd_read;
  54. int sockfd_write;
  55. int ptyfd;
  56. /* two circular buffers */
  57. /*char *buf1, *buf2;*/
  58. /*#define TS_BUF1(ts) ts->buf1*/
  59. /*#define TS_BUF2(ts) TS_BUF2(ts)*/
  60. #define TS_BUF1(ts) ((unsigned char*)(ts + 1))
  61. #define TS_BUF2(ts) (((unsigned char*)(ts + 1)) + BUFSIZE)
  62. int rdidx1, wridx1, size1;
  63. int rdidx2, wridx2, size2;
  64. };
  65. /* Two buffers are directly after tsession in malloced memory.
  66. * Make whole thing fit in 4k */
  67. enum { BUFSIZE = (4 * 1024 - sizeof(struct tsession)) / 2 };
  68. /* Globals */
  69. struct globals {
  70. struct tsession *sessions;
  71. const char *loginpath;
  72. const char *issuefile;
  73. int maxfd;
  74. } FIX_ALIASING;
  75. #define G (*(struct globals*)&bb_common_bufsiz1)
  76. #define INIT_G() do { \
  77. G.loginpath = "/bin/login"; \
  78. G.issuefile = "/etc/issue.net"; \
  79. } while (0)
  80. /*
  81. Remove all IAC's from buf1 (received IACs are ignored and must be removed
  82. so as to not be interpreted by the terminal). Make an uninterrupted
  83. string of characters fit for the terminal. Do this by packing
  84. all characters meant for the terminal sequentially towards the end of buf.
  85. Return a pointer to the beginning of the characters meant for the terminal
  86. and make *num_totty the number of characters that should be sent to
  87. the terminal.
  88. Note - if an IAC (3 byte quantity) starts before (bf + len) but extends
  89. past (bf + len) then that IAC will be left unprocessed and *processed
  90. will be less than len.
  91. CR-LF ->'s CR mapping is also done here, for convenience.
  92. NB: may fail to remove iacs which wrap around buffer!
  93. */
  94. static unsigned char *
  95. remove_iacs(struct tsession *ts, int *pnum_totty)
  96. {
  97. unsigned char *ptr0 = TS_BUF1(ts) + ts->wridx1;
  98. unsigned char *ptr = ptr0;
  99. unsigned char *totty = ptr;
  100. unsigned char *end = ptr + MIN(BUFSIZE - ts->wridx1, ts->size1);
  101. int num_totty;
  102. while (ptr < end) {
  103. if (*ptr != IAC) {
  104. char c = *ptr;
  105. *totty++ = c;
  106. ptr++;
  107. /* We map \r\n ==> \r for pragmatic reasons.
  108. * Many client implementations send \r\n when
  109. * the user hits the CarriageReturn key.
  110. * See RFC 1123 3.3.1 Telnet End-of-Line Convention.
  111. */
  112. if (c == '\r' && ptr < end && (*ptr == '\n' || *ptr == '\0'))
  113. ptr++;
  114. continue;
  115. }
  116. if ((ptr+1) >= end)
  117. break;
  118. if (ptr[1] == NOP) { /* Ignore? (putty keepalive, etc.) */
  119. ptr += 2;
  120. continue;
  121. }
  122. if (ptr[1] == IAC) { /* Literal IAC? (emacs M-DEL) */
  123. *totty++ = ptr[1];
  124. ptr += 2;
  125. continue;
  126. }
  127. /*
  128. * TELOPT_NAWS support!
  129. */
  130. if ((ptr+2) >= end) {
  131. /* Only the beginning of the IAC is in the
  132. buffer we were asked to process, we can't
  133. process this char */
  134. break;
  135. }
  136. /*
  137. * IAC -> SB -> TELOPT_NAWS -> 4-byte -> IAC -> SE
  138. */
  139. if (ptr[1] == SB && ptr[2] == TELOPT_NAWS) {
  140. struct winsize ws;
  141. if ((ptr+8) >= end)
  142. break; /* incomplete, can't process */
  143. ws.ws_col = (ptr[3] << 8) | ptr[4];
  144. ws.ws_row = (ptr[5] << 8) | ptr[6];
  145. ioctl(ts->ptyfd, TIOCSWINSZ, (char *)&ws);
  146. ptr += 9;
  147. continue;
  148. }
  149. /* skip 3-byte IAC non-SB cmd */
  150. #if DEBUG
  151. fprintf(stderr, "Ignoring IAC %s,%s\n",
  152. TELCMD(ptr[1]), TELOPT(ptr[2]));
  153. #endif
  154. ptr += 3;
  155. }
  156. num_totty = totty - ptr0;
  157. *pnum_totty = num_totty;
  158. /* The difference between ptr and totty is number of iacs
  159. we removed from the stream. Adjust buf1 accordingly */
  160. if ((ptr - totty) == 0) /* 99.999% of cases */
  161. return ptr0;
  162. ts->wridx1 += ptr - totty;
  163. ts->size1 -= ptr - totty;
  164. /* Move chars meant for the terminal towards the end of the buffer */
  165. return memmove(ptr - num_totty, ptr0, num_totty);
  166. }
  167. /*
  168. * Converting single IAC into double on output
  169. */
  170. static size_t iac_safe_write(int fd, const char *buf, size_t count)
  171. {
  172. const char *IACptr;
  173. size_t wr, rc, total;
  174. total = 0;
  175. while (1) {
  176. if (count == 0)
  177. return total;
  178. if (*buf == (char)IAC) {
  179. static const char IACIAC[] ALIGN1 = { IAC, IAC };
  180. rc = safe_write(fd, IACIAC, 2);
  181. if (rc != 2)
  182. break;
  183. buf++;
  184. total++;
  185. count--;
  186. continue;
  187. }
  188. /* count != 0, *buf != IAC */
  189. IACptr = memchr(buf, IAC, count);
  190. wr = count;
  191. if (IACptr)
  192. wr = IACptr - buf;
  193. rc = safe_write(fd, buf, wr);
  194. if (rc != wr)
  195. break;
  196. buf += rc;
  197. total += rc;
  198. count -= rc;
  199. }
  200. /* here: rc - result of last short write */
  201. if ((ssize_t)rc < 0) { /* error? */
  202. if (total == 0)
  203. return rc;
  204. rc = 0;
  205. }
  206. return total + rc;
  207. }
  208. /* Must match getopt32 string */
  209. enum {
  210. OPT_WATCHCHILD = (1 << 2), /* -K */
  211. OPT_INETD = (1 << 3) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -i */
  212. OPT_PORT = (1 << 4) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -p PORT */
  213. OPT_FOREGROUND = (1 << 6) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -F */
  214. OPT_SYSLOG = (1 << 7) * ENABLE_FEATURE_TELNETD_INETD_WAIT, /* -S */
  215. OPT_WAIT = (1 << 8) * ENABLE_FEATURE_TELNETD_INETD_WAIT, /* -w SEC */
  216. };
  217. static struct tsession *
  218. make_new_session(
  219. IF_FEATURE_TELNETD_STANDALONE(int sock)
  220. IF_NOT_FEATURE_TELNETD_STANDALONE(void)
  221. ) {
  222. #if !ENABLE_FEATURE_TELNETD_STANDALONE
  223. enum { sock = 0 };
  224. #endif
  225. const char *login_argv[2];
  226. struct termios termbuf;
  227. int fd, pid;
  228. char tty_name[GETPTY_BUFSIZE];
  229. struct tsession *ts = xzalloc(sizeof(struct tsession) + BUFSIZE * 2);
  230. /*ts->buf1 = (char *)(ts + 1);*/
  231. /*ts->buf2 = ts->buf1 + BUFSIZE;*/
  232. /* Got a new connection, set up a tty */
  233. fd = xgetpty(tty_name);
  234. if (fd > G.maxfd)
  235. G.maxfd = fd;
  236. ts->ptyfd = fd;
  237. ndelay_on(fd);
  238. close_on_exec_on(fd);
  239. /* SO_KEEPALIVE by popular demand */
  240. setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
  241. #if ENABLE_FEATURE_TELNETD_STANDALONE
  242. ts->sockfd_read = sock;
  243. ndelay_on(sock);
  244. if (sock == 0) { /* We are called with fd 0 - we are in inetd mode */
  245. sock++; /* so use fd 1 for output */
  246. ndelay_on(sock);
  247. }
  248. ts->sockfd_write = sock;
  249. if (sock > G.maxfd)
  250. G.maxfd = sock;
  251. #else
  252. /* ts->sockfd_read = 0; - done by xzalloc */
  253. ts->sockfd_write = 1;
  254. ndelay_on(0);
  255. ndelay_on(1);
  256. #endif
  257. /* Make the telnet client understand we will echo characters so it
  258. * should not do it locally. We don't tell the client to run linemode,
  259. * because we want to handle line editing and tab completion and other
  260. * stuff that requires char-by-char support. */
  261. {
  262. static const char iacs_to_send[] ALIGN1 = {
  263. IAC, DO, TELOPT_ECHO,
  264. IAC, DO, TELOPT_NAWS,
  265. /* This requires telnetd.ctrlSQ.patch (incomplete) */
  266. /*IAC, DO, TELOPT_LFLOW,*/
  267. IAC, WILL, TELOPT_ECHO,
  268. IAC, WILL, TELOPT_SGA
  269. };
  270. /* This confuses iac_safe_write(), it will try to duplicate
  271. * each IAC... */
  272. //memcpy(TS_BUF2(ts), iacs_to_send, sizeof(iacs_to_send));
  273. //ts->rdidx2 = sizeof(iacs_to_send);
  274. //ts->size2 = sizeof(iacs_to_send);
  275. /* So just stuff it into TCP stream! (no error check...) */
  276. #if ENABLE_FEATURE_TELNETD_STANDALONE
  277. safe_write(sock, iacs_to_send, sizeof(iacs_to_send));
  278. #else
  279. safe_write(1, iacs_to_send, sizeof(iacs_to_send));
  280. #endif
  281. /*ts->rdidx2 = 0; - xzalloc did it */
  282. /*ts->size2 = 0;*/
  283. }
  284. fflush_all();
  285. pid = vfork(); /* NOMMU-friendly */
  286. if (pid < 0) {
  287. free(ts);
  288. close(fd);
  289. /* sock will be closed by caller */
  290. bb_perror_msg("vfork");
  291. return NULL;
  292. }
  293. if (pid > 0) {
  294. /* Parent */
  295. ts->shell_pid = pid;
  296. return ts;
  297. }
  298. /* Child */
  299. /* Careful - we are after vfork! */
  300. /* Restore default signal handling ASAP */
  301. bb_signals((1 << SIGCHLD) + (1 << SIGPIPE), SIG_DFL);
  302. pid = getpid();
  303. if (ENABLE_FEATURE_UTMP) {
  304. len_and_sockaddr *lsa = get_peer_lsa(sock);
  305. char *hostname = NULL;
  306. if (lsa) {
  307. hostname = xmalloc_sockaddr2dotted(&lsa->u.sa);
  308. free(lsa);
  309. }
  310. write_new_utmp(pid, LOGIN_PROCESS, tty_name, /*username:*/ "LOGIN", hostname);
  311. free(hostname);
  312. }
  313. /* Make new session and process group */
  314. setsid();
  315. /* Open the child's side of the tty */
  316. /* NB: setsid() disconnects from any previous ctty's. Therefore
  317. * we must open child's side of the tty AFTER setsid! */
  318. close(0);
  319. xopen(tty_name, O_RDWR); /* becomes our ctty */
  320. xdup2(0, 1);
  321. xdup2(0, 2);
  322. tcsetpgrp(0, pid); /* switch this tty's process group to us */
  323. /* The pseudo-terminal allocated to the client is configured to operate
  324. * in cooked mode, and with XTABS CRMOD enabled (see tty(4)) */
  325. tcgetattr(0, &termbuf);
  326. termbuf.c_lflag |= ECHO; /* if we use readline we dont want this */
  327. termbuf.c_oflag |= ONLCR | XTABS;
  328. termbuf.c_iflag |= ICRNL;
  329. termbuf.c_iflag &= ~IXOFF;
  330. /*termbuf.c_lflag &= ~ICANON;*/
  331. tcsetattr_stdin_TCSANOW(&termbuf);
  332. /* Uses FILE-based I/O to stdout, but does fflush_all(),
  333. * so should be safe with vfork.
  334. * I fear, though, that some users will have ridiculously big
  335. * issue files, and they may block writing to fd 1,
  336. * (parent is supposed to read it, but parent waits
  337. * for vforked child to exec!) */
  338. print_login_issue(G.issuefile, tty_name);
  339. /* Exec shell / login / whatever */
  340. login_argv[0] = G.loginpath;
  341. login_argv[1] = NULL;
  342. /* exec busybox applet (if PREFER_APPLETS=y), if that fails,
  343. * exec external program.
  344. * NB: sock is either 0 or has CLOEXEC set on it.
  345. * fd has CLOEXEC set on it too. These two fds will be closed here.
  346. */
  347. BB_EXECVP(G.loginpath, (char **)login_argv);
  348. /* _exit is safer with vfork, and we shouldn't send message
  349. * to remote clients anyway */
  350. _exit(EXIT_FAILURE); /*bb_perror_msg_and_die("execv %s", G.loginpath);*/
  351. }
  352. #if ENABLE_FEATURE_TELNETD_STANDALONE
  353. static void
  354. free_session(struct tsession *ts)
  355. {
  356. struct tsession *t;
  357. if (option_mask32 & OPT_INETD)
  358. exit(EXIT_SUCCESS);
  359. /* Unlink this telnet session from the session list */
  360. t = G.sessions;
  361. if (t == ts)
  362. G.sessions = ts->next;
  363. else {
  364. while (t->next != ts)
  365. t = t->next;
  366. t->next = ts->next;
  367. }
  368. #if 0
  369. /* It was said that "normal" telnetd just closes ptyfd,
  370. * doesn't send SIGKILL. When we close ptyfd,
  371. * kernel sends SIGHUP to processes having slave side opened. */
  372. kill(ts->shell_pid, SIGKILL);
  373. waitpid(ts->shell_pid, NULL, 0);
  374. #endif
  375. close(ts->ptyfd);
  376. close(ts->sockfd_read);
  377. /* We do not need to close(ts->sockfd_write), it's the same
  378. * as sockfd_read unless we are in inetd mode. But in inetd mode
  379. * we do not reach this */
  380. free(ts);
  381. /* Scan all sessions and find new maxfd */
  382. G.maxfd = 0;
  383. ts = G.sessions;
  384. while (ts) {
  385. if (G.maxfd < ts->ptyfd)
  386. G.maxfd = ts->ptyfd;
  387. if (G.maxfd < ts->sockfd_read)
  388. G.maxfd = ts->sockfd_read;
  389. #if 0
  390. /* Again, sockfd_write == sockfd_read here */
  391. if (G.maxfd < ts->sockfd_write)
  392. G.maxfd = ts->sockfd_write;
  393. #endif
  394. ts = ts->next;
  395. }
  396. }
  397. #else /* !FEATURE_TELNETD_STANDALONE */
  398. /* Used in main() only, thus "return 0" actually is exit(EXIT_SUCCESS). */
  399. #define free_session(ts) return 0
  400. #endif
  401. static void handle_sigchld(int sig UNUSED_PARAM)
  402. {
  403. pid_t pid;
  404. struct tsession *ts;
  405. int save_errno = errno;
  406. /* Looping: more than one child may have exited */
  407. while (1) {
  408. pid = wait_any_nohang(NULL);
  409. if (pid <= 0)
  410. break;
  411. ts = G.sessions;
  412. while (ts) {
  413. if (ts->shell_pid == pid) {
  414. ts->shell_pid = -1;
  415. // man utmp:
  416. // When init(8) finds that a process has exited, it locates its utmp entry
  417. // by ut_pid, sets ut_type to DEAD_PROCESS, and clears ut_user, ut_host
  418. // and ut_time with null bytes.
  419. // [same applies to other processes which maintain utmp entries, like telnetd]
  420. //
  421. // We do not bother actually clearing fields:
  422. // it might be interesting to know who was logged in and from where
  423. update_utmp(pid, DEAD_PROCESS, /*tty_name:*/ NULL, /*username:*/ NULL, /*hostname:*/ NULL);
  424. break;
  425. }
  426. ts = ts->next;
  427. }
  428. }
  429. errno = save_errno;
  430. }
  431. int telnetd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  432. int telnetd_main(int argc UNUSED_PARAM, char **argv)
  433. {
  434. fd_set rdfdset, wrfdset;
  435. unsigned opt;
  436. int count;
  437. struct tsession *ts;
  438. #if ENABLE_FEATURE_TELNETD_STANDALONE
  439. #define IS_INETD (opt & OPT_INETD)
  440. int master_fd = master_fd; /* for compiler */
  441. int sec_linger = sec_linger;
  442. char *opt_bindaddr = NULL;
  443. char *opt_portnbr;
  444. #else
  445. enum {
  446. IS_INETD = 1,
  447. master_fd = -1,
  448. };
  449. #endif
  450. INIT_G();
  451. /* -w NUM, and implies -F. -w and -i don't mix */
  452. IF_FEATURE_TELNETD_INETD_WAIT(opt_complementary = "wF:w+:i--w:w--i";)
  453. /* Even if !STANDALONE, we accept (and ignore) -i, thus people
  454. * don't need to guess whether it's ok to pass -i to us */
  455. opt = getopt32(argv, "f:l:Ki"
  456. IF_FEATURE_TELNETD_STANDALONE("p:b:F")
  457. IF_FEATURE_TELNETD_INETD_WAIT("Sw:"),
  458. &G.issuefile, &G.loginpath
  459. IF_FEATURE_TELNETD_STANDALONE(, &opt_portnbr, &opt_bindaddr)
  460. IF_FEATURE_TELNETD_INETD_WAIT(, &sec_linger)
  461. );
  462. if (!IS_INETD /*&& !re_execed*/) {
  463. /* inform that we start in standalone mode?
  464. * May be useful when people forget to give -i */
  465. /*bb_error_msg("listening for connections");*/
  466. if (!(opt & OPT_FOREGROUND)) {
  467. /* DAEMON_CHDIR_ROOT was giving inconsistent
  468. * behavior with/without -F, -i */
  469. bb_daemonize_or_rexec(0 /*was DAEMON_CHDIR_ROOT*/, argv);
  470. }
  471. }
  472. /* Redirect log to syslog early, if needed */
  473. if (IS_INETD || (opt & OPT_SYSLOG) || !(opt & OPT_FOREGROUND)) {
  474. openlog(applet_name, LOG_PID, LOG_DAEMON);
  475. logmode = LOGMODE_SYSLOG;
  476. }
  477. #if ENABLE_FEATURE_TELNETD_STANDALONE
  478. if (IS_INETD) {
  479. G.sessions = make_new_session(0);
  480. if (!G.sessions) /* pty opening or vfork problem, exit */
  481. return 1; /* make_new_session printed error message */
  482. } else {
  483. master_fd = 0;
  484. if (!(opt & OPT_WAIT)) {
  485. unsigned portnbr = 23;
  486. if (opt & OPT_PORT)
  487. portnbr = xatou16(opt_portnbr);
  488. master_fd = create_and_bind_stream_or_die(opt_bindaddr, portnbr);
  489. xlisten(master_fd, 1);
  490. }
  491. close_on_exec_on(master_fd);
  492. }
  493. #else
  494. G.sessions = make_new_session();
  495. if (!G.sessions) /* pty opening or vfork problem, exit */
  496. return 1; /* make_new_session printed error message */
  497. #endif
  498. /* We don't want to die if just one session is broken */
  499. signal(SIGPIPE, SIG_IGN);
  500. if (opt & OPT_WATCHCHILD)
  501. signal(SIGCHLD, handle_sigchld);
  502. else /* prevent dead children from becoming zombies */
  503. signal(SIGCHLD, SIG_IGN);
  504. /*
  505. This is how the buffers are used. The arrows indicate data flow.
  506. +-------+ wridx1++ +------+ rdidx1++ +----------+
  507. | | <-------------- | buf1 | <-------------- | |
  508. | | size1-- +------+ size1++ | |
  509. | pty | | socket |
  510. | | rdidx2++ +------+ wridx2++ | |
  511. | | --------------> | buf2 | --------------> | |
  512. +-------+ size2++ +------+ size2-- +----------+
  513. size1: "how many bytes are buffered for pty between rdidx1 and wridx1?"
  514. size2: "how many bytes are buffered for socket between rdidx2 and wridx2?"
  515. Each session has got two buffers. Buffers are circular. If sizeN == 0,
  516. buffer is empty. If sizeN == BUFSIZE, buffer is full. In both these cases
  517. rdidxN == wridxN.
  518. */
  519. again:
  520. FD_ZERO(&rdfdset);
  521. FD_ZERO(&wrfdset);
  522. /* Select on the master socket, all telnet sockets and their
  523. * ptys if there is room in their session buffers.
  524. * NB: scalability problem: we recalculate entire bitmap
  525. * before each select. Can be a problem with 500+ connections. */
  526. ts = G.sessions;
  527. while (ts) {
  528. struct tsession *next = ts->next; /* in case we free ts */
  529. if (ts->shell_pid == -1) {
  530. /* Child died and we detected that */
  531. free_session(ts);
  532. } else {
  533. if (ts->size1 > 0) /* can write to pty */
  534. FD_SET(ts->ptyfd, &wrfdset);
  535. if (ts->size1 < BUFSIZE) /* can read from socket */
  536. FD_SET(ts->sockfd_read, &rdfdset);
  537. if (ts->size2 > 0) /* can write to socket */
  538. FD_SET(ts->sockfd_write, &wrfdset);
  539. if (ts->size2 < BUFSIZE) /* can read from pty */
  540. FD_SET(ts->ptyfd, &rdfdset);
  541. }
  542. ts = next;
  543. }
  544. if (!IS_INETD) {
  545. FD_SET(master_fd, &rdfdset);
  546. /* This is needed because free_session() does not
  547. * take master_fd into account when it finds new
  548. * maxfd among remaining fd's */
  549. if (master_fd > G.maxfd)
  550. G.maxfd = master_fd;
  551. }
  552. {
  553. struct timeval *tv_ptr = NULL;
  554. #if ENABLE_FEATURE_TELNETD_INETD_WAIT
  555. struct timeval tv;
  556. if ((opt & OPT_WAIT) && !G.sessions) {
  557. tv.tv_sec = sec_linger;
  558. tv.tv_usec = 0;
  559. tv_ptr = &tv;
  560. }
  561. #endif
  562. count = select(G.maxfd + 1, &rdfdset, &wrfdset, NULL, tv_ptr);
  563. }
  564. if (count == 0) /* "telnetd -w SEC" timed out */
  565. return 0;
  566. if (count < 0)
  567. goto again; /* EINTR or ENOMEM */
  568. #if ENABLE_FEATURE_TELNETD_STANDALONE
  569. /* Check for and accept new sessions */
  570. if (!IS_INETD && FD_ISSET(master_fd, &rdfdset)) {
  571. int fd;
  572. struct tsession *new_ts;
  573. fd = accept(master_fd, NULL, NULL);
  574. if (fd < 0)
  575. goto again;
  576. close_on_exec_on(fd);
  577. /* Create a new session and link it into active list */
  578. new_ts = make_new_session(fd);
  579. if (new_ts) {
  580. new_ts->next = G.sessions;
  581. G.sessions = new_ts;
  582. } else {
  583. close(fd);
  584. }
  585. }
  586. #endif
  587. /* Then check for data tunneling */
  588. ts = G.sessions;
  589. while (ts) { /* For all sessions... */
  590. struct tsession *next = ts->next; /* in case we free ts */
  591. if (/*ts->size1 &&*/ FD_ISSET(ts->ptyfd, &wrfdset)) {
  592. int num_totty;
  593. unsigned char *ptr;
  594. /* Write to pty from buffer 1 */
  595. ptr = remove_iacs(ts, &num_totty);
  596. count = safe_write(ts->ptyfd, ptr, num_totty);
  597. if (count < 0) {
  598. if (errno == EAGAIN)
  599. goto skip1;
  600. goto kill_session;
  601. }
  602. ts->size1 -= count;
  603. ts->wridx1 += count;
  604. if (ts->wridx1 >= BUFSIZE) /* actually == BUFSIZE */
  605. ts->wridx1 = 0;
  606. }
  607. skip1:
  608. if (/*ts->size2 &&*/ FD_ISSET(ts->sockfd_write, &wrfdset)) {
  609. /* Write to socket from buffer 2 */
  610. count = MIN(BUFSIZE - ts->wridx2, ts->size2);
  611. count = iac_safe_write(ts->sockfd_write, (void*)(TS_BUF2(ts) + ts->wridx2), count);
  612. if (count < 0) {
  613. if (errno == EAGAIN)
  614. goto skip2;
  615. goto kill_session;
  616. }
  617. ts->size2 -= count;
  618. ts->wridx2 += count;
  619. if (ts->wridx2 >= BUFSIZE) /* actually == BUFSIZE */
  620. ts->wridx2 = 0;
  621. }
  622. skip2:
  623. /* Should not be needed, but... remove_iacs is actually buggy
  624. * (it cannot process iacs which wrap around buffer's end)!
  625. * Since properly fixing it requires writing bigger code,
  626. * we rely instead on this code making it virtually impossible
  627. * to have wrapped iac (people don't type at 2k/second).
  628. * It also allows for bigger reads in common case. */
  629. if (ts->size1 == 0) {
  630. ts->rdidx1 = 0;
  631. ts->wridx1 = 0;
  632. }
  633. if (ts->size2 == 0) {
  634. ts->rdidx2 = 0;
  635. ts->wridx2 = 0;
  636. }
  637. if (/*ts->size1 < BUFSIZE &&*/ FD_ISSET(ts->sockfd_read, &rdfdset)) {
  638. /* Read from socket to buffer 1 */
  639. count = MIN(BUFSIZE - ts->rdidx1, BUFSIZE - ts->size1);
  640. count = safe_read(ts->sockfd_read, TS_BUF1(ts) + ts->rdidx1, count);
  641. if (count <= 0) {
  642. if (count < 0 && errno == EAGAIN)
  643. goto skip3;
  644. goto kill_session;
  645. }
  646. /* Ignore trailing NUL if it is there */
  647. if (!TS_BUF1(ts)[ts->rdidx1 + count - 1]) {
  648. --count;
  649. }
  650. ts->size1 += count;
  651. ts->rdidx1 += count;
  652. if (ts->rdidx1 >= BUFSIZE) /* actually == BUFSIZE */
  653. ts->rdidx1 = 0;
  654. }
  655. skip3:
  656. if (/*ts->size2 < BUFSIZE &&*/ FD_ISSET(ts->ptyfd, &rdfdset)) {
  657. /* Read from pty to buffer 2 */
  658. count = MIN(BUFSIZE - ts->rdidx2, BUFSIZE - ts->size2);
  659. count = safe_read(ts->ptyfd, TS_BUF2(ts) + ts->rdidx2, count);
  660. if (count <= 0) {
  661. if (count < 0 && errno == EAGAIN)
  662. goto skip4;
  663. goto kill_session;
  664. }
  665. ts->size2 += count;
  666. ts->rdidx2 += count;
  667. if (ts->rdidx2 >= BUFSIZE) /* actually == BUFSIZE */
  668. ts->rdidx2 = 0;
  669. }
  670. skip4:
  671. ts = next;
  672. continue;
  673. kill_session:
  674. if (ts->shell_pid > 0)
  675. update_utmp(ts->shell_pid, DEAD_PROCESS, /*tty_name:*/ NULL, /*username:*/ NULL, /*hostname:*/ NULL);
  676. free_session(ts);
  677. ts = next;
  678. }
  679. goto again;
  680. }