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