telnetd.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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_keepalive(sock);
  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. update_utmp_DEAD_PROCESS(pid);
  416. break;
  417. }
  418. ts = ts->next;
  419. }
  420. }
  421. errno = save_errno;
  422. }
  423. int telnetd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  424. int telnetd_main(int argc UNUSED_PARAM, char **argv)
  425. {
  426. fd_set rdfdset, wrfdset;
  427. unsigned opt;
  428. int count;
  429. struct tsession *ts;
  430. #if ENABLE_FEATURE_TELNETD_STANDALONE
  431. #define IS_INETD (opt & OPT_INETD)
  432. int master_fd = master_fd; /* for compiler */
  433. int sec_linger = sec_linger;
  434. char *opt_bindaddr = NULL;
  435. char *opt_portnbr;
  436. #else
  437. enum {
  438. IS_INETD = 1,
  439. master_fd = -1,
  440. };
  441. #endif
  442. INIT_G();
  443. /* -w NUM, and implies -F. -w and -i don't mix */
  444. IF_FEATURE_TELNETD_INETD_WAIT(opt_complementary = "wF:w+:i--w:w--i";)
  445. /* Even if !STANDALONE, we accept (and ignore) -i, thus people
  446. * don't need to guess whether it's ok to pass -i to us */
  447. opt = getopt32(argv, "f:l:Ki"
  448. IF_FEATURE_TELNETD_STANDALONE("p:b:F")
  449. IF_FEATURE_TELNETD_INETD_WAIT("Sw:"),
  450. &G.issuefile, &G.loginpath
  451. IF_FEATURE_TELNETD_STANDALONE(, &opt_portnbr, &opt_bindaddr)
  452. IF_FEATURE_TELNETD_INETD_WAIT(, &sec_linger)
  453. );
  454. if (!IS_INETD /*&& !re_execed*/) {
  455. /* inform that we start in standalone mode?
  456. * May be useful when people forget to give -i */
  457. /*bb_error_msg("listening for connections");*/
  458. if (!(opt & OPT_FOREGROUND)) {
  459. /* DAEMON_CHDIR_ROOT was giving inconsistent
  460. * behavior with/without -F, -i */
  461. bb_daemonize_or_rexec(0 /*was DAEMON_CHDIR_ROOT*/, argv);
  462. }
  463. }
  464. /* Redirect log to syslog early, if needed */
  465. if (IS_INETD || (opt & OPT_SYSLOG) || !(opt & OPT_FOREGROUND)) {
  466. openlog(applet_name, LOG_PID, LOG_DAEMON);
  467. logmode = LOGMODE_SYSLOG;
  468. }
  469. #if ENABLE_FEATURE_TELNETD_STANDALONE
  470. if (IS_INETD) {
  471. G.sessions = make_new_session(0);
  472. if (!G.sessions) /* pty opening or vfork problem, exit */
  473. return 1; /* make_new_session printed error message */
  474. } else {
  475. master_fd = 0;
  476. if (!(opt & OPT_WAIT)) {
  477. unsigned portnbr = 23;
  478. if (opt & OPT_PORT)
  479. portnbr = xatou16(opt_portnbr);
  480. master_fd = create_and_bind_stream_or_die(opt_bindaddr, portnbr);
  481. xlisten(master_fd, 1);
  482. }
  483. close_on_exec_on(master_fd);
  484. }
  485. #else
  486. G.sessions = make_new_session();
  487. if (!G.sessions) /* pty opening or vfork problem, exit */
  488. return 1; /* make_new_session printed error message */
  489. #endif
  490. /* We don't want to die if just one session is broken */
  491. signal(SIGPIPE, SIG_IGN);
  492. if (opt & OPT_WATCHCHILD)
  493. signal(SIGCHLD, handle_sigchld);
  494. else /* prevent dead children from becoming zombies */
  495. signal(SIGCHLD, SIG_IGN);
  496. /*
  497. This is how the buffers are used. The arrows indicate data flow.
  498. +-------+ wridx1++ +------+ rdidx1++ +----------+
  499. | | <-------------- | buf1 | <-------------- | |
  500. | | size1-- +------+ size1++ | |
  501. | pty | | socket |
  502. | | rdidx2++ +------+ wridx2++ | |
  503. | | --------------> | buf2 | --------------> | |
  504. +-------+ size2++ +------+ size2-- +----------+
  505. size1: "how many bytes are buffered for pty between rdidx1 and wridx1?"
  506. size2: "how many bytes are buffered for socket between rdidx2 and wridx2?"
  507. Each session has got two buffers. Buffers are circular. If sizeN == 0,
  508. buffer is empty. If sizeN == BUFSIZE, buffer is full. In both these cases
  509. rdidxN == wridxN.
  510. */
  511. again:
  512. FD_ZERO(&rdfdset);
  513. FD_ZERO(&wrfdset);
  514. /* Select on the master socket, all telnet sockets and their
  515. * ptys if there is room in their session buffers.
  516. * NB: scalability problem: we recalculate entire bitmap
  517. * before each select. Can be a problem with 500+ connections. */
  518. ts = G.sessions;
  519. while (ts) {
  520. struct tsession *next = ts->next; /* in case we free ts */
  521. if (ts->shell_pid == -1) {
  522. /* Child died and we detected that */
  523. free_session(ts);
  524. } else {
  525. if (ts->size1 > 0) /* can write to pty */
  526. FD_SET(ts->ptyfd, &wrfdset);
  527. if (ts->size1 < BUFSIZE) /* can read from socket */
  528. FD_SET(ts->sockfd_read, &rdfdset);
  529. if (ts->size2 > 0) /* can write to socket */
  530. FD_SET(ts->sockfd_write, &wrfdset);
  531. if (ts->size2 < BUFSIZE) /* can read from pty */
  532. FD_SET(ts->ptyfd, &rdfdset);
  533. }
  534. ts = next;
  535. }
  536. if (!IS_INETD) {
  537. FD_SET(master_fd, &rdfdset);
  538. /* This is needed because free_session() does not
  539. * take master_fd into account when it finds new
  540. * maxfd among remaining fd's */
  541. if (master_fd > G.maxfd)
  542. G.maxfd = master_fd;
  543. }
  544. {
  545. struct timeval *tv_ptr = NULL;
  546. #if ENABLE_FEATURE_TELNETD_INETD_WAIT
  547. struct timeval tv;
  548. if ((opt & OPT_WAIT) && !G.sessions) {
  549. tv.tv_sec = sec_linger;
  550. tv.tv_usec = 0;
  551. tv_ptr = &tv;
  552. }
  553. #endif
  554. count = select(G.maxfd + 1, &rdfdset, &wrfdset, NULL, tv_ptr);
  555. }
  556. if (count == 0) /* "telnetd -w SEC" timed out */
  557. return 0;
  558. if (count < 0)
  559. goto again; /* EINTR or ENOMEM */
  560. #if ENABLE_FEATURE_TELNETD_STANDALONE
  561. /* Check for and accept new sessions */
  562. if (!IS_INETD && FD_ISSET(master_fd, &rdfdset)) {
  563. int fd;
  564. struct tsession *new_ts;
  565. fd = accept(master_fd, NULL, NULL);
  566. if (fd < 0)
  567. goto again;
  568. close_on_exec_on(fd);
  569. /* Create a new session and link it into active list */
  570. new_ts = make_new_session(fd);
  571. if (new_ts) {
  572. new_ts->next = G.sessions;
  573. G.sessions = new_ts;
  574. } else {
  575. close(fd);
  576. }
  577. }
  578. #endif
  579. /* Then check for data tunneling */
  580. ts = G.sessions;
  581. while (ts) { /* For all sessions... */
  582. struct tsession *next = ts->next; /* in case we free ts */
  583. if (/*ts->size1 &&*/ FD_ISSET(ts->ptyfd, &wrfdset)) {
  584. int num_totty;
  585. unsigned char *ptr;
  586. /* Write to pty from buffer 1 */
  587. ptr = remove_iacs(ts, &num_totty);
  588. count = safe_write(ts->ptyfd, ptr, num_totty);
  589. if (count < 0) {
  590. if (errno == EAGAIN)
  591. goto skip1;
  592. goto kill_session;
  593. }
  594. ts->size1 -= count;
  595. ts->wridx1 += count;
  596. if (ts->wridx1 >= BUFSIZE) /* actually == BUFSIZE */
  597. ts->wridx1 = 0;
  598. }
  599. skip1:
  600. if (/*ts->size2 &&*/ FD_ISSET(ts->sockfd_write, &wrfdset)) {
  601. /* Write to socket from buffer 2 */
  602. count = MIN(BUFSIZE - ts->wridx2, ts->size2);
  603. count = iac_safe_write(ts->sockfd_write, (void*)(TS_BUF2(ts) + ts->wridx2), count);
  604. if (count < 0) {
  605. if (errno == EAGAIN)
  606. goto skip2;
  607. goto kill_session;
  608. }
  609. ts->size2 -= count;
  610. ts->wridx2 += count;
  611. if (ts->wridx2 >= BUFSIZE) /* actually == BUFSIZE */
  612. ts->wridx2 = 0;
  613. }
  614. skip2:
  615. /* Should not be needed, but... remove_iacs is actually buggy
  616. * (it cannot process iacs which wrap around buffer's end)!
  617. * Since properly fixing it requires writing bigger code,
  618. * we rely instead on this code making it virtually impossible
  619. * to have wrapped iac (people don't type at 2k/second).
  620. * It also allows for bigger reads in common case. */
  621. if (ts->size1 == 0) {
  622. ts->rdidx1 = 0;
  623. ts->wridx1 = 0;
  624. }
  625. if (ts->size2 == 0) {
  626. ts->rdidx2 = 0;
  627. ts->wridx2 = 0;
  628. }
  629. if (/*ts->size1 < BUFSIZE &&*/ FD_ISSET(ts->sockfd_read, &rdfdset)) {
  630. /* Read from socket to buffer 1 */
  631. count = MIN(BUFSIZE - ts->rdidx1, BUFSIZE - ts->size1);
  632. count = safe_read(ts->sockfd_read, TS_BUF1(ts) + ts->rdidx1, count);
  633. if (count <= 0) {
  634. if (count < 0 && errno == EAGAIN)
  635. goto skip3;
  636. goto kill_session;
  637. }
  638. /* Ignore trailing NUL if it is there */
  639. if (!TS_BUF1(ts)[ts->rdidx1 + count - 1]) {
  640. --count;
  641. }
  642. ts->size1 += count;
  643. ts->rdidx1 += count;
  644. if (ts->rdidx1 >= BUFSIZE) /* actually == BUFSIZE */
  645. ts->rdidx1 = 0;
  646. }
  647. skip3:
  648. if (/*ts->size2 < BUFSIZE &&*/ FD_ISSET(ts->ptyfd, &rdfdset)) {
  649. /* Read from pty to buffer 2 */
  650. count = MIN(BUFSIZE - ts->rdidx2, BUFSIZE - ts->size2);
  651. count = safe_read(ts->ptyfd, TS_BUF2(ts) + ts->rdidx2, count);
  652. if (count <= 0) {
  653. if (count < 0 && errno == EAGAIN)
  654. goto skip4;
  655. goto kill_session;
  656. }
  657. ts->size2 += count;
  658. ts->rdidx2 += count;
  659. if (ts->rdidx2 >= BUFSIZE) /* actually == BUFSIZE */
  660. ts->rdidx2 = 0;
  661. }
  662. skip4:
  663. ts = next;
  664. continue;
  665. kill_session:
  666. if (ts->shell_pid > 0)
  667. update_utmp_DEAD_PROCESS(ts->shell_pid);
  668. free_session(ts);
  669. ts = next;
  670. }
  671. goto again;
  672. }