don't whine if all we need to do is remove a bg job
[oweals/busybox.git] / 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()
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 int create_socket();
125 static void setup_sockaddr_in(struct sockaddr_in * addr, int port);
126 static int remote_connect(struct in_addr addr, int port);
127 static void rawmode();
128 static void cookmode();
129 static void do_linemode();
130 static void will_charmode();
131 static void telopt(byte c);
132 static int subneg(byte c);
133 #if 0
134 static int local_bind(int port);
135 #endif
136
137 /* Some globals */
138 static int one = 1;
139
140 #ifdef BB_FEATURE_TELNET_TTYPE
141 static char *ttype;
142 #endif
143
144 static void doexit(int ev)
145 {
146         cookmode();
147         exit(ev);
148 }       
149
150 static void conescape()
151 {
152         char b;
153
154         if (G.gotsig)   /* came from line  mode... go raw */
155                 rawmode();
156
157         WriteCS(1, "\r\nConsole escape. Commands are:\r\n\n"
158                         " l     go to line mode\r\n"
159                         " c     go to character mode\r\n"
160                         " z     suspend telnet\r\n"
161                         " e     exit telnet\r\n");
162
163         if (read(0, &b, 1) <= 0)
164                 doexit(1);
165
166         switch (b)
167         {
168         case 'l':
169                 if (!G.gotsig)
170                 {
171                         do_linemode();
172                         goto rrturn;
173                 }
174                 break;
175         case 'c':
176                 if (G.gotsig)
177                 {
178                         will_charmode();
179                         goto rrturn;
180                 }
181                 break;
182         case 'z':
183                 cookmode();
184                 kill(0, SIGTSTP);
185                 rawmode();
186                 break;
187         case 'e':
188                 doexit(0);
189         }
190
191         WriteCS(1, "continuing...\r\n");
192
193         if (G.gotsig)
194                 cookmode();
195         
196  rrturn:
197         G.gotsig = 0;
198         
199 }
200 static void handlenetoutput(int len)
201 {
202         /*      here we could do smart tricks how to handle 0xFF:s in output
203          *      stream  like writing twice every sequence of FF:s (thus doing
204          *      many write()s. But I think interactive telnet application does
205          *      not need to be 100% 8-bit clean, so changing every 0xff:s to
206          *      0x7f:s */
207
208         int i;
209         byte * p = G.buf;
210
211         for (i = len; i > 0; i--, p++)
212         {
213                 if (*p == 0x1d)
214                 {
215                         conescape();
216                         return;
217                 }
218                 if (*p == 0xff)
219                         *p = 0x7f;
220         }
221         write(G.netfd, G.buf, len);
222 }
223
224
225 static void handlenetinput(int len)
226 {
227         int i;
228         int cstart = 0;
229
230         for (i = 0; i < len; i++)
231         {
232                 byte c = G.buf[i];
233
234                 if (G.telstate == 0) /* most of the time state == 0 */
235                 {
236                         if (c == IAC)
237                         {
238                                 cstart = i;
239                                 G.telstate = TS_IAC;
240                         }
241                 }
242                 else
243                         switch (G.telstate)
244                          {
245                          case TS_0:
246                                  if (c == IAC)
247                                          G.telstate = TS_IAC;
248                                  else
249                                          G.buf[cstart++] = c;
250                                  break;
251
252                          case TS_IAC:
253                                  if (c == IAC) /* IAC IAC -> 0xFF */
254                                  {
255                                          G.buf[cstart++] = c;
256                                          G.telstate = TS_0;
257                                          break;
258                                  }
259                                  /* else */
260                                  switch (c)
261                                  {
262                                  case SB:
263                                          G.telstate = TS_SUB1;
264                                          break;
265                                  case DO:
266                                  case DONT:
267                                  case WILL:
268                                  case WONT:
269                                          G.telwish =  c;
270                                          G.telstate = TS_OPT;
271                                          break;
272                                  default:
273                                          G.telstate = TS_0;     /* DATA MARK must be added later */
274                                  }
275                                  break;
276                          case TS_OPT: /* WILL, WONT, DO, DONT */
277                                  telopt(c);
278                                  G.telstate = TS_0;
279                                  break;
280                          case TS_SUB1: /* Subnegotiation */
281                          case TS_SUB2: /* Subnegotiation */
282                                  if (subneg(c) == TRUE)
283                                          G.telstate = TS_0;
284                                  break;
285                          }
286         }
287         if (G.telstate)
288         {
289                 if (G.iaclen)                   iacflush();
290                 if (G.telstate == TS_0) G.telstate = 0;
291
292                 len = cstart;
293         }
294
295         if (len)
296                 write(1, G.buf, len);
297 }
298
299
300 /* ******************************* */
301
302 static inline void putiac(int c)
303 {
304         G.iacbuf[G.iaclen++] = c;
305 }
306
307
308 static void putiac2(byte wwdd, byte c)
309 {
310         if (G.iaclen + 3 > IACBUFSIZE)
311                 iacflush();
312
313         putiac(IAC);
314         putiac(wwdd);
315         putiac(c);
316 }
317
318 #if 0
319 static void putiac1(byte c)
320 {
321         if (G.iaclen + 2 > IACBUFSIZE)
322                 iacflush();
323
324         putiac(IAC);
325         putiac(c);
326 }
327 #endif
328
329 #ifdef BB_FEATURE_TELNET_TTYPE
330 static void putiac_subopt(byte c, char *str)
331 {
332         int     len = strlen(str) + 6;   // ( 2 + 1 + 1 + strlen + 2 )
333
334         if (G.iaclen + len > IACBUFSIZE)
335                 iacflush();
336
337         putiac(IAC);
338         putiac(SB);
339         putiac(c);
340         putiac(0);
341
342         while(*str)
343                 putiac(*str++);
344
345         putiac(IAC);
346         putiac(SE);
347 }
348 #endif
349
350 /* void putiacstring (subneg strings) */
351
352 /* ******************************* */
353
354 static char const escapecharis[] = "\r\nEscape character is ";
355
356 static void setConMode()
357 {
358         if (G.telflags & UF_ECHO)
359         {
360                 if (G.charmode == CHM_TRY) {
361                         G.charmode = CHM_ON;
362                         printf("\r\nEntering character mode%s'^]'.\r\n", escapecharis);
363                         rawmode();
364                 }
365         }
366         else
367         {
368                 if (G.charmode != CHM_OFF) {
369                         G.charmode = CHM_OFF;
370                         printf("\r\nEntering line mode%s'^C'.\r\n", escapecharis);
371                         cookmode();
372                 }
373         }
374 }
375
376 /* ******************************* */
377
378 static void will_charmode()
379 {
380         G.charmode = CHM_TRY;
381         G.telflags |= (UF_ECHO | UF_SGA);
382         setConMode();
383   
384         putiac2(DO, TELOPT_ECHO);
385         putiac2(DO, TELOPT_SGA);
386         iacflush();
387 }
388
389 static void do_linemode()
390 {
391         G.charmode = CHM_TRY;
392         G.telflags &= ~(UF_ECHO | UF_SGA);
393         setConMode();
394
395         putiac2(DONT, TELOPT_ECHO);
396         putiac2(DONT, TELOPT_SGA);
397         iacflush();
398 }
399
400 /* ******************************* */
401
402 static inline void to_notsup(char c)
403 {
404         if      (G.telwish == WILL)     putiac2(DONT, c);
405         else if (G.telwish == DO)       putiac2(WONT, c);
406 }
407
408 static inline void to_echo()
409 {
410         /* if server requests ECHO, don't agree */
411         if      (G.telwish == DO) {     putiac2(WONT, TELOPT_ECHO);     return; }
412         else if (G.telwish == DONT)     return;
413   
414         if (G.telflags & UF_ECHO)
415         {
416                 if (G.telwish == WILL)
417                         return;
418         }
419         else
420                 if (G.telwish == WONT)
421                         return;
422
423         if (G.charmode != CHM_OFF)
424                 G.telflags ^= UF_ECHO;
425
426         if (G.telflags & UF_ECHO)
427                 putiac2(DO, TELOPT_ECHO);
428         else
429                 putiac2(DONT, TELOPT_ECHO);
430
431         setConMode();
432         WriteCS(1, "\r\n");  /* sudden modec */
433 }
434
435 static inline void to_sga()
436 {
437         /* daemon always sends will/wont, client do/dont */
438
439         if (G.telflags & UF_SGA)
440         {
441                 if (G.telwish == WILL)
442                         return;
443         }
444         else
445                 if (G.telwish == WONT)
446                         return;
447   
448         if ((G.telflags ^= UF_SGA) & UF_SGA) /* toggle */
449                 putiac2(DO, TELOPT_SGA);
450         else
451                 putiac2(DONT, TELOPT_SGA);
452
453         return;
454 }
455
456 #ifdef BB_FEATURE_TELNET_TTYPE
457 static inline void to_ttype()
458 {
459         /* Tell server we will (or won't) do TTYPE */
460
461         if(ttype)
462                 putiac2(WILL, TELOPT_TTYPE);
463         else
464                 putiac2(WONT, TELOPT_TTYPE);
465
466         return;
467 }
468 #endif
469
470 static void telopt(byte c)
471 {
472         switch (c)
473         {
474         case TELOPT_ECHO:               to_echo(c);             break;
475         case TELOPT_SGA:                to_sga(c);              break;
476 #ifdef BB_FEATURE_TELNET_TTYPE
477         case TELOPT_TTYPE:              to_ttype(c);    break;
478 #endif
479         default:                                to_notsup(c);   break;
480         }
481 }
482
483
484 /* ******************************* */
485
486 /* subnegotiation -- ignore all (except TTYPE) */
487
488 static int subneg(byte c)
489 {
490         switch (G.telstate)
491         {
492         case TS_SUB1:
493                 if (c == IAC)
494                         G.telstate = TS_SUB2;
495 #ifdef BB_FEATURE_TELNET_TTYPE
496                 else
497                 if (c == TELOPT_TTYPE)
498                         putiac_subopt(TELOPT_TTYPE,ttype);
499 #endif
500                 break;
501         case TS_SUB2:
502                 if (c == SE)
503                         return TRUE;
504                 G.telstate = TS_SUB1;
505                 /* break; */
506         }
507         return FALSE;
508 }
509
510 /* ******************************* */
511
512 static void fgotsig(int sig)
513 {
514         G.gotsig = sig;
515 }
516
517
518 static void rawmode()
519 {
520         tcsetattr(0, TCSADRAIN, &G.termios_raw);
521 }       
522
523 static void cookmode()
524 {
525         tcsetattr(0, TCSADRAIN, &G.termios_def);
526 }
527
528 extern int telnet_main(int argc, char** argv)
529 {
530         struct in_addr host;
531         int port;
532         int len;
533 #ifdef USE_POLL
534         struct pollfd ufds[2];
535 #else   
536         fd_set readfds;
537         int maxfd;
538 #endif  
539
540 #ifdef BB_FEATURE_TELNET_TTYPE
541     ttype = getenv("TERM");
542 #endif
543
544         memset(&G, 0, sizeof G);
545
546         if (tcgetattr(0, &G.termios_def) < 0)
547                 exit(1);
548         
549         G.termios_raw = G.termios_def;
550         cfmakeraw(&G.termios_raw);
551         
552         if (argc < 2)   show_usage();
553         port = (argc > 2)? getport(argv[2]): 23;
554         
555         host = getserver(argv[1]);
556
557         G.netfd = remote_connect(host, port);
558
559         signal(SIGINT, fgotsig);
560
561 #ifdef USE_POLL
562         ufds[0].fd = 0; ufds[1].fd = G.netfd;
563         ufds[0].events = ufds[1].events = POLLIN;
564 #else   
565         FD_ZERO(&readfds);
566         FD_SET(0, &readfds);
567         FD_SET(G.netfd, &readfds);
568         maxfd = G.netfd + 1;
569 #endif
570         
571         while (1)
572         {
573 #ifndef USE_POLL
574                 fd_set rfds = readfds;
575                 
576                 switch (select(maxfd, &rfds, NULL, NULL, NULL))
577 #else
578                 switch (poll(ufds, 2, -1))
579 #endif                  
580                 {
581                 case 0:
582                         /* timeout */
583                 case -1:
584                         /* error, ignore and/or log something, bay go to loop */
585                         if (G.gotsig)
586                                 conescape();
587                         else
588                                 sleep(1);
589                         break;
590                 default:
591
592 #ifdef USE_POLL
593                         if (ufds[0].revents) /* well, should check POLLIN, but ... */
594 #else                           
595                         if (FD_ISSET(0, &rfds))
596 #endif                          
597                         {
598                                 len = read(0, G.buf, DATABUFSIZE);
599
600                                 if (len <= 0)
601                                         doexit(0);
602
603                                 TRACE(0, ("Read con: %d\n", len));
604                                 
605                                 handlenetoutput(len);
606                         }
607
608 #ifdef USE_POLL
609                         if (ufds[1].revents) /* well, should check POLLIN, but ... */
610 #else                           
611                         if (FD_ISSET(G.netfd, &rfds))
612 #endif                          
613                         {
614                                 len = read(G.netfd, G.buf, DATABUFSIZE);
615
616                                 if (len <= 0)
617                                 {
618                                         WriteCS(1, "Connection closed by foreign host.\r\n");
619                                         doexit(1);
620                                 }
621                                 TRACE(0, ("Read netfd (%d): %d\n", G.netfd, len));
622
623                                 handlenetinput(len);
624                         }
625                 }
626         }
627 }
628
629 static int getport(char * p)
630 {
631         unsigned int port = atoi(p);
632
633         if ((unsigned)(port - 1 ) > 65534)
634         {
635                 error_msg_and_die("%s: bad port number", p);
636         }
637         return port;
638 }
639
640 static struct in_addr getserver(char * host)
641 {
642         struct in_addr addr;
643
644         struct hostent * he;
645         he = xgethostbyname(host);
646         memcpy(&addr, he->h_addr, sizeof addr);
647
648         TRACE(1, ("addr: %s\n", inet_ntoa(addr)));
649
650         return addr;
651 }
652
653 static int create_socket()
654 {
655         return socket(AF_INET, SOCK_STREAM, 0);
656 }
657
658 static void setup_sockaddr_in(struct sockaddr_in * addr, int port)
659 {
660         memset(addr, 0, sizeof(struct sockaddr_in));
661         addr->sin_family = AF_INET;
662         addr->sin_port = htons(port);
663 }
664   
665 #if 0
666 static int local_bind(int port)
667 {
668         struct sockaddr_in s_addr;
669         int s = create_socket();
670   
671         setup_sockaddr_in(&s_addr, port);
672   
673         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
674   
675         if (bind(s, &s_addr, sizeof s_addr) < 0)
676         {
677                 char * e = sys_errlist[errno];
678                 syserrorexit("bind");
679                 exit(1);
680         }
681         listen(s, 1);
682         
683         return s;
684 }
685 #endif
686
687 static int remote_connect(struct in_addr addr, int port)
688 {
689         struct sockaddr_in s_addr;
690         int s = create_socket();
691
692         setup_sockaddr_in(&s_addr, port);
693         s_addr.sin_addr = addr;
694
695         setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &one, sizeof one);
696
697         if (connect(s, (struct sockaddr *)&s_addr, sizeof s_addr) < 0)
698         {
699                 perror_msg_and_die("Unable to connect to remote host");
700         }
701         return s;
702 }
703
704 /*
705 Local Variables:
706 c-file-style: "linux"
707 c-basic-offset: 4
708 tab-width: 4
709 End:
710 */
711