Resync
[CMakeLuaTailorHgBridge.git] / CMakeLua / Utilities / cmcurl-7.19.0 / lib / socks.c
blobf91a5fa103f517b20a345fd9cf569326ec9a8412
1 /***************************************************************************
2 * _ _ ____ _
3 * Project ___| | | | _ \| |
4 * / __| | | | |_) | |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2008, Daniel Stenberg, <daniel@haxx.se>, et al.
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.
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.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 * $Id: socks.c,v 1.1.1.1 2008-09-23 16:32:05 hoffman Exp $
22 ***************************************************************************/
24 #include "setup.h"
26 #include <string.h>
28 #ifdef NEED_MALLOC_H
29 #include <malloc.h>
30 #endif
31 #ifdef HAVE_STDLIB_H
32 #include <stdlib.h>
33 #endif
34 #ifdef HAVE_SYS_SOCKET_H
35 #include <sys/socket.h>
36 #endif
37 #ifdef HAVE_NETINET_IN_H
38 #include <netinet/in.h>
39 #endif
40 #ifdef HAVE_ARPA_INET_H
41 #include <arpa/inet.h>
42 #endif
44 #include "urldata.h"
45 #include "sendf.h"
46 #include "strequal.h"
47 #include "select.h"
48 #include "connect.h"
49 #include "timeval.h"
50 #include "socks.h"
52 /* The last #include file should be: */
53 #include "memdebug.h"
56 * Helper read-from-socket functions. Does the same as Curl_read() but it
57 * blocks until all bytes amount of buffersize will be read. No more, no less.
59 * This is STUPID BLOCKING behaviour which we frown upon, but right now this
60 * is what we have...
62 static int blockread_all(struct connectdata *conn, /* connection data */
63 curl_socket_t sockfd, /* read from this socket */
64 char *buf, /* store read data here */
65 ssize_t buffersize, /* max amount to read */
66 ssize_t *n, /* amount bytes read */
67 long conn_timeout) /* timeout for data wait
68 relative to
69 conn->created */
71 ssize_t nread;
72 ssize_t allread = 0;
73 int result;
74 struct timeval tvnow;
75 long conntime;
76 *n = 0;
77 do {
78 tvnow = Curl_tvnow();
79 /* calculating how long connection is establishing */
80 conntime = Curl_tvdiff(tvnow, conn->created);
81 if(conntime > conn_timeout) {
82 /* we already got the timeout */
83 result = ~CURLE_OK;
84 break;
86 if(Curl_socket_ready(sockfd, CURL_SOCKET_BAD,
87 (int)(conn_timeout - conntime)) <= 0) {
88 result = ~CURLE_OK;
89 break;
91 result = Curl_read(conn, sockfd, buf, buffersize, &nread);
92 if(result)
93 break;
95 if(buffersize == nread) {
96 allread += nread;
97 *n = allread;
98 result = CURLE_OK;
99 break;
101 if(!nread) {
102 result = ~CURLE_OK;
103 break;
106 buffersize -= nread;
107 buf += nread;
108 allread += nread;
109 } while(1);
110 return result;
114 * This function logs in to a SOCKS4 proxy and sends the specifics to the final
115 * destination server.
117 * Reference :
118 * http://socks.permeo.com/protocol/socks4.protocol
120 * Note :
121 * Set protocol4a=true for "SOCKS 4A (Simple Extension to SOCKS 4 Protocol)"
122 * Nonsupport "Identification Protocol (RFC1413)"
124 CURLcode Curl_SOCKS4(const char *proxy_name,
125 const char *hostname,
126 int remote_port,
127 int sockindex,
128 struct connectdata *conn,
129 bool protocol4a)
131 #define SOCKS4REQLEN 262
132 unsigned char socksreq[SOCKS4REQLEN]; /* room for SOCKS4 request incl. user
133 id */
134 int result;
135 CURLcode code;
136 curl_socket_t sock = conn->sock[sockindex];
137 long timeout;
138 struct SessionHandle *data = conn->data;
140 /* get timeout */
141 timeout = Curl_timeleft(conn, NULL, TRUE);
143 if(timeout < 0) {
144 /* time-out, bail out, go home */
145 failf(data, "Connection time-out");
146 return CURLE_OPERATION_TIMEDOUT;
149 Curl_nonblock(sock, FALSE);
152 * Compose socks4 request
154 * Request format
156 * +----+----+----+----+----+----+----+----+----+----+....+----+
157 * | VN | CD | DSTPORT | DSTIP | USERID |NULL|
158 * +----+----+----+----+----+----+----+----+----+----+....+----+
159 * # of bytes: 1 1 2 4 variable 1
162 socksreq[0] = 4; /* version (SOCKS4) */
163 socksreq[1] = 1; /* connect */
164 *((unsigned short*)&socksreq[2]) = htons((unsigned short)remote_port);
166 /* DNS resolve only for SOCKS4, not SOCKS4a */
167 if (!protocol4a) {
168 struct Curl_dns_entry *dns;
169 Curl_addrinfo *hp=NULL;
170 int rc;
172 rc = Curl_resolv(conn, hostname, remote_port, &dns);
174 if(rc == CURLRESOLV_ERROR)
175 return CURLE_COULDNT_RESOLVE_PROXY;
177 if(rc == CURLRESOLV_PENDING)
178 /* this requires that we're in "wait for resolve" state */
179 rc = Curl_wait_for_resolv(conn, &dns);
182 * We cannot use 'hostent' as a struct that Curl_resolv() returns. It
183 * returns a Curl_addrinfo pointer that may not always look the same.
185 if(dns)
186 hp=dns->addr;
187 if(hp) {
188 char buf[64];
189 unsigned short ip[4];
190 Curl_printable_address(hp, buf, sizeof(buf));
192 if(4 == sscanf( buf, "%hu.%hu.%hu.%hu",
193 &ip[0], &ip[1], &ip[2], &ip[3])) {
194 /* Set DSTIP */
195 socksreq[4] = (unsigned char)ip[0];
196 socksreq[5] = (unsigned char)ip[1];
197 socksreq[6] = (unsigned char)ip[2];
198 socksreq[7] = (unsigned char)ip[3];
200 else
201 hp = NULL; /* fail! */
203 Curl_resolv_unlock(data, dns); /* not used anymore from now on */
206 if(!hp) {
207 failf(data, "Failed to resolve \"%s\" for SOCKS4 connect.",
208 hostname);
209 return CURLE_COULDNT_RESOLVE_HOST;
214 * This is currently not supporting "Identification Protocol (RFC1413)".
216 socksreq[8] = 0; /* ensure empty userid is NUL-terminated */
217 if(proxy_name)
218 strlcat((char*)socksreq + 8, proxy_name, sizeof(socksreq) - 8);
221 * Make connection
224 ssize_t actualread;
225 ssize_t written;
226 ssize_t hostnamelen = 0;
227 int packetsize = 9 +
228 (int)strlen((char*)socksreq + 8); /* size including NUL */
230 /* If SOCKS4a, set special invalid IP address 0.0.0.x */
231 if (protocol4a) {
232 socksreq[4] = 0;
233 socksreq[5] = 0;
234 socksreq[6] = 0;
235 socksreq[7] = 1;
236 /* If still enough room in buffer, also append hostname */
237 hostnamelen = (ssize_t)strlen(hostname) + 1; /* length including NUL */
238 if (packetsize + hostnamelen <= SOCKS4REQLEN)
239 strcpy((char*)socksreq + packetsize, hostname);
240 else
241 hostnamelen = 0; /* Flag: hostname did not fit in buffer */
244 /* Send request */
245 code = Curl_write_plain(conn, sock, (char *)socksreq,
246 packetsize + hostnamelen,
247 &written);
248 if((code != CURLE_OK) || (written != packetsize + hostnamelen)) {
249 failf(data, "Failed to send SOCKS4 connect request.");
250 return CURLE_COULDNT_CONNECT;
252 if (protocol4a && hostnamelen == 0) {
253 /* SOCKS4a with very long hostname - send that name separately */
254 hostnamelen = (ssize_t)strlen(hostname) + 1;
255 code = Curl_write_plain(conn, sock, (char *)hostname, hostnamelen,
256 &written);
257 if((code != CURLE_OK) || (written != hostnamelen)) {
258 failf(data, "Failed to send SOCKS4 connect request.");
259 return CURLE_COULDNT_CONNECT;
263 packetsize = 8; /* receive data size */
265 /* Receive response */
266 result = blockread_all(conn, sock, (char *)socksreq, packetsize,
267 &actualread, timeout);
268 if((result != CURLE_OK) || (actualread != packetsize)) {
269 failf(data, "Failed to receive SOCKS4 connect request ack.");
270 return CURLE_COULDNT_CONNECT;
274 * Response format
276 * +----+----+----+----+----+----+----+----+
277 * | VN | CD | DSTPORT | DSTIP |
278 * +----+----+----+----+----+----+----+----+
279 * # of bytes: 1 1 2 4
281 * VN is the version of the reply code and should be 0. CD is the result
282 * code with one of the following values:
284 * 90: request granted
285 * 91: request rejected or failed
286 * 92: request rejected because SOCKS server cannot connect to
287 * identd on the client
288 * 93: request rejected because the client program and identd
289 * report different user-ids
292 /* wrong version ? */
293 if(socksreq[0] != 0) {
294 failf(data,
295 "SOCKS4 reply has wrong version, version should be 4.");
296 return CURLE_COULDNT_CONNECT;
299 /* Result */
300 switch(socksreq[1])
302 case 90:
303 if (protocol4a)
304 infof(data, "SOCKS4a request granted.\n");
305 else
306 infof(data, "SOCKS4 request granted.\n");
307 break;
308 case 91:
309 failf(data,
310 "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
311 ", request rejected or failed.",
312 (unsigned char)socksreq[4], (unsigned char)socksreq[5],
313 (unsigned char)socksreq[6], (unsigned char)socksreq[7],
314 (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
315 socksreq[1]);
316 return CURLE_COULDNT_CONNECT;
317 case 92:
318 failf(data,
319 "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
320 ", request rejected because SOCKS server cannot connect to "
321 "identd on the client.",
322 (unsigned char)socksreq[4], (unsigned char)socksreq[5],
323 (unsigned char)socksreq[6], (unsigned char)socksreq[7],
324 (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
325 socksreq[1]);
326 return CURLE_COULDNT_CONNECT;
327 case 93:
328 failf(data,
329 "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
330 ", request rejected because the client program and identd "
331 "report different user-ids.",
332 (unsigned char)socksreq[4], (unsigned char)socksreq[5],
333 (unsigned char)socksreq[6], (unsigned char)socksreq[7],
334 (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
335 socksreq[1]);
336 return CURLE_COULDNT_CONNECT;
337 default:
338 failf(data,
339 "Can't complete SOCKS4 connection to %d.%d.%d.%d:%d. (%d)"
340 ", Unknown.",
341 (unsigned char)socksreq[4], (unsigned char)socksreq[5],
342 (unsigned char)socksreq[6], (unsigned char)socksreq[7],
343 (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
344 socksreq[1]);
345 return CURLE_COULDNT_CONNECT;
349 Curl_nonblock(sock, TRUE);
351 return CURLE_OK; /* Proxy was successful! */
355 * This function logs in to a SOCKS5 proxy and sends the specifics to the final
356 * destination server.
358 CURLcode Curl_SOCKS5(const char *proxy_name,
359 const char *proxy_password,
360 const char *hostname,
361 int remote_port,
362 int sockindex,
363 struct connectdata *conn)
366 According to the RFC1928, section "6. Replies". This is what a SOCK5
367 replies:
369 +----+-----+-------+------+----------+----------+
370 |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
371 +----+-----+-------+------+----------+----------+
372 | 1 | 1 | X'00' | 1 | Variable | 2 |
373 +----+-----+-------+------+----------+----------+
375 Where:
377 o VER protocol version: X'05'
378 o REP Reply field:
379 o X'00' succeeded
382 unsigned char socksreq[600]; /* room for large user/pw (255 max each) */
383 ssize_t actualread;
384 ssize_t written;
385 int result;
386 CURLcode code;
387 curl_socket_t sock = conn->sock[sockindex];
388 struct SessionHandle *data = conn->data;
389 long timeout;
390 bool socks5_resolve_local = (bool)(data->set.proxytype == CURLPROXY_SOCKS5);
391 const size_t hostname_len = strlen(hostname);
392 ssize_t packetsize = 0;
394 /* RFC1928 chapter 5 specifies max 255 chars for domain name in packet */
395 if(!socks5_resolve_local && hostname_len > 255)
397 infof(conn->data,"SOCKS5: server resolving disabled for hostnames of "
398 "length > 255 [actual len=%d]\n", hostname_len);
399 socks5_resolve_local = TRUE;
402 /* get timeout */
403 timeout = Curl_timeleft(conn, NULL, TRUE);
405 if(timeout < 0) {
406 /* time-out, bail out, go home */
407 failf(data, "Connection time-out");
408 return CURLE_OPERATION_TIMEDOUT;
411 Curl_nonblock(sock, TRUE);
413 /* wait until socket gets connected */
414 result = Curl_socket_ready(CURL_SOCKET_BAD, sock, (int)timeout);
416 if(-1 == result) {
417 failf(conn->data, "SOCKS5: no connection here");
418 return CURLE_COULDNT_CONNECT;
420 else if(0 == result) {
421 failf(conn->data, "SOCKS5: connection timeout");
422 return CURLE_OPERATION_TIMEDOUT;
425 if(result & CURL_CSELECT_ERR) {
426 failf(conn->data, "SOCKS5: error occured during connection");
427 return CURLE_COULDNT_CONNECT;
430 socksreq[0] = 5; /* version */
431 socksreq[1] = (char)(proxy_name ? 2 : 1); /* number of methods (below) */
432 socksreq[2] = 0; /* no authentication */
433 socksreq[3] = 2; /* username/password */
435 Curl_nonblock(sock, FALSE);
437 code = Curl_write_plain(conn, sock, (char *)socksreq, (2 + (int)socksreq[1]),
438 &written);
439 if((code != CURLE_OK) || (written != (2 + (int)socksreq[1]))) {
440 failf(data, "Unable to send initial SOCKS5 request.");
441 return CURLE_COULDNT_CONNECT;
444 Curl_nonblock(sock, TRUE);
446 result = Curl_socket_ready(sock, CURL_SOCKET_BAD, (int)timeout);
448 if(-1 == result) {
449 failf(conn->data, "SOCKS5 nothing to read");
450 return CURLE_COULDNT_CONNECT;
452 else if(0 == result) {
453 failf(conn->data, "SOCKS5 read timeout");
454 return CURLE_OPERATION_TIMEDOUT;
457 if(result & CURL_CSELECT_ERR) {
458 failf(conn->data, "SOCKS5 read error occured");
459 return CURLE_RECV_ERROR;
462 Curl_nonblock(sock, FALSE);
464 result=blockread_all(conn, sock, (char *)socksreq, 2, &actualread, timeout);
465 if((result != CURLE_OK) || (actualread != 2)) {
466 failf(data, "Unable to receive initial SOCKS5 response.");
467 return CURLE_COULDNT_CONNECT;
470 if(socksreq[0] != 5) {
471 failf(data, "Received invalid version in initial SOCKS5 response.");
472 return CURLE_COULDNT_CONNECT;
474 if(socksreq[1] == 0) {
475 /* Nothing to do, no authentication needed */
478 else if(socksreq[1] == 2) {
479 /* Needs user name and password */
480 size_t userlen, pwlen;
481 int len;
482 if(proxy_name && proxy_password) {
483 userlen = strlen(proxy_name);
484 pwlen = strlen(proxy_password);
486 else {
487 userlen = 0;
488 pwlen = 0;
491 /* username/password request looks like
492 * +----+------+----------+------+----------+
493 * |VER | ULEN | UNAME | PLEN | PASSWD |
494 * +----+------+----------+------+----------+
495 * | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
496 * +----+------+----------+------+----------+
498 len = 0;
499 socksreq[len++] = 1; /* username/pw subnegotiation version */
500 socksreq[len++] = (char) userlen;
501 memcpy(socksreq + len, proxy_name, (int) userlen);
502 len += userlen;
503 socksreq[len++] = (char) pwlen;
504 memcpy(socksreq + len, proxy_password, (int) pwlen);
505 len += pwlen;
507 code = Curl_write_plain(conn, sock, (char *)socksreq, len, &written);
508 if((code != CURLE_OK) || (len != written)) {
509 failf(data, "Failed to send SOCKS5 sub-negotiation request.");
510 return CURLE_COULDNT_CONNECT;
513 result=blockread_all(conn, sock, (char *)socksreq, 2, &actualread,
514 timeout);
515 if((result != CURLE_OK) || (actualread != 2)) {
516 failf(data, "Unable to receive SOCKS5 sub-negotiation response.");
517 return CURLE_COULDNT_CONNECT;
520 /* ignore the first (VER) byte */
521 if(socksreq[1] != 0) { /* status */
522 failf(data, "User was rejected by the SOCKS5 server (%d %d).",
523 socksreq[0], socksreq[1]);
524 return CURLE_COULDNT_CONNECT;
527 /* Everything is good so far, user was authenticated! */
529 else {
530 /* error */
531 if(socksreq[1] == 1) {
532 failf(data,
533 "SOCKS5 GSSAPI per-message authentication is not supported.");
534 return CURLE_COULDNT_CONNECT;
536 else if(socksreq[1] == 255) {
537 if(!proxy_name || !*proxy_name) {
538 failf(data,
539 "No authentication method was acceptable. (It is quite likely"
540 " that the SOCKS5 server wanted a username/password, since none"
541 " was supplied to the server on this connection.)");
543 else {
544 failf(data, "No authentication method was acceptable.");
546 return CURLE_COULDNT_CONNECT;
548 else {
549 failf(data,
550 "Undocumented SOCKS5 mode attempted to be used by server.");
551 return CURLE_COULDNT_CONNECT;
555 /* Authentication is complete, now specify destination to the proxy */
556 socksreq[0] = 5; /* version (SOCKS5) */
557 socksreq[1] = 1; /* connect */
558 socksreq[2] = 0; /* must be zero */
560 if(!socks5_resolve_local) {
561 packetsize = (ssize_t)(5 + hostname_len + 2);
563 socksreq[3] = 3; /* ATYP: domain name = 3 */
564 socksreq[4] = (char) hostname_len; /* address length */
565 memcpy(&socksreq[5], hostname, hostname_len); /* address bytes w/o NULL */
567 *((unsigned short*)&socksreq[hostname_len+5]) =
568 htons((unsigned short)remote_port);
570 else {
571 struct Curl_dns_entry *dns;
572 Curl_addrinfo *hp=NULL;
573 int rc = Curl_resolv(conn, hostname, remote_port, &dns);
575 packetsize = 10;
577 socksreq[3] = 1; /* IPv4 = 1 */
579 if(rc == CURLRESOLV_ERROR)
580 return CURLE_COULDNT_RESOLVE_HOST;
582 if(rc == CURLRESOLV_PENDING)
583 /* this requires that we're in "wait for resolve" state */
584 rc = Curl_wait_for_resolv(conn, &dns);
587 * We cannot use 'hostent' as a struct that Curl_resolv() returns. It
588 * returns a Curl_addrinfo pointer that may not always look the same.
590 if(dns)
591 hp=dns->addr;
592 if(hp) {
593 char buf[64];
594 unsigned short ip[4];
595 Curl_printable_address(hp, buf, sizeof(buf));
597 if(4 == sscanf( buf, "%hu.%hu.%hu.%hu",
598 &ip[0], &ip[1], &ip[2], &ip[3])) {
599 socksreq[4] = (unsigned char)ip[0];
600 socksreq[5] = (unsigned char)ip[1];
601 socksreq[6] = (unsigned char)ip[2];
602 socksreq[7] = (unsigned char)ip[3];
604 else
605 hp = NULL; /* fail! */
607 Curl_resolv_unlock(data, dns); /* not used anymore from now on */
609 if(!hp) {
610 failf(data, "Failed to resolve \"%s\" for SOCKS5 connect.",
611 hostname);
612 return CURLE_COULDNT_RESOLVE_HOST;
615 *((unsigned short*)&socksreq[8]) = htons((unsigned short)remote_port);
618 code = Curl_write_plain(conn, sock, (char *)socksreq, packetsize, &written);
619 if((code != CURLE_OK) || (written != packetsize)) {
620 failf(data, "Failed to send SOCKS5 connect request.");
621 return CURLE_COULDNT_CONNECT;
624 packetsize = 10; /* minimum packet size is 10 */
626 result = blockread_all(conn, sock, (char *)socksreq, packetsize,
627 &actualread, timeout);
628 if((result != CURLE_OK) || (actualread != packetsize)) {
629 failf(data, "Failed to receive SOCKS5 connect request ack.");
630 return CURLE_COULDNT_CONNECT;
633 if(socksreq[0] != 5) { /* version */
634 failf(data,
635 "SOCKS5 reply has wrong version, version should be 5.");
636 return CURLE_COULDNT_CONNECT;
638 if(socksreq[1] != 0) { /* Anything besides 0 is an error */
639 failf(data,
640 "Can't complete SOCKS5 connection to %d.%d.%d.%d:%d. (%d)",
641 (unsigned char)socksreq[4], (unsigned char)socksreq[5],
642 (unsigned char)socksreq[6], (unsigned char)socksreq[7],
643 (unsigned int)ntohs(*(unsigned short*)(&socksreq[8])),
644 socksreq[1]);
645 return CURLE_COULDNT_CONNECT;
648 /* Fix: in general, returned BND.ADDR is variable length parameter by RFC
649 1928, so the reply packet should be read until the end to avoid errors at
650 subsequent protocol level.
652 +----+-----+-------+------+----------+----------+
653 |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
654 +----+-----+-------+------+----------+----------+
655 | 1 | 1 | X'00' | 1 | Variable | 2 |
656 +----+-----+-------+------+----------+----------+
658 ATYP:
659 o IP v4 address: X'01', BND.ADDR = 4 byte
660 o domain name: X'03', BND.ADDR = [ 1 byte length, string ]
661 o IP v6 address: X'04', BND.ADDR = 16 byte
664 /* Calculate real packet size */
665 if(socksreq[3] == 3) {
666 /* domain name */
667 int addrlen = (int) socksreq[4];
668 packetsize = 5 + addrlen + 2;
670 else if(socksreq[3] == 4) {
671 /* IPv6 */
672 packetsize = 4 + 16 + 2;
675 /* At this point we already read first 10 bytes */
676 if(packetsize > 10) {
677 packetsize -= 10;
678 result = blockread_all(conn, sock, (char *)&socksreq[10], packetsize,
679 &actualread, timeout);
680 if((result != CURLE_OK) || (actualread != packetsize)) {
681 failf(data, "Failed to receive SOCKS5 connect request ack.");
682 return CURLE_COULDNT_CONNECT;
686 Curl_nonblock(sock, TRUE);
687 return CURLE_OK; /* Proxy was successful! */