telnetd.c 20 KB

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