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