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