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