socks5: please static code analyzer
[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++] = (unsigned char) userlen;
515     if(proxy_name && userlen)
516       memcpy(socksreq + len, proxy_name, userlen);
517     len += (int)userlen;
518     socksreq[len++] = (unsigned char) pwlen;
519     if(proxy_password && pwlen)
520       memcpy(socksreq + len, proxy_password, pwlen);
521     len += (int)pwlen;
522
523     code = Curl_write_plain(conn, sock, (char *)socksreq, len, &written);
524     if((code != CURLE_OK) || (len != written)) {
525       failf(data, "Failed to send SOCKS5 sub-negotiation request.");
526       return CURLE_COULDNT_CONNECT;
527     }
528
529     result=Curl_blockread_all(conn, sock, (char *)socksreq, 2, &actualread,
530                          timeout);
531     if((result != CURLE_OK) || (actualread != 2)) {
532       failf(data, "Unable to receive SOCKS5 sub-negotiation response.");
533       return CURLE_COULDNT_CONNECT;
534     }
535
536     /* ignore the first (VER) byte */
537     if(socksreq[1] != 0) { /* status */
538       failf(data, "User was rejected by the SOCKS5 server (%d %d).",
539             socksreq[0], socksreq[1]);
540       return CURLE_COULDNT_CONNECT;
541     }
542
543     /* Everything is good so far, user was authenticated! */
544   }
545   else {
546     /* error */
547 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
548     if(socksreq[1] == 255) {
549 #else
550     if(socksreq[1] == 1) {
551       failf(data,
552             "SOCKS5 GSSAPI per-message authentication is not supported.");
553       return CURLE_COULDNT_CONNECT;
554     }
555     else if(socksreq[1] == 255) {
556 #endif
557       if(!proxy_name || !*proxy_name) {
558         failf(data,
559               "No authentication method was acceptable. (It is quite likely"
560               " that the SOCKS5 server wanted a username/password, since none"
561               " was supplied to the server on this connection.)");
562       }
563       else {
564         failf(data, "No authentication method was acceptable.");
565       }
566       return CURLE_COULDNT_CONNECT;
567     }
568     else {
569       failf(data,
570             "Undocumented SOCKS5 mode attempted to be used by server.");
571       return CURLE_COULDNT_CONNECT;
572     }
573   }
574
575   /* Authentication is complete, now specify destination to the proxy */
576   socksreq[0] = 5; /* version (SOCKS5) */
577   socksreq[1] = 1; /* connect */
578   socksreq[2] = 0; /* must be zero */
579
580   if(!socks5_resolve_local) {
581     packetsize = (ssize_t)(5 + hostname_len + 2);
582
583     socksreq[3] = 3; /* ATYP: domain name = 3 */
584     socksreq[4] = (char) hostname_len; /* address length */
585     memcpy(&socksreq[5], hostname, hostname_len); /* address bytes w/o NULL */
586
587     *((unsigned short*)&socksreq[hostname_len+5]) =
588       htons((unsigned short)remote_port);
589   }
590   else {
591     struct Curl_dns_entry *dns;
592     Curl_addrinfo *hp=NULL;
593     int rc = Curl_resolv(conn, hostname, remote_port, &dns);
594
595     packetsize = 10;
596
597     socksreq[3] = 1; /* IPv4 = 1 */
598
599     if(rc == CURLRESOLV_ERROR)
600       return CURLE_COULDNT_RESOLVE_HOST;
601
602     if(rc == CURLRESOLV_PENDING) {
603       /* this requires that we're in "wait for resolve" state */
604       rc = Curl_wait_for_resolv(conn, &dns);
605       if(rc)
606         return rc;
607     }
608
609     /*
610      * We cannot use 'hostent' as a struct that Curl_resolv() returns.  It
611      * returns a Curl_addrinfo pointer that may not always look the same.
612      */
613     if(dns)
614       hp=dns->addr;
615     if(hp) {
616       char buf[64];
617       unsigned short ip[4];
618       Curl_printable_address(hp, buf, sizeof(buf));
619
620       if(4 == sscanf( buf, "%hu.%hu.%hu.%hu",
621                       &ip[0], &ip[1], &ip[2], &ip[3])) {
622         socksreq[4] = (unsigned char)ip[0];
623         socksreq[5] = (unsigned char)ip[1];
624         socksreq[6] = (unsigned char)ip[2];
625         socksreq[7] = (unsigned char)ip[3];
626       }
627       else
628         hp = NULL; /* fail! */
629
630       Curl_resolv_unlock(data, dns); /* not used anymore from now on */
631     }
632     if(!hp) {
633       failf(data, "Failed to resolve \"%s\" for SOCKS5 connect.",
634             hostname);
635       return CURLE_COULDNT_RESOLVE_HOST;
636     }
637
638     *((unsigned short*)&socksreq[8]) = htons((unsigned short)remote_port);
639   }
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   } else
645 #endif
646   code = Curl_write_plain(conn, sock, (char *)socksreq, packetsize, &written);
647   if((code != CURLE_OK) || (written != packetsize)) {
648     failf(data, "Failed to send SOCKS5 connect request.");
649     return CURLE_COULDNT_CONNECT;
650   }
651
652   packetsize = 10; /* minimum packet size is 10 */
653
654 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
655   if(conn->socks5_gssapi_enctype) {
656     failf(data, "SOCKS5 gssapi protection not yet implemented.");
657   } else
658 #endif
659     result = Curl_blockread_all(conn, sock, (char *)socksreq, packetsize,
660                            &actualread, timeout);
661   if((result != CURLE_OK) || (actualread != packetsize)) {
662     failf(data, "Failed to receive SOCKS5 connect request ack.");
663     return CURLE_COULDNT_CONNECT;
664   }
665
666   if(socksreq[0] != 5) { /* version */
667     failf(data,
668           "SOCKS5 reply has wrong version, version should be 5.");
669     return CURLE_COULDNT_CONNECT;
670   }
671   if(socksreq[1] != 0) { /* Anything besides 0 is an error */
672       failf(data,
673             "Can't complete SOCKS5 connection to %d.%d.%d.%d:%d. (%d)",
674             (unsigned char)socksreq[4], (unsigned char)socksreq[5],
675             (unsigned char)socksreq[6], (unsigned char)socksreq[7],
676             (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
677             socksreq[1]);
678       return CURLE_COULDNT_CONNECT;
679   }
680
681   /* Fix: in general, returned BND.ADDR is variable length parameter by RFC
682      1928, so the reply packet should be read until the end to avoid errors at
683      subsequent protocol level.
684
685     +----+-----+-------+------+----------+----------+
686     |VER | REP |  RSV  | ATYP | BND.ADDR | BND.PORT |
687     +----+-----+-------+------+----------+----------+
688     | 1  |  1  | X'00' |  1   | Variable |    2     |
689     +----+-----+-------+------+----------+----------+
690
691      ATYP:
692      o  IP v4 address: X'01', BND.ADDR = 4 byte
693      o  domain name:  X'03', BND.ADDR = [ 1 byte length, string ]
694      o  IP v6 address: X'04', BND.ADDR = 16 byte
695      */
696
697   /* Calculate real packet size */
698   if(socksreq[3] == 3) {
699     /* domain name */
700     int addrlen = (int) socksreq[4];
701     packetsize = 5 + addrlen + 2;
702   }
703   else if(socksreq[3] == 4) {
704     /* IPv6 */
705     packetsize = 4 + 16 + 2;
706   }
707
708   /* At this point we already read first 10 bytes */
709 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
710   if(!conn->socks5_gssapi_enctype) {
711     /* decrypt_gssapi_blockread already read the whole packet */
712 #endif
713     if(packetsize > 10) {
714       packetsize -= 10;
715       result = Curl_blockread_all(conn, sock, (char *)&socksreq[10],
716                                   packetsize, &actualread, timeout);
717       if((result != CURLE_OK) || (actualread != packetsize)) {
718         failf(data, "Failed to receive SOCKS5 connect request ack.");
719         return CURLE_COULDNT_CONNECT;
720       }
721     }
722 #if defined(HAVE_GSSAPI) || defined(USE_WINDOWS_SSPI)
723   }
724 #endif
725
726   curlx_nonblock(sock, TRUE);
727   return CURLE_OK; /* Proxy was successful! */
728 }
729
730 #endif /* CURL_DISABLE_PROXY */
731