3
0

telnetd.c 21 KB

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