Try to pull in PATH_MAX properly
[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  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24  *
25  * HISTORY
26  * Revision 3.1  1994/04/17  11:31:54  too
27  * initial revision
28  * Modified 2000/06/13 for inclusion into BusyBox by Erik Andersen
29  * <andersen@lineo.com> 
30  * Modified 2001/05/07 to add ability to pass TTYPE to remote host by Jim McQuillan
31  * <jam@ltsp.org>
32  *
33  */
34
35 #include <termios.h>
36 #include <unistd.h>
37 #include <errno.h>
38 #include <stdlib.h>
39 #include <stdarg.h>
40 #include <string.h>
41 #include <signal.h>
42 #include <arpa/telnet.h>
43 #include <sys/types.h>
44 #include <sys/socket.h>
45 #include <netinet/in.h>
46 #include <netdb.h>
47 #include "busybox.h"
48
49 #if 0
50 static const int DOTRACE = 1;
51 #endif
52
53 #ifdef DOTRACE
54 #include <arpa/inet.h> /* for inet_ntoa()... */
55 #define TRACE(x, y) do { if (x) printf y; } while (0)
56 #else
57 #define TRACE(x, y) 
58 #endif
59
60 #if 0
61 #define USE_POLL
62 #include <sys/poll.h>
63 #else
64 #include <sys/time.h>
65 #endif
66
67 #define DATABUFSIZE  128
68 #define IACBUFSIZE   128
69
70 static const int CHM_TRY = 0;
71 static const int CHM_ON = 1;
72 static const int CHM_OFF = 2;
73
74 static const int UF_ECHO = 0x01;
75 static const int UF_SGA = 0x02;
76
77 enum {
78         TS_0 = 1,
79         TS_IAC = 2,
80         TS_OPT = 3,
81         TS_SUB1 = 4,
82         TS_SUB2 = 5,
83 };
84
85 #define WriteCS(fd, str) write(fd, str, sizeof str -1)
86
87 typedef unsigned char byte;
88
89 /* use globals to reduce size ??? */ /* test this hypothesis later */
90 static struct Globalvars {
91         int             netfd; /* console fd:s are 0 and 1 (and 2) */
92     /* same buffer used both for network and console read/write */
93         char    buf[DATABUFSIZE]; /* allocating so static size is smaller */
94         byte    telstate; /* telnet negotiation state from network input */
95         byte    telwish;  /* DO, DONT, WILL, WONT */
96         byte    charmode;
97         byte    telflags;
98         byte    gotsig;
99         /* buffer to handle telnet negotiations */
100         char    iacbuf[IACBUFSIZE];
101         short   iaclen; /* could even use byte */
102         struct termios termios_def;     
103         struct termios termios_raw;     
104 } G;
105
106 #define xUSE_GLOBALVAR_PTR /* xUSE... -> don't use :D (makes smaller code) */
107
108 #ifdef USE_GLOBALVAR_PTR
109 struct Globalvars * Gptr;
110 #define G (*Gptr)
111 #else
112 static struct Globalvars G;
113 #endif
114
115 static inline void iacflush(void)
116 {
117         write(G.netfd, G.iacbuf, G.iaclen);
118         G.iaclen = 0;
119 }
120
121 /* Function prototypes */
122 static int getport(char * p);
123 static struct in_addr getserver(char * p);
124 static void setup_sockaddr_in(struct sockaddr_in * addr, int port);
125 static int remote_connect(struct in_addr addr, int port);
126 static void rawmode(void);
127 static void cookmode(void);
128 static void do_linemode(void);
129 static void will_charmode(void);
130 static void telopt(byte c);
131 static int subneg(byte c);
132 #if 0
133 static int local_bind(int port);
134 #endif
135
136 /* Some globals */
137 static int one = 1;
138
139 #ifdef CONFIG_FEATURE_TELNET_TTYPE
140 static char *ttype;
141 #endif
142
143 static void doexit(int ev)
144 {
145         cookmode();
146         exit(ev);
147 }       
148
149 static void conescape(void)
150 {
151         char b;
152
153         if (G.gotsig)   /* came from line  mode... go raw */
154                 rawmode();
155
156         WriteCS(1, "\r\nConsole escape. Commands are:\r\n\n"
157                         " l     go to line mode\r\n"
158                         " c     go to character mode\r\n"
159                         " z     suspend telnet\r\n"
160                         " e     exit telnet\r\n");
161
162         if (read(0, &b, 1) <= 0)
163                 doexit(1);
164
165         switch (b)
166         {
167         case 'l':
168                 if (!G.gotsig)
169                 {
170                         do_linemode();
171                         goto rrturn;
172                 }
173                 break;
174         case 'c':
175                 if (G.gotsig)
176                 {
177                         will_charmode();
178                         goto rrturn;
179                 }
180                 break;
181         case 'z':
182                 cookmode();
183                 kill(0, SIGTSTP);
184                 rawmode();
185                 break;
186         case 'e':
187                 doexit(0);
188         }
189
190         WriteCS(1, "continuing...\r\n");
191
192         if (G.gotsig)
193                 cookmode();
194         
195  rrturn:
196         G.gotsig = 0;
197         
198 }
199 static void handlenetoutput(int len)
200 {
201         /*      here we could do smart tricks how to handle 0xFF:s in output
202          *      stream  like writing twice every sequence of FF:s (thus doing
203          *      many write()s. But I think interactive telnet application does
204          *      not need to be 100% 8-bit clean, so changing every 0xff:s to
205          *      0x7f:s */
206
207         int i;
208         byte * p = G.buf;
209
210         for (i = len; i > 0; i--, p++)
211         {
212                 if (*p == 0x1d)
213                 {
214                         conescape();
215                         return;
216                 }
217                 if (*p == 0xff)
218                         *p = 0x7f;
219         }
220         write(G.netfd, G.buf, len);
221 }
222
223
224 static void handlenetinput(int len)
225 {
226         int i;
227         int cstart = 0;
228
229         for (i = 0; i < len; i++)
230         {
231                 byte c = G.buf[i];
232
233                 if (G.telstate == 0) /* most of the time state == 0 */
234                 {
235                         if (c == IAC)
236                         {
237                                 cstart = i;
238                                 G.telstate = TS_IAC;
239                         }
240                 }
241                 else
242                         switch (G.telstate)
243                          {
244                          case TS_0:
245                                  if (c == IAC)
246                                          G.telstate = TS_IAC;
247                                  else
248                                          G.buf[cstart++] = c;
249                                  break;
250
251                          case TS_IAC:
252                                  if (c == IAC) /* IAC IAC -> 0xFF */
253                                  {
254                                          G.buf[cstart++] = c;
255                                          G.telstate = TS_0;
256                                          break;
257                                  }
258                                  /* else */
259                                  switch (c)
260                                  {
261                                  case SB:
262                                          G.telstate = TS_SUB1;
263                                          break;
264                                  case DO:
265                                  case DONT:
266                                  case WILL:
267                                  case WONT:
268                                          G.telwish =  c;
269                                          G.telstate = TS_OPT;
270                                          break;
271                                  default:
272                                          G.telstate = TS_0;     /* DATA MARK must be added later */
273                                  }
274                                  break;
275                          case TS_OPT: /* WILL, WONT, DO, DONT */
276                                  telopt(c);
277                                  G.telstate = TS_0;
278                                  break;
279                          case TS_SUB1: /* Subnegotiation */
280                          case TS_SUB2: /* Subnegotiation */
281                                  if (subneg(c))
282                                          G.telstate = TS_0;
283                                  break;
284                          }
285         }
286         if (G.telstate)
287         {
288                 if (G.iaclen)                   iacflush();
289                 if (G.telstate == TS_0) G.telstate = 0;
290
291                 len = cstart;
292         }
293
294         if (len)
295                 write(1, G.buf, len);
296 }
297
298
299 /* ******************************* */
300
301 static inline void putiac(int c)
302 {
303         G.iacbuf[G.iaclen++] = c;
304 }
305
306
307 static void putiac2(byte wwdd, byte c)
308 {
309         if (G.iaclen + 3 > IACBUFSIZE)
310                 iacflush();
311
312         putiac(IAC);
313         putiac(wwdd);
314         putiac(c);
315 }
316
317 #if 0
318 static void putiac1(byte c)
319 {
320         if (G.iaclen + 2 > IACBUFSIZE)
321                 iacflush();
322
323         putiac(IAC);
324         putiac(c);
325 }
326 #endif
327
328 #ifdef CONFIG_FEATURE_TELNET_TTYPE
329 static void putiac_subopt(byte c, char *str)
330 {
331         int     len = strlen(str) + 6;   // ( 2 + 1 + 1 + strlen + 2 )
332
333         if (G.iaclen + len > IACBUFSIZE)
334                 iacflush();
335
336         putiac(IAC);
337         putiac(SB);
338         putiac(c);
339         putiac(0);
340
341         while(*str)
342                 putiac(*str++);
343
344         putiac(IAC);
345         putiac(SE);
346 }
347 #endif
348
349 /* void putiacstring (subneg strings) */
350
351 /* ******************************* */
352
353 static char const escapecharis[] = "\r\nEscape character is ";
354
355 static void setConMode(void)
356 {
357         if (G.telflags & UF_ECHO)
358         {
359                 if (G.charmode == CHM_TRY) {
360                         G.charmode = CHM_ON;
361                         printf("\r\nEntering character mode%s'^]'.\r\n", escapecharis);
362                         rawmode();
363                 }
364         }
365         else
366         {
367                 if (G.charmode != CHM_OFF) {
368                         G.charmode = CHM_OFF;
369                         printf("\r\nEntering line mode%s'^C'.\r\n", escapecharis);
370                         cookmode();
371                 }
372         }
373 }
374
375 /* ******************************* */
376
377 static void will_charmode(void)
378 {
379         G.charmode = CHM_TRY;
380         G.telflags |= (UF_ECHO | UF_SGA);
381         setConMode();
382   
383         putiac2(DO, TELOPT_ECHO);
384         putiac2(DO, TELOPT_SGA);
385         iacflush();
386 }
387
388 static void do_linemode(void)
389 {
390         G.charmode = CHM_TRY;
391         G.telflags &= ~(UF_ECHO | UF_SGA);
392         setConMode();
393
394         putiac2(DONT, TELOPT_ECHO);
395         putiac2(DONT, TELOPT_SGA);
396         iacflush();
397 }
398
399 /* ******************************* */
400
401 static inline void to_notsup(char c)
402 {
403         if      (G.telwish == WILL)     putiac2(DONT, c);
404         else if (G.telwish == DO)       putiac2(WONT, c);
405 }
406
407 static inline void to_echo(void)
408 {
409         /* if server requests ECHO, don't agree */
410         if      (G.telwish == DO) {     putiac2(WONT, TELOPT_ECHO);     return; }
411         else if (G.telwish == DONT)     return;
412   
413         if (G.telflags & UF_ECHO)
414         {
415                 if (G.telwish == WILL)
416                         return;
417         }
418         else
419                 if (G.telwish == WONT)
420                         return;
421
422         if (G.charmode != CHM_OFF)
423                 G.telflags ^= UF_ECHO;
424
425         if (G.telflags & UF_ECHO)
426                 putiac2(DO, TELOPT_ECHO);
427         else
428                 putiac2(DONT, TELOPT_ECHO);
429
430         setConMode();
431         WriteCS(1, "\r\n");  /* sudden modec */
432 }
433
434 static inline void to_sga(void)
435 {
436         /* daemon always sends will/wont, client do/dont */
437
438         if (G.telflags & UF_SGA)
439         {
440                 if (G.telwish == WILL)
441                         return;
442         }
443         else
444                 if (G.telwish == WONT)
445                         return;
446   
447         if ((G.telflags ^= UF_SGA) & UF_SGA) /* toggle */
448                 putiac2(DO, TELOPT_SGA);
449         else
450                 putiac2(DONT, TELOPT_SGA);
451
452         return;
453 }
454
455 #ifdef CONFIG_FEATURE_TELNET_TTYPE
456 static inline void to_ttype(void)
457 {
458         /* Tell server we will (or won't) do TTYPE */
459
460         if(ttype)
461                 putiac2(WILL, TELOPT_TTYPE);
462         else
463                 putiac2(WONT, TELOPT_TTYPE);
464
465         return;
466 }
467 #endif
468
469 static void telopt(byte c)
470 {
471         switch (c)
472         {
473         case TELOPT_ECHO:               to_echo();             break;
474         case TELOPT_SGA:                to_sga();              break;
475 #ifdef CONFIG_FEATURE_TELNET_TTYPE
476         case TELOPT_TTYPE:              to_ttype();    break;
477 #endif
478         default:                                to_notsup(c);   break;
479         }
480 }
481
482
483 /* ******************************* */
484
485 /* subnegotiation -- ignore all (except TTYPE) */
486
487 static int subneg(byte c)
488 {
489         switch (G.telstate)
490         {
491         case TS_SUB1:
492                 if (c == IAC)
493                         G.telstate = TS_SUB2;
494 #ifdef CONFIG_FEATURE_TELNET_TTYPE
495                 else
496                 if (c == TELOPT_TTYPE)
497                         putiac_subopt(TELOPT_TTYPE,ttype);
498 #endif
499                 break;
500         case TS_SUB2:
501                 if (c == SE)
502                         return TRUE;
503                 G.telstate = TS_SUB1;
504                 /* break; */
505         }
506         return FALSE;
507 }
508
509 /* ******************************* */
510
511 static void fgotsig(int sig)
512 {
513         G.gotsig = sig;
514 }
515
516
517 static void rawmode(void)
518 {
519         tcsetattr(0, TCSADRAIN, &G.termios_raw);
520 }       
521
522 static void cookmode(void)
523 {
524         tcsetattr(0, TCSADRAIN, &G.termios_def);
525 }
526
527 extern int telnet_main(int argc, char** argv)
528 {
529         struct in_addr host;
530         int port;
531         int len;
532 #ifdef USE_POLL
533         struct pollfd ufds[2];
534 #else   
535         fd_set readfds;
536         int maxfd;
537 #endif  
538
539 #ifdef CONFIG_FEATURE_TELNET_TTYPE
540     ttype = getenv("TERM");
541 #endif
542
543         memset(&G, 0, sizeof G);
544
545         if (tcgetattr(0, &G.termios_def) < 0)
546                 exit(1);
547         
548         G.termios_raw = G.termios_def;
549         cfmakeraw(&G.termios_raw);
550         
551         if (argc < 2)   show_usage();
552         port = (argc > 2)? getport(argv[2]): 23;
553         
554         host = getserver(argv[1]);
555
556         G.netfd = remote_connect(host, port);
557
558         signal(SIGINT, fgotsig);
559
560 #ifdef USE_POLL
561         ufds[0].fd = 0; ufds[1].fd = G.netfd;
562         ufds[0].events = ufds[1].events = POLLIN;
563 #else   
564         FD_ZERO(&readfds);
565         FD_SET(0, &readfds);
566         FD_SET(G.netfd, &readfds);
567         maxfd = G.netfd + 1;
568 #endif
569         
570         while (1)
571         {
572 #ifndef USE_POLL
573                 fd_set rfds = readfds;
574                 
575                 switch (select(maxfd, &rfds, NULL, NULL, NULL))
576 #else
577                 switch (poll(ufds, 2, -1))
578 #endif                  
579                 {
580                 case 0:
581                         /* timeout */
582                 case -1:
583                         /* error, ignore and/or log something, bay go to loop */
584                         if (G.gotsig)
585                                 conescape();
586                         else
587                                 sleep(1);
588                         break;
589                 default:
590
591 #ifdef USE_POLL
592                         if (ufds[0].revents) /* well, should check POLLIN, but ... */
593 #else                           
594                         if (FD_ISSET(0, &rfds))
595 #endif                          
596                         {
597                                 len = read(0, G.buf, DATABUFSIZE);
598
599                                 if (len <= 0)
600                                         doexit(0);
601
602                                 TRACE(0, ("Read con: %d\n", len));
603                                 
604                                 handlenetoutput(len);
605                         }
606
607 #ifdef USE_POLL
608                         if (ufds[1].revents) /* well, should check POLLIN, but ... */
609 #else                           
610                         if (FD_ISSET(G.netfd, &rfds))
611 #endif                          
612                         {
613                                 len = read(G.netfd, G.buf, DATABUFSIZE);
614
615                                 if (len <= 0)
616                                 {
617                                         WriteCS(1, "Connection closed by foreign host.\r\n");
618                                         doexit(1);
619                                 }
620                                 TRACE(0, ("Read netfd (%d): %d\n", G.netfd, len));
621
622                                 handlenetinput(len);
623                         }
624                 }
625         }
626 }
627
628 static int getport(char * p)
629 {
630         unsigned int port = atoi(p);
631
632         if ((unsigned)(port - 1 ) > 65534)
633         {
634                 error_msg_and_die("%s: bad port number", p);
635         }
636         return port;
637 }
638
639 static struct in_addr getserver(char * host)
640 {
641         struct in_addr addr;
642
643         struct hostent * he;
644         he = xgethostbyname(host);
645         memcpy(&addr, he->h_addr, sizeof addr);
646
647         TRACE(1, ("addr: %s\n", inet_ntoa(addr)));
648
649         return addr;
650 }
651
652 static int create_socket(void)
653 {
654         return socket(AF_INET, SOCK_STREAM, 0);
655 }
656
657 static void setup_sockaddr_in(struct sockaddr_in * addr, int port)
658 {
659         memset(addr, 0, sizeof(struct sockaddr_in));
660         addr->sin_family = AF_INET;
661         addr->sin_port = htons(port);
662 }
663   
664 #if 0
665 static int local_bind(int port)
666 {
667         struct sockaddr_in s_addr;
668         int s = create_socket();
669   
670         setup_sockaddr_in(&s_addr, port);
671   
672         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
673   
674         if (bind(s, &s_addr, sizeof s_addr) < 0)
675         {
676                 char * e = sys_errlist[errno];
677                 syserrorexit("bind");
678                 exit(1);
679         }
680         listen(s, 1);
681         
682         return s;
683 }
684 #endif
685
686 static int remote_connect(struct in_addr addr, int port)
687 {
688         struct sockaddr_in s_addr;
689         int s = create_socket();
690
691         setup_sockaddr_in(&s_addr, port);
692         s_addr.sin_addr = addr;
693
694         setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof one);
695
696         if (connect(s, (struct sockaddr *)&s_addr, sizeof s_addr) < 0)
697         {
698                 perror_msg_and_die("Unable to connect to remote host");
699         }
700         return s;
701 }
702
703 /*
704 Local Variables:
705 c-file-style: "linux"
706 c-basic-offset: 4
707 tab-width: 4
708 End:
709 */