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