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