Improved telnet support by drastically reducing the number of write
[platform/upstream/curl.git] / lib / telnet.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2007, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  *
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id$
22  ***************************************************************************/
23
24 #include "setup.h"
25
26 #ifndef CURL_DISABLE_TELNET
27 /* -- WIN32 approved -- */
28 #include <stdio.h>
29 #include <string.h>
30 #include <stdarg.h>
31 #include <stdlib.h>
32 #include <ctype.h>
33
34 #if defined(WIN32)
35 #include <time.h>
36 #include <io.h>
37 #else
38 #ifdef HAVE_SYS_SOCKET_H
39 #include <sys/socket.h>
40 #endif
41 #include <netinet/in.h>
42 #ifdef HAVE_SYS_TIME_H
43 #include <sys/time.h>
44 #endif
45 #ifdef HAVE_UNISTD_H
46 #include <unistd.h>
47 #endif
48 #include <netdb.h>
49 #ifdef HAVE_ARPA_INET_H
50 #include <arpa/inet.h>
51 #endif
52 #ifdef HAVE_NET_IF_H
53 #include <net/if.h>
54 #endif
55 #include <sys/ioctl.h>
56 #include <signal.h>
57
58 #ifdef HAVE_SYS_PARAM_H
59 #include <sys/param.h>
60 #endif
61
62 #endif  /* WIN32 */
63
64 #include "urldata.h"
65 #include <curl/curl.h>
66 #include "transfer.h"
67 #include "sendf.h"
68 #include "telnet.h"
69 #include "connect.h"
70
71 #define _MPRINTF_REPLACE /* use our functions only */
72 #include <curl/mprintf.h>
73
74 #define  TELOPTS
75 #define  TELCMDS
76
77 #include "arpa_telnet.h"
78 #include "memory.h"
79 #include "select.h"
80
81 /* The last #include file should be: */
82 #include "memdebug.h"
83
84 #define SUBBUFSIZE 512
85
86 #define CURL_SB_CLEAR(x)  x->subpointer = x->subbuffer;
87 #define CURL_SB_TERM(x)   { x->subend = x->subpointer; CURL_SB_CLEAR(x); }
88 #define CURL_SB_ACCUM(x,c) \
89   if(x->subpointer < (x->subbuffer+sizeof x->subbuffer)) { \
90     *x->subpointer++ = (c); \
91   }
92
93 #define  CURL_SB_GET(x) ((*x->subpointer++)&0xff)
94 #define  CURL_SB_PEEK(x)   ((*x->subpointer)&0xff)
95 #define  CURL_SB_EOF(x) (x->subpointer >= x->subend)
96 #define  CURL_SB_LEN(x) (x->subend - x->subpointer)
97
98 #ifdef CURL_DISABLE_VERBOSE_STRINGS
99 #define printoption(a,b,c,d)  do { } while(0)
100 #endif
101
102 #ifdef USE_WINSOCK
103 typedef FARPROC WSOCK2_FUNC;
104 static CURLcode check_wsock2 ( struct SessionHandle *data );
105 #endif
106
107 static
108 void telrcv(struct connectdata *,
109             const unsigned char *inbuf, /* Data received from socket */
110             ssize_t count);             /* Number of bytes received */
111
112 #ifndef CURL_DISABLE_VERBOSE_STRINGS
113 static void printoption(struct SessionHandle *data,
114                         const char *direction,
115                         int cmd, int option);
116 #endif
117
118 static void negotiate(struct connectdata *);
119 static void send_negotiation(struct connectdata *, int cmd, int option);
120 static void set_local_option(struct connectdata *, int cmd, int option);
121 static void set_remote_option(struct connectdata *, int cmd, int option);
122
123 static void printsub(struct SessionHandle *data,
124                      int direction, unsigned char *pointer,
125                      size_t length);
126 static void suboption(struct connectdata *);
127
128 static CURLcode Curl_telnet(struct connectdata *conn, bool *done);
129 static CURLcode Curl_telnet_done(struct connectdata *conn,
130                                  CURLcode, bool premature);
131
132 /* For negotiation compliant to RFC 1143 */
133 #define CURL_NO          0
134 #define CURL_YES         1
135 #define CURL_WANTYES     2
136 #define CURL_WANTNO      3
137
138 #define CURL_EMPTY       0
139 #define CURL_OPPOSITE    1
140
141 /*
142  * Telnet receiver states for fsm
143  */
144 typedef enum
145 {
146    CURL_TS_DATA = 0,
147    CURL_TS_IAC,
148    CURL_TS_WILL,
149    CURL_TS_WONT,
150    CURL_TS_DO,
151    CURL_TS_DONT,
152    CURL_TS_CR,
153    CURL_TS_SB,   /* sub-option collection */
154    CURL_TS_SE   /* looking for sub-option end */
155 } TelnetReceive;
156
157 struct TELNET {
158   int please_negotiate;
159   int already_negotiated;
160   int us[256];
161   int usq[256];
162   int us_preferred[256];
163   int him[256];
164   int himq[256];
165   int him_preferred[256];
166   char subopt_ttype[32];             /* Set with suboption TTYPE */
167   char subopt_xdisploc[128];          /* Set with suboption XDISPLOC */
168   struct curl_slist *telnet_vars; /* Environment variables */
169
170   /* suboptions */
171   unsigned char subbuffer[SUBBUFSIZE];
172   unsigned char *subpointer, *subend;      /* buffer for sub-options */
173
174   TelnetReceive telrcv_state;
175 };
176
177
178 /*
179  * TELNET protocol handler.
180  */
181
182 const struct Curl_handler Curl_handler_telnet = {
183   "TELNET",                             /* scheme */
184   ZERO_NULL,                            /* setup_connection */
185   Curl_telnet,                          /* do_it */
186   Curl_telnet_done,                     /* done */
187   ZERO_NULL,                            /* do_more */
188   ZERO_NULL,                            /* connect_it */
189   ZERO_NULL,                            /* connecting */
190   ZERO_NULL,                            /* doing */
191   ZERO_NULL,                            /* proto_getsock */
192   ZERO_NULL,                            /* doing_getsock */
193   ZERO_NULL,                            /* disconnect */
194   PORT_TELNET,                          /* defport */
195   PROT_TELNET                           /* protocol */
196 };
197
198
199 #ifdef USE_WINSOCK
200 static CURLcode
201 check_wsock2 ( struct SessionHandle *data )
202 {
203   int err;
204   WORD wVersionRequested;
205   WSADATA wsaData;
206
207   DEBUGASSERT(data);
208
209   /* telnet requires at least WinSock 2.0 so ask for it. */
210   wVersionRequested = MAKEWORD(2, 0);
211
212   err = WSAStartup(wVersionRequested, &wsaData);
213
214   /* We must've called this once already, so this call */
215   /* should always succeed.  But, just in case... */
216   if(err != 0) {
217     failf(data,"WSAStartup failed (%d)",err);
218     return CURLE_FAILED_INIT;
219   }
220
221   /* We have to have a WSACleanup call for every successful */
222   /* WSAStartup call. */
223   WSACleanup();
224
225   /* Check that our version is supported */
226   if(LOBYTE(wsaData.wVersion) != LOBYTE(wVersionRequested) ||
227       HIBYTE(wsaData.wVersion) != HIBYTE(wVersionRequested)) {
228       /* Our version isn't supported */
229       failf(data,"insufficient winsock version to support "
230             "telnet");
231       return CURLE_FAILED_INIT;
232   }
233
234   /* Our version is supported */
235   return CURLE_OK;
236 }
237 #endif
238
239 static
240 CURLcode init_telnet(struct connectdata *conn)
241 {
242   struct TELNET *tn;
243
244   tn = (struct TELNET *)calloc(1, sizeof(struct TELNET));
245   if(!tn)
246     return CURLE_OUT_OF_MEMORY;
247
248   conn->data->reqdata.proto.telnet = (void *)tn; /* make us known */
249
250   tn->telrcv_state = CURL_TS_DATA;
251
252   /* Init suboptions */
253   CURL_SB_CLEAR(tn);
254
255   /* Set the options we want by default */
256   tn->us_preferred[CURL_TELOPT_BINARY] = CURL_YES;
257   tn->us_preferred[CURL_TELOPT_SGA] = CURL_YES;
258   tn->him_preferred[CURL_TELOPT_BINARY] = CURL_YES;
259   tn->him_preferred[CURL_TELOPT_SGA] = CURL_YES;
260
261   return CURLE_OK;
262 }
263
264 static void negotiate(struct connectdata *conn)
265 {
266   int i;
267   struct TELNET *tn = (struct TELNET *) conn->data->reqdata.proto.telnet;
268
269   for(i = 0;i < CURL_NTELOPTS;i++)
270   {
271     if(tn->us_preferred[i] == CURL_YES)
272       set_local_option(conn, i, CURL_YES);
273
274     if(tn->him_preferred[i] == CURL_YES)
275       set_remote_option(conn, i, CURL_YES);
276   }
277 }
278
279 #ifndef CURL_DISABLE_VERBOSE_STRINGS
280 static void printoption(struct SessionHandle *data,
281                         const char *direction, int cmd, int option)
282 {
283   const char *fmt;
284   const char *opt;
285
286   if(data->set.verbose)
287   {
288     if(cmd == CURL_IAC)
289     {
290       if(CURL_TELCMD_OK(option))
291         infof(data, "%s IAC %s\n", direction, CURL_TELCMD(option));
292       else
293         infof(data, "%s IAC %d\n", direction, option);
294     }
295     else
296     {
297       fmt = (cmd == CURL_WILL) ? "WILL" : (cmd == CURL_WONT) ? "WONT" :
298         (cmd == CURL_DO) ? "DO" : (cmd == CURL_DONT) ? "DONT" : 0;
299       if(fmt)
300       {
301         if(CURL_TELOPT_OK(option))
302           opt = CURL_TELOPT(option);
303         else if(option == CURL_TELOPT_EXOPL)
304           opt = "EXOPL";
305         else
306           opt = NULL;
307
308         if(opt)
309           infof(data, "%s %s %s\n", direction, fmt, opt);
310         else
311           infof(data, "%s %s %d\n", direction, fmt, option);
312       }
313       else
314         infof(data, "%s %d %d\n", direction, cmd, option);
315     }
316   }
317 }
318 #endif
319
320 static void send_negotiation(struct connectdata *conn, int cmd, int option)
321 {
322    unsigned char buf[3];
323    ssize_t bytes_written;
324    int err;
325    struct SessionHandle *data = conn->data;
326
327    buf[0] = CURL_IAC;
328    buf[1] = (unsigned char)cmd;
329    buf[2] = (unsigned char)option;
330
331    bytes_written = swrite(conn->sock[FIRSTSOCKET], buf, 3);
332    if(bytes_written < 0) {
333      err = SOCKERRNO;
334      failf(data,"Sending data failed (%d)",err);
335    }
336
337    printoption(conn->data, "SENT", cmd, option);
338 }
339
340 static
341 void set_remote_option(struct connectdata *conn, int option, int newstate)
342 {
343   struct TELNET *tn = (struct TELNET *)conn->data->reqdata.proto.telnet;
344   if(newstate == CURL_YES)
345   {
346     switch(tn->him[option])
347     {
348       case CURL_NO:
349         tn->him[option] = CURL_WANTYES;
350         send_negotiation(conn, CURL_DO, option);
351         break;
352
353       case CURL_YES:
354         /* Already enabled */
355         break;
356
357       case CURL_WANTNO:
358         switch(tn->himq[option])
359         {
360           case CURL_EMPTY:
361             /* Already negotiating for CURL_YES, queue the request */
362             tn->himq[option] = CURL_OPPOSITE;
363             break;
364           case CURL_OPPOSITE:
365             /* Error: already queued an enable request */
366             break;
367         }
368         break;
369
370       case CURL_WANTYES:
371         switch(tn->himq[option])
372         {
373           case CURL_EMPTY:
374             /* Error: already negotiating for enable */
375             break;
376           case CURL_OPPOSITE:
377             tn->himq[option] = CURL_EMPTY;
378             break;
379         }
380         break;
381     }
382   }
383   else /* NO */
384   {
385     switch(tn->him[option])
386     {
387       case CURL_NO:
388         /* Already disabled */
389         break;
390
391       case CURL_YES:
392         tn->him[option] = CURL_WANTNO;
393         send_negotiation(conn, CURL_DONT, option);
394         break;
395
396       case CURL_WANTNO:
397         switch(tn->himq[option])
398         {
399           case CURL_EMPTY:
400             /* Already negotiating for NO */
401             break;
402           case CURL_OPPOSITE:
403             tn->himq[option] = CURL_EMPTY;
404             break;
405         }
406         break;
407
408       case CURL_WANTYES:
409         switch(tn->himq[option])
410         {
411           case CURL_EMPTY:
412             tn->himq[option] = CURL_OPPOSITE;
413             break;
414           case CURL_OPPOSITE:
415             break;
416         }
417         break;
418     }
419   }
420 }
421
422 static
423 void rec_will(struct connectdata *conn, int option)
424 {
425   struct TELNET *tn = (struct TELNET *)conn->data->reqdata.proto.telnet;
426   switch(tn->him[option])
427   {
428     case CURL_NO:
429       if(tn->him_preferred[option] == CURL_YES)
430       {
431         tn->him[option] = CURL_YES;
432         send_negotiation(conn, CURL_DO, option);
433       }
434       else
435       {
436         send_negotiation(conn, CURL_DONT, option);
437       }
438       break;
439
440     case CURL_YES:
441       /* Already enabled */
442       break;
443
444     case CURL_WANTNO:
445       switch(tn->himq[option])
446       {
447         case CURL_EMPTY:
448           /* Error: DONT answered by WILL */
449           tn->him[option] = CURL_NO;
450           break;
451         case CURL_OPPOSITE:
452           /* Error: DONT answered by WILL */
453           tn->him[option] = CURL_YES;
454           tn->himq[option] = CURL_EMPTY;
455           break;
456       }
457       break;
458
459     case CURL_WANTYES:
460       switch(tn->himq[option])
461       {
462         case CURL_EMPTY:
463           tn->him[option] = CURL_YES;
464           break;
465         case CURL_OPPOSITE:
466           tn->him[option] = CURL_WANTNO;
467           tn->himq[option] = CURL_EMPTY;
468           send_negotiation(conn, CURL_DONT, option);
469           break;
470       }
471       break;
472   }
473 }
474
475 static
476 void rec_wont(struct connectdata *conn, int option)
477 {
478   struct TELNET *tn = (struct TELNET *)conn->data->reqdata.proto.telnet;
479   switch(tn->him[option])
480   {
481     case CURL_NO:
482       /* Already disabled */
483       break;
484
485     case CURL_YES:
486       tn->him[option] = CURL_NO;
487       send_negotiation(conn, CURL_DONT, option);
488       break;
489
490     case CURL_WANTNO:
491       switch(tn->himq[option])
492       {
493         case CURL_EMPTY:
494           tn->him[option] = CURL_NO;
495           break;
496
497         case CURL_OPPOSITE:
498           tn->him[option] = CURL_WANTYES;
499           tn->himq[option] = CURL_EMPTY;
500           send_negotiation(conn, CURL_DO, option);
501           break;
502       }
503       break;
504
505     case CURL_WANTYES:
506       switch(tn->himq[option])
507       {
508         case CURL_EMPTY:
509           tn->him[option] = CURL_NO;
510           break;
511         case CURL_OPPOSITE:
512           tn->him[option] = CURL_NO;
513           tn->himq[option] = CURL_EMPTY;
514           break;
515       }
516       break;
517   }
518 }
519
520 static void
521 set_local_option(struct connectdata *conn, int option, int newstate)
522 {
523   struct TELNET *tn = (struct TELNET *)conn->data->reqdata.proto.telnet;
524   if(newstate == CURL_YES)
525   {
526     switch(tn->us[option])
527     {
528       case CURL_NO:
529         tn->us[option] = CURL_WANTYES;
530         send_negotiation(conn, CURL_WILL, option);
531         break;
532
533       case CURL_YES:
534         /* Already enabled */
535         break;
536
537       case CURL_WANTNO:
538         switch(tn->usq[option])
539         {
540           case CURL_EMPTY:
541             /* Already negotiating for CURL_YES, queue the request */
542             tn->usq[option] = CURL_OPPOSITE;
543             break;
544           case CURL_OPPOSITE:
545             /* Error: already queued an enable request */
546             break;
547         }
548         break;
549
550       case CURL_WANTYES:
551         switch(tn->usq[option])
552         {
553           case CURL_EMPTY:
554             /* Error: already negotiating for enable */
555             break;
556           case CURL_OPPOSITE:
557             tn->usq[option] = CURL_EMPTY;
558             break;
559         }
560         break;
561     }
562   }
563   else /* NO */
564   {
565     switch(tn->us[option])
566     {
567       case CURL_NO:
568         /* Already disabled */
569         break;
570
571       case CURL_YES:
572         tn->us[option] = CURL_WANTNO;
573         send_negotiation(conn, CURL_WONT, option);
574         break;
575
576       case CURL_WANTNO:
577         switch(tn->usq[option])
578         {
579           case CURL_EMPTY:
580             /* Already negotiating for NO */
581             break;
582           case CURL_OPPOSITE:
583             tn->usq[option] = CURL_EMPTY;
584             break;
585         }
586         break;
587
588       case CURL_WANTYES:
589         switch(tn->usq[option])
590         {
591           case CURL_EMPTY:
592             tn->usq[option] = CURL_OPPOSITE;
593             break;
594           case CURL_OPPOSITE:
595             break;
596         }
597         break;
598     }
599   }
600 }
601
602 static
603 void rec_do(struct connectdata *conn, int option)
604 {
605   struct TELNET *tn = (struct TELNET *)conn->data->reqdata.proto.telnet;
606   switch(tn->us[option])
607   {
608     case CURL_NO:
609       if(tn->us_preferred[option] == CURL_YES)
610       {
611         tn->us[option] = CURL_YES;
612         send_negotiation(conn, CURL_WILL, option);
613       }
614       else
615       {
616         send_negotiation(conn, CURL_WONT, option);
617       }
618       break;
619
620     case CURL_YES:
621       /* Already enabled */
622       break;
623
624     case CURL_WANTNO:
625       switch(tn->usq[option])
626       {
627         case CURL_EMPTY:
628           /* Error: DONT answered by WILL */
629           tn->us[option] = CURL_NO;
630           break;
631         case CURL_OPPOSITE:
632           /* Error: DONT answered by WILL */
633           tn->us[option] = CURL_YES;
634           tn->usq[option] = CURL_EMPTY;
635           break;
636       }
637       break;
638
639     case CURL_WANTYES:
640       switch(tn->usq[option])
641       {
642         case CURL_EMPTY:
643           tn->us[option] = CURL_YES;
644           break;
645         case CURL_OPPOSITE:
646           tn->us[option] = CURL_WANTNO;
647           tn->himq[option] = CURL_EMPTY;
648           send_negotiation(conn, CURL_WONT, option);
649           break;
650       }
651       break;
652   }
653 }
654
655 static
656 void rec_dont(struct connectdata *conn, int option)
657 {
658   struct TELNET *tn = (struct TELNET *)conn->data->reqdata.proto.telnet;
659   switch(tn->us[option])
660   {
661     case CURL_NO:
662       /* Already disabled */
663       break;
664
665     case CURL_YES:
666       tn->us[option] = CURL_NO;
667       send_negotiation(conn, CURL_WONT, option);
668       break;
669
670     case CURL_WANTNO:
671       switch(tn->usq[option])
672       {
673         case CURL_EMPTY:
674           tn->us[option] = CURL_NO;
675           break;
676
677         case CURL_OPPOSITE:
678           tn->us[option] = CURL_WANTYES;
679           tn->usq[option] = CURL_EMPTY;
680           send_negotiation(conn, CURL_WILL, option);
681           break;
682       }
683       break;
684
685     case CURL_WANTYES:
686       switch(tn->usq[option])
687       {
688         case CURL_EMPTY:
689           tn->us[option] = CURL_NO;
690           break;
691         case CURL_OPPOSITE:
692           tn->us[option] = CURL_NO;
693           tn->usq[option] = CURL_EMPTY;
694           break;
695       }
696       break;
697   }
698 }
699
700
701 static void printsub(struct SessionHandle *data,
702                      int direction,             /* '<' or '>' */
703                      unsigned char *pointer,    /* where suboption data is */
704                      size_t length)             /* length of suboption data */
705 {
706   unsigned int i = 0;
707
708   if(data->set.verbose)
709   {
710     if(direction)
711     {
712       infof(data, "%s IAC SB ", (direction == '<')? "RCVD":"SENT");
713       if(length >= 3)
714       {
715         int j;
716
717         i = pointer[length-2];
718         j = pointer[length-1];
719
720         if(i != CURL_IAC || j != CURL_SE)
721         {
722           infof(data, "(terminated by ");
723           if(CURL_TELOPT_OK(i))
724             infof(data, "%s ", CURL_TELOPT(i));
725           else if(CURL_TELCMD_OK(i))
726             infof(data, "%s ", CURL_TELCMD(i));
727           else
728             infof(data, "%d ", i);
729           if(CURL_TELOPT_OK(j))
730             infof(data, "%s", CURL_TELOPT(j));
731           else if(CURL_TELCMD_OK(j))
732             infof(data, "%s", CURL_TELCMD(j));
733           else
734             infof(data, "%d", j);
735           infof(data, ", not IAC SE!) ");
736         }
737       }
738       length -= 2;
739     }
740     if(length < 1)
741     {
742       infof(data, "(Empty suboption?)");
743       return;
744     }
745
746     if(CURL_TELOPT_OK(pointer[0])) {
747       switch(pointer[0]) {
748         case CURL_TELOPT_TTYPE:
749         case CURL_TELOPT_XDISPLOC:
750         case CURL_TELOPT_NEW_ENVIRON:
751           infof(data, "%s", CURL_TELOPT(pointer[0]));
752           break;
753         default:
754           infof(data, "%s (unsupported)", CURL_TELOPT(pointer[0]));
755           break;
756       }
757     }
758     else
759       infof(data, "%d (unknown)", pointer[i]);
760
761     switch(pointer[1]) {
762       case CURL_TELQUAL_IS:
763         infof(data, " IS");
764         break;
765       case CURL_TELQUAL_SEND:
766         infof(data, " SEND");
767         break;
768       case CURL_TELQUAL_INFO:
769         infof(data, " INFO/REPLY");
770         break;
771       case CURL_TELQUAL_NAME:
772         infof(data, " NAME");
773         break;
774     }
775
776     switch(pointer[0]) {
777       case CURL_TELOPT_TTYPE:
778       case CURL_TELOPT_XDISPLOC:
779         pointer[length] = 0;
780         infof(data, " \"%s\"", &pointer[2]);
781         break;
782       case CURL_TELOPT_NEW_ENVIRON:
783         if(pointer[1] == CURL_TELQUAL_IS) {
784           infof(data, " ");
785           for(i = 3;i < length;i++) {
786             switch(pointer[i]) {
787               case CURL_NEW_ENV_VAR:
788                 infof(data, ", ");
789                 break;
790               case CURL_NEW_ENV_VALUE:
791                 infof(data, " = ");
792                 break;
793               default:
794                 infof(data, "%c", pointer[i]);
795                 break;
796             }
797           }
798         }
799         break;
800       default:
801         for (i = 2; i < length; i++)
802           infof(data, " %.2x", pointer[i]);
803         break;
804     }
805
806     if(direction)
807     {
808       infof(data, "\n");
809     }
810   }
811 }
812
813 static CURLcode check_telnet_options(struct connectdata *conn)
814 {
815   struct curl_slist *head;
816   char option_keyword[128];
817   char option_arg[256];
818   char *buf;
819   struct SessionHandle *data = conn->data;
820   struct TELNET *tn = (struct TELNET *)conn->data->reqdata.proto.telnet;
821
822   /* Add the user name as an environment variable if it
823      was given on the command line */
824   if(conn->bits.user_passwd)
825   {
826     snprintf(option_arg, sizeof(option_arg), "USER,%s", conn->user);
827     tn->telnet_vars = curl_slist_append(tn->telnet_vars, option_arg);
828
829     tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES;
830   }
831
832   for(head = data->set.telnet_options; head; head=head->next) {
833     if(sscanf(head->data, "%127[^= ]%*[ =]%255s",
834               option_keyword, option_arg) == 2) {
835
836       /* Terminal type */
837       if(curl_strequal(option_keyword, "TTYPE")) {
838         strncpy(tn->subopt_ttype, option_arg, 31);
839         tn->subopt_ttype[31] = 0; /* String termination */
840         tn->us_preferred[CURL_TELOPT_TTYPE] = CURL_YES;
841         continue;
842       }
843
844       /* Display variable */
845       if(curl_strequal(option_keyword, "XDISPLOC")) {
846         strncpy(tn->subopt_xdisploc, option_arg, 127);
847         tn->subopt_xdisploc[127] = 0; /* String termination */
848         tn->us_preferred[CURL_TELOPT_XDISPLOC] = CURL_YES;
849         continue;
850       }
851
852       /* Environment variable */
853       if(curl_strequal(option_keyword, "NEW_ENV")) {
854         buf = strdup(option_arg);
855         if(!buf)
856           return CURLE_OUT_OF_MEMORY;
857         tn->telnet_vars = curl_slist_append(tn->telnet_vars, buf);
858         tn->us_preferred[CURL_TELOPT_NEW_ENVIRON] = CURL_YES;
859         continue;
860       }
861
862       failf(data, "Unknown telnet option %s", head->data);
863       return CURLE_UNKNOWN_TELNET_OPTION;
864     } else {
865       failf(data, "Syntax error in telnet option: %s", head->data);
866       return CURLE_TELNET_OPTION_SYNTAX;
867     }
868   }
869
870   return CURLE_OK;
871 }
872
873 /*
874  * suboption()
875  *
876  * Look at the sub-option buffer, and try to be helpful to the other
877  * side.
878  */
879
880 static void suboption(struct connectdata *conn)
881 {
882   struct curl_slist *v;
883   unsigned char temp[2048];
884   ssize_t bytes_written;
885   size_t len;
886   size_t tmplen;
887   int err;
888   char varname[128];
889   char varval[128];
890   struct SessionHandle *data = conn->data;
891   struct TELNET *tn = (struct TELNET *)data->reqdata.proto.telnet;
892
893   printsub(data, '<', (unsigned char *)tn->subbuffer, CURL_SB_LEN(tn)+2);
894   switch (CURL_SB_GET(tn)) {
895     case CURL_TELOPT_TTYPE:
896       len = strlen(tn->subopt_ttype) + 4 + 2;
897       snprintf((char *)temp, sizeof(temp),
898                "%c%c%c%c%s%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_TTYPE,
899                CURL_TELQUAL_IS, tn->subopt_ttype, CURL_IAC, CURL_SE);
900       bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);
901       if(bytes_written < 0) {
902         err = SOCKERRNO;
903         failf(data,"Sending data failed (%d)",err);
904       }
905       printsub(data, '>', &temp[2], len-2);
906       break;
907     case CURL_TELOPT_XDISPLOC:
908       len = strlen(tn->subopt_xdisploc) + 4 + 2;
909       snprintf((char *)temp, sizeof(temp),
910                "%c%c%c%c%s%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_XDISPLOC,
911                CURL_TELQUAL_IS, tn->subopt_xdisploc, CURL_IAC, CURL_SE);
912       bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);
913       if(bytes_written < 0) {
914         err = SOCKERRNO;
915         failf(data,"Sending data failed (%d)",err);
916       }
917       printsub(data, '>', &temp[2], len-2);
918       break;
919     case CURL_TELOPT_NEW_ENVIRON:
920       snprintf((char *)temp, sizeof(temp),
921                "%c%c%c%c", CURL_IAC, CURL_SB, CURL_TELOPT_NEW_ENVIRON,
922                CURL_TELQUAL_IS);
923       len = 4;
924
925       for(v = tn->telnet_vars;v;v = v->next) {
926         tmplen = (strlen(v->data) + 1);
927         /* Add the variable only if it fits */
928         if(len + tmplen < (int)sizeof(temp)-6) {
929           sscanf(v->data, "%127[^,],%127s", varname, varval);
930           snprintf((char *)&temp[len], sizeof(temp) - len,
931                    "%c%s%c%s", CURL_NEW_ENV_VAR, varname,
932                    CURL_NEW_ENV_VALUE, varval);
933           len += tmplen;
934         }
935       }
936       snprintf((char *)&temp[len], sizeof(temp) - len,
937                "%c%c", CURL_IAC, CURL_SE);
938       len += 2;
939       bytes_written = swrite(conn->sock[FIRSTSOCKET], temp, len);
940       if(bytes_written < 0) {
941         err = SOCKERRNO;
942         failf(data,"Sending data failed (%d)",err);
943       }
944       printsub(data, '>', &temp[2], len-2);
945       break;
946   }
947   return;
948 }
949
950 static
951 void telrcv(struct connectdata *conn,
952             const unsigned char *inbuf, /* Data received from socket */
953             ssize_t count)              /* Number of bytes received */
954 {
955   unsigned char c;
956   int in = 0;
957   int startwrite=-1;
958   struct SessionHandle *data = conn->data;
959   struct TELNET *tn = (struct TELNET *)data->reqdata.proto.telnet;
960
961 #define startskipping() \
962     if (startwrite >= 0) \
963        Curl_client_write(conn, CLIENTWRITE_BODY, (char *)&inbuf[startwrite], in-startwrite); \
964     startwrite = -1
965
966 #define writebyte() \
967     if (startwrite < 0) \
968       startwrite = in
969
970 #define bufferflush() startskipping()
971
972   while(count--)
973   {
974     c = inbuf[in];
975
976     /*infof(data,"In rcv state %d char %d\n", tn->telrcv_state, c);*/
977     switch (tn->telrcv_state)
978     {
979       case CURL_TS_CR:
980         tn->telrcv_state = CURL_TS_DATA;
981         if(c == '\0')
982         {
983           startskipping();
984           break;   /* Ignore \0 after CR */
985         }
986         writebyte();
987         break;
988
989       case CURL_TS_DATA:
990         if(c == CURL_IAC)
991         {
992           tn->telrcv_state = CURL_TS_IAC;
993           startskipping();
994           break;
995         }
996         else if(c == '\r')
997         {
998           tn->telrcv_state = CURL_TS_CR;
999         }
1000         writebyte();
1001         break;
1002
1003       case CURL_TS_IAC:
1004       process_iac:
1005       DEBUGASSERT(startwrite < 0);
1006       switch (c)
1007       {
1008         case CURL_WILL:
1009           tn->telrcv_state = CURL_TS_WILL;
1010           break;
1011         case CURL_WONT:
1012           tn->telrcv_state = CURL_TS_WONT;
1013           break;
1014         case CURL_DO:
1015           tn->telrcv_state = CURL_TS_DO;
1016           break;
1017         case CURL_DONT:
1018           tn->telrcv_state = CURL_TS_DONT;
1019           break;
1020         case CURL_SB:
1021           CURL_SB_CLEAR(tn);
1022           tn->telrcv_state = CURL_TS_SB;
1023           break;
1024         case CURL_IAC:
1025           tn->telrcv_state = CURL_TS_DATA;
1026           writebyte();
1027           break;
1028         case CURL_DM:
1029         case CURL_NOP:
1030         case CURL_GA:
1031         default:
1032           tn->telrcv_state = CURL_TS_DATA;
1033           printoption(data, "RCVD", CURL_IAC, c);
1034           break;
1035       }
1036       break;
1037
1038       case CURL_TS_WILL:
1039         printoption(data, "RCVD", CURL_WILL, c);
1040         tn->please_negotiate = 1;
1041         rec_will(conn, c);
1042         tn->telrcv_state = CURL_TS_DATA;
1043         break;
1044
1045       case CURL_TS_WONT:
1046         printoption(data, "RCVD", CURL_WONT, c);
1047         tn->please_negotiate = 1;
1048         rec_wont(conn, c);
1049         tn->telrcv_state = CURL_TS_DATA;
1050         break;
1051
1052       case CURL_TS_DO:
1053         printoption(data, "RCVD", CURL_DO, c);
1054         tn->please_negotiate = 1;
1055         rec_do(conn, c);
1056         tn->telrcv_state = CURL_TS_DATA;
1057         break;
1058
1059       case CURL_TS_DONT:
1060         printoption(data, "RCVD", CURL_DONT, c);
1061         tn->please_negotiate = 1;
1062         rec_dont(conn, c);
1063         tn->telrcv_state = CURL_TS_DATA;
1064         break;
1065
1066       case CURL_TS_SB:
1067         if(c == CURL_IAC)
1068         {
1069           tn->telrcv_state = CURL_TS_SE;
1070         }
1071         else
1072         {
1073           CURL_SB_ACCUM(tn,c);
1074         }
1075         break;
1076
1077       case CURL_TS_SE:
1078         if(c != CURL_SE)
1079         {
1080           if(c != CURL_IAC)
1081           {
1082             /*
1083              * This is an error.  We only expect to get "IAC IAC" or "IAC SE".
1084              * Several things may have happend.  An IAC was not doubled, the
1085              * IAC SE was left off, or another option got inserted into the
1086              * suboption are all possibilities.  If we assume that the IAC was
1087              * not doubled, and really the IAC SE was left off, we could get
1088              * into an infinate loop here.  So, instead, we terminate the
1089              * suboption, and process the partial suboption if we can.
1090              */
1091             CURL_SB_ACCUM(tn, CURL_IAC);
1092             CURL_SB_ACCUM(tn, c);
1093             tn->subpointer -= 2;
1094             CURL_SB_TERM(tn);
1095
1096             printoption(data, "In SUBOPTION processing, RCVD", CURL_IAC, c);
1097             suboption(conn);   /* handle sub-option */
1098             tn->telrcv_state = CURL_TS_IAC;
1099             goto process_iac;
1100           }
1101           CURL_SB_ACCUM(tn,c);
1102           tn->telrcv_state = CURL_TS_SB;
1103         }
1104         else
1105         {
1106           CURL_SB_ACCUM(tn, CURL_IAC);
1107           CURL_SB_ACCUM(tn, CURL_SE);
1108           tn->subpointer -= 2;
1109           CURL_SB_TERM(tn);
1110           suboption(conn);   /* handle sub-option */
1111           tn->telrcv_state = CURL_TS_DATA;
1112         }
1113         break;
1114     }
1115     ++in;
1116   }
1117   bufferflush();
1118 }
1119
1120 static CURLcode Curl_telnet_done(struct connectdata *conn,
1121                                  CURLcode status, bool premature)
1122 {
1123   struct TELNET *tn = (struct TELNET *)conn->data->reqdata.proto.telnet;
1124   (void)status; /* unused */
1125   (void)premature; /* not used */
1126
1127   curl_slist_free_all(tn->telnet_vars);
1128
1129   free(conn->data->reqdata.proto.telnet);
1130   conn->data->reqdata.proto.telnet = NULL;
1131
1132   return CURLE_OK;
1133 }
1134
1135 static CURLcode Curl_telnet(struct connectdata *conn, bool *done)
1136 {
1137   CURLcode code;
1138   struct SessionHandle *data = conn->data;
1139   curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
1140 #ifdef USE_WINSOCK
1141   HMODULE wsock2;
1142   WSOCK2_FUNC close_event_func;
1143   WSOCK2_FUNC create_event_func;
1144   WSOCK2_FUNC event_select_func;
1145   WSOCK2_FUNC enum_netevents_func;
1146   WSAEVENT event_handle;
1147   WSANETWORKEVENTS events;
1148   HANDLE stdin_handle;
1149   HANDLE objs[2];
1150   DWORD  obj_count;
1151   DWORD  wait_timeout;
1152   DWORD waitret;
1153   DWORD readfile_read;
1154 #else
1155   int interval_ms;
1156   struct pollfd pfd[2];
1157 #endif
1158   ssize_t nread;
1159   bool keepon = TRUE;
1160   char *buf = data->state.buffer;
1161   struct TELNET *tn;
1162
1163   *done = TRUE; /* unconditionally */
1164
1165   code = init_telnet(conn);
1166   if(code)
1167     return code;
1168
1169   tn = (struct TELNET *)data->reqdata.proto.telnet;
1170
1171   code = check_telnet_options(conn);
1172   if(code)
1173     return code;
1174
1175 #ifdef USE_WINSOCK
1176   /*
1177   ** This functionality only works with WinSock >= 2.0.  So,
1178   ** make sure have it.
1179   */
1180   code = check_wsock2(data);
1181   if(code)
1182     return code;
1183
1184   /* OK, so we have WinSock 2.0.  We need to dynamically */
1185   /* load ws2_32.dll and get the function pointers we need. */
1186   wsock2 = LoadLibrary("WS2_32.DLL");
1187   if(wsock2 == NULL) {
1188     failf(data,"failed to load WS2_32.DLL (%d)", ERRNO);
1189     return CURLE_FAILED_INIT;
1190   }
1191
1192   /* Grab a pointer to WSACreateEvent */
1193   create_event_func = GetProcAddress(wsock2,"WSACreateEvent");
1194   if(create_event_func == NULL) {
1195     failf(data,"failed to find WSACreateEvent function (%d)",
1196           ERRNO);
1197     FreeLibrary(wsock2);
1198     return CURLE_FAILED_INIT;
1199   }
1200
1201   /* And WSACloseEvent */
1202   close_event_func = GetProcAddress(wsock2,"WSACloseEvent");
1203   if(close_event_func == NULL) {
1204     failf(data,"failed to find WSACloseEvent function (%d)",
1205           ERRNO);
1206     FreeLibrary(wsock2);
1207     return CURLE_FAILED_INIT;
1208   }
1209
1210   /* And WSAEventSelect */
1211   event_select_func = GetProcAddress(wsock2,"WSAEventSelect");
1212   if(event_select_func == NULL) {
1213     failf(data,"failed to find WSAEventSelect function (%d)",
1214           ERRNO);
1215     FreeLibrary(wsock2);
1216     return CURLE_FAILED_INIT;
1217   }
1218
1219   /* And WSAEnumNetworkEvents */
1220   enum_netevents_func = GetProcAddress(wsock2,"WSAEnumNetworkEvents");
1221   if(enum_netevents_func == NULL) {
1222     failf(data,"failed to find WSAEnumNetworkEvents function (%d)",
1223           ERRNO);
1224     FreeLibrary(wsock2);
1225     return CURLE_FAILED_INIT;
1226   }
1227
1228   /* We want to wait for both stdin and the socket. Since
1229   ** the select() function in winsock only works on sockets
1230   ** we have to use the WaitForMultipleObjects() call.
1231   */
1232
1233   /* First, create a sockets event object */
1234   event_handle = (WSAEVENT)create_event_func();
1235   if(event_handle == WSA_INVALID_EVENT) {
1236     failf(data,"WSACreateEvent failed (%d)", SOCKERRNO);
1237     FreeLibrary(wsock2);
1238     return CURLE_FAILED_INIT;
1239   }
1240
1241   /* The get the Windows file handle for stdin */
1242   stdin_handle = GetStdHandle(STD_INPUT_HANDLE);
1243
1244   /* Create the list of objects to wait for */
1245   objs[0] = event_handle;
1246   objs[1] = stdin_handle;
1247
1248   /* Tell winsock what events we want to listen to */
1249   if(event_select_func(sockfd, event_handle, FD_READ|FD_CLOSE) == SOCKET_ERROR) {
1250     close_event_func(event_handle);
1251     FreeLibrary(wsock2);
1252     return 0;
1253   }
1254
1255   /* If stdin_handle is a pipe, use PeekNamedPipe() method to check it,
1256      else use the old WaitForMultipleObjects() way */
1257   if(GetFileType(stdin_handle) == FILE_TYPE_PIPE) {
1258     /* Don't wait for stdin_handle, just wait for event_handle */
1259     obj_count = 1;
1260     /* Check stdin_handle per 100 milliseconds */
1261     wait_timeout = 100;
1262   } else {
1263     obj_count = 2;
1264     wait_timeout = INFINITE;
1265   }
1266
1267   /* Keep on listening and act on events */
1268   while(keepon) {
1269     waitret = WaitForMultipleObjects(obj_count, objs, FALSE, wait_timeout);
1270     switch(waitret) {
1271     case WAIT_TIMEOUT:
1272     {
1273       unsigned char outbuf[2];
1274       int out_count = 0;
1275       ssize_t bytes_written;
1276       char *buffer = buf;
1277
1278       while(1) {
1279         if(!PeekNamedPipe(stdin_handle, NULL, 0, NULL, &readfile_read, NULL)) {
1280           keepon = FALSE;
1281           break;
1282         }
1283         nread = readfile_read;
1284
1285         if(!nread)
1286           break;
1287
1288         if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer),
1289                      &readfile_read, NULL)) {
1290           keepon = FALSE;
1291           break;
1292         }
1293         nread = readfile_read;
1294
1295         while(nread--) {
1296           outbuf[0] = *buffer++;
1297           out_count = 1;
1298           if(outbuf[0] == CURL_IAC)
1299             outbuf[out_count++] = CURL_IAC;
1300
1301           Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf,
1302                      out_count, &bytes_written);
1303         }
1304       }
1305     }
1306     break;
1307
1308     case WAIT_OBJECT_0 + 1:
1309     {
1310       unsigned char outbuf[2];
1311       int out_count = 0;
1312       ssize_t bytes_written;
1313       char *buffer = buf;
1314
1315       if(!ReadFile(stdin_handle, buf, sizeof(data->state.buffer),
1316                    &readfile_read, NULL)) {
1317         keepon = FALSE;
1318         break;
1319       }
1320       nread = readfile_read;
1321
1322       while(nread--) {
1323         outbuf[0] = *buffer++;
1324         out_count = 1;
1325         if(outbuf[0] == CURL_IAC)
1326           outbuf[out_count++] = CURL_IAC;
1327
1328         Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf,
1329                    out_count, &bytes_written);
1330       }
1331     }
1332     break;
1333
1334     case WAIT_OBJECT_0:
1335       if(enum_netevents_func(sockfd, event_handle, &events)
1336          != SOCKET_ERROR) {
1337         if(events.lNetworkEvents & FD_READ) {
1338           /* This reallu OUGHT to check its return code. */
1339           (void)Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread);
1340
1341           telrcv(conn, (unsigned char *)buf, nread);
1342
1343           fflush(stdout);
1344
1345           /* Negotiate if the peer has started negotiating,
1346              otherwise don't. We don't want to speak telnet with
1347              non-telnet servers, like POP or SMTP. */
1348           if(tn->please_negotiate && !tn->already_negotiated) {
1349             negotiate(conn);
1350             tn->already_negotiated = 1;
1351           }
1352         }
1353
1354         if(events.lNetworkEvents & FD_CLOSE) {
1355           keepon = FALSE;
1356         }
1357       }
1358       break;
1359     }
1360   }
1361
1362   /* We called WSACreateEvent, so call WSACloseEvent */
1363   if(close_event_func(event_handle) == FALSE) {
1364     infof(data,"WSACloseEvent failed (%d)", SOCKERRNO);
1365   }
1366
1367   /* "Forget" pointers into the library we're about to free */
1368   create_event_func = NULL;
1369   close_event_func = NULL;
1370   event_select_func = NULL;
1371   enum_netevents_func = NULL;
1372
1373   /* We called LoadLibrary, so call FreeLibrary */
1374   if(!FreeLibrary(wsock2))
1375     infof(data,"FreeLibrary(wsock2) failed (%d)", ERRNO);
1376 #else
1377   pfd[0].fd = sockfd;
1378   pfd[0].events = POLLIN;
1379   pfd[1].fd = 0;
1380   pfd[1].events = POLLIN;
1381   interval_ms = 1 * 1000;
1382
1383   while(keepon) {
1384     switch (Curl_poll(pfd, 2, interval_ms)) {
1385     case -1:                    /* error, stop reading */
1386       keepon = FALSE;
1387       continue;
1388     case 0:                     /* timeout */
1389       break;
1390     default:                    /* read! */
1391       if(pfd[1].revents & POLLIN) { /* read from stdin */
1392         unsigned char outbuf[2];
1393         int out_count = 0;
1394         ssize_t bytes_written;
1395         char *buffer = buf;
1396
1397         nread = read(0, buf, 255);
1398
1399         while(nread--) {
1400           outbuf[0] = *buffer++;
1401           out_count = 1;
1402           if(outbuf[0] == CURL_IAC)
1403             outbuf[out_count++] = CURL_IAC;
1404
1405           Curl_write(conn, conn->sock[FIRSTSOCKET], outbuf,
1406                      out_count, &bytes_written);
1407         }
1408       }
1409
1410       if(pfd[0].revents & POLLIN) {
1411         /* This OUGHT to check the return code... */
1412         (void)Curl_read(conn, sockfd, buf, BUFSIZE - 1, &nread);
1413
1414         /* if we receive 0 or less here, the server closed the connection and
1415            we bail out from this! */
1416         if(nread <= 0) {
1417           keepon = FALSE;
1418           break;
1419         }
1420
1421         telrcv(conn, (unsigned char *)buf, nread);
1422
1423         /* Negotiate if the peer has started negotiating,
1424            otherwise don't. We don't want to speak telnet with
1425            non-telnet servers, like POP or SMTP. */
1426         if(tn->please_negotiate && !tn->already_negotiated) {
1427           negotiate(conn);
1428           tn->already_negotiated = 1;
1429         }
1430       }
1431     }
1432     if(data->set.timeout) {
1433       struct timeval now;           /* current time */
1434       now = Curl_tvnow();
1435       if(Curl_tvdiff(now, conn->created) >= data->set.timeout) {
1436         failf(data, "Time-out");
1437         code = CURLE_OPERATION_TIMEDOUT;
1438         keepon = FALSE;
1439       }
1440     }
1441   }
1442 #endif
1443   /* mark this as "no further transfer wanted" */
1444   Curl_setup_transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1445
1446   return code;
1447 }
1448 #endif