12d1970fa98ab318a1a24dd440c61c4610492519
[oweals/busybox.git] / networking / telnet.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * telnet implementation for busybox
4  *
5  * Author: Tomi Ollila <too@iki.fi>
6  * Copyright (C) 1994-2000 by Tomi Ollila
7  *
8  * Created: Thu Apr  7 13:29:41 1994 too
9  * Last modified: Fri Jun  9 14:34:24 2000 too
10  *
11  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12  *
13  * HISTORY
14  * Revision 3.1  1994/04/17  11:31:54  too
15  * initial revision
16  * Modified 2000/06/13 for inclusion into BusyBox by Erik Andersen <andersen@codepoet.org>
17  * Modified 2001/05/07 to add ability to pass TTYPE to remote host by Jim McQuillan
18  * <jam@ltsp.org>
19  * Modified 2004/02/11 to add ability to pass the USER variable to remote host
20  * by Fernando Silveira <swrh@gmx.net>
21  *
22  */
23
24 #include <arpa/telnet.h>
25 #include <netinet/in.h>
26 #include "libbb.h"
27
28 #ifdef DOTRACE
29 #define TRACE(x, y) do { if (x) printf y; } while (0)
30 #else
31 #define TRACE(x, y)
32 #endif
33
34 enum {
35         DATABUFSIZE = 128,
36         IACBUFSIZE  = 128,
37
38         CHM_TRY = 0,
39         CHM_ON = 1,
40         CHM_OFF = 2,
41
42         UF_ECHO = 0x01,
43         UF_SGA = 0x02,
44
45         TS_0 = 1,
46         TS_IAC = 2,
47         TS_OPT = 3,
48         TS_SUB1 = 4,
49         TS_SUB2 = 5,
50 };
51
52 typedef unsigned char byte;
53
54 enum { netfd = 3 };
55
56 struct globals {
57         int     iaclen; /* could even use byte, but it's a loss on x86 */
58         byte    telstate; /* telnet negotiation state from network input */
59         byte    telwish;  /* DO, DONT, WILL, WONT */
60         byte    charmode;
61         byte    telflags;
62         byte    do_termios;
63 #if ENABLE_FEATURE_TELNET_TTYPE
64         char    *ttype;
65 #endif
66 #if ENABLE_FEATURE_TELNET_AUTOLOGIN
67         const char *autologin;
68 #endif
69 #if ENABLE_FEATURE_AUTOWIDTH
70         unsigned win_width, win_height;
71 #endif
72         /* same buffer used both for network and console read/write */
73         char    buf[DATABUFSIZE];
74         /* buffer to handle telnet negotiations */
75         char    iacbuf[IACBUFSIZE];
76         struct termios termios_def;
77         struct termios termios_raw;
78 } FIX_ALIASING;
79 #define G (*(struct globals*)&bb_common_bufsiz1)
80 #define INIT_G() do { \
81         struct G_sizecheck { \
82                 char G_sizecheck[sizeof(G) > COMMON_BUFSIZE ? -1 : 1]; \
83         }; \
84 } while (0)
85
86 /* Function prototypes */
87 static void rawmode(void);
88 static void cookmode(void);
89 static void do_linemode(void);
90 static void will_charmode(void);
91 static void telopt(byte c);
92 static int subneg(byte c);
93
94 static void iac_flush(void)
95 {
96         write(netfd, G.iacbuf, G.iaclen);
97         G.iaclen = 0;
98 }
99
100 #define write_str(fd, str) write(fd, str, sizeof(str) - 1)
101
102 static void doexit(int ev) NORETURN;
103 static void doexit(int ev)
104 {
105         cookmode();
106         exit(ev);
107 }
108
109 static void con_escape(void)
110 {
111         char b;
112
113         if (bb_got_signal) /* came from line mode... go raw */
114                 rawmode();
115
116         write_str(1, "\r\nConsole escape. Commands are:\r\n\n"
117                         " l     go to line mode\r\n"
118                         " c     go to character mode\r\n"
119                         " z     suspend telnet\r\n"
120                         " e     exit telnet\r\n");
121
122         if (read(STDIN_FILENO, &b, 1) <= 0)
123                 doexit(EXIT_FAILURE);
124
125         switch (b) {
126         case 'l':
127                 if (!bb_got_signal) {
128                         do_linemode();
129                         goto ret;
130                 }
131                 break;
132         case 'c':
133                 if (bb_got_signal) {
134                         will_charmode();
135                         goto ret;
136                 }
137                 break;
138         case 'z':
139                 cookmode();
140                 kill(0, SIGTSTP);
141                 rawmode();
142                 break;
143         case 'e':
144                 doexit(EXIT_SUCCESS);
145         }
146
147         write_str(1, "continuing...\r\n");
148
149         if (bb_got_signal)
150                 cookmode();
151  ret:
152         bb_got_signal = 0;
153 }
154
155 static void handle_net_output(int len)
156 {
157         /* here we could do smart tricks how to handle 0xFF:s in output
158          * stream like writing twice every sequence of FF:s (thus doing
159          * many write()s. But I think interactive telnet application does
160          * not need to be 100% 8-bit clean, so changing every 0xff:s to
161          * 0x7f:s
162          *
163          * 2002-mar-21, Przemyslaw Czerpak (druzus@polbox.com)
164          * I don't agree.
165          * first - I cannot use programs like sz/rz
166          * second - the 0x0D is sent as one character and if the next
167          *      char is 0x0A then it's eaten by a server side.
168          * third - why do you have to make 'many write()s'?
169          *      I don't understand.
170          * So I implemented it. It's really useful for me. I hope that
171          * other people will find it interesting too.
172          */
173
174         int i, j;
175         byte *p = (byte*)G.buf;
176         byte outbuf[4*DATABUFSIZE];
177
178         for (i = len, j = 0; i > 0; i--, p++) {
179                 if (*p == 0x1d) {
180                         con_escape();
181                         return;
182                 }
183                 outbuf[j++] = *p;
184                 if (*p == 0xff)
185                         outbuf[j++] = 0xff;
186                 else if (*p == 0x0d)
187                         outbuf[j++] = 0x00;
188         }
189         if (j > 0)
190                 write(netfd, outbuf, j);
191 }
192
193 static void handle_net_input(int len)
194 {
195         int i;
196         int cstart = 0;
197
198         for (i = 0; i < len; i++) {
199                 byte c = G.buf[i];
200
201                 if (G.telstate == 0) { /* most of the time state == 0 */
202                         if (c == IAC) {
203                                 cstart = i;
204                                 G.telstate = TS_IAC;
205                         }
206                         continue;
207                 }
208                 switch (G.telstate) {
209                 case TS_0:
210                         if (c == IAC)
211                                 G.telstate = TS_IAC;
212                         else
213                                 G.buf[cstart++] = c;
214                         break;
215
216                 case TS_IAC:
217                         if (c == IAC) { /* IAC IAC -> 0xFF */
218                                 G.buf[cstart++] = c;
219                                 G.telstate = TS_0;
220                                 break;
221                         }
222                         /* else */
223                         switch (c) {
224                         case SB:
225                                 G.telstate = TS_SUB1;
226                                 break;
227                         case DO:
228                         case DONT:
229                         case WILL:
230                         case WONT:
231                                 G.telwish =  c;
232                                 G.telstate = TS_OPT;
233                                 break;
234                         default:
235                                 G.telstate = TS_0;      /* DATA MARK must be added later */
236                         }
237                         break;
238                 case TS_OPT: /* WILL, WONT, DO, DONT */
239                         telopt(c);
240                         G.telstate = TS_0;
241                         break;
242                 case TS_SUB1: /* Subnegotiation */
243                 case TS_SUB2: /* Subnegotiation */
244                         if (subneg(c))
245                                 G.telstate = TS_0;
246                         break;
247                 }
248         }
249         if (G.telstate) {
250                 if (G.iaclen)
251                         iac_flush();
252                 if (G.telstate == TS_0)
253                         G.telstate = 0;
254                 len = cstart;
255         }
256
257         if (len)
258                 write(STDOUT_FILENO, G.buf, len);
259 }
260
261 static void put_iac(int c)
262 {
263         G.iacbuf[G.iaclen++] = c;
264 }
265
266 static void put_iac2(byte wwdd, byte c)
267 {
268         if (G.iaclen + 3 > IACBUFSIZE)
269                 iac_flush();
270
271         put_iac(IAC);
272         put_iac(wwdd);
273         put_iac(c);
274 }
275
276 #if ENABLE_FEATURE_TELNET_TTYPE
277 static void put_iac_subopt(byte c, char *str)
278 {
279         int len = strlen(str) + 6;   // ( 2 + 1 + 1 + strlen + 2 )
280
281         if (G.iaclen + len > IACBUFSIZE)
282                 iac_flush();
283
284         put_iac(IAC);
285         put_iac(SB);
286         put_iac(c);
287         put_iac(0);
288
289         while (*str)
290                 put_iac(*str++);
291
292         put_iac(IAC);
293         put_iac(SE);
294 }
295 #endif
296
297 #if ENABLE_FEATURE_TELNET_AUTOLOGIN
298 static void put_iac_subopt_autologin(void)
299 {
300         int len = strlen(G.autologin) + 6;      // (2 + 1 + 1 + strlen + 2)
301         const char *p = "USER";
302
303         if (G.iaclen + len > IACBUFSIZE)
304                 iac_flush();
305
306         put_iac(IAC);
307         put_iac(SB);
308         put_iac(TELOPT_NEW_ENVIRON);
309         put_iac(TELQUAL_IS);
310         put_iac(NEW_ENV_VAR);
311
312         while (*p)
313                 put_iac(*p++);
314
315         put_iac(NEW_ENV_VALUE);
316
317         p = G.autologin;
318         while (*p)
319                 put_iac(*p++);
320
321         put_iac(IAC);
322         put_iac(SE);
323 }
324 #endif
325
326 #if ENABLE_FEATURE_AUTOWIDTH
327 static void put_iac_naws(byte c, int x, int y)
328 {
329         if (G.iaclen + 9 > IACBUFSIZE)
330                 iac_flush();
331
332         put_iac(IAC);
333         put_iac(SB);
334         put_iac(c);
335
336         put_iac((x >> 8) & 0xff);
337         put_iac(x & 0xff);
338         put_iac((y >> 8) & 0xff);
339         put_iac(y & 0xff);
340
341         put_iac(IAC);
342         put_iac(SE);
343 }
344 #endif
345
346 static char const escapecharis[] ALIGN1 = "\r\nEscape character is ";
347
348 static void setConMode(void)
349 {
350         if (G.telflags & UF_ECHO) {
351                 if (G.charmode == CHM_TRY) {
352                         G.charmode = CHM_ON;
353                         printf("\r\nEntering character mode%s'^]'.\r\n", escapecharis);
354                         rawmode();
355                 }
356         } else {
357                 if (G.charmode != CHM_OFF) {
358                         G.charmode = CHM_OFF;
359                         printf("\r\nEntering line mode%s'^C'.\r\n", escapecharis);
360                         cookmode();
361                 }
362         }
363 }
364
365 static void will_charmode(void)
366 {
367         G.charmode = CHM_TRY;
368         G.telflags |= (UF_ECHO | UF_SGA);
369         setConMode();
370
371         put_iac2(DO, TELOPT_ECHO);
372         put_iac2(DO, TELOPT_SGA);
373         iac_flush();
374 }
375
376 static void do_linemode(void)
377 {
378         G.charmode = CHM_TRY;
379         G.telflags &= ~(UF_ECHO | UF_SGA);
380         setConMode();
381
382         put_iac2(DONT, TELOPT_ECHO);
383         put_iac2(DONT, TELOPT_SGA);
384         iac_flush();
385 }
386
387 static void to_notsup(char c)
388 {
389         if (G.telwish == WILL)
390                 put_iac2(DONT, c);
391         else if (G.telwish == DO)
392                 put_iac2(WONT, c);
393 }
394
395 static void to_echo(void)
396 {
397         /* if server requests ECHO, don't agree */
398         if (G.telwish == DO) {
399                 put_iac2(WONT, TELOPT_ECHO);
400                 return;
401         }
402         if (G.telwish == DONT)
403                 return;
404
405         if (G.telflags & UF_ECHO) {
406                 if (G.telwish == WILL)
407                         return;
408         } else if (G.telwish == WONT)
409                 return;
410
411         if (G.charmode != CHM_OFF)
412                 G.telflags ^= UF_ECHO;
413
414         if (G.telflags & UF_ECHO)
415                 put_iac2(DO, TELOPT_ECHO);
416         else
417                 put_iac2(DONT, TELOPT_ECHO);
418
419         setConMode();
420         full_write1_str("\r\n");  /* sudden modec */
421 }
422
423 static void to_sga(void)
424 {
425         /* daemon always sends will/wont, client do/dont */
426
427         if (G.telflags & UF_SGA) {
428                 if (G.telwish == WILL)
429                         return;
430         } else if (G.telwish == WONT)
431                 return;
432
433         G.telflags ^= UF_SGA; /* toggle */
434         if (G.telflags & UF_SGA)
435                 put_iac2(DO, TELOPT_SGA);
436         else
437                 put_iac2(DONT, TELOPT_SGA);
438 }
439
440 #if ENABLE_FEATURE_TELNET_TTYPE
441 static void to_ttype(void)
442 {
443         /* Tell server we will (or won't) do TTYPE */
444         if (G.ttype)
445                 put_iac2(WILL, TELOPT_TTYPE);
446         else
447                 put_iac2(WONT, TELOPT_TTYPE);
448 }
449 #endif
450
451 #if ENABLE_FEATURE_TELNET_AUTOLOGIN
452 static void to_new_environ(void)
453 {
454         /* Tell server we will (or will not) do AUTOLOGIN */
455         if (G.autologin)
456                 put_iac2(WILL, TELOPT_NEW_ENVIRON);
457         else
458                 put_iac2(WONT, TELOPT_NEW_ENVIRON);
459 }
460 #endif
461
462 #if ENABLE_FEATURE_AUTOWIDTH
463 static void to_naws(void)
464 {
465         /* Tell server we will do NAWS */
466         put_iac2(WILL, TELOPT_NAWS);
467 }
468 #endif
469
470 static void telopt(byte c)
471 {
472         switch (c) {
473         case TELOPT_ECHO:
474                 to_echo(); break;
475         case TELOPT_SGA:
476                 to_sga(); break;
477 #if ENABLE_FEATURE_TELNET_TTYPE
478         case TELOPT_TTYPE:
479                 to_ttype(); break;
480 #endif
481 #if ENABLE_FEATURE_TELNET_AUTOLOGIN
482         case TELOPT_NEW_ENVIRON:
483                 to_new_environ(); break;
484 #endif
485 #if ENABLE_FEATURE_AUTOWIDTH
486         case TELOPT_NAWS:
487                 to_naws();
488                 put_iac_naws(c, G.win_width, G.win_height);
489                 break;
490 #endif
491         default:
492                 to_notsup(c);
493                 break;
494         }
495 }
496
497 /* subnegotiation -- ignore all (except TTYPE,NAWS) */
498 static int subneg(byte c)
499 {
500         switch (G.telstate) {
501         case TS_SUB1:
502                 if (c == IAC)
503                         G.telstate = TS_SUB2;
504 #if ENABLE_FEATURE_TELNET_TTYPE
505                 else
506                 if (c == TELOPT_TTYPE && G.ttype)
507                         put_iac_subopt(TELOPT_TTYPE, G.ttype);
508 #endif
509 #if ENABLE_FEATURE_TELNET_AUTOLOGIN
510                 else
511                 if (c == TELOPT_NEW_ENVIRON && G.autologin)
512                         put_iac_subopt_autologin();
513 #endif
514                 break;
515         case TS_SUB2:
516                 if (c == SE)
517                         return TRUE;
518                 G.telstate = TS_SUB1;
519                 /* break; */
520         }
521         return FALSE;
522 }
523
524 static void rawmode(void)
525 {
526         if (G.do_termios)
527                 tcsetattr(0, TCSADRAIN, &G.termios_raw);
528 }
529
530 static void cookmode(void)
531 {
532         if (G.do_termios)
533                 tcsetattr(0, TCSADRAIN, &G.termios_def);
534 }
535
536 /* poll gives smaller (-70 bytes) code */
537 #define USE_POLL 1
538
539 int telnet_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
540 int telnet_main(int argc UNUSED_PARAM, char **argv)
541 {
542         char *host;
543         int port;
544         int len;
545 #ifdef USE_POLL
546         struct pollfd ufds[2];
547 #else
548         fd_set readfds;
549         int maxfd;
550 #endif
551
552         INIT_G();
553
554 #if ENABLE_FEATURE_AUTOWIDTH
555         get_terminal_width_height(0, &G.win_width, &G.win_height);
556 #endif
557
558 #if ENABLE_FEATURE_TELNET_TTYPE
559         G.ttype = getenv("TERM");
560 #endif
561
562         if (tcgetattr(0, &G.termios_def) >= 0) {
563                 G.do_termios = 1;
564                 G.termios_raw = G.termios_def;
565                 cfmakeraw(&G.termios_raw);
566         }
567
568 #if ENABLE_FEATURE_TELNET_AUTOLOGIN
569         if (1 & getopt32(argv, "al:", &G.autologin))
570                 G.autologin = getenv("USER");
571         argv += optind;
572 #else
573         argv++;
574 #endif
575         if (!*argv)
576                 bb_show_usage();
577         host = *argv++;
578         port = bb_lookup_port(*argv ? *argv++ : "telnet", "tcp", 23);
579         if (*argv) /* extra params?? */
580                 bb_show_usage();
581
582         xmove_fd(create_and_connect_stream_or_die(host, port), netfd);
583
584         setsockopt(netfd, SOL_SOCKET, SO_KEEPALIVE, &const_int_1, sizeof(const_int_1));
585
586         signal(SIGINT, record_signo);
587
588 #ifdef USE_POLL
589         ufds[0].fd = 0; ufds[1].fd = netfd;
590         ufds[0].events = ufds[1].events = POLLIN;
591 #else
592         FD_ZERO(&readfds);
593         FD_SET(STDIN_FILENO, &readfds);
594         FD_SET(netfd, &readfds);
595         maxfd = netfd + 1;
596 #endif
597
598         while (1) {
599 #ifndef USE_POLL
600                 fd_set rfds = readfds;
601
602                 switch (select(maxfd, &rfds, NULL, NULL, NULL))
603 #else
604                 switch (poll(ufds, 2, -1))
605 #endif
606                 {
607                 case 0:
608                         /* timeout */
609                 case -1:
610                         /* error, ignore and/or log something, bay go to loop */
611                         if (bb_got_signal)
612                                 con_escape();
613                         else
614                                 sleep(1);
615                         break;
616                 default:
617
618 #ifdef USE_POLL
619                         if (ufds[0].revents)
620 #else
621                         if (FD_ISSET(STDIN_FILENO, &rfds))
622 #endif
623                         {
624                                 len = safe_read(STDIN_FILENO, G.buf, DATABUFSIZE);
625                                 if (len <= 0)
626                                         doexit(EXIT_SUCCESS);
627                                 TRACE(0, ("Read con: %d\n", len));
628                                 handle_net_output(len);
629                         }
630
631 #ifdef USE_POLL
632                         if (ufds[1].revents)
633 #else
634                         if (FD_ISSET(netfd, &rfds))
635 #endif
636                         {
637                                 len = safe_read(netfd, G.buf, DATABUFSIZE);
638                                 if (len <= 0) {
639                                         full_write1_str("Connection closed by foreign host\r\n");
640                                         doexit(EXIT_FAILURE);
641                                 }
642                                 TRACE(0, ("Read netfd (%d): %d\n", netfd, len));
643                                 handle_net_input(len);
644                         }
645                 }
646         } /* while (1) */
647 }