Merge branch 'master' of github.com:bagder/curl
[platform/upstream/curl.git] / lib / socks.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2010, 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  ***************************************************************************/
22
23 #include "setup.h"
24
25 #if !defined(CURL_DISABLE_PROXY) || defined(USE_WINDOWS_SSPI)
26 #include <string.h>
27
28 #ifdef HAVE_STDLIB_H
29 #include <stdlib.h>
30 #endif
31 #ifdef HAVE_SYS_SOCKET_H
32 #include <sys/socket.h>
33 #endif
34 #ifdef HAVE_NETINET_IN_H
35 #include <netinet/in.h>
36 #endif
37 #ifdef HAVE_ARPA_INET_H
38 #include <arpa/inet.h>
39 #endif
40
41 #include "urldata.h"
42 #include "sendf.h"
43 #include "strequal.h"
44 #include "select.h"
45 #include "connect.h"
46 #include "timeval.h"
47 #include "socks.h"
48
49 /* The last #include file should be: */
50 #include "memdebug.h"
51
52 /*
53  * Helper read-from-socket functions. Does the same as Curl_read() but it
54  * blocks until all bytes amount of buffersize will be read. No more, no less.
55  *
56  * This is STUPID BLOCKING behaviour which we frown upon, but right now this
57  * is what we have...
58  */
59 int Curl_blockread_all(struct connectdata *conn, /* connection data */
60                        curl_socket_t sockfd,     /* read from this socket */
61                        char *buf,                /* store read data here */
62                        ssize_t buffersize,       /* max amount to read */
63                        ssize_t *n,               /* amount bytes read */
64                        long conn_timeout)        /* timeout for data wait
65                                                     relative to
66                                                     conn->created */
67 {
68   ssize_t nread;
69   ssize_t allread = 0;
70   int result;
71   struct timeval tvnow;
72   long conntime;
73   *n = 0;
74   for(;;) {
75     tvnow = Curl_tvnow();
76     /* calculating how long connection is establishing */
77     conntime = Curl_tvdiff(tvnow, conn->created);
78     if(conntime > conn_timeout) {
79       /* we already got the timeout */
80       result = ~CURLE_OK;
81       break;
82     }
83     if(Curl_socket_ready(sockfd, CURL_SOCKET_BAD,
84                    (int)(conn_timeout - conntime)) <= 0) {
85       result = ~CURLE_OK;
86       break;
87     }
88     result = Curl_read_plain(sockfd, buf, buffersize, &nread);
89     if(result)
90       break;
91
92     if(buffersize == nread) {
93       allread += nread;
94       *n = allread;
95       result = CURLE_OK;
96       break;
97     }
98     if(!nread) {
99       result = ~CURLE_OK;
100       break;
101     }
102
103     buffersize -= nread;
104     buf += nread;
105     allread += nread;
106   }
107   return result;
108 }
109
110 /*
111 * This function logs in to a SOCKS4 proxy and sends the specifics to the final
112 * destination server.
113 *
114 * Reference :
115 *   http://socks.permeo.com/protocol/socks4.protocol
116 *
117 * Note :
118 *   Set protocol4a=true for  "SOCKS 4A (Simple Extension to SOCKS 4 Protocol)"
119 *   Nonsupport "Identification Protocol (RFC1413)"
120 */
121 CURLcode Curl_SOCKS4(const char *proxy_name,
122                      const char *hostname,
123                      int remote_port,
124                      int sockindex,
125                      struct connectdata *conn,
126                      bool protocol4a)
127 {
128 #define SOCKS4REQLEN 262
129   unsigned char socksreq[SOCKS4REQLEN]; /* room for SOCKS4 request incl. user
130                                            id */
131   int result;
132   CURLcode code;
133   curl_socket_t sock = conn->sock[sockindex];
134   long timeout;
135   struct SessionHandle *data = conn->data;
136
137   /* get timeout */
138   timeout = Curl_timeleft(conn, NULL, TRUE);
139
140   if(timeout < 0) {
141     /* time-out, bail out, go home */
142     failf(data, "Connection time-out");
143     return CURLE_OPERATION_TIMEDOUT;
144   }
145
146   curlx_nonblock(sock, FALSE);
147
148   /*
149    * Compose socks4 request
150    *
151    * Request format
152    *
153    *     +----+----+----+----+----+----+----+----+----+----+....+----+
154    *     | VN | CD | DSTPORT |      DSTIP        | USERID       |NULL|
155    *     +----+----+----+----+----+----+----+----+----+----+....+----+
156    * # of bytes:  1    1      2              4           variable       1
157    */
158
159   socksreq[0] = 4; /* version (SOCKS4) */
160   socksreq[1] = 1; /* connect */
161   *((unsigned short*)&socksreq[2]) = htons((unsigned short)remote_port);
162
163   /* DNS resolve only for SOCKS4, not SOCKS4a */
164   if (!protocol4a) {
165     struct Curl_dns_entry *dns;
166     Curl_addrinfo *hp=NULL;
167     int rc;
168
169     rc = Curl_resolv(conn, hostname, remote_port, &dns);
170
171     if(rc == CURLRESOLV_ERROR)
172       return CURLE_COULDNT_RESOLVE_PROXY;
173
174     if(rc == CURLRESOLV_PENDING)
175       /* ignores the return code, but 'dns' remains NULL on failure */
176       (void)Curl_wait_for_resolv(conn, &dns);
177
178     /*
179      * We cannot use 'hostent' as a struct that Curl_resolv() returns.  It
180      * returns a Curl_addrinfo pointer that may not always look the same.
181      */
182     if(dns)
183       hp=dns->addr;
184     if(hp) {
185       char buf[64];
186       unsigned short ip[4];
187       Curl_printable_address(hp, buf, sizeof(buf));
188
189       if(4 == sscanf( buf, "%hu.%hu.%hu.%hu",
190                       &ip[0], &ip[1], &ip[2], &ip[3])) {
191         /* Set DSTIP */
192         socksreq[4] = (unsigned char)ip[0];
193         socksreq[5] = (unsigned char)ip[1];
194         socksreq[6] = (unsigned char)ip[2];
195         socksreq[7] = (unsigned char)ip[3];
196       }
197       else
198         hp = NULL; /* fail! */
199
200       Curl_resolv_unlock(data, dns); /* not used anymore from now on */
201
202     }
203     if(!hp) {
204       failf(data, "Failed to resolve \"%s\" for SOCKS4 connect.",
205             hostname);
206       return CURLE_COULDNT_RESOLVE_HOST;
207     }
208   }
209
210   /*
211    * This is currently not supporting "Identification Protocol (RFC1413)".
212    */
213   socksreq[8] = 0; /* ensure empty userid is NUL-terminated */
214   if(proxy_name)
215     strlcat((char*)socksreq + 8, proxy_name, sizeof(socksreq) - 8);
216
217   /*
218    * Make connection
219    */
220   {
221     ssize_t actualread;
222     ssize_t written;
223     ssize_t hostnamelen = 0;
224     int packetsize = 9 +
225       (int)strlen((char*)socksreq + 8); /* size including NUL */
226
227     /* If SOCKS4a, set special invalid IP address 0.0.0.x */
228     if (protocol4a) {
229       socksreq[4] = 0;
230       socksreq[5] = 0;
231       socksreq[6] = 0;
232       socksreq[7] = 1;
233       /* If still enough room in buffer, also append hostname */
234       hostnamelen = (ssize_t)strlen(hostname) + 1; /* length including NUL */
235       if (packetsize + hostnamelen <= SOCKS4REQLEN)
236         strcpy((char*)socksreq + packetsize, hostname);
237       else
238         hostnamelen = 0; /* Flag: hostname did not fit in buffer */
239     }
240
241     /* Send request */
242     code = Curl_write_plain(conn, sock, (char *)socksreq,
243                             packetsize + hostnamelen,
244                             &written);
245     if((code != CURLE_OK) || (written != packetsize + hostnamelen)) {
246       failf(data, "Failed to send SOCKS4 connect request.");
247       return CURLE_COULDNT_CONNECT;
248     }
249     if (protocol4a && hostnamelen == 0) {
250       /* SOCKS4a with very long hostname - send that name separately */
251       hostnamelen = (ssize_t)strlen(hostname) + 1;
252       code = Curl_write_plain(conn, sock, (char *)hostname, hostnamelen,
253                               &written);
254       if((code != CURLE_OK) || (written != hostnamelen)) {
255         failf(data, "Failed to send SOCKS4 connect request.");
256         return CURLE_COULDNT_CONNECT;
257       }
258     }
259
260     packetsize = 8; /* receive data size */
261
262     /* Receive response */
263     result = Curl_blockread_all(conn, sock, (char *)socksreq, packetsize,
264                            &actualread, timeout);
265     if((result != CURLE_OK) || (actualread != packetsize)) {
266       failf(data, "Failed to receive SOCKS4 connect request ack.");
267       return CURLE_COULDNT_CONNECT;
268     }
269
270     /*
271      * Response format
272      *
273      *     +----+----+----+----+----+----+----+----+
274      *     | VN | CD | DSTPORT |      DSTIP        |
275      *     +----+----+----+----+----+----+----+----+
276      * # of bytes:  1    1      2              4
277      *
278      * VN is the version of the reply code and should be 0. CD is the result
279      * code with one of the following values:
280      *
281      * 90: request granted
282      * 91: request rejected or failed
283      * 92: request rejected because SOCKS server cannot connect to
284      *     identd on the client
285      * 93: request rejected because the client program and identd
286      *     report different user-ids
287      */
288
289     /* wrong version ? */
290     if(socksreq[0] != 0) {
291       failf(data,
292             "SOCKS4 reply has wrong version, version should be 4.");
293       return CURLE_COULDNT_CONNECT;
294     }
295
296     /* Result */
297     switch(socksreq[1])
298     {
299     case 90:
300       if (protocol4a)
301         infof(data, "SOCKS4a request granted.\n");
302       else
303         infof(data, "SOCKS4 request granted.\n");
304       break;
305     case 91:
306       failf(data,
307             "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
308             ", request rejected or failed.",
309             (unsigned char)socksreq[4], (unsigned char)socksreq[5],
310             (unsigned char)socksreq[6], (unsigned char)socksreq[7],
311             (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
312             socksreq[1]);
313       return CURLE_COULDNT_CONNECT;
314     case 92:
315       failf(data,
316             "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
317             ", request rejected because SOCKS server cannot connect to "
318             "identd on the client.",
319             (unsigned char)socksreq[4], (unsigned char)socksreq[5],
320             (unsigned char)socksreq[6], (unsigned char)socksreq[7],
321             (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
322             socksreq[1]);
323       return CURLE_COULDNT_CONNECT;
324     case 93:
325       failf(data,
326             "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
327             ", request rejected because the client program and identd "
328             "report different user-ids.",
329             (unsigned char)socksreq[4], (unsigned char)socksreq[5],
330             (unsigned char)socksreq[6], (unsigned char)socksreq[7],
331             (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
332             socksreq[1]);
333       return CURLE_COULDNT_CONNECT;
334     default:
335       failf(data,
336             "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
337             ", Unknown.",
338             (unsigned char)socksreq[4], (unsigned char)socksreq[5],
339             (unsigned char)socksreq[6], (unsigned char)socksreq[7],
340             (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
341             socksreq[1]);
342       return CURLE_COULDNT_CONNECT;
343     }
344   }
345
346   curlx_nonblock(sock, TRUE);
347
348   return CURLE_OK; /* Proxy was successful! */
349 }
350
351 /*
352  * This function logs in to a SOCKS5 proxy and sends the specifics to the final
353  * destination server.
354  */
355 CURLcode Curl_SOCKS5(const char *proxy_name,
356                      const char *proxy_password,
357                      const char *hostname,
358                      int remote_port,
359                      int sockindex,
360                      struct connectdata *conn)
361 {
362   /*
363     According to the RFC1928, section "6.  Replies". This is what a SOCK5
364     replies:
365
366         +----+-----+-------+------+----------+----------+
367         |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
368         +----+-----+-------+------+----------+----------+
369         | 1  |  1  | X'00' |  1   | Variable |    2     |
370         +----+-----+-------+------+----------+----------+
371
372     Where:
373
374     o  VER    protocol version: X'05'
375     o  REP    Reply field:
376     o  X'00' succeeded
377   */
378
379   unsigned char socksreq[600]; /* room for large user/pw (255 max each) */
380   ssize_t actualread;
381   ssize_t written;
382   int result;
383   CURLcode code;
384   curl_socket_t sock = conn->sock[sockindex];
385   struct SessionHandle *data = conn->data;
386   long timeout;
387   bool socks5_resolve_local = (bool)(data->set.proxytype == CURLPROXY_SOCKS5);
388   const size_t hostname_len = strlen(hostname);
389   ssize_t packetsize = 0;
390
391   /* RFC1928 chapter 5 specifies max 255 chars for domain name in packet */
392   if(!socks5_resolve_local && hostname_len > 255)
393   {
394     infof(conn->data,"SOCKS5: server resolving disabled for hostnames of "
395           "length > 255 [actual len=%zu]\n", hostname_len);
396     socks5_resolve_local = TRUE;
397   }
398
399   /* get timeout */
400   timeout = Curl_timeleft(conn, NULL, TRUE);
401
402   if(timeout < 0) {
403     /* time-out, bail out, go home */
404     failf(data, "Connection time-out");
405     return CURLE_OPERATION_TIMEDOUT;
406   }
407
408   curlx_nonblock(sock, TRUE);
409
410   /* wait until socket gets connected */
411   result = Curl_socket_ready(CURL_SOCKET_BAD, sock, (int)timeout);
412
413   if(-1 == result) {
414     failf(conn->data, "SOCKS5: no connection here");
415     return CURLE_COULDNT_CONNECT;
416   }
417   else if(0 == result) {
418     failf(conn->data, "SOCKS5: connection timeout");
419     return CURLE_OPERATION_TIMEDOUT;
420   }
421
422   if(result & CURL_CSELECT_ERR) {
423     failf(conn->data, "SOCKS5: error occured during connection");
424     return CURLE_COULDNT_CONNECT;
425   }
426
427   socksreq[0] = 5; /* version */
428 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
429   socksreq[1] = (char)(proxy_name ? 3 : 2); /* number of methods (below) */
430   socksreq[2] = 0; /* no authentication */
431   socksreq[3] = 1; /* gssapi */
432   socksreq[4] = 2; /* username/password */
433 #else
434   socksreq[1] = (char)(proxy_name ? 2 : 1); /* number of methods (below) */
435   socksreq[2] = 0; /* no authentication */
436   socksreq[3] = 2; /* username/password */
437 #endif
438
439   curlx_nonblock(sock, FALSE);
440
441   code = Curl_write_plain(conn, sock, (char *)socksreq, (2 + (int)socksreq[1]),
442                           &written);
443   if((code != CURLE_OK) || (written != (2 + (int)socksreq[1]))) {
444     failf(data, "Unable to send initial SOCKS5 request.");
445     return CURLE_COULDNT_CONNECT;
446   }
447
448   curlx_nonblock(sock, TRUE);
449
450   result = Curl_socket_ready(sock, CURL_SOCKET_BAD, (int)timeout);
451
452   if(-1 == result) {
453     failf(conn->data, "SOCKS5 nothing to read");
454     return CURLE_COULDNT_CONNECT;
455   }
456   else if(0 == result) {
457     failf(conn->data, "SOCKS5 read timeout");
458     return CURLE_OPERATION_TIMEDOUT;
459   }
460
461   if(result & CURL_CSELECT_ERR) {
462     failf(conn->data, "SOCKS5 read error occured");
463     return CURLE_RECV_ERROR;
464   }
465
466   curlx_nonblock(sock, FALSE);
467
468   result=Curl_blockread_all(conn, sock, (char *)socksreq, 2, &actualread,
469                             timeout);
470   if((result != CURLE_OK) || (actualread != 2)) {
471     failf(data, "Unable to receive initial SOCKS5 response.");
472     return CURLE_COULDNT_CONNECT;
473   }
474
475   if(socksreq[0] != 5) {
476     failf(data, "Received invalid version in initial SOCKS5 response.");
477     return CURLE_COULDNT_CONNECT;
478   }
479   if(socksreq[1] == 0) {
480     /* Nothing to do, no authentication needed */
481     ;
482   }
483 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
484   else if(socksreq[1] == 1) {
485     code = Curl_SOCKS5_gssapi_negotiate(sockindex, conn);
486     if(code != CURLE_OK) {
487       failf(data, "Unable to negotiate SOCKS5 gssapi context.");
488       return CURLE_COULDNT_CONNECT;
489     }
490   }
491 #endif
492   else if(socksreq[1] == 2) {
493     /* Needs user name and password */
494     size_t userlen, pwlen;
495     int len;
496     if(proxy_name && proxy_password) {
497       userlen = strlen(proxy_name);
498       pwlen = strlen(proxy_password);
499     }
500     else {
501       userlen = 0;
502       pwlen = 0;
503     }
504
505     /*   username/password request looks like
506      * +----+------+----------+------+----------+
507      * |VER | ULEN |  UNAME   | PLEN |  PASSWD  |
508      * +----+------+----------+------+----------+
509      * | 1  |  1   | 1 to 255 |  1   | 1 to 255 |
510      * +----+------+----------+------+----------+
511      */
512     len = 0;
513     socksreq[len++] = 1;    /* username/pw subnegotiation version */
514     socksreq[len++] = (char) userlen;
515     memcpy(socksreq + len, proxy_name, userlen);
516     len += (int)userlen;
517     socksreq[len++] = (char) pwlen;
518     memcpy(socksreq + len, proxy_password, pwlen);
519     len += (int)pwlen;
520
521     code = Curl_write_plain(conn, sock, (char *)socksreq, len, &written);
522     if((code != CURLE_OK) || (len != written)) {
523       failf(data, "Failed to send SOCKS5 sub-negotiation request.");
524       return CURLE_COULDNT_CONNECT;
525     }
526
527     result=Curl_blockread_all(conn, sock, (char *)socksreq, 2, &actualread,
528                          timeout);
529     if((result != CURLE_OK) || (actualread != 2)) {
530       failf(data, "Unable to receive SOCKS5 sub-negotiation response.");
531       return CURLE_COULDNT_CONNECT;
532     }
533
534     /* ignore the first (VER) byte */
535     if(socksreq[1] != 0) { /* status */
536       failf(data, "User was rejected by the SOCKS5 server (%d %d).",
537             socksreq[0], socksreq[1]);
538       return CURLE_COULDNT_CONNECT;
539     }
540
541     /* Everything is good so far, user was authenticated! */
542   }
543   else {
544     /* error */
545 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
546     if(socksreq[1] == 255) {
547 #else
548     if(socksreq[1] == 1) {
549       failf(data,
550             "SOCKS5 GSSAPI per-message authentication is not supported.");
551       return CURLE_COULDNT_CONNECT;
552     }
553     else if(socksreq[1] == 255) {
554 #endif
555       if(!proxy_name || !*proxy_name) {
556         failf(data,
557               "No authentication method was acceptable. (It is quite likely"
558               " that the SOCKS5 server wanted a username/password, since none"
559               " was supplied to the server on this connection.)");
560       }
561       else {
562         failf(data, "No authentication method was acceptable.");
563       }
564       return CURLE_COULDNT_CONNECT;
565     }
566     else {
567       failf(data,
568             "Undocumented SOCKS5 mode attempted to be used by server.");
569       return CURLE_COULDNT_CONNECT;
570     }
571   }
572
573   /* Authentication is complete, now specify destination to the proxy */
574   socksreq[0] = 5; /* version (SOCKS5) */
575   socksreq[1] = 1; /* connect */
576   socksreq[2] = 0; /* must be zero */
577
578   if(!socks5_resolve_local) {
579     packetsize = (ssize_t)(5 + hostname_len + 2);
580
581     socksreq[3] = 3; /* ATYP: domain name = 3 */
582     socksreq[4] = (char) hostname_len; /* address length */
583     memcpy(&socksreq[5], hostname, hostname_len); /* address bytes w/o NULL */
584
585     *((unsigned short*)&socksreq[hostname_len+5]) =
586       htons((unsigned short)remote_port);
587   }
588   else {
589     struct Curl_dns_entry *dns;
590     Curl_addrinfo *hp=NULL;
591     int rc = Curl_resolv(conn, hostname, remote_port, &dns);
592
593     packetsize = 10;
594
595     socksreq[3] = 1; /* IPv4 = 1 */
596
597     if(rc == CURLRESOLV_ERROR)
598       return CURLE_COULDNT_RESOLVE_HOST;
599
600     if(rc == CURLRESOLV_PENDING) {
601       /* this requires that we're in "wait for resolve" state */
602       rc = Curl_wait_for_resolv(conn, &dns);
603       if(rc)
604         return rc;
605     }
606
607     /*
608      * We cannot use 'hostent' as a struct that Curl_resolv() returns.  It
609      * returns a Curl_addrinfo pointer that may not always look the same.
610      */
611     if(dns)
612       hp=dns->addr;
613     if(hp) {
614       char buf[64];
615       unsigned short ip[4];
616       Curl_printable_address(hp, buf, sizeof(buf));
617
618       if(4 == sscanf( buf, "%hu.%hu.%hu.%hu",
619                       &ip[0], &ip[1], &ip[2], &ip[3])) {
620         socksreq[4] = (unsigned char)ip[0];
621         socksreq[5] = (unsigned char)ip[1];
622         socksreq[6] = (unsigned char)ip[2];
623         socksreq[7] = (unsigned char)ip[3];
624       }
625       else
626         hp = NULL; /* fail! */
627
628       Curl_resolv_unlock(data, dns); /* not used anymore from now on */
629     }
630     if(!hp) {
631       failf(data, "Failed to resolve \"%s\" for SOCKS5 connect.",
632             hostname);
633       return CURLE_COULDNT_RESOLVE_HOST;
634     }
635
636     *((unsigned short*)&socksreq[8]) = htons((unsigned short)remote_port);
637   }
638
639 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
640   if(conn->socks5_gssapi_enctype) {
641     failf(data, "SOCKS5 gssapi protection not yet implemented.");
642   } else
643 #endif
644   code = Curl_write_plain(conn, sock, (char *)socksreq, packetsize, &written);
645   if((code != CURLE_OK) || (written != packetsize)) {
646     failf(data, "Failed to send SOCKS5 connect request.");
647     return CURLE_COULDNT_CONNECT;
648   }
649
650   packetsize = 10; /* minimum packet size is 10 */
651
652 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
653   if(conn->socks5_gssapi_enctype) {
654     failf(data, "SOCKS5 gssapi protection not yet implemented.");
655   } else
656 #endif
657     result = Curl_blockread_all(conn, sock, (char *)socksreq, packetsize,
658                            &actualread, timeout);
659   if((result != CURLE_OK) || (actualread != packetsize)) {
660     failf(data, "Failed to receive SOCKS5 connect request ack.");
661     return CURLE_COULDNT_CONNECT;
662   }
663
664   if(socksreq[0] != 5) { /* version */
665     failf(data,
666           "SOCKS5 reply has wrong version, version should be 5.");
667     return CURLE_COULDNT_CONNECT;
668   }
669   if(socksreq[1] != 0) { /* Anything besides 0 is an error */
670       failf(data,
671             "Can't complete SOCKS5 connection to %d.%d.%d.%d:%d. (%d)",
672             (unsigned char)socksreq[4], (unsigned char)socksreq[5],
673             (unsigned char)socksreq[6], (unsigned char)socksreq[7],
674             (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
675             socksreq[1]);
676       return CURLE_COULDNT_CONNECT;
677   }
678
679   /* Fix: in general, returned BND.ADDR is variable length parameter by RFC
680      1928, so the reply packet should be read until the end to avoid errors at
681      subsequent protocol level.
682
683     +----+-----+-------+------+----------+----------+
684     |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
685     +----+-----+-------+------+----------+----------+
686     | 1  |  1  | X'00' |  1   | Variable |    2     |
687     +----+-----+-------+------+----------+----------+
688
689      ATYP:
690      o  IP v4 address: X'01', BND.ADDR = 4 byte
691      o  domain name:  X'03', BND.ADDR = [ 1 byte length, string ]
692      o  IP v6 address: X'04', BND.ADDR = 16 byte
693      */
694
695   /* Calculate real packet size */
696   if(socksreq[3] == 3) {
697     /* domain name */
698     int addrlen = (int) socksreq[4];
699     packetsize = 5 + addrlen + 2;
700   }
701   else if(socksreq[3] == 4) {
702     /* IPv6 */
703     packetsize = 4 + 16 + 2;
704   }
705
706   /* At this point we already read first 10 bytes */
707 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
708   if(!conn->socks5_gssapi_enctype) {
709     /* decrypt_gssapi_blockread already read the whole packet */
710 #endif
711     if(packetsize > 10) {
712       packetsize -= 10;
713       result = Curl_blockread_all(conn, sock, (char *)&socksreq[10],
714                                   packetsize, &actualread, timeout);
715       if((result != CURLE_OK) || (actualread != packetsize)) {
716         failf(data, "Failed to receive SOCKS5 connect request ack.");
717         return CURLE_COULDNT_CONNECT;
718       }
719     }
720 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
721   }
722 #endif
723
724   curlx_nonblock(sock, TRUE);
725   return CURLE_OK; /* Proxy was successful! */
726 }
727
728 #endif /* CURL_DISABLE_PROXY */
729