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