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