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