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