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-2020 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].auth_username == NULL);
235 assert(reusable_connection[slot].auth_password == NULL);
236 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
237 assert(reusable_connection[slot].forward_host == NULL);
238 assert(reusable_connection[slot].forward_port == 0);
240 reusable_connection[slot].forwarder_type = connection->forwarder_type;
241 if (NULL != connection->gateway_host)
243 reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
247 reusable_connection[slot].gateway_host = NULL;
249 reusable_connection[slot].gateway_port = connection->gateway_port;
250 if (NULL != connection->auth_username)
252 reusable_connection[slot].auth_username = strdup_or_die(connection->auth_username);
256 reusable_connection[slot].auth_username = NULL;
258 if (NULL != connection->auth_password)
260 reusable_connection[slot].auth_password = strdup_or_die(connection->auth_password);
264 reusable_connection[slot].auth_password = NULL;
267 if (NULL != connection->forward_host)
269 reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
273 reusable_connection[slot].forward_host = NULL;
275 reusable_connection[slot].forward_port = connection->forward_port;
277 privoxy_mutex_unlock(&connection_reuse_mutex);
279 #endif /* def FEATURE_CONNECTION_SHARING */
282 /*********************************************************************
284 * Function : mark_connection_closed
286 * Description : Marks a reused connection closed.
289 * 1 : closed_connection = The connection to mark as closed.
293 *********************************************************************/
294 void mark_connection_closed(struct reusable_connection *closed_connection)
296 closed_connection->in_use = FALSE;
297 closed_connection->sfd = JB_INVALID_SOCKET;
298 freez(closed_connection->host);
299 closed_connection->port = 0;
300 closed_connection->timestamp = 0;
301 closed_connection->request_sent = 0;
302 closed_connection->response_received = 0;
303 closed_connection->keep_alive_timeout = 0;
304 closed_connection->requests_sent_total = 0;
305 closed_connection->forwarder_type = SOCKS_NONE;
306 freez(closed_connection->gateway_host);
307 closed_connection->gateway_port = 0;
308 freez(closed_connection->auth_username);
309 freez(closed_connection->auth_password);
310 freez(closed_connection->forward_host);
311 closed_connection->forward_port = 0;
315 #ifdef FEATURE_CONNECTION_SHARING
316 /*********************************************************************
318 * Function : forget_connection
320 * Description : Removes a previously remembered connection from
321 * the list of reusable connections.
324 * 1 : sfd = The socket belonging to the connection in question.
328 *********************************************************************/
329 void forget_connection(jb_socket sfd)
331 unsigned int slot = 0;
333 assert(sfd != JB_INVALID_SOCKET);
335 privoxy_mutex_lock(&connection_reuse_mutex);
337 for (slot = 0; slot < SZ(reusable_connection); slot++)
339 if (reusable_connection[slot].sfd == sfd)
341 assert(reusable_connection[slot].in_use);
343 log_error(LOG_LEVEL_CONNECT,
344 "Forgetting socket %d for %s:%d in slot %d.",
345 sfd, reusable_connection[slot].host,
346 reusable_connection[slot].port, slot);
347 mark_connection_closed(&reusable_connection[slot]);
352 privoxy_mutex_unlock(&connection_reuse_mutex);
355 #endif /* def FEATURE_CONNECTION_SHARING */
358 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
359 /*********************************************************************
361 * Function : connection_detail_matches
363 * Description : Helper function for connection_destination_matches().
364 * Compares strings which can be NULL.
367 * 1 : connection_detail = The connection detail to compare.
368 * 2 : fowarder_detail = The forwarder detail to compare.
370 * Returns : TRUE for yes, FALSE otherwise.
372 *********************************************************************/
373 static int connection_detail_matches(const char *connection_detail,
374 const char *forwarder_detail)
376 if (connection_detail == NULL && forwarder_detail == NULL)
378 /* Both details are unset. */
382 if ((connection_detail == NULL && forwarder_detail != NULL)
383 || (connection_detail != NULL && forwarder_detail == NULL))
385 /* Only one detail isn't set. */
389 /* Both details are set, but do they match? */
390 return(!strcmpic(connection_detail, forwarder_detail));
395 /*********************************************************************
397 * Function : connection_destination_matches
399 * Description : Determines whether a remembered connection can
400 * be reused. That is, whether the destination and
401 * the forwarding settings match.
404 * 1 : connection = The connection to check.
405 * 2 : http = The destination for the connection.
406 * 3 : fwd = The forwarder settings.
408 * Returns : TRUE for yes, FALSE otherwise.
410 *********************************************************************/
411 int connection_destination_matches(const struct reusable_connection *connection,
412 const struct http_request *http,
413 const struct forward_spec *fwd)
415 if ((connection->forwarder_type != fwd->type)
416 || (connection->gateway_port != fwd->gateway_port)
417 || (connection->forward_port != fwd->forward_port)
418 || (connection->port != http->port))
423 if (!connection_detail_matches(connection->gateway_host, fwd->gateway_host))
425 log_error(LOG_LEVEL_CONNECT,
426 "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
427 connection->gateway_host != NULL ? connection->gateway_host : "none",
428 fwd->gateway_host != NULL ? fwd->gateway_host : "none");
432 if (!connection_detail_matches(connection->auth_username, fwd->auth_username))
434 log_error(LOG_LEVEL_CONNECT, "Socks user name mismatch. "
435 "Previous user name: %s. Current user name: %s",
436 connection->auth_username != NULL ? connection->auth_username : "none",
437 fwd->auth_username != NULL ? fwd->auth_username : "none");
441 if (!connection_detail_matches(connection->auth_password, fwd->auth_password))
443 log_error(LOG_LEVEL_CONNECT, "Socks user name mismatch. "
444 "Previous password: %s. Current password: %s",
445 connection->auth_password != NULL ? connection->auth_password : "none",
446 fwd->auth_password != NULL ? fwd->auth_password : "none");
450 if (!connection_detail_matches(connection->forward_host, fwd->forward_host))
452 log_error(LOG_LEVEL_CONNECT,
453 "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
454 connection->forward_host != NULL ? connection->forward_host : "none",
455 fwd->forward_host != NULL ? fwd->forward_host : "none");
459 return (!strcmpic(connection->host, http->host));
462 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
465 #ifdef FEATURE_CONNECTION_SHARING
466 /*********************************************************************
468 * Function : close_unusable_connections
470 * Description : Closes remembered connections that have timed
471 * out or have been closed on the other side.
475 * Returns : Number of connections that are still alive.
477 *********************************************************************/
478 int close_unusable_connections(void)
480 unsigned int slot = 0;
481 int connections_alive = 0;
483 privoxy_mutex_lock(&connection_reuse_mutex);
485 for (slot = 0; slot < SZ(reusable_connection); slot++)
487 if (!reusable_connection[slot].in_use
488 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
490 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
491 time_t latency = (reusable_connection[slot].response_received -
492 reusable_connection[slot].request_sent) / 2;
494 if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
496 log_error(LOG_LEVEL_CONNECT,
497 "The connection to %s:%d in slot %d timed out. "
498 "Closing socket %d. Timeout is: %d. Assumed latency: %ld.",
499 reusable_connection[slot].host,
500 reusable_connection[slot].port, slot,
501 reusable_connection[slot].sfd,
502 reusable_connection[slot].keep_alive_timeout,
504 close_socket(reusable_connection[slot].sfd);
505 mark_connection_closed(&reusable_connection[slot]);
507 else if (!socket_is_still_alive(reusable_connection[slot].sfd))
509 log_error(LOG_LEVEL_CONNECT,
510 "The connection to %s:%d in slot %d is no longer usable. "
511 "Closing socket %d.", reusable_connection[slot].host,
512 reusable_connection[slot].port, slot,
513 reusable_connection[slot].sfd);
514 close_socket(reusable_connection[slot].sfd);
515 mark_connection_closed(&reusable_connection[slot]);
524 privoxy_mutex_unlock(&connection_reuse_mutex);
526 return connections_alive;
531 /*********************************************************************
533 * Function : get_reusable_connection
535 * Description : Returns an open socket to a previously remembered
536 * open connection (if there is one).
539 * 1 : http = The destination for the connection.
540 * 2 : fwd = The forwarder settings.
542 * Returns : JB_INVALID_SOCKET => No reusable connection found,
543 * otherwise a usable socket.
545 *********************************************************************/
546 static jb_socket get_reusable_connection(const struct http_request *http,
547 const struct forward_spec *fwd)
549 jb_socket sfd = JB_INVALID_SOCKET;
550 unsigned int slot = 0;
552 close_unusable_connections();
554 privoxy_mutex_lock(&connection_reuse_mutex);
556 for (slot = 0; slot < SZ(reusable_connection); slot++)
558 if (!reusable_connection[slot].in_use
559 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
561 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
563 reusable_connection[slot].in_use = TRUE;
564 sfd = reusable_connection[slot].sfd;
565 log_error(LOG_LEVEL_CONNECT,
566 "Found reusable socket %d for %s:%d in slot %d. Timestamp made %ld "
567 "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
568 sfd, reusable_connection[slot].host, reusable_connection[slot].port,
569 slot, time(NULL) - reusable_connection[slot].timestamp,
570 reusable_connection[slot].keep_alive_timeout,
571 (int)(reusable_connection[slot].response_received -
572 reusable_connection[slot].request_sent),
573 reusable_connection[slot].requests_sent_total);
579 privoxy_mutex_unlock(&connection_reuse_mutex);
586 /*********************************************************************
588 * Function : mark_connection_unused
590 * Description : Gives a remembered connection free for reuse.
593 * 1 : connection = The connection in question.
595 * Returns : TRUE => Socket found and marked as unused.
596 * FALSE => Socket not found.
598 *********************************************************************/
599 static int mark_connection_unused(const struct reusable_connection *connection)
601 unsigned int slot = 0;
602 int socket_found = FALSE;
604 assert(connection->sfd != JB_INVALID_SOCKET);
606 privoxy_mutex_lock(&connection_reuse_mutex);
608 for (slot = 0; slot < SZ(reusable_connection); slot++)
610 if (reusable_connection[slot].sfd == connection->sfd)
612 assert(reusable_connection[slot].in_use);
614 log_error(LOG_LEVEL_CONNECT,
615 "Marking open socket %d for %s:%d in slot %d as unused.",
616 connection->sfd, reusable_connection[slot].host,
617 reusable_connection[slot].port, slot);
618 reusable_connection[slot].in_use = 0;
619 reusable_connection[slot].timestamp = connection->timestamp;
624 privoxy_mutex_unlock(&connection_reuse_mutex);
629 #endif /* def FEATURE_CONNECTION_SHARING */
632 /*********************************************************************
634 * Function : forwarded_connect
636 * Description : Connect to a specified web server, possibly via
637 * a HTTP proxy and/or a SOCKS proxy.
640 * 1 : fwd = the proxies to use when connecting.
641 * 2 : http = the http request and apropos headers
642 * 3 : csp = Current client state (buffers, headers, etc...)
644 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
646 *********************************************************************/
647 jb_socket forwarded_connect(const struct forward_spec *fwd,
648 struct http_request *http,
649 struct client_state *csp)
651 const char *dest_host;
653 jb_socket sfd = JB_INVALID_SOCKET;
655 #ifdef FEATURE_CONNECTION_SHARING
656 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
657 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
659 sfd = get_reusable_connection(http, fwd);
660 if (JB_INVALID_SOCKET != sfd)
665 #endif /* def FEATURE_CONNECTION_SHARING */
667 /* Figure out if we need to connect to the web server or a HTTP proxy. */
668 if (fwd->forward_host)
671 dest_host = fwd->forward_host;
672 dest_port = fwd->forward_port;
677 dest_host = http->host;
678 dest_port = http->port;
681 /* Connect, maybe using a SOCKS proxy */
685 case FORWARD_WEBSERVER:
686 sfd = connect_to(dest_host, dest_port, csp);
690 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
694 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
697 /* Should never get here */
698 log_error(LOG_LEVEL_FATAL,
699 "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
702 if (JB_INVALID_SOCKET != sfd)
704 log_error(LOG_LEVEL_CONNECT,
705 "Created new connection to %s:%d on socket %d.",
706 http->host, http->port, sfd);
715 /*********************************************************************
717 * Function : socks_fuzz
719 * Description : Wrapper around socks[45]_connect() used for fuzzing.
722 * 1 : csp = Current client state (buffers, headers, etc...)
724 * Returns : JB_ERR_OK or JB_ERR_PARSE
726 *********************************************************************/
727 extern jb_err socks_fuzz(struct client_state *csp)
730 static struct forward_spec fwd;
731 char target_host[] = "fuzz.example.org";
732 int target_port = 12345;
734 fwd.gateway_host = strdup_or_die("fuzz.example.org");
735 fwd.gateway_port = 12345;
738 socket = socks4_connect(&fwd, target_host, target_port, csp);
740 if (JB_INVALID_SOCKET != socket)
743 socket = socks5_connect(&fwd, target_host, target_port, csp);
746 if (JB_INVALID_SOCKET == socket)
748 log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
752 log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
759 /*********************************************************************
761 * Function : socks4_connect
763 * Description : Connect to the SOCKS server, and connect through
764 * it to the specified server. This handles
765 * all the SOCKS negotiation, and returns a file
766 * descriptor for a socket which can be treated as a
767 * normal (non-SOCKS) socket.
769 * Logged error messages are saved to csp->error_message
770 * and later reused by error_response() for the CGI
771 * message. strdup allocation failures are handled there.
774 * 1 : fwd = Specifies the SOCKS proxy to use.
775 * 2 : target_host = The final server to connect to.
776 * 3 : target_port = The final port to connect to.
777 * 4 : csp = Current client state (buffers, headers, etc...)
779 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
781 *********************************************************************/
782 static jb_socket socks4_connect(const struct forward_spec *fwd,
783 const char *target_host,
785 struct client_state *csp)
787 unsigned long web_server_addr;
788 char buf[BUFFER_SIZE];
789 struct socks_op *c = (struct socks_op *)buf;
790 struct socks_reply *s = (struct socks_reply *)buf;
797 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
799 /* XXX: Shouldn't the config file parser prevent this? */
800 errstr = "NULL gateway host specified.";
804 if (fwd->gateway_port <= 0)
806 errstr = "invalid gateway port specified.";
812 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
813 csp->error_message = strdup(errstr);
815 return(JB_INVALID_SOCKET);
818 /* build a socks request for connection to the web server */
820 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
822 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
827 web_server_addr = resolve_hostname_to_ip(target_host);
828 if (web_server_addr == INADDR_NONE)
830 errstr = "could not resolve target host";
831 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
836 web_server_addr = htonl(web_server_addr);
840 web_server_addr = 0x00000001;
841 n = csiz + strlen(target_host) + 1;
845 errstr = "buffer cbuf too small.";
846 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
851 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
853 * What we forward to the socks4a server should have the
854 * size of socks_op, plus the length of the userid plus
855 * its \0 byte (which we don't have to add because the
856 * first byte of the userid is counted twice as it's also
857 * part of sock_op) minus the padding bytes (which are part
858 * of the userid as well), plus the length of the target_host
859 * (which is stored csiz bytes after the beginning of the buffer),
860 * plus another \0 byte.
862 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
867 /* Should never get here */
868 log_error(LOG_LEVEL_FATAL,
869 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
871 return(JB_INVALID_SOCKET);
876 csp->error_message = strdup(errstr);
877 return(JB_INVALID_SOCKET);
882 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
883 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
884 c->dstip[0] = (unsigned char)((web_server_addr >> 24) & 0xff);
885 c->dstip[1] = (unsigned char)((web_server_addr >> 16) & 0xff);
886 c->dstip[2] = (unsigned char)((web_server_addr >> 8) & 0xff);
887 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
892 /* pass the request to the socks server */
893 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
895 if (sfd == JB_INVALID_SOCKET)
897 /* The error an its reason have already been logged by connect_to() */
898 return(JB_INVALID_SOCKET);
900 else if (write_socket(sfd, (char *)c, csiz))
902 errstr = "SOCKS4 negotiation write failed.";
903 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
907 else if (!data_is_available(sfd, csp->config->socket_timeout))
909 if (socket_is_still_alive(sfd))
911 errstr = "SOCKS4 negotiation timed out";
915 errstr = "SOCKS4 negotiation got aborted by the server";
917 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
923 if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
925 errstr = "SOCKS4 negotiation read failed.";
926 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
933 csp->error_message = strdup(errstr);
934 return(JB_INVALID_SOCKET);
939 case SOCKS4_REQUEST_GRANTED:
941 case SOCKS4_REQUEST_REJECT:
942 errstr = "SOCKS request rejected or failed.";
945 case SOCKS4_REQUEST_IDENT_FAILED:
946 errstr = "SOCKS request rejected because "
947 "SOCKS server cannot connect to identd on the client.";
950 case SOCKS4_REQUEST_IDENT_CONFLICT:
951 errstr = "SOCKS request rejected because "
952 "the client program and identd report "
953 "different user-ids.";
958 snprintf(buf, sizeof(buf),
959 "SOCKS request rejected for reason code %d.", s->cd);
963 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
964 csp->error_message = strdup(errstr);
967 return(JB_INVALID_SOCKET);
971 /*********************************************************************
973 * Function : translate_socks5_error
975 * Description : Translates a SOCKS errors to a string.
978 * 1 : socks_error = The error code to translate.
980 * Returns : The string translation.
982 *********************************************************************/
983 static const char *translate_socks5_error(int socks_error)
987 /* XXX: these should be more descriptive */
988 case SOCKS5_REQUEST_FAILED:
989 return "SOCKS5 request failed";
990 case SOCKS5_REQUEST_DENIED:
991 return "SOCKS5 request denied";
992 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
993 return "SOCKS5 network unreachable";
994 case SOCKS5_REQUEST_HOST_UNREACHABLE:
995 return "SOCKS5 destination host unreachable";
996 case SOCKS5_REQUEST_CONNECTION_REFUSED:
997 return "SOCKS5 connection refused";
998 case SOCKS5_REQUEST_TTL_EXPIRED:
999 return "SOCKS5 TTL expired";
1000 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1001 return "SOCKS5 client protocol error";
1002 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1003 return "SOCKS5 domain names unsupported";
1004 case SOCKS5_REQUEST_GRANTED:
1005 return "everything's peachy";
1007 return "SOCKS5 negotiation protocol error";
1012 /*********************************************************************
1014 * Function : socks5_connect
1016 * Description : Connect to the SOCKS server, and connect through
1017 * it to the specified server. This handles
1018 * all the SOCKS negotiation, and returns a file
1019 * descriptor for a socket which can be treated as a
1020 * normal (non-SOCKS) socket.
1023 * 1 : fwd = Specifies the SOCKS proxy to use.
1024 * 2 : target_host = The final server to connect to.
1025 * 3 : target_port = The final port to connect to.
1026 * 4 : csp = Current client state (buffers, headers, etc...)
1028 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1030 *********************************************************************/
1031 static jb_socket socks5_connect(const struct forward_spec *fwd,
1032 const char *target_host,
1034 struct client_state *csp)
1036 #define SIZE_SOCKS5_REPLY_IPV4 10
1037 #define SIZE_SOCKS5_REPLY_IPV6 22
1038 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
1041 char sbuf[SIZE_SOCKS5_REPLY_IPV6];
1042 size_t client_pos = 0;
1043 int server_size = 0;
1046 const char *errstr = NULL;
1048 assert(fwd->gateway_host);
1049 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1051 errstr = "NULL gateway host specified";
1055 if (fwd->gateway_port <= 0)
1058 * XXX: currently this can't happen because in
1059 * case of invalid gateway ports we use the defaults.
1060 * Of course we really shouldn't do that.
1062 errstr = "invalid gateway port specified";
1066 hostlen = strlen(target_host);
1067 if (hostlen > (size_t)255)
1069 errstr = "target host name is longer than 255 characters";
1073 if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1075 /* Should never get here */
1076 log_error(LOG_LEVEL_FATAL,
1077 "SOCKS5 impossible internal error - bad SOCKS type");
1084 assert(errstr != NULL);
1085 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1086 csp->error_message = strdup(errstr);
1087 return(JB_INVALID_SOCKET);
1092 if (!err && read_socket(sfd, sbuf, 2) != 2)
1094 /* pass the request to the socks server */
1095 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1097 if (sfd == JB_INVALID_SOCKET)
1099 errstr = "socks5 server unreachable";
1100 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1101 /* Free the generic error message provided by connect_to() */
1102 freez(csp->error_message);
1103 csp->error_message = strdup(errstr);
1104 return(JB_INVALID_SOCKET);
1108 cbuf[client_pos++] = '\x05'; /* Version */
1110 if (fwd->auth_username && fwd->auth_password)
1112 cbuf[client_pos++] = '\x02'; /* Two authentication methods supported */
1113 cbuf[client_pos++] = '\x02'; /* Username/password */
1117 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1119 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1121 if (write_socket(sfd, cbuf, client_pos))
1123 errstr = "SOCKS5 negotiation write failed";
1124 csp->error_message = strdup(errstr);
1125 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1127 return(JB_INVALID_SOCKET);
1129 if (!data_is_available(sfd, csp->config->socket_timeout))
1131 if (socket_is_still_alive(sfd))
1133 errstr = "SOCKS5 negotiation timed out";
1137 errstr = "SOCKS5 negotiation got aborted by the server";
1142 if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1145 errstr = "SOCKS5 negotiation read failed";
1149 if (!err && (sbuf[0] != '\x05'))
1151 errstr = "SOCKS5 negotiation protocol version error";
1155 if (!err && (sbuf[1] == '\xff'))
1157 errstr = "SOCKS5 authentication required";
1161 if (!err && (sbuf[1] == '\x02'))
1163 /* check cbuf overflow */
1164 size_t auth_len = strlen(fwd->auth_username) + strlen(fwd->auth_password) + 3;
1165 if (auth_len > sizeof(cbuf))
1167 errstr = "SOCKS5 username and/or password too long";
1174 cbuf[client_pos++] = '\x01'; /* Version */
1175 cbuf[client_pos++] = (char)strlen(fwd->auth_username);
1177 memcpy(cbuf + client_pos, fwd->auth_username, strlen(fwd->auth_username));
1178 client_pos += strlen(fwd->auth_username);
1179 cbuf[client_pos++] = (char)strlen(fwd->auth_password);
1180 memcpy(cbuf + client_pos, fwd->auth_password, strlen(fwd->auth_password));
1181 client_pos += strlen(fwd->auth_password);
1183 if (write_socket(sfd, cbuf, client_pos))
1185 errstr = "SOCKS5 negotiation auth write failed";
1186 csp->error_message = strdup(errstr);
1187 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1189 return(JB_INVALID_SOCKET);
1192 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1194 errstr = "SOCKS5 negotiation auth read failed";
1199 if (!err && (sbuf[1] != '\x00'))
1201 errstr = "SOCKS5 authentication failed";
1205 else if (!err && (sbuf[1] != '\x00'))
1207 errstr = "SOCKS5 negotiation protocol error";
1213 assert(errstr != NULL);
1214 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1215 csp->error_message = strdup(errstr);
1218 return(JB_INVALID_SOCKET);
1222 cbuf[client_pos++] = '\x05'; /* Version */
1223 cbuf[client_pos++] = '\x01'; /* TCP connect */
1224 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1225 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1226 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1227 assert(sizeof(cbuf) - client_pos > (size_t)255);
1228 /* Using strncpy because we really want the nul byte padding. */
1229 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1230 client_pos += (hostlen & 0xffu);
1231 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1232 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1235 if (write_socket(sfd, cbuf, client_pos))
1237 errstr = "SOCKS5 negotiation write failed";
1238 csp->error_message = strdup(errstr);
1239 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1242 return(JB_INVALID_SOCKET);
1246 * Optimistically send the HTTP request with the initial
1247 * SOCKS request if the user enabled the use of Tor extensions,
1248 * the CONNECT method isn't being used (in which case the client
1249 * doesn't send data until it gets our 200 response) and the
1250 * client request has actually been completely read already.
1252 if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1253 && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1255 char *client_headers = list_to_text(csp->headers);
1256 size_t header_length;
1258 if (client_headers == NULL)
1260 log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1262 list_remove_all(csp->headers);
1263 header_length= strlen(client_headers);
1265 log_error(LOG_LEVEL_CONNECT,
1266 "Optimistically sending %lu bytes of client headers intended for %s",
1267 header_length, csp->http->hostport);
1269 if (write_socket(sfd, client_headers, header_length))
1271 log_error(LOG_LEVEL_CONNECT,
1272 "optimistically writing header to: %s failed: %E", csp->http->hostport);
1273 freez(client_headers);
1274 return(JB_INVALID_SOCKET);
1276 freez(client_headers);
1277 if (csp->expected_client_content_length != 0)
1279 unsigned long long buffered_request_bytes =
1280 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1281 log_error(LOG_LEVEL_CONNECT,
1282 "Optimistically sending %llu bytes of client body. Expected %llu",
1283 csp->expected_client_content_length, buffered_request_bytes);
1284 assert(csp->expected_client_content_length == buffered_request_bytes);
1285 if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1287 log_error(LOG_LEVEL_CONNECT,
1288 "optimistically writing %llu bytes of client body to: %s failed: %E",
1289 buffered_request_bytes, csp->http->hostport);
1290 return(JB_INVALID_SOCKET);
1292 clear_iob(csp->client_iob);
1297 server_size = read_socket(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4);
1298 if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1300 errstr = "SOCKS5 negotiation read failed";
1304 if (sbuf[0] != '\x05')
1306 errstr = "SOCKS5 negotiation protocol version error";
1308 else if (sbuf[2] != '\x00')
1310 errstr = "SOCKS5 negotiation protocol error";
1312 else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1314 errstr = translate_socks5_error(sbuf[1]);
1318 if (sbuf[3] == '\x04')
1321 * The address field contains an IPv6 address
1322 * which means we didn't get the whole reply
1323 * yet. Read and discard the rest of it to make
1324 * sure it isn't treated as HTTP data later on.
1326 server_size = read_socket(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE);
1327 if (server_size != SOCKS5_REPLY_DIFFERENCE)
1329 errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1332 else if (sbuf[3] != '\x01')
1334 errstr = "SOCKS5 reply contains unsupported address type";
1343 assert(errstr != NULL);
1344 csp->error_message = strdup(errstr);
1345 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1349 return(JB_INVALID_SOCKET);