1de3abcc77510b22786ac8d5b46309afbbd0e501
[oweals/busybox.git] / networking / telnetd.c
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
24 //usage:#define telnetd_trivial_usage
25 //usage:       "[OPTIONS]"
26 //usage:#define telnetd_full_usage "\n\n"
27 //usage:       "Handle incoming telnet connections"
28 //usage:        IF_NOT_FEATURE_TELNETD_STANDALONE(" via inetd") "\n"
29 //usage:     "\n        -l LOGIN        Exec LOGIN on connect"
30 //usage:     "\n        -f ISSUE_FILE   Display ISSUE_FILE instead of /etc/issue"
31 //usage:     "\n        -K              Close connection as soon as login exits"
32 //usage:     "\n                        (normally wait until all programs close slave pty)"
33 //usage:        IF_FEATURE_TELNETD_STANDALONE(
34 //usage:     "\n        -p PORT         Port to listen on"
35 //usage:     "\n        -b ADDR[:PORT]  Address to bind to"
36 //usage:     "\n        -F              Run in foreground"
37 //usage:     "\n        -i              Inetd mode"
38 //usage:        IF_FEATURE_TELNETD_INETD_WAIT(
39 //usage:     "\n        -w SEC          Inetd 'wait' mode, linger time SEC"
40 //usage:     "\n        -S              Log to syslog (implied by -i or without -F and -w)"
41 //usage:        )
42 //usage:        )
43
44 #define DEBUG 0
45
46 #include "libbb.h"
47 #include "common_bufsiz.h"
48 #include <syslog.h>
49
50 #if DEBUG
51 # define TELCMDS
52 # define TELOPTS
53 #endif
54 #include <arpa/telnet.h>
55
56
57 struct tsession {
58         struct tsession *next;
59         pid_t shell_pid;
60         int sockfd_read;
61         int sockfd_write;
62         int ptyfd;
63         smallint buffered_IAC_for_pty;
64
65         /* two circular buffers */
66         /*char *buf1, *buf2;*/
67 /*#define TS_BUF1(ts) ts->buf1*/
68 /*#define TS_BUF2(ts) TS_BUF2(ts)*/
69 #define TS_BUF1(ts) ((unsigned char*)(ts + 1))
70 #define TS_BUF2(ts) (((unsigned char*)(ts + 1)) + BUFSIZE)
71         int rdidx1, wridx1, size1;
72         int rdidx2, wridx2, size2;
73 };
74
75 /* Two buffers are directly after tsession in malloced memory.
76  * Make whole thing fit in 4k */
77 enum { BUFSIZE = (4 * 1024 - sizeof(struct tsession)) / 2 };
78
79
80 /* Globals */
81 struct globals {
82         struct tsession *sessions;
83         const char *loginpath;
84         const char *issuefile;
85         int maxfd;
86 } FIX_ALIASING;
87 #define G (*(struct globals*)bb_common_bufsiz1)
88 #define INIT_G() do { \
89         setup_common_bufsiz(); \
90         G.loginpath = "/bin/login"; \
91         G.issuefile = "/etc/issue.net"; \
92 } while (0)
93
94
95 /* Write some buf1 data to pty, processing IACs.
96  * Update wridx1 and size1. Return < 0 on error.
97  * Buggy if IAC is present but incomplete: skips them.
98  */
99 static ssize_t
100 safe_write_to_pty_decode_iac(struct tsession *ts)
101 {
102         unsigned wr;
103         ssize_t rc;
104         unsigned char *buf;
105         unsigned char *found;
106
107         buf = TS_BUF1(ts) + ts->wridx1;
108         wr = MIN(BUFSIZE - ts->wridx1, ts->size1);
109         /* wr is at least 1 here */
110
111         if (ts->buffered_IAC_for_pty) {
112                 /* Last time we stopped on a "dangling" IAC byte.
113                  * We removed it from the buffer back then.
114                  * Now pretend it's still there, and jump to IAC processing.
115                  */
116                 ts->buffered_IAC_for_pty = 0;
117                 wr++;
118                 ts->size1++;
119                 buf--; /* Yes, this can point before the buffer. It's ok */
120                 ts->wridx1--;
121                 goto handle_iac;
122         }
123
124         found = memchr(buf, IAC, wr);
125         if (found != buf) {
126                 /* There is a "prefix" of non-IAC chars.
127                  * Write only them, and return.
128                  */
129                 if (found)
130                         wr = found - buf;
131
132                 /* We map \r\n ==> \r for pragmatic reasons:
133                  * many client implementations send \r\n when
134                  * the user hits the CarriageReturn key.
135                  * See RFC 1123 3.3.1 Telnet End-of-Line Convention.
136                  */
137                 rc = wr;
138                 found = memchr(buf, '\r', wr);
139                 if (found)
140                         rc = found - buf + 1;
141                 rc = safe_write(ts->ptyfd, buf, rc);
142                 if (rc <= 0)
143                         return rc;
144                 if (rc < wr /* don't look past available data */
145                  && buf[rc-1] == '\r' /* need this: imagine that write was _short_ */
146                  && (buf[rc] == '\n' || buf[rc] == '\0')
147                 ) {
148                         rc++;
149                 }
150                 goto update_and_return;
151         }
152
153         /* buf starts with IAC char. Process that sequence.
154          * Example: we get this from our own (bbox) telnet client:
155          * read(5, "\377\374\1""\377\373\37""\377\372\37\0\262\0@\377\360""\377\375\1""\377\375\3"):
156          * IAC WONT ECHO, IAC WILL NAWS, IAC SB NAWS <cols> <rows> IAC SE, IAC DO SGA
157          * Another example (telnet-0.17 from old-netkit):
158          * read(4, "\377\375\3""\377\373\30""\377\373\37""\377\373 ""\377\373!""\377\373\"""\377\373'"
159          * "\377\375\5""\377\373#""\377\374\1""\377\372\37\0\257\0I\377\360""\377\375\1"):
160          * IAC DO SGA, IAC WILL TTYPE, IAC WILL NAWS, IAC WILL TSPEED, IAC WILL LFLOW, IAC WILL LINEMODE, IAC WILL NEW_ENVIRON,
161          * IAC DO STATUS, IAC WILL XDISPLOC, IAC WONT ECHO, IAC SB NAWS <cols> <rows> IAC SE, IAC DO ECHO
162          */
163         if (wr <= 1) {
164                 /* Only the single IAC byte is in the buffer, eat it
165                  * and set a flag "process the rest of the sequence
166                  * next time we are here".
167                  */
168                 //bb_error_msg("dangling IAC!");
169                 ts->buffered_IAC_for_pty = 1;
170                 rc = 1;
171                 goto update_and_return;
172         }
173
174  handle_iac:
175         /* 2-byte commands (240..250 and 255):
176          * IAC IAC (255) Literal 255. Supported.
177          * IAC SE  (240) End of subnegotiation. Treated as NOP.
178          * IAC NOP (241) NOP. Supported.
179          * IAC BRK (243) Break. Like serial line break. TODO via tcsendbreak()?
180          * IAC AYT (246) Are you there. Send back evidence that AYT was seen. TODO (send NOP back)?
181          *  These don't look useful:
182          * IAC DM  (242) Data mark. What is this?
183          * IAC IP  (244) Suspend, interrupt or abort the process. (Ancient cousin of ^C).
184          * IAC AO  (245) Abort output. "You can continue running, but do not send me the output".
185          * IAC EC  (247) Erase character. The receiver should delete the last received char.
186          * IAC EL  (248) Erase line. The receiver should delete everything up tp last newline.
187          * IAC GA  (249) Go ahead. For half-duplex lines: "now you talk".
188          *  Implemented only as part of NAWS:
189          * IAC SB  (250) Subnegotiation of an option follows.
190          */
191         if (buf[1] == IAC) {
192                 /* Literal 255 (emacs M-DEL) */
193                 //bb_error_msg("255!");
194                 rc = safe_write(ts->ptyfd, &buf[1], 1);
195                 if (rc <= 0)
196                         return rc;
197                 rc = 2;
198                 goto update_and_return;
199         }
200         if (buf[1] >= 240 && buf[1] <= 249) {
201                 /* NOP (241). Ignore (putty keepalive, etc) */
202                 /* All other 2-byte commands also treated as NOPs here */
203                 rc = 2;
204                 goto update_and_return;
205         }
206
207         if (wr <= 2) {
208 /* BUG: only 2 bytes of the IAC is in the buffer, we just eat them.
209  * This is not a practical problem since >2 byte IACs are seen only
210  * in initial negotiation, when buffer is empty
211  */
212                 rc = 2;
213                 goto update_and_return;
214         }
215
216         if (buf[1] == SB) {
217                 if (buf[2] == TELOPT_NAWS) {
218                         /* IAC SB, TELOPT_NAWS, 4-byte, IAC SE */
219                         struct winsize ws;
220                         if (wr <= 6) {
221 /* BUG: incomplete, can't process */
222                                 rc = wr;
223                                 goto update_and_return;
224                         }
225                         memset(&ws, 0, sizeof(ws)); /* pixel sizes are set to 0 */
226                         ws.ws_col = (buf[3] << 8) | buf[4];
227                         ws.ws_row = (buf[5] << 8) | buf[6];
228                         ioctl(ts->ptyfd, TIOCSWINSZ, (char *)&ws);
229                         rc = 7;
230                         /* trailing IAC SE will be eaten separately, as 2-byte NOP */
231                         goto update_and_return;
232                 }
233                 /* else: other subnegs not supported yet */
234         }
235
236         /* Assume it is a 3-byte WILL/WONT/DO/DONT 251..254 command and skip it */
237 #if DEBUG
238         fprintf(stderr, "Ignoring IAC %s,%s\n",
239                         TELCMD(buf[1]), TELOPT(buf[2]));
240 #endif
241         rc = 3;
242
243  update_and_return:
244         ts->wridx1 += rc;
245         if (ts->wridx1 >= BUFSIZE) /* actually == BUFSIZE */
246                 ts->wridx1 = 0;
247         ts->size1 -= rc;
248         /*
249          * Hack. We cannot process IACs which wrap around buffer's end.
250          * Since properly fixing it requires writing bigger code,
251          * we rely instead on this code making it virtually impossible
252          * to have wrapped IAC (people don't type at 2k/second).
253          * It also allows for bigger reads in common case.
254          */
255         if (ts->size1 == 0) { /* very typical */
256                 //bb_error_msg("zero size1");
257                 ts->rdidx1 = 0;
258                 ts->wridx1 = 0;
259                 return rc;
260         }
261         wr = ts->wridx1;
262         if (wr != 0 && wr < ts->rdidx1) {
263                 /* Buffer is not wrapped yet.
264                  * We can easily move it to the beginning.
265                  */
266                 //bb_error_msg("moved %d", wr);
267                 memmove(TS_BUF1(ts), TS_BUF1(ts) + wr, ts->size1);
268                 ts->rdidx1 -= wr;
269                 ts->wridx1 = 0;
270         }
271         return rc;
272 }
273
274 /*
275  * Converting single IAC into double on output
276  */
277 static size_t safe_write_double_iac(int fd, const char *buf, size_t count)
278 {
279         const char *IACptr;
280         size_t wr, rc, total;
281
282         total = 0;
283         while (1) {
284                 if (count == 0)
285                         return total;
286                 if (*buf == (char)IAC) {
287                         static const char IACIAC[] ALIGN1 = { IAC, IAC };
288                         rc = safe_write(fd, IACIAC, 2);
289 /* BUG: if partial write was only 1 byte long, we end up emitting just one IAC */
290                         if (rc != 2)
291                                 break;
292                         buf++;
293                         total++;
294                         count--;
295                         continue;
296                 }
297                 /* count != 0, *buf != IAC */
298                 IACptr = memchr(buf, IAC, count);
299                 wr = count;
300                 if (IACptr)
301                         wr = IACptr - buf;
302                 rc = safe_write(fd, buf, wr);
303                 if (rc != wr)
304                         break;
305                 buf += rc;
306                 total += rc;
307                 count -= rc;
308         }
309         /* here: rc - result of last short write */
310         if ((ssize_t)rc < 0) { /* error? */
311                 if (total == 0)
312                         return rc;
313                 rc = 0;
314         }
315         return total + rc;
316 }
317
318 /* Must match getopt32 string */
319 enum {
320         OPT_WATCHCHILD = (1 << 2), /* -K */
321         OPT_INETD      = (1 << 3) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -i */
322         OPT_PORT       = (1 << 4) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -p PORT */
323         OPT_FOREGROUND = (1 << 6) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -F */
324         OPT_SYSLOG     = (1 << 7) * ENABLE_FEATURE_TELNETD_INETD_WAIT, /* -S */
325         OPT_WAIT       = (1 << 8) * ENABLE_FEATURE_TELNETD_INETD_WAIT, /* -w SEC */
326 };
327
328 static struct tsession *
329 make_new_session(
330                 IF_FEATURE_TELNETD_STANDALONE(int sock)
331                 IF_NOT_FEATURE_TELNETD_STANDALONE(void)
332 ) {
333 #if !ENABLE_FEATURE_TELNETD_STANDALONE
334         enum { sock = 0 };
335 #endif
336         const char *login_argv[2];
337         struct termios termbuf;
338         int fd, pid;
339         char tty_name[GETPTY_BUFSIZE];
340         struct tsession *ts = xzalloc(sizeof(struct tsession) + BUFSIZE * 2);
341
342         /*ts->buf1 = (char *)(ts + 1);*/
343         /*ts->buf2 = ts->buf1 + BUFSIZE;*/
344
345         /* Got a new connection, set up a tty */
346         fd = xgetpty(tty_name);
347         if (fd > G.maxfd)
348                 G.maxfd = fd;
349         ts->ptyfd = fd;
350         ndelay_on(fd);
351         close_on_exec_on(fd);
352
353         /* SO_KEEPALIVE by popular demand */
354         setsockopt_keepalive(sock);
355 #if ENABLE_FEATURE_TELNETD_STANDALONE
356         ts->sockfd_read = sock;
357         ndelay_on(sock);
358         if (sock == 0) { /* We are called with fd 0 - we are in inetd mode */
359                 sock++; /* so use fd 1 for output */
360                 ndelay_on(sock);
361         }
362         ts->sockfd_write = sock;
363         if (sock > G.maxfd)
364                 G.maxfd = sock;
365 #else
366         /* ts->sockfd_read = 0; - done by xzalloc */
367         ts->sockfd_write = 1;
368         ndelay_on(0);
369         ndelay_on(1);
370 #endif
371
372         /* Make the telnet client understand we will echo characters so it
373          * should not do it locally. We don't tell the client to run linemode,
374          * because we want to handle line editing and tab completion and other
375          * stuff that requires char-by-char support. */
376         {
377                 static const char iacs_to_send[] ALIGN1 = {
378                         IAC, DO, TELOPT_ECHO,
379                         IAC, DO, TELOPT_NAWS,
380                         /* This requires telnetd.ctrlSQ.patch (incomplete) */
381                         /*IAC, DO, TELOPT_LFLOW,*/
382                         IAC, WILL, TELOPT_ECHO,
383                         IAC, WILL, TELOPT_SGA
384                 };
385                 /* This confuses safe_write_double_iac(), it will try to duplicate
386                  * each IAC... */
387                 //memcpy(TS_BUF2(ts), iacs_to_send, sizeof(iacs_to_send));
388                 //ts->rdidx2 = sizeof(iacs_to_send);
389                 //ts->size2 = sizeof(iacs_to_send);
390                 /* So just stuff it into TCP stream! (no error check...) */
391 #if ENABLE_FEATURE_TELNETD_STANDALONE
392                 safe_write(sock, iacs_to_send, sizeof(iacs_to_send));
393 #else
394                 safe_write(1, iacs_to_send, sizeof(iacs_to_send));
395 #endif
396                 /*ts->rdidx2 = 0; - xzalloc did it */
397                 /*ts->size2 = 0;*/
398         }
399
400         fflush_all();
401         pid = vfork(); /* NOMMU-friendly */
402         if (pid < 0) {
403                 free(ts);
404                 close(fd);
405                 /* sock will be closed by caller */
406                 bb_perror_msg("vfork");
407                 return NULL;
408         }
409         if (pid > 0) {
410                 /* Parent */
411                 ts->shell_pid = pid;
412                 return ts;
413         }
414
415         /* Child */
416         /* Careful - we are after vfork! */
417
418         /* Restore default signal handling ASAP */
419         bb_signals((1 << SIGCHLD) + (1 << SIGPIPE), SIG_DFL);
420
421         pid = getpid();
422
423         if (ENABLE_FEATURE_UTMP) {
424                 len_and_sockaddr *lsa = get_peer_lsa(sock);
425                 char *hostname = NULL;
426                 if (lsa) {
427                         hostname = xmalloc_sockaddr2dotted(&lsa->u.sa);
428                         free(lsa);
429                 }
430                 write_new_utmp(pid, LOGIN_PROCESS, tty_name, /*username:*/ "LOGIN", hostname);
431                 free(hostname);
432         }
433
434         /* Make new session and process group */
435         setsid();
436
437         /* Open the child's side of the tty */
438         /* NB: setsid() disconnects from any previous ctty's. Therefore
439          * we must open child's side of the tty AFTER setsid! */
440         close(0);
441         xopen(tty_name, O_RDWR); /* becomes our ctty */
442         xdup2(0, 1);
443         xdup2(0, 2);
444         tcsetpgrp(0, pid); /* switch this tty's process group to us */
445
446         /* The pseudo-terminal allocated to the client is configured to operate
447          * in cooked mode, and with XTABS CRMOD enabled (see tty(4)) */
448         tcgetattr(0, &termbuf);
449         termbuf.c_lflag |= ECHO; /* if we use readline we dont want this */
450         termbuf.c_oflag |= ONLCR | XTABS;
451         termbuf.c_iflag |= ICRNL;
452         termbuf.c_iflag &= ~IXOFF;
453         /*termbuf.c_lflag &= ~ICANON;*/
454         tcsetattr_stdin_TCSANOW(&termbuf);
455
456         /* Uses FILE-based I/O to stdout, but does fflush_all(),
457          * so should be safe with vfork.
458          * I fear, though, that some users will have ridiculously big
459          * issue files, and they may block writing to fd 1,
460          * (parent is supposed to read it, but parent waits
461          * for vforked child to exec!) */
462         print_login_issue(G.issuefile, tty_name);
463
464         /* Exec shell / login / whatever */
465         login_argv[0] = G.loginpath;
466         login_argv[1] = NULL;
467         /* exec busybox applet (if PREFER_APPLETS=y), if that fails,
468          * exec external program.
469          * NB: sock is either 0 or has CLOEXEC set on it.
470          * fd has CLOEXEC set on it too. These two fds will be closed here.
471          */
472         BB_EXECVP(G.loginpath, (char **)login_argv);
473         /* _exit is safer with vfork, and we shouldn't send message
474          * to remote clients anyway */
475         _exit(EXIT_FAILURE); /*bb_perror_msg_and_die("execv %s", G.loginpath);*/
476 }
477
478 #if ENABLE_FEATURE_TELNETD_STANDALONE
479
480 static void
481 free_session(struct tsession *ts)
482 {
483         struct tsession *t;
484
485         if (option_mask32 & OPT_INETD)
486                 exit(EXIT_SUCCESS);
487
488         /* Unlink this telnet session from the session list */
489         t = G.sessions;
490         if (t == ts)
491                 G.sessions = ts->next;
492         else {
493                 while (t->next != ts)
494                         t = t->next;
495                 t->next = ts->next;
496         }
497
498 #if 0
499         /* It was said that "normal" telnetd just closes ptyfd,
500          * doesn't send SIGKILL. When we close ptyfd,
501          * kernel sends SIGHUP to processes having slave side opened. */
502         kill(ts->shell_pid, SIGKILL);
503         waitpid(ts->shell_pid, NULL, 0);
504 #endif
505         close(ts->ptyfd);
506         close(ts->sockfd_read);
507         /* We do not need to close(ts->sockfd_write), it's the same
508          * as sockfd_read unless we are in inetd mode. But in inetd mode
509          * we do not reach this */
510         free(ts);
511
512         /* Scan all sessions and find new maxfd */
513         G.maxfd = 0;
514         ts = G.sessions;
515         while (ts) {
516                 if (G.maxfd < ts->ptyfd)
517                         G.maxfd = ts->ptyfd;
518                 if (G.maxfd < ts->sockfd_read)
519                         G.maxfd = ts->sockfd_read;
520 #if 0
521                 /* Again, sockfd_write == sockfd_read here */
522                 if (G.maxfd < ts->sockfd_write)
523                         G.maxfd = ts->sockfd_write;
524 #endif
525                 ts = ts->next;
526         }
527 }
528
529 #else /* !FEATURE_TELNETD_STANDALONE */
530
531 /* Used in main() only, thus "return 0" actually is exit(EXIT_SUCCESS). */
532 #define free_session(ts) return 0
533
534 #endif
535
536 static void handle_sigchld(int sig UNUSED_PARAM)
537 {
538         pid_t pid;
539         struct tsession *ts;
540         int save_errno = errno;
541
542         /* Looping: more than one child may have exited */
543         while (1) {
544                 pid = wait_any_nohang(NULL);
545                 if (pid <= 0)
546                         break;
547                 ts = G.sessions;
548                 while (ts) {
549                         if (ts->shell_pid == pid) {
550                                 ts->shell_pid = -1;
551                                 update_utmp_DEAD_PROCESS(pid);
552                                 break;
553                         }
554                         ts = ts->next;
555                 }
556         }
557
558         errno = save_errno;
559 }
560
561 int telnetd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
562 int telnetd_main(int argc UNUSED_PARAM, char **argv)
563 {
564         fd_set rdfdset, wrfdset;
565         unsigned opt;
566         int count;
567         struct tsession *ts;
568 #if ENABLE_FEATURE_TELNETD_STANDALONE
569 #define IS_INETD (opt & OPT_INETD)
570         int master_fd = master_fd; /* for compiler */
571         int sec_linger = sec_linger;
572         char *opt_bindaddr = NULL;
573         char *opt_portnbr;
574 #else
575         enum {
576                 IS_INETD = 1,
577                 master_fd = -1,
578         };
579 #endif
580         INIT_G();
581
582         /* -w NUM, and implies -F. -w and -i don't mix */
583         IF_FEATURE_TELNETD_INETD_WAIT(opt_complementary = "wF:i--w:w--i";)
584         /* Even if !STANDALONE, we accept (and ignore) -i, thus people
585          * don't need to guess whether it's ok to pass -i to us */
586         opt = getopt32(argv, "f:l:Ki"
587                         IF_FEATURE_TELNETD_STANDALONE("p:b:F")
588                         IF_FEATURE_TELNETD_INETD_WAIT("Sw:+"),
589                         &G.issuefile, &G.loginpath
590                         IF_FEATURE_TELNETD_STANDALONE(, &opt_portnbr, &opt_bindaddr)
591                         IF_FEATURE_TELNETD_INETD_WAIT(, &sec_linger)
592         );
593         if (!IS_INETD /*&& !re_execed*/) {
594                 /* inform that we start in standalone mode?
595                  * May be useful when people forget to give -i */
596                 /*bb_error_msg("listening for connections");*/
597                 if (!(opt & OPT_FOREGROUND)) {
598                         /* DAEMON_CHDIR_ROOT was giving inconsistent
599                          * behavior with/without -F, -i */
600                         bb_daemonize_or_rexec(0 /*was DAEMON_CHDIR_ROOT*/, argv);
601                 }
602         }
603         /* Redirect log to syslog early, if needed */
604         if (IS_INETD || (opt & OPT_SYSLOG) || !(opt & OPT_FOREGROUND)) {
605                 openlog(applet_name, LOG_PID, LOG_DAEMON);
606                 logmode = LOGMODE_SYSLOG;
607         }
608 #if ENABLE_FEATURE_TELNETD_STANDALONE
609         if (IS_INETD) {
610                 G.sessions = make_new_session(0);
611                 if (!G.sessions) /* pty opening or vfork problem, exit */
612                         return 1; /* make_new_session printed error message */
613         } else {
614                 master_fd = 0;
615                 if (!(opt & OPT_WAIT)) {
616                         unsigned portnbr = 23;
617                         if (opt & OPT_PORT)
618                                 portnbr = xatou16(opt_portnbr);
619                         master_fd = create_and_bind_stream_or_die(opt_bindaddr, portnbr);
620                         xlisten(master_fd, 1);
621                 }
622                 close_on_exec_on(master_fd);
623         }
624 #else
625         G.sessions = make_new_session();
626         if (!G.sessions) /* pty opening or vfork problem, exit */
627                 return 1; /* make_new_session printed error message */
628 #endif
629
630         /* We don't want to die if just one session is broken */
631         signal(SIGPIPE, SIG_IGN);
632
633         if (opt & OPT_WATCHCHILD)
634                 signal(SIGCHLD, handle_sigchld);
635         else /* prevent dead children from becoming zombies */
636                 signal(SIGCHLD, SIG_IGN);
637
638 /*
639    This is how the buffers are used. The arrows indicate data flow.
640
641    +-------+     wridx1++     +------+     rdidx1++     +----------+
642    |       | <--------------  | buf1 | <--------------  |          |
643    |       |     size1--      +------+     size1++      |          |
644    |  pty  |                                            |  socket  |
645    |       |     rdidx2++     +------+     wridx2++     |          |
646    |       |  --------------> | buf2 |  --------------> |          |
647    +-------+     size2++      +------+     size2--      +----------+
648
649    size1: "how many bytes are buffered for pty between rdidx1 and wridx1?"
650    size2: "how many bytes are buffered for socket between rdidx2 and wridx2?"
651
652    Each session has got two buffers. Buffers are circular. If sizeN == 0,
653    buffer is empty. If sizeN == BUFSIZE, buffer is full. In both these cases
654    rdidxN == wridxN.
655 */
656  again:
657         FD_ZERO(&rdfdset);
658         FD_ZERO(&wrfdset);
659
660         /* Select on the master socket, all telnet sockets and their
661          * ptys if there is room in their session buffers.
662          * NB: scalability problem: we recalculate entire bitmap
663          * before each select. Can be a problem with 500+ connections. */
664         ts = G.sessions;
665         while (ts) {
666                 struct tsession *next = ts->next; /* in case we free ts */
667                 if (ts->shell_pid == -1) {
668                         /* Child died and we detected that */
669                         free_session(ts);
670                 } else {
671                         if (ts->size1 > 0)       /* can write to pty */
672                                 FD_SET(ts->ptyfd, &wrfdset);
673                         if (ts->size1 < BUFSIZE) /* can read from socket */
674                                 FD_SET(ts->sockfd_read, &rdfdset);
675                         if (ts->size2 > 0)       /* can write to socket */
676                                 FD_SET(ts->sockfd_write, &wrfdset);
677                         if (ts->size2 < BUFSIZE) /* can read from pty */
678                                 FD_SET(ts->ptyfd, &rdfdset);
679                 }
680                 ts = next;
681         }
682         if (!IS_INETD) {
683                 FD_SET(master_fd, &rdfdset);
684                 /* This is needed because free_session() does not
685                  * take master_fd into account when it finds new
686                  * maxfd among remaining fd's */
687                 if (master_fd > G.maxfd)
688                         G.maxfd = master_fd;
689         }
690
691         {
692                 struct timeval *tv_ptr = NULL;
693 #if ENABLE_FEATURE_TELNETD_INETD_WAIT
694                 struct timeval tv;
695                 if ((opt & OPT_WAIT) && !G.sessions) {
696                         tv.tv_sec = sec_linger;
697                         tv.tv_usec = 0;
698                         tv_ptr = &tv;
699                 }
700 #endif
701                 count = select(G.maxfd + 1, &rdfdset, &wrfdset, NULL, tv_ptr);
702         }
703         if (count == 0) /* "telnetd -w SEC" timed out */
704                 return 0;
705         if (count < 0)
706                 goto again; /* EINTR or ENOMEM */
707
708 #if ENABLE_FEATURE_TELNETD_STANDALONE
709         /* Check for and accept new sessions */
710         if (!IS_INETD && FD_ISSET(master_fd, &rdfdset)) {
711                 int fd;
712                 struct tsession *new_ts;
713
714                 fd = accept(master_fd, NULL, NULL);
715                 if (fd < 0)
716                         goto again;
717                 close_on_exec_on(fd);
718
719                 /* Create a new session and link it into active list */
720                 new_ts = make_new_session(fd);
721                 if (new_ts) {
722                         new_ts->next = G.sessions;
723                         G.sessions = new_ts;
724                 } else {
725                         close(fd);
726                 }
727         }
728 #endif
729
730         /* Then check for data tunneling */
731         ts = G.sessions;
732         while (ts) { /* For all sessions... */
733                 struct tsession *next = ts->next; /* in case we free ts */
734
735                 if (/*ts->size1 &&*/ FD_ISSET(ts->ptyfd, &wrfdset)) {
736                         /* Write to pty from buffer 1 */
737                         count = safe_write_to_pty_decode_iac(ts);
738                         if (count < 0) {
739                                 if (errno == EAGAIN)
740                                         goto skip1;
741                                 goto kill_session;
742                         }
743                 }
744  skip1:
745                 if (/*ts->size2 &&*/ FD_ISSET(ts->sockfd_write, &wrfdset)) {
746                         /* Write to socket from buffer 2 */
747                         count = MIN(BUFSIZE - ts->wridx2, ts->size2);
748                         count = safe_write_double_iac(ts->sockfd_write, (void*)(TS_BUF2(ts) + ts->wridx2), count);
749                         if (count < 0) {
750                                 if (errno == EAGAIN)
751                                         goto skip2;
752                                 goto kill_session;
753                         }
754                         ts->wridx2 += count;
755                         if (ts->wridx2 >= BUFSIZE) /* actually == BUFSIZE */
756                                 ts->wridx2 = 0;
757                         ts->size2 -= count;
758                         if (ts->size2 == 0) {
759                                 ts->rdidx2 = 0;
760                                 ts->wridx2 = 0;
761                         }
762                 }
763  skip2:
764
765                 if (/*ts->size1 < BUFSIZE &&*/ FD_ISSET(ts->sockfd_read, &rdfdset)) {
766                         /* Read from socket to buffer 1 */
767                         count = MIN(BUFSIZE - ts->rdidx1, BUFSIZE - ts->size1);
768                         count = safe_read(ts->sockfd_read, TS_BUF1(ts) + ts->rdidx1, count);
769                         if (count <= 0) {
770                                 if (count < 0 && errno == EAGAIN)
771                                         goto skip3;
772                                 goto kill_session;
773                         }
774                         /* Ignore trailing NUL if it is there */
775                         if (!TS_BUF1(ts)[ts->rdidx1 + count - 1]) {
776                                 --count;
777                         }
778                         ts->size1 += count;
779                         ts->rdidx1 += count;
780                         if (ts->rdidx1 >= BUFSIZE) /* actually == BUFSIZE */
781                                 ts->rdidx1 = 0;
782                 }
783  skip3:
784                 if (/*ts->size2 < BUFSIZE &&*/ FD_ISSET(ts->ptyfd, &rdfdset)) {
785                         /* Read from pty to buffer 2 */
786                         count = MIN(BUFSIZE - ts->rdidx2, BUFSIZE - ts->size2);
787                         count = safe_read(ts->ptyfd, TS_BUF2(ts) + ts->rdidx2, count);
788                         if (count <= 0) {
789                                 if (count < 0 && errno == EAGAIN)
790                                         goto skip4;
791                                 goto kill_session;
792                         }
793                         ts->size2 += count;
794                         ts->rdidx2 += count;
795                         if (ts->rdidx2 >= BUFSIZE) /* actually == BUFSIZE */
796                                 ts->rdidx2 = 0;
797                 }
798  skip4:
799                 ts = next;
800                 continue;
801  kill_session:
802                 if (ts->shell_pid > 0)
803                         update_utmp_DEAD_PROCESS(ts->shell_pid);
804                 free_session(ts);
805                 ts = next;
806         }
807
808         goto again;
809 }