1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/gateway.c,v $
5 * Purpose : Contains functions to connect to a server, possibly
6 * using a "forwarder" (i.e. HTTP proxy and/or a SOCKS4
9 * Copyright : Written by and Copyright (C) 2001-2017 the
10 * Privoxy team. https://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
40 #include <sys/types.h>
43 #include <netinet/in.h>
52 #endif /* def _WIN32 */
56 #endif /* def __BEOS__ */
61 #include "jbsockets.h"
67 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
73 #endif /* def __GLIBC__ */
74 #endif /* HAVE_POLL */
75 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
77 static jb_socket socks4_connect(const struct forward_spec *fwd,
78 const char *target_host,
80 struct client_state *csp);
82 static jb_socket socks5_connect(const struct forward_spec *fwd,
83 const char *target_host,
85 struct client_state *csp);
88 SOCKS4_REQUEST_GRANTED = 90,
89 SOCKS4_REQUEST_REJECT = 91,
90 SOCKS4_REQUEST_IDENT_FAILED = 92,
91 SOCKS4_REQUEST_IDENT_CONFLICT = 93
95 SOCKS5_REQUEST_GRANTED = 0,
96 SOCKS5_REQUEST_FAILED = 1,
97 SOCKS5_REQUEST_DENIED = 2,
98 SOCKS5_REQUEST_NETWORK_UNREACHABLE = 3,
99 SOCKS5_REQUEST_HOST_UNREACHABLE = 4,
100 SOCKS5_REQUEST_CONNECTION_REFUSED = 5,
101 SOCKS5_REQUEST_TTL_EXPIRED = 6,
102 SOCKS5_REQUEST_PROTOCOL_ERROR = 7,
103 SOCKS5_REQUEST_BAD_ADDRESS_TYPE = 8
106 /* structure of a socks client operation */
108 unsigned char vn; /* socks version number */
109 unsigned char cd; /* command code */
110 unsigned char dstport[2]; /* destination port */
111 unsigned char dstip[4]; /* destination address */
112 char userid; /* first byte of userid */
113 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
114 /* more bytes of the userid follow, terminated by a NULL */
117 /* structure of a socks server reply */
119 unsigned char vn; /* socks version number */
120 unsigned char cd; /* command code */
121 unsigned char dstport[2]; /* destination port */
122 unsigned char dstip[4]; /* destination address */
125 static const char socks_userid[] = "anonymous";
127 #ifdef FEATURE_CONNECTION_SHARING
128 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
129 #error Using FEATURE_CONNECTION_SHARING without FEATURE_CONNECTION_KEEP_ALIVE is impossible
132 #define MAX_REUSABLE_CONNECTIONS 100
134 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
135 static int mark_connection_unused(const struct reusable_connection *connection);
137 /*********************************************************************
139 * Function : initialize_reusable_connections
141 * Description : Initializes the reusable_connection structures.
142 * Must be called with connection_reuse_mutex locked.
148 *********************************************************************/
149 extern void initialize_reusable_connections(void)
151 unsigned int slot = 0;
153 #if !defined(HAVE_POLL) && !defined(_WIN32)
154 log_error(LOG_LEVEL_INFO,
155 "Detecting already dead connections might not work "
156 "correctly on your platform. In case of problems, "
157 "unset the keep-alive-timeout option.");
160 for (slot = 0; slot < SZ(reusable_connection); slot++)
162 mark_connection_closed(&reusable_connection[slot]);
165 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
169 /*********************************************************************
171 * Function : remember_connection
173 * Description : Remembers a server connection for reuse later on.
176 * 1 : connection = The server connection to remember.
180 *********************************************************************/
181 void remember_connection(const struct reusable_connection *connection)
183 unsigned int slot = 0;
184 int free_slot_found = FALSE;
186 assert(NULL != connection);
187 assert(connection->sfd != JB_INVALID_SOCKET);
189 if (mark_connection_unused(connection))
194 privoxy_mutex_lock(&connection_reuse_mutex);
196 /* Find free socket slot. */
197 for (slot = 0; slot < SZ(reusable_connection); slot++)
199 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
201 assert(reusable_connection[slot].in_use == 0);
202 log_error(LOG_LEVEL_CONNECT,
203 "Remembering socket %d for %s:%d in slot %d.",
204 connection->sfd, connection->host, connection->port, slot);
205 free_slot_found = TRUE;
210 if (!free_slot_found)
212 log_error(LOG_LEVEL_CONNECT,
213 "No free slots found to remember socket for %s:%d. Last slot %d.",
214 connection->host, connection->port, slot);
215 privoxy_mutex_unlock(&connection_reuse_mutex);
216 close_socket(connection->sfd);
220 assert(slot < SZ(reusable_connection));
221 assert(NULL != connection->host);
222 reusable_connection[slot].host = strdup_or_die(connection->host);
223 reusable_connection[slot].sfd = connection->sfd;
224 reusable_connection[slot].port = connection->port;
225 reusable_connection[slot].in_use = 0;
226 reusable_connection[slot].timestamp = connection->timestamp;
227 reusable_connection[slot].request_sent = connection->request_sent;
228 reusable_connection[slot].response_received = connection->response_received;
229 reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
230 reusable_connection[slot].requests_sent_total = connection->requests_sent_total;
232 assert(reusable_connection[slot].gateway_host == NULL);
233 assert(reusable_connection[slot].gateway_port == 0);
234 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
235 assert(reusable_connection[slot].forward_host == NULL);
236 assert(reusable_connection[slot].forward_port == 0);
238 reusable_connection[slot].forwarder_type = connection->forwarder_type;
239 if (NULL != connection->gateway_host)
241 reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
245 reusable_connection[slot].gateway_host = NULL;
247 reusable_connection[slot].gateway_port = connection->gateway_port;
249 if (NULL != connection->forward_host)
251 reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
255 reusable_connection[slot].forward_host = NULL;
257 reusable_connection[slot].forward_port = connection->forward_port;
259 privoxy_mutex_unlock(&connection_reuse_mutex);
261 #endif /* def FEATURE_CONNECTION_SHARING */
264 /*********************************************************************
266 * Function : mark_connection_closed
268 * Description : Marks a reused connection closed.
271 * 1 : closed_connection = The connection to mark as closed.
275 *********************************************************************/
276 void mark_connection_closed(struct reusable_connection *closed_connection)
278 closed_connection->in_use = FALSE;
279 closed_connection->sfd = JB_INVALID_SOCKET;
280 freez(closed_connection->host);
281 closed_connection->port = 0;
282 closed_connection->timestamp = 0;
283 closed_connection->request_sent = 0;
284 closed_connection->response_received = 0;
285 closed_connection->keep_alive_timeout = 0;
286 closed_connection->requests_sent_total = 0;
287 closed_connection->forwarder_type = SOCKS_NONE;
288 freez(closed_connection->gateway_host);
289 closed_connection->gateway_port = 0;
290 freez(closed_connection->forward_host);
291 closed_connection->forward_port = 0;
295 #ifdef FEATURE_CONNECTION_SHARING
296 /*********************************************************************
298 * Function : forget_connection
300 * Description : Removes a previously remembered connection from
301 * the list of reusable connections.
304 * 1 : sfd = The socket belonging to the connection in question.
308 *********************************************************************/
309 void forget_connection(jb_socket sfd)
311 unsigned int slot = 0;
313 assert(sfd != JB_INVALID_SOCKET);
315 privoxy_mutex_lock(&connection_reuse_mutex);
317 for (slot = 0; slot < SZ(reusable_connection); slot++)
319 if (reusable_connection[slot].sfd == sfd)
321 assert(reusable_connection[slot].in_use);
323 log_error(LOG_LEVEL_CONNECT,
324 "Forgetting socket %d for %s:%d in slot %d.",
325 sfd, reusable_connection[slot].host,
326 reusable_connection[slot].port, slot);
327 mark_connection_closed(&reusable_connection[slot]);
332 privoxy_mutex_unlock(&connection_reuse_mutex);
335 #endif /* def FEATURE_CONNECTION_SHARING */
338 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
339 /*********************************************************************
341 * Function : connection_destination_matches
343 * Description : Determines whether a remembered connection can
344 * be reused. That is, whether the destination and
345 * the forwarding settings match.
348 * 1 : connection = The connection to check.
349 * 2 : http = The destination for the connection.
350 * 3 : fwd = The forwarder settings.
352 * Returns : TRUE for yes, FALSE otherwise.
354 *********************************************************************/
355 int connection_destination_matches(const struct reusable_connection *connection,
356 const struct http_request *http,
357 const struct forward_spec *fwd)
359 if ((connection->forwarder_type != fwd->type)
360 || (connection->gateway_port != fwd->gateway_port)
361 || (connection->forward_port != fwd->forward_port)
362 || (connection->port != http->port))
367 if (( (NULL != connection->gateway_host)
368 && (NULL != fwd->gateway_host)
369 && strcmpic(connection->gateway_host, fwd->gateway_host))
370 && (connection->gateway_host != fwd->gateway_host))
372 log_error(LOG_LEVEL_CONNECT,
373 "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
374 connection->gateway_host, fwd->gateway_host);
378 if (( (NULL != connection->forward_host)
379 && (NULL != fwd->forward_host)
380 && strcmpic(connection->forward_host, fwd->forward_host))
381 && (connection->forward_host != fwd->forward_host))
383 log_error(LOG_LEVEL_CONNECT,
384 "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
385 connection->forward_host, fwd->forward_host);
389 return (!strcmpic(connection->host, http->host));
392 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
395 #ifdef FEATURE_CONNECTION_SHARING
396 /*********************************************************************
398 * Function : close_unusable_connections
400 * Description : Closes remembered connections that have timed
401 * out or have been closed on the other side.
405 * Returns : Number of connections that are still alive.
407 *********************************************************************/
408 int close_unusable_connections(void)
410 unsigned int slot = 0;
411 int connections_alive = 0;
413 privoxy_mutex_lock(&connection_reuse_mutex);
415 for (slot = 0; slot < SZ(reusable_connection); slot++)
417 if (!reusable_connection[slot].in_use
418 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
420 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
421 time_t latency = (reusable_connection[slot].response_received -
422 reusable_connection[slot].request_sent) / 2;
424 if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
426 log_error(LOG_LEVEL_CONNECT,
427 "The connection to %s:%d in slot %d timed out. "
428 "Closing socket %d. Timeout is: %d. Assumed latency: %d.",
429 reusable_connection[slot].host,
430 reusable_connection[slot].port, slot,
431 reusable_connection[slot].sfd,
432 reusable_connection[slot].keep_alive_timeout,
434 close_socket(reusable_connection[slot].sfd);
435 mark_connection_closed(&reusable_connection[slot]);
437 else if (!socket_is_still_alive(reusable_connection[slot].sfd))
439 log_error(LOG_LEVEL_CONNECT,
440 "The connection to %s:%d in slot %d is no longer usable. "
441 "Closing socket %d.", reusable_connection[slot].host,
442 reusable_connection[slot].port, slot,
443 reusable_connection[slot].sfd);
444 close_socket(reusable_connection[slot].sfd);
445 mark_connection_closed(&reusable_connection[slot]);
454 privoxy_mutex_unlock(&connection_reuse_mutex);
456 return connections_alive;
461 /*********************************************************************
463 * Function : get_reusable_connection
465 * Description : Returns an open socket to a previously remembered
466 * open connection (if there is one).
469 * 1 : http = The destination for the connection.
470 * 2 : fwd = The forwarder settings.
472 * Returns : JB_INVALID_SOCKET => No reusable connection found,
473 * otherwise a usable socket.
475 *********************************************************************/
476 static jb_socket get_reusable_connection(const struct http_request *http,
477 const struct forward_spec *fwd)
479 jb_socket sfd = JB_INVALID_SOCKET;
480 unsigned int slot = 0;
482 close_unusable_connections();
484 privoxy_mutex_lock(&connection_reuse_mutex);
486 for (slot = 0; slot < SZ(reusable_connection); slot++)
488 if (!reusable_connection[slot].in_use
489 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
491 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
493 reusable_connection[slot].in_use = TRUE;
494 sfd = reusable_connection[slot].sfd;
495 log_error(LOG_LEVEL_CONNECT,
496 "Found reusable socket %d for %s:%d in slot %d. Timestamp made %d "
497 "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
498 sfd, reusable_connection[slot].host, reusable_connection[slot].port,
499 slot, time(NULL) - reusable_connection[slot].timestamp,
500 reusable_connection[slot].keep_alive_timeout,
501 (int)(reusable_connection[slot].response_received -
502 reusable_connection[slot].request_sent),
503 reusable_connection[slot].requests_sent_total);
509 privoxy_mutex_unlock(&connection_reuse_mutex);
516 /*********************************************************************
518 * Function : mark_connection_unused
520 * Description : Gives a remembered connection free for reuse.
523 * 1 : connection = The connection in question.
525 * Returns : TRUE => Socket found and marked as unused.
526 * FALSE => Socket not found.
528 *********************************************************************/
529 static int mark_connection_unused(const struct reusable_connection *connection)
531 unsigned int slot = 0;
532 int socket_found = FALSE;
534 assert(connection->sfd != JB_INVALID_SOCKET);
536 privoxy_mutex_lock(&connection_reuse_mutex);
538 for (slot = 0; slot < SZ(reusable_connection); slot++)
540 if (reusable_connection[slot].sfd == connection->sfd)
542 assert(reusable_connection[slot].in_use);
544 log_error(LOG_LEVEL_CONNECT,
545 "Marking open socket %d for %s:%d in slot %d as unused.",
546 connection->sfd, reusable_connection[slot].host,
547 reusable_connection[slot].port, slot);
548 reusable_connection[slot].in_use = 0;
549 reusable_connection[slot].timestamp = connection->timestamp;
554 privoxy_mutex_unlock(&connection_reuse_mutex);
559 #endif /* def FEATURE_CONNECTION_SHARING */
562 /*********************************************************************
564 * Function : forwarded_connect
566 * Description : Connect to a specified web server, possibly via
567 * a HTTP proxy and/or a SOCKS proxy.
570 * 1 : fwd = the proxies to use when connecting.
571 * 2 : http = the http request and apropos headers
572 * 3 : csp = Current client state (buffers, headers, etc...)
574 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
576 *********************************************************************/
577 jb_socket forwarded_connect(const struct forward_spec *fwd,
578 struct http_request *http,
579 struct client_state *csp)
581 const char *dest_host;
583 jb_socket sfd = JB_INVALID_SOCKET;
585 #ifdef FEATURE_CONNECTION_SHARING
586 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
587 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
589 sfd = get_reusable_connection(http, fwd);
590 if (JB_INVALID_SOCKET != sfd)
595 #endif /* def FEATURE_CONNECTION_SHARING */
597 /* Figure out if we need to connect to the web server or a HTTP proxy. */
598 if (fwd->forward_host)
601 dest_host = fwd->forward_host;
602 dest_port = fwd->forward_port;
607 dest_host = http->host;
608 dest_port = http->port;
611 /* Connect, maybe using a SOCKS proxy */
615 case FORWARD_WEBSERVER:
616 sfd = connect_to(dest_host, dest_port, csp);
620 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
624 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
627 /* Should never get here */
628 log_error(LOG_LEVEL_FATAL,
629 "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
632 if (JB_INVALID_SOCKET != sfd)
634 log_error(LOG_LEVEL_CONNECT,
635 "Created new connection to %s:%d on socket %d.",
636 http->host, http->port, sfd);
645 /*********************************************************************
647 * Function : socks_fuzz
649 * Description : Wrapper around socks[45]_connect() used for fuzzing.
652 * 1 : csp = Current client state (buffers, headers, etc...)
654 * Returns : JB_ERR_OK or JB_ERR_PARSE
656 *********************************************************************/
657 extern jb_err socks_fuzz(struct client_state *csp)
660 static struct forward_spec fwd;
661 char target_host[] = "fuzz.example.org";
662 int target_port = 12345;
664 fwd.gateway_host = strdup_or_die("fuzz.example.org");
665 fwd.gateway_port = 12345;
668 socket = socks4_connect(&fwd, target_host, target_port, csp);
670 if (JB_INVALID_SOCKET != socket)
673 socket = socks5_connect(&fwd, target_host, target_port, csp);
676 if (JB_INVALID_SOCKET == socket)
678 log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
682 log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
689 /*********************************************************************
691 * Function : socks4_connect
693 * Description : Connect to the SOCKS server, and connect through
694 * it to the specified server. This handles
695 * all the SOCKS negotiation, and returns a file
696 * descriptor for a socket which can be treated as a
697 * normal (non-SOCKS) socket.
699 * Logged error messages are saved to csp->error_message
700 * and later reused by error_response() for the CGI
701 * message. strdup allocation failures are handled there.
704 * 1 : fwd = Specifies the SOCKS proxy to use.
705 * 2 : target_host = The final server to connect to.
706 * 3 : target_port = The final port to connect to.
707 * 4 : csp = Current client state (buffers, headers, etc...)
709 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
711 *********************************************************************/
712 static jb_socket socks4_connect(const struct forward_spec *fwd,
713 const char *target_host,
715 struct client_state *csp)
717 unsigned long web_server_addr;
718 char buf[BUFFER_SIZE];
719 struct socks_op *c = (struct socks_op *)buf;
720 struct socks_reply *s = (struct socks_reply *)buf;
727 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
729 /* XXX: Shouldn't the config file parser prevent this? */
730 errstr = "NULL gateway host specified.";
734 if (fwd->gateway_port <= 0)
736 errstr = "invalid gateway port specified.";
742 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
743 csp->error_message = strdup(errstr);
745 return(JB_INVALID_SOCKET);
748 /* build a socks request for connection to the web server */
750 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
752 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
757 web_server_addr = resolve_hostname_to_ip(target_host);
758 if (web_server_addr == INADDR_NONE)
760 errstr = "could not resolve target host";
761 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
766 web_server_addr = htonl(web_server_addr);
770 web_server_addr = 0x00000001;
771 n = csiz + strlen(target_host) + 1;
775 errstr = "buffer cbuf too small.";
776 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
781 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
783 * What we forward to the socks4a server should have the
784 * size of socks_op, plus the length of the userid plus
785 * its \0 byte (which we don't have to add because the
786 * first byte of the userid is counted twice as it's also
787 * part of sock_op) minus the padding bytes (which are part
788 * of the userid as well), plus the length of the target_host
789 * (which is stored csiz bytes after the beginning of the buffer),
790 * plus another \0 byte.
792 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
797 /* Should never get here */
798 log_error(LOG_LEVEL_FATAL,
799 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
801 return(JB_INVALID_SOCKET);
806 csp->error_message = strdup(errstr);
807 return(JB_INVALID_SOCKET);
812 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
813 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
814 c->dstip[0] = (unsigned char)((web_server_addr >> 24) & 0xff);
815 c->dstip[1] = (unsigned char)((web_server_addr >> 16) & 0xff);
816 c->dstip[2] = (unsigned char)((web_server_addr >> 8) & 0xff);
817 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
822 /* pass the request to the socks server */
823 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
825 if (sfd == JB_INVALID_SOCKET)
827 /* The error an its reason have already been logged by connect_to() */
828 return(JB_INVALID_SOCKET);
830 else if (write_socket(sfd, (char *)c, csiz))
832 errstr = "SOCKS4 negotiation write failed.";
833 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
837 else if (!data_is_available(sfd, csp->config->socket_timeout))
839 if (socket_is_still_alive(sfd))
841 errstr = "SOCKS4 negotiation timed out";
845 errstr = "SOCKS4 negotiation got aborted by the server";
847 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
853 if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
855 errstr = "SOCKS4 negotiation read failed.";
856 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
863 csp->error_message = strdup(errstr);
864 return(JB_INVALID_SOCKET);
869 case SOCKS4_REQUEST_GRANTED:
871 case SOCKS4_REQUEST_REJECT:
872 errstr = "SOCKS request rejected or failed.";
875 case SOCKS4_REQUEST_IDENT_FAILED:
876 errstr = "SOCKS request rejected because "
877 "SOCKS server cannot connect to identd on the client.";
880 case SOCKS4_REQUEST_IDENT_CONFLICT:
881 errstr = "SOCKS request rejected because "
882 "the client program and identd report "
883 "different user-ids.";
888 snprintf(buf, sizeof(buf),
889 "SOCKS request rejected for reason code %d.", s->cd);
893 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
894 csp->error_message = strdup(errstr);
897 return(JB_INVALID_SOCKET);
901 /*********************************************************************
903 * Function : translate_socks5_error
905 * Description : Translates a SOCKS errors to a string.
908 * 1 : socks_error = The error code to translate.
910 * Returns : The string translation.
912 *********************************************************************/
913 static const char *translate_socks5_error(int socks_error)
917 /* XXX: these should be more descriptive */
918 case SOCKS5_REQUEST_FAILED:
919 return "SOCKS5 request failed";
920 case SOCKS5_REQUEST_DENIED:
921 return "SOCKS5 request denied";
922 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
923 return "SOCKS5 network unreachable";
924 case SOCKS5_REQUEST_HOST_UNREACHABLE:
925 return "SOCKS5 destination host unreachable";
926 case SOCKS5_REQUEST_CONNECTION_REFUSED:
927 return "SOCKS5 connection refused";
928 case SOCKS5_REQUEST_TTL_EXPIRED:
929 return "SOCKS5 TTL expired";
930 case SOCKS5_REQUEST_PROTOCOL_ERROR:
931 return "SOCKS5 client protocol error";
932 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
933 return "SOCKS5 domain names unsupported";
934 case SOCKS5_REQUEST_GRANTED:
935 return "everything's peachy";
937 return "SOCKS5 negotiation protocol error";
942 /*********************************************************************
944 * Function : socks5_connect
946 * Description : Connect to the SOCKS server, and connect through
947 * it to the specified server. This handles
948 * all the SOCKS negotiation, and returns a file
949 * descriptor for a socket which can be treated as a
950 * normal (non-SOCKS) socket.
953 * 1 : fwd = Specifies the SOCKS proxy to use.
954 * 2 : target_host = The final server to connect to.
955 * 3 : target_port = The final port to connect to.
956 * 4 : csp = Current client state (buffers, headers, etc...)
958 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
960 *********************************************************************/
961 static jb_socket socks5_connect(const struct forward_spec *fwd,
962 const char *target_host,
964 struct client_state *csp)
966 #define SIZE_SOCKS5_REPLY_IPV4 10
967 #define SIZE_SOCKS5_REPLY_IPV6 22
968 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
971 char sbuf[SIZE_SOCKS5_REPLY_IPV6];
972 size_t client_pos = 0;
976 const char *errstr = NULL;
978 assert(fwd->gateway_host);
979 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
981 errstr = "NULL gateway host specified";
985 if (fwd->gateway_port <= 0)
988 * XXX: currently this can't happen because in
989 * case of invalid gateway ports we use the defaults.
990 * Of course we really shouldn't do that.
992 errstr = "invalid gateway port specified";
996 hostlen = strlen(target_host);
997 if (hostlen > (size_t)255)
999 errstr = "target host name is longer than 255 characters";
1003 if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1005 /* Should never get here */
1006 log_error(LOG_LEVEL_FATAL,
1007 "SOCKS5 impossible internal error - bad SOCKS type");
1014 assert(errstr != NULL);
1015 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1016 csp->error_message = strdup(errstr);
1017 return(JB_INVALID_SOCKET);
1022 if (!err && read_socket(sfd, sbuf, 2) != 2)
1024 /* pass the request to the socks server */
1025 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1027 if (sfd == JB_INVALID_SOCKET)
1029 errstr = "socks5 server unreachable";
1030 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1031 /* Free the generic error message provided by connect_to() */
1032 freez(csp->error_message);
1033 csp->error_message = strdup(errstr);
1034 return(JB_INVALID_SOCKET);
1038 cbuf[client_pos++] = '\x05'; /* Version */
1040 if (fwd->auth_username && fwd->auth_password)
1042 cbuf[client_pos++] = '\x02'; /* Two authentication methods supported */
1043 cbuf[client_pos++] = '\x02'; /* Username/password */
1047 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1049 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1051 if (write_socket(sfd, cbuf, client_pos))
1053 errstr = "SOCKS5 negotiation write failed";
1054 csp->error_message = strdup(errstr);
1055 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1057 return(JB_INVALID_SOCKET);
1059 if (!data_is_available(sfd, csp->config->socket_timeout))
1061 if (socket_is_still_alive(sfd))
1063 errstr = "SOCKS5 negotiation timed out";
1067 errstr = "SOCKS5 negotiation got aborted by the server";
1072 if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1075 errstr = "SOCKS5 negotiation read failed";
1079 if (!err && (sbuf[0] != '\x05'))
1081 errstr = "SOCKS5 negotiation protocol version error";
1085 if (!err && (sbuf[1] == '\xff'))
1087 errstr = "SOCKS5 authentication required";
1091 if (!err && (sbuf[1] == '\x02'))
1093 /* check cbuf overflow */
1094 size_t auth_len = strlen(fwd->auth_username) + strlen(fwd->auth_password) + 3;
1095 if (auth_len > sizeof(cbuf))
1097 errstr = "SOCKS5 username and/or password too long";
1104 cbuf[client_pos++] = '\x01'; /* Version */
1105 cbuf[client_pos++] = (char)strlen(fwd->auth_username);
1107 memcpy(cbuf + client_pos, fwd->auth_username, strlen(fwd->auth_username));
1108 client_pos += strlen(fwd->auth_username);
1109 cbuf[client_pos++] = (char)strlen(fwd->auth_password);
1110 memcpy(cbuf + client_pos, fwd->auth_password, strlen(fwd->auth_password));
1111 client_pos += strlen(fwd->auth_password);
1113 if (write_socket(sfd, cbuf, client_pos))
1115 errstr = "SOCKS5 negotiation auth write failed";
1116 csp->error_message = strdup(errstr);
1117 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1119 return(JB_INVALID_SOCKET);
1122 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1124 errstr = "SOCKS5 negotiation auth read failed";
1129 if (!err && (sbuf[1] != '\x00'))
1131 errstr = "SOCKS5 authentication failed";
1135 else if (!err && (sbuf[1] != '\x00'))
1137 errstr = "SOCKS5 negotiation protocol error";
1143 assert(errstr != NULL);
1144 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1145 csp->error_message = strdup(errstr);
1148 return(JB_INVALID_SOCKET);
1152 cbuf[client_pos++] = '\x05'; /* Version */
1153 cbuf[client_pos++] = '\x01'; /* TCP connect */
1154 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1155 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1156 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1157 assert(sizeof(cbuf) - client_pos > (size_t)255);
1158 /* Using strncpy because we really want the nul byte padding. */
1159 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1160 client_pos += (hostlen & 0xffu);
1161 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1162 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1165 if (write_socket(sfd, cbuf, client_pos))
1167 errstr = "SOCKS5 negotiation write failed";
1168 csp->error_message = strdup(errstr);
1169 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1172 return(JB_INVALID_SOCKET);
1176 * Optimistically send the HTTP request with the initial
1177 * SOCKS request if the user enabled the use of Tor extensions,
1178 * the CONNECT method isn't being used (in which case the client
1179 * doesn't send data until it gets our 200 response) and the
1180 * client request has actually been completely read already.
1182 if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1183 && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1185 char *client_headers = list_to_text(csp->headers);
1186 size_t header_length;
1188 if (client_headers == NULL)
1190 log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1192 list_remove_all(csp->headers);
1193 header_length= strlen(client_headers);
1195 log_error(LOG_LEVEL_CONNECT,
1196 "Optimistically sending %d bytes of client headers intended for %s",
1197 header_length, csp->http->hostport);
1199 if (write_socket(sfd, client_headers, header_length))
1201 log_error(LOG_LEVEL_CONNECT,
1202 "optimistically writing header to: %s failed: %E", csp->http->hostport);
1203 freez(client_headers);
1204 return(JB_INVALID_SOCKET);
1206 freez(client_headers);
1207 if (csp->expected_client_content_length != 0)
1209 unsigned long long buffered_request_bytes =
1210 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1211 log_error(LOG_LEVEL_CONNECT,
1212 "Optimistically sending %llu bytes of client body. Expected %llu",
1213 csp->expected_client_content_length, buffered_request_bytes);
1214 assert(csp->expected_client_content_length == buffered_request_bytes);
1215 if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1217 log_error(LOG_LEVEL_CONNECT,
1218 "optimistically writing %llu bytes of client body to: %s failed: %E",
1219 buffered_request_bytes, csp->http->hostport);
1220 return(JB_INVALID_SOCKET);
1222 clear_iob(csp->client_iob);
1227 server_size = read_socket(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4);
1228 if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1230 errstr = "SOCKS5 negotiation read failed";
1234 if (sbuf[0] != '\x05')
1236 errstr = "SOCKS5 negotiation protocol version error";
1238 else if (sbuf[2] != '\x00')
1240 errstr = "SOCKS5 negotiation protocol error";
1242 else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1244 errstr = translate_socks5_error(sbuf[1]);
1248 if (sbuf[3] == '\x04')
1251 * The address field contains an IPv6 address
1252 * which means we didn't get the whole reply
1253 * yet. Read and discard the rest of it to make
1254 * sure it isn't treated as HTTP data later on.
1256 server_size = read_socket(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE);
1257 if (server_size != SOCKS5_REPLY_DIFFERENCE)
1259 errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1262 else if (sbuf[3] != '\x01')
1264 errstr = "SOCKS5 reply contains unsupported address type";
1273 assert(errstr != NULL);
1274 csp->error_message = strdup(errstr);
1275 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1279 return(JB_INVALID_SOCKET);