3
0

telnetd.c 21 KB

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