Patch from Fillod Stephane:
[oweals/busybox.git] / networking / telnetd.c
1 /* $Id: telnetd.c,v 1.9 2003/12/19 11:30:13 andersen Exp $
2  *
3  * Simple telnet server
4  * Bjorn Wesen, Axis Communications AB (bjornw@axis.com)
5  *
6  * This file is distributed under the Gnu Public License (GPL),
7  * please see the file LICENSE for further information.
8  *
9  * ---------------------------------------------------------------------------
10  * (C) Copyright 2000, Axis Communications AB, LUND, SWEDEN
11  ****************************************************************************
12  *
13  * The telnetd manpage says it all:
14  *
15  *   Telnetd operates by allocating a pseudo-terminal device (see pty(4))  for
16  *   a client, then creating a login process which has the slave side of the
17  *   pseudo-terminal as stdin, stdout, and stderr. Telnetd manipulates the
18  *   master side of the pseudo-terminal, implementing the telnet protocol and
19  *   passing characters between the remote client and the login process.
20  *
21  * Vladimir Oleynik <dzo@simtreas.ru> 2001
22  *     Set process group corrections, initial busybox port
23  */
24
25 /*#define DEBUG 1 */
26
27 #include <sys/time.h>
28 #include <sys/socket.h>
29 #include <sys/wait.h>
30 #include <string.h>
31 #include <stdlib.h>
32 #include <unistd.h>
33 #include <errno.h>
34 #include <netinet/in.h>
35 #include <fcntl.h>
36 #include <stdio.h>
37 #include <signal.h>
38 #include <termios.h>
39 #ifdef DEBUG
40 #define TELCMDS
41 #define TELOPTS
42 #endif
43 #include <arpa/telnet.h>
44 #include <ctype.h>
45 #include <sys/syslog.h>
46
47 #include "busybox.h"
48
49 #define BUFSIZE 4000
50
51 static const char *loginpath 
52 #ifdef CONFIG_LOGIN
53  = "/bin/login";
54 #else
55 ;
56 #endif
57 static const char *issuefile = "/etc/issue.net";
58
59 /* shell name and arguments */
60
61 static const char *argv_init[] = {NULL, NULL};
62
63 /* structure that describes a session */
64
65 struct tsession {
66 #ifdef CONFIG_FEATURE_TELNETD_INETD
67         int sockfd_read, sockfd_write, ptyfd;
68 #else /* CONFIG_FEATURE_TELNETD_INETD */
69         struct tsession *next;
70         int sockfd, ptyfd;
71 #endif /* CONFIG_FEATURE_TELNETD_INETD */
72         int shell_pid;
73         /* two circular buffers */
74         char *buf1, *buf2;
75         int rdidx1, wridx1, size1;
76         int rdidx2, wridx2, size2;
77 };
78
79 /*
80
81    This is how the buffers are used. The arrows indicate the movement
82    of data.
83
84    +-------+     wridx1++     +------+     rdidx1++     +----------+
85    |       | <--------------  | buf1 | <--------------  |          |
86    |       |     size1--      +------+     size1++      |          |
87    |  pty  |                                            |  socket  |
88    |       |     rdidx2++     +------+     wridx2++     |          |
89    |       |  --------------> | buf2 |  --------------> |          |
90    +-------+     size2++      +------+     size2--      +----------+
91
92    Each session has got two buffers.
93
94 */
95
96 static int maxfd;
97
98 static struct tsession *sessions;
99
100
101 /*
102
103    Remove all IAC's from the buffer pointed to by bf (recieved IACs are ignored
104    and must be removed so as to not be interpreted by the terminal).  Make an
105    uninterrupted string of characters fit for the terminal.  Do this by packing
106    all characters meant for the terminal sequentially towards the end of bf.
107
108    Return a pointer to the beginning of the characters meant for the terminal.
109    and make *num_totty the number of characters that should be sent to
110    the terminal.
111
112    Note - If an IAC (3 byte quantity) starts before (bf + len) but extends
113    past (bf + len) then that IAC will be left unprocessed and *processed will be
114    less than len.
115
116    FIXME - if we mean to send 0xFF to the terminal then it will be escaped,
117    what is the escape character?  We aren't handling that situation here.
118
119    CR-LF ->'s CR mapping is also done here, for convenience
120
121   */
122 static char *
123 remove_iacs(struct tsession *ts, int *pnum_totty) {
124         unsigned char *ptr0 = ts->buf1 + ts->wridx1;
125         unsigned char *ptr = ptr0;
126         unsigned char *totty = ptr;
127         unsigned char *end = ptr + MIN(BUFSIZE - ts->wridx1, ts->size1);
128         int processed;
129         int num_totty;
130
131         while (ptr < end) {
132                 if (*ptr != IAC) {
133                         int c = *ptr;
134                         *totty++ = *ptr++;
135                         /* We now map \r\n ==> \r for pragmatic reasons.
136                          * Many client implementations send \r\n when
137                          * the user hits the CarriageReturn key.
138                          */
139                         if (c == '\r' && (*ptr == '\n' || *ptr == 0) && ptr < end)
140                                 ptr++;
141                 }
142                 else {
143                         if ((ptr+2) < end) {
144                         /* the entire IAC is contained in the buffer
145                         we were asked to process. */
146 #ifdef DEBUG
147                                 fprintf(stderr, "Ignoring IAC %s,%s\n",
148                                     *ptr, TELCMD(*(ptr+1)), TELOPT(*(ptr+2)));
149 #endif
150                                 ptr += 3;
151                         } else {
152                                 /* only the beginning of the IAC is in the
153                                 buffer we were asked to process, we can't
154                                 process this char. */
155                                 break;
156                         }
157                 }
158         }
159
160         processed = ptr - ptr0;
161         num_totty = totty - ptr0;
162         /* the difference between processed and num_to tty
163            is all the iacs we removed from the stream.
164            Adjust buf1 accordingly. */
165         ts->wridx1 += processed - num_totty;
166         ts->size1 -= processed - num_totty;
167         *pnum_totty = num_totty;
168         /* move the chars meant for the terminal towards the end of the
169         buffer. */
170         return memmove(ptr - num_totty, ptr0, num_totty);
171 }
172
173
174 static int
175 getpty(char *line)
176 {
177         int p;
178 #ifdef CONFIG_FEATURE_DEVPTS
179         p = open("/dev/ptmx", 2);
180         if (p > 0) {
181                 grantpt(p);
182                 unlockpt(p);
183                 strcpy(line, ptsname(p));
184                 return(p);
185         }
186 #else
187         struct stat stb;
188         int i;
189         int j;
190
191         strcpy(line, "/dev/ptyXX");
192
193         for (i = 0; i < 16; i++) {
194                 line[8] = "pqrstuvwxyzabcde"[i];
195                 line[9] = '0';
196                 if (stat(line, &stb) < 0) {
197                         continue;
198                 }
199                 for (j = 0; j < 16; j++) {
200                         line[9] = j < 10 ? j + '0' : j - 10 + 'a';
201                         if ((p = open(line, O_RDWR | O_NOCTTY)) >= 0) {
202                                 line[5] = 't';
203                                 return p;
204                         }
205                 }
206         }
207 #endif /* CONFIG_FEATURE_DEVPTS */
208         return -1;
209 }
210
211
212 static void
213 send_iac(struct tsession *ts, unsigned char command, int option)
214 {
215         /* We rely on that there is space in the buffer for now.  */
216         char *b = ts->buf2 + ts->rdidx2;
217         *b++ = IAC;
218         *b++ = command;
219         *b++ = option;
220         ts->rdidx2 += 3;
221         ts->size2 += 3;
222 }
223
224
225 static struct tsession *
226 #ifdef CONFIG_FEATURE_TELNETD_INETD
227 make_new_session(void)
228 #else /* CONFIG_FEATURE_TELNETD_INETD */
229 make_new_session(int sockfd)
230 #endif /* CONFIG_FEATURE_TELNETD_INETD */
231 {
232         struct termios termbuf;
233         int pty, pid;
234         char tty_name[32];
235         struct tsession *ts = malloc(sizeof(struct tsession) + BUFSIZE * 2);
236
237         ts->buf1 = (char *)(&ts[1]);
238         ts->buf2 = ts->buf1 + BUFSIZE;
239
240 #ifdef CONFIG_FEATURE_TELNETD_INETD
241         ts->sockfd_read = 0;
242         ts->sockfd_write = 1;
243 #else /* CONFIG_FEATURE_TELNETD_INETD */
244         ts->sockfd = sockfd;
245 #endif /* CONFIG_FEATURE_TELNETD_INETD */
246
247         ts->rdidx1 = ts->wridx1 = ts->size1 = 0;
248         ts->rdidx2 = ts->wridx2 = ts->size2 = 0;
249
250         /* Got a new connection, set up a tty and spawn a shell.  */
251
252         pty = getpty(tty_name);
253
254         if (pty < 0) {
255                 syslog_msg(LOG_USER, LOG_ERR, "All network ports in use!");
256                 return 0;
257         }
258
259         if (pty > maxfd)
260                 maxfd = pty;
261
262         ts->ptyfd = pty;
263
264         /* Make the telnet client understand we will echo characters so it
265          * should not do it locally. We don't tell the client to run linemode,
266          * because we want to handle line editing and tab completion and other
267          * stuff that requires char-by-char support.
268          */
269
270         send_iac(ts, DO, TELOPT_ECHO);
271         send_iac(ts, DO, TELOPT_LFLOW);
272         send_iac(ts, WILL, TELOPT_ECHO);
273         send_iac(ts, WILL, TELOPT_SGA);
274
275
276         if ((pid = fork()) < 0) {
277                 syslog_msg(LOG_USER, LOG_ERR, "Can`t forking");
278         }
279         if (pid == 0) {
280                 /* In child, open the child's side of the tty.  */
281                 int i;
282
283                 for(i = 0; i <= maxfd; i++)
284                         close(i);
285                 /* make new process group */
286                 setsid();
287
288                 if (open(tty_name, O_RDWR /*| O_NOCTTY*/) < 0) {
289                         syslog_msg(LOG_USER, LOG_ERR, "Could not open tty");
290                         exit(1);
291                         }
292                 dup(0);
293                 dup(0);
294
295                 tcsetpgrp(0, getpid());
296
297                 /* The pseudo-terminal allocated to the client is configured to operate in
298                  * cooked mode, and with XTABS CRMOD enabled (see tty(4)).
299                  */
300
301                 tcgetattr(0, &termbuf);
302                 termbuf.c_lflag |= ECHO; /* if we use readline we dont want this */
303                 termbuf.c_oflag |= ONLCR|XTABS;
304                 termbuf.c_iflag |= ICRNL;
305                 termbuf.c_iflag &= ~IXOFF;
306                 /*termbuf.c_lflag &= ~ICANON;*/
307                 tcsetattr(0, TCSANOW, &termbuf);
308
309                 print_login_issue(issuefile, NULL);
310
311                 /* exec shell, with correct argv and env */
312                 execv(loginpath, (char *const *)argv_init);
313
314                 /* NOT REACHED */
315                 syslog_msg(LOG_USER, LOG_ERR, "execv error");
316                 exit(1);
317         }
318
319         ts->shell_pid = pid;
320
321         return ts;
322 }
323
324 #ifndef CONFIG_FEATURE_TELNETD_INETD
325 static void
326 free_session(struct tsession *ts)
327 {
328         struct tsession *t = sessions;
329
330         /* Unlink this telnet session from the session list.  */
331         if(t == ts)
332                 sessions = ts->next;
333         else {
334                 while(t->next != ts)
335                         t = t->next;
336                 t->next = ts->next;
337         }
338
339         kill(ts->shell_pid, SIGKILL);
340
341         wait4(ts->shell_pid, NULL, 0, NULL);
342
343         close(ts->ptyfd);
344         close(ts->sockfd);
345
346         if(ts->ptyfd == maxfd || ts->sockfd == maxfd)
347                 maxfd--;
348         if(ts->ptyfd == maxfd || ts->sockfd == maxfd)
349                 maxfd--;
350
351         free(ts);
352 }
353 #endif /* CONFIG_FEATURE_TELNETD_INETD */
354
355 int
356 telnetd_main(int argc, char **argv)
357 {
358 #ifndef CONFIG_FEATURE_TELNETD_INETD
359         struct sockaddr_in sa;
360         int master_fd;
361 #endif /* CONFIG_FEATURE_TELNETD_INETD */
362         fd_set rdfdset, wrfdset;
363         int selret;
364 #ifndef CONFIG_FEATURE_TELNETD_INETD
365         int on = 1;
366         int portnbr = 23;
367 #endif /* CONFIG_FEATURE_TELNETD_INETD */
368         int c;
369         static const char options[] =
370 #ifdef CONFIG_FEATURE_TELNETD_INETD
371                 "f:l:";
372 #else /* CONFIG_EATURE_TELNETD_INETD */
373                 "f:l:p:";
374 #endif /* CONFIG_FEATURE_TELNETD_INETD */
375         int maxlen, w, r;
376
377 #ifndef CONFIG_LOGIN
378         loginpath = DEFAULT_SHELL;
379 #endif
380
381         for (;;) {
382                 c = getopt( argc, argv, options);
383                 if (c == EOF) break;
384                 switch (c) {
385                         case 'f':
386                                 issuefile = strdup (optarg);
387                                 break;
388                         case 'l':
389                                 loginpath = strdup (optarg);
390                                 break;
391 #ifndef CONFIG_FEATURE_TELNETD_INETD
392                         case 'p':
393                                 portnbr = atoi(optarg);
394                                 break;
395 #endif /* CONFIG_FEATURE_TELNETD_INETD */
396                         default:
397                                 bb_show_usage();
398                 }
399         }
400
401         if (access(loginpath, X_OK) < 0) {
402                 bb_error_msg_and_die ("'%s' unavailable.", loginpath);
403         }
404
405         argv_init[0] = loginpath;
406
407 #ifdef CONFIG_FEATURE_TELNETD_INETD
408         maxfd = 1;
409         sessions = make_new_session();
410 #else /* CONFIG_EATURE_TELNETD_INETD */
411         sessions = 0;
412
413         /* Grab a TCP socket.  */
414
415         master_fd = socket(AF_INET, SOCK_STREAM, 0);
416         if (master_fd < 0) {
417                 bb_perror_msg_and_die("socket");
418         }
419         (void)setsockopt(master_fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
420
421         /* Set it to listen to specified port.  */
422
423         memset((void *)&sa, 0, sizeof(sa));
424         sa.sin_family = AF_INET;
425         sa.sin_port = htons(portnbr);
426
427         if (bind(master_fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
428                 bb_perror_msg_and_die("bind");
429         }
430
431         if (listen(master_fd, 1) < 0) {
432                 bb_perror_msg_and_die("listen");
433         }
434
435         if (daemon(0, 0) < 0)
436                 bb_perror_msg_and_die("daemon");
437
438
439         maxfd = master_fd;
440 #endif /* CONFIG_FEATURE_TELNETD_INETD */
441
442         do {
443                 struct tsession *ts;
444
445                 FD_ZERO(&rdfdset);
446                 FD_ZERO(&wrfdset);
447
448                 /* select on the master socket, all telnet sockets and their
449                  * ptys if there is room in their respective session buffers.
450                  */
451
452 #ifndef CONFIG_FEATURE_TELNETD_INETD
453                 FD_SET(master_fd, &rdfdset);
454 #endif /* CONFIG_FEATURE_TELNETD_INETD */
455
456                 ts = sessions;
457 #ifndef CONFIG_FEATURE_TELNETD_INETD
458                 while (ts) {
459 #endif /* CONFIG_FEATURE_TELNETD_INETD */
460                         /* buf1 is used from socket to pty
461                          * buf2 is used from pty to socket
462                          */
463                         if (ts->size1 > 0) {
464                                 FD_SET(ts->ptyfd, &wrfdset);  /* can write to pty */
465                         }
466                         if (ts->size1 < BUFSIZE) {
467 #ifdef CONFIG_FEATURE_TELNETD_INETD
468                                 FD_SET(ts->sockfd_read, &rdfdset); /* can read from socket */
469 #else /* CONFIG_FEATURE_TELNETD_INETD */
470                                 FD_SET(ts->sockfd, &rdfdset); /* can read from socket */
471 #endif /* CONFIG_FEATURE_TELNETD_INETD */
472                         }
473                         if (ts->size2 > 0) {
474 #ifdef CONFIG_FEATURE_TELNETD_INETD
475                                 FD_SET(ts->sockfd_write, &wrfdset); /* can write to socket */
476 #else /* CONFIG_FEATURE_TELNETD_INETD */
477                                 FD_SET(ts->sockfd, &wrfdset); /* can write to socket */
478 #endif /* CONFIG_FEATURE_TELNETD_INETD */
479                         }
480                         if (ts->size2 < BUFSIZE) {
481                                 FD_SET(ts->ptyfd, &rdfdset);  /* can read from pty */
482                         }
483 #ifndef CONFIG_FEATURE_TELNETD_INETD
484                         ts = ts->next;
485                 }
486 #endif /* CONFIG_FEATURE_TELNETD_INETD */
487
488                 selret = select(maxfd + 1, &rdfdset, &wrfdset, 0, 0);
489
490                 if (!selret)
491                         break;
492
493 #ifndef CONFIG_FEATURE_TELNETD_INETD
494                 /* First check for and accept new sessions.  */
495                 if (FD_ISSET(master_fd, &rdfdset)) {
496                         int fd, salen;
497
498                         salen = sizeof(sa);
499                         if ((fd = accept(master_fd, (struct sockaddr *)&sa,
500                                                 &salen)) < 0) {
501                                 continue;
502                         } else {
503                                 /* Create a new session and link it into
504                                         our active list.  */
505                                 struct tsession *new_ts = make_new_session(fd);
506                                 if (new_ts) {
507                                         new_ts->next = sessions;
508                                         sessions = new_ts;
509                                         if (fd > maxfd)
510                                                 maxfd = fd;
511                                 } else {
512                                         close(fd);
513                                 }
514                         }
515                 }
516
517                 /* Then check for data tunneling.  */
518
519                 ts = sessions;
520                 while (ts) { /* For all sessions...  */
521 #endif /* CONFIG_FEATURE_TELNETD_INETD */
522 #ifndef CONFIG_FEATURE_TELNETD_INETD
523                         struct tsession *next = ts->next; /* in case we free ts. */
524 #endif /* CONFIG_FEATURE_TELNETD_INETD */
525                         
526                         if (ts->size1 && FD_ISSET(ts->ptyfd, &wrfdset)) {
527                                 int num_totty;
528                                 char *ptr;
529                                 /* Write to pty from buffer 1.  */
530
531                                 ptr = remove_iacs(ts, &num_totty);
532
533                                 w = write(ts->ptyfd, ptr, num_totty);
534                                 if (w < 0) {
535 #ifdef CONFIG_FEATURE_TELNETD_INETD
536                                         exit(0);
537 #else /* CONFIG_FEATURE_TELNETD_INETD */
538                                         free_session(ts);
539                                         ts = next;
540                                         continue;
541 #endif /* CONFIG_FEATURE_TELNETD_INETD */
542                                 }
543                                 ts->wridx1 += w;
544                                 ts->size1 -= w;
545                                 if (ts->wridx1 == BUFSIZE)
546                                         ts->wridx1 = 0;
547                         }
548
549 #ifdef CONFIG_FEATURE_TELNETD_INETD
550                         if (ts->size2 && FD_ISSET(ts->sockfd_write, &wrfdset)) {
551 #else /* CONFIG_FEATURE_TELNETD_INETD */
552                         if (ts->size2 && FD_ISSET(ts->sockfd, &wrfdset)) {
553 #endif /* CONFIG_FEATURE_TELNETD_INETD */
554                                 /* Write to socket from buffer 2.  */
555                                 maxlen = MIN(BUFSIZE - ts->wridx2, ts->size2);
556 #ifdef CONFIG_FEATURE_TELNETD_INETD
557                                 w = write(ts->sockfd_write, ts->buf2 + ts->wridx2, maxlen);
558                                 if (w < 0)
559                                         exit(0);
560 #else /* CONFIG_FEATURE_TELNETD_INETD */
561                                 w = write(ts->sockfd, ts->buf2 + ts->wridx2, maxlen);
562                                 if (w < 0) {
563                                         free_session(ts);
564                                         ts = next;
565                                         continue;
566                                 }
567 #endif /* CONFIG_FEATURE_TELNETD_INETD */
568                                 ts->wridx2 += w;
569                                 ts->size2 -= w;
570                                 if (ts->wridx2 == BUFSIZE)
571                                         ts->wridx2 = 0;
572                         }
573
574 #ifdef CONFIG_FEATURE_TELNETD_INETD
575                         if (ts->size1 < BUFSIZE && FD_ISSET(ts->sockfd_read, &rdfdset)) {
576 #else /* CONFIG_FEATURE_TELNETD_INETD */
577                         if (ts->size1 < BUFSIZE && FD_ISSET(ts->sockfd, &rdfdset)) {
578 #endif /* CONFIG_FEATURE_TELNETD_INETD */
579                                 /* Read from socket to buffer 1. */
580                                 maxlen = MIN(BUFSIZE - ts->rdidx1,
581                                                 BUFSIZE - ts->size1);
582 #ifdef CONFIG_FEATURE_TELNETD_INETD
583                                 r = read(ts->sockfd_read, ts->buf1 + ts->rdidx1, maxlen);
584                                 if (!r || (r < 0 && errno != EINTR))
585                                         exit(0);
586 #else /* CONFIG_FEATURE_TELNETD_INETD */
587                                 r = read(ts->sockfd, ts->buf1 + ts->rdidx1, maxlen);
588                                 if (!r || (r < 0 && errno != EINTR)) {
589                                         free_session(ts);
590                                         ts = next;
591                                         continue;
592                                 }
593 #endif /* CONFIG_FEATURE_TELNETD_INETD */
594                                 if(!*(ts->buf1 + ts->rdidx1 + r - 1)) {
595                                         r--;
596                                         if(!r)
597                                                 continue;
598                                 }
599                                 ts->rdidx1 += r;
600                                 ts->size1 += r;
601                                 if (ts->rdidx1 == BUFSIZE)
602                                         ts->rdidx1 = 0;
603                         }
604
605                         if (ts->size2 < BUFSIZE && FD_ISSET(ts->ptyfd, &rdfdset)) {
606                                 /* Read from pty to buffer 2.  */
607                                 maxlen = MIN(BUFSIZE - ts->rdidx2,
608                                                 BUFSIZE - ts->size2);
609                                 r = read(ts->ptyfd, ts->buf2 + ts->rdidx2, maxlen);
610                                 if (!r || (r < 0 && errno != EINTR)) {
611 #ifdef CONFIG_FEATURE_TELNETD_INETD
612                                         exit(0);
613 #else /* CONFIG_FEATURE_TELNETD_INETD */
614                                         free_session(ts);
615                                         ts = next;
616                                         continue;
617 #endif /* CONFIG_FEATURE_TELNETD_INETD */
618                                 }
619                                 ts->rdidx2 += r;
620                                 ts->size2 += r;
621                                 if (ts->rdidx2 == BUFSIZE)
622                                         ts->rdidx2 = 0;
623                         }
624
625                         if (ts->size1 == 0) {
626                                 ts->rdidx1 = 0;
627                                 ts->wridx1 = 0;
628                         }
629                         if (ts->size2 == 0) {
630                                 ts->rdidx2 = 0;
631                                 ts->wridx2 = 0;
632                         }
633 #ifndef CONFIG_FEATURE_TELNETD_INETD
634                         ts = next;
635                 }
636 #endif /* CONFIG_FEATURE_TELNETD_INETD */
637
638         } while (1);
639
640         return 0;
641 }