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-2023 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 : string_or_none
363 * Description : Returns a given string or "none" if a NULL pointer
365 * Helper function for connection_destination_matches().
368 * 1 : string = The string to check.
370 * Returns : The string if non-NULL, "none" otherwise.
372 *********************************************************************/
373 static const char *string_or_none(const char *string)
375 return(string != NULL ? string : "none");
379 /*********************************************************************
381 * Function : connection_detail_matches
383 * Description : Helper function for connection_destination_matches().
384 * Compares strings which can be NULL.
387 * 1 : connection_detail = The connection detail to compare.
388 * 2 : fowarder_detail = The forwarder detail to compare.
390 * Returns : TRUE for yes, FALSE otherwise.
392 *********************************************************************/
393 static int connection_detail_matches(const char *connection_detail,
394 const char *forwarder_detail)
396 if (connection_detail == NULL && forwarder_detail == NULL)
398 /* Both details are unset. */
402 if ((connection_detail == NULL && forwarder_detail != NULL)
403 || (connection_detail != NULL && forwarder_detail == NULL))
405 /* Only one detail isn't set. */
409 /* Both details are set, but do they match? */
410 return(!strcmpic(connection_detail, forwarder_detail));
415 /*********************************************************************
417 * Function : connection_destination_matches
419 * Description : Determines whether a remembered connection can
420 * be reused. That is, whether the destination and
421 * the forwarding settings match.
424 * 1 : connection = The connection to check.
425 * 2 : http = The destination for the connection.
426 * 3 : fwd = The forwarder settings.
428 * Returns : TRUE for yes, FALSE otherwise.
430 *********************************************************************/
431 int connection_destination_matches(const struct reusable_connection *connection,
432 const struct http_request *http,
433 const struct forward_spec *fwd)
435 if ((connection->forwarder_type != fwd->type)
436 || (connection->gateway_port != fwd->gateway_port)
437 || (connection->forward_port != fwd->forward_port)
438 || (connection->port != http->port))
443 if (!connection_detail_matches(connection->gateway_host, fwd->gateway_host))
445 log_error(LOG_LEVEL_CONNECT,
446 "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
447 string_or_none(connection->gateway_host),
448 string_or_none(fwd->gateway_host));
452 if (!connection_detail_matches(connection->auth_username, fwd->auth_username))
454 log_error(LOG_LEVEL_CONNECT, "Socks user name mismatch. "
455 "Previous user name: %s. Current user name: %s",
456 string_or_none(connection->auth_username),
457 string_or_none(fwd->auth_username));
461 if (!connection_detail_matches(connection->auth_password, fwd->auth_password))
463 log_error(LOG_LEVEL_CONNECT, "Socks user name mismatch. "
464 "Previous password: %s. Current password: %s",
465 string_or_none(connection->auth_password),
466 string_or_none(fwd->auth_password));
470 if (!connection_detail_matches(connection->forward_host, fwd->forward_host))
472 log_error(LOG_LEVEL_CONNECT,
473 "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
474 string_or_none(connection->forward_host),
475 string_or_none(fwd->forward_host));
479 return (!strcmpic(connection->host, http->host));
482 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
485 #ifdef FEATURE_CONNECTION_SHARING
486 /*********************************************************************
488 * Function : close_unusable_connections
490 * Description : Closes remembered connections that have timed
491 * out or have been closed on the other side.
495 * Returns : Number of connections that are still alive.
497 *********************************************************************/
498 int close_unusable_connections(void)
500 unsigned int slot = 0;
501 int connections_alive = 0;
503 privoxy_mutex_lock(&connection_reuse_mutex);
505 for (slot = 0; slot < SZ(reusable_connection); slot++)
507 if (!reusable_connection[slot].in_use
508 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
510 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
511 time_t latency = (reusable_connection[slot].response_received -
512 reusable_connection[slot].request_sent) / 2;
514 if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
516 log_error(LOG_LEVEL_CONNECT,
517 "The connection to %s:%d in slot %d timed out. "
518 "Closing socket %d. Timeout is: %d. Assumed latency: %ld.",
519 reusable_connection[slot].host,
520 reusable_connection[slot].port, slot,
521 reusable_connection[slot].sfd,
522 reusable_connection[slot].keep_alive_timeout,
524 close_socket(reusable_connection[slot].sfd);
525 mark_connection_closed(&reusable_connection[slot]);
527 else if (!socket_is_still_alive(reusable_connection[slot].sfd))
529 log_error(LOG_LEVEL_CONNECT,
530 "The connection to %s:%d in slot %d is no longer usable. "
531 "Closing socket %d.", reusable_connection[slot].host,
532 reusable_connection[slot].port, slot,
533 reusable_connection[slot].sfd);
534 close_socket(reusable_connection[slot].sfd);
535 mark_connection_closed(&reusable_connection[slot]);
544 privoxy_mutex_unlock(&connection_reuse_mutex);
546 return connections_alive;
551 /*********************************************************************
553 * Function : get_reusable_connection
555 * Description : Returns an open socket to a previously remembered
556 * open connection (if there is one).
559 * 1 : http = The destination for the connection.
560 * 2 : fwd = The forwarder settings.
562 * Returns : JB_INVALID_SOCKET => No reusable connection found,
563 * otherwise a usable socket.
565 *********************************************************************/
566 static jb_socket get_reusable_connection(const struct http_request *http,
567 const struct forward_spec *fwd)
569 jb_socket sfd = JB_INVALID_SOCKET;
570 unsigned int slot = 0;
572 close_unusable_connections();
574 privoxy_mutex_lock(&connection_reuse_mutex);
576 for (slot = 0; slot < SZ(reusable_connection); slot++)
578 if (!reusable_connection[slot].in_use
579 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
581 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
583 reusable_connection[slot].in_use = TRUE;
584 sfd = reusable_connection[slot].sfd;
585 log_error(LOG_LEVEL_CONNECT,
586 "Found reusable socket %d for %s:%d in slot %d. Timestamp made %ld "
587 "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
588 sfd, reusable_connection[slot].host, reusable_connection[slot].port,
589 slot, time(NULL) - reusable_connection[slot].timestamp,
590 reusable_connection[slot].keep_alive_timeout,
591 (int)(reusable_connection[slot].response_received -
592 reusable_connection[slot].request_sent),
593 reusable_connection[slot].requests_sent_total);
599 privoxy_mutex_unlock(&connection_reuse_mutex);
606 /*********************************************************************
608 * Function : mark_connection_unused
610 * Description : Gives a remembered connection free for reuse.
613 * 1 : connection = The connection in question.
615 * Returns : TRUE => Socket found and marked as unused.
616 * FALSE => Socket not found.
618 *********************************************************************/
619 static int mark_connection_unused(const struct reusable_connection *connection)
621 unsigned int slot = 0;
622 int socket_found = FALSE;
624 assert(connection->sfd != JB_INVALID_SOCKET);
626 privoxy_mutex_lock(&connection_reuse_mutex);
628 for (slot = 0; slot < SZ(reusable_connection); slot++)
630 if (reusable_connection[slot].sfd == connection->sfd)
632 assert(reusable_connection[slot].in_use);
634 log_error(LOG_LEVEL_CONNECT,
635 "Marking open socket %d for %s:%d in slot %d as unused.",
636 connection->sfd, reusable_connection[slot].host,
637 reusable_connection[slot].port, slot);
638 reusable_connection[slot].in_use = 0;
639 reusable_connection[slot].timestamp = connection->timestamp;
644 privoxy_mutex_unlock(&connection_reuse_mutex);
649 #endif /* def FEATURE_CONNECTION_SHARING */
652 /*********************************************************************
654 * Function : forwarded_connect
656 * Description : Connect to a specified web server, possibly via
657 * a HTTP proxy and/or a SOCKS proxy.
660 * 1 : fwd = the proxies to use when connecting.
661 * 2 : http = the http request and apropos headers
662 * 3 : csp = Current client state (buffers, headers, etc...)
664 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
666 *********************************************************************/
667 jb_socket forwarded_connect(const struct forward_spec *fwd,
668 struct http_request *http,
669 struct client_state *csp)
671 const char *dest_host;
673 jb_socket sfd = JB_INVALID_SOCKET;
675 #ifdef FEATURE_CONNECTION_SHARING
676 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
677 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
679 sfd = get_reusable_connection(http, fwd);
680 if (JB_INVALID_SOCKET != sfd)
685 #endif /* def FEATURE_CONNECTION_SHARING */
687 /* Figure out if we need to connect to the web server or a HTTP proxy. */
688 if (fwd->forward_host)
691 dest_host = fwd->forward_host;
692 dest_port = fwd->forward_port;
697 dest_host = http->host;
698 dest_port = http->port;
701 /* Connect, maybe using a SOCKS proxy */
705 case FORWARD_WEBSERVER:
706 sfd = connect_to(dest_host, dest_port, csp);
710 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
714 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
717 /* Should never get here */
718 log_error(LOG_LEVEL_FATAL,
719 "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
722 if (JB_INVALID_SOCKET != sfd)
724 log_error(LOG_LEVEL_CONNECT,
725 "Created new connection to %s:%d on socket %d.",
726 http->host, http->port, sfd);
735 /*********************************************************************
737 * Function : socks_fuzz
739 * Description : Wrapper around socks[45]_connect() used for fuzzing.
742 * 1 : csp = Current client state (buffers, headers, etc...)
744 * Returns : JB_ERR_OK or JB_ERR_PARSE
746 *********************************************************************/
747 extern jb_err socks_fuzz(struct client_state *csp)
750 static struct forward_spec fwd;
751 char target_host[] = "fuzz.example.org";
752 int target_port = 12345;
754 fwd.gateway_host = strdup_or_die("fuzz.example.org");
755 fwd.gateway_port = 12345;
758 socket = socks4_connect(&fwd, target_host, target_port, csp);
760 if (JB_INVALID_SOCKET != socket)
763 socket = socks5_connect(&fwd, target_host, target_port, csp);
766 if (JB_INVALID_SOCKET == socket)
768 log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
772 log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
779 /*********************************************************************
781 * Function : socks4_connect
783 * Description : Connect to the SOCKS server, and connect through
784 * it to the specified server. This handles
785 * all the SOCKS negotiation, and returns a file
786 * descriptor for a socket which can be treated as a
787 * normal (non-SOCKS) socket.
789 * Logged error messages are saved to csp->error_message
790 * and later reused by error_response() for the CGI
791 * message. strdup allocation failures are handled there.
794 * 1 : fwd = Specifies the SOCKS proxy to use.
795 * 2 : target_host = The final server to connect to.
796 * 3 : target_port = The final port to connect to.
797 * 4 : csp = Current client state (buffers, headers, etc...)
799 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
801 *********************************************************************/
802 static jb_socket socks4_connect(const struct forward_spec *fwd,
803 const char *target_host,
805 struct client_state *csp)
807 unsigned long web_server_addr;
808 char buf[BUFFER_SIZE];
809 struct socks_op *c = (struct socks_op *)buf;
810 struct socks_reply *s = (struct socks_reply *)buf;
817 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
819 /* XXX: Shouldn't the config file parser prevent this? */
820 errstr = "NULL gateway host specified.";
824 if (fwd->gateway_port <= 0)
826 errstr = "invalid gateway port specified.";
832 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
833 csp->error_message = strdup(errstr);
835 return(JB_INVALID_SOCKET);
838 /* build a socks request for connection to the web server */
841 * The more straightforward &(c->userid) destination pointer can
842 * cause some gcc versions to misidentify the size of the destination
843 * buffer, tripping the runtime check of glibc's source fortification.
845 strlcpy(buf + offsetof(struct socks_op, userid), socks_userid,
846 sizeof(buf) - sizeof(struct socks_op));
848 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
853 web_server_addr = resolve_hostname_to_ip(target_host);
854 if (web_server_addr == INADDR_NONE)
856 errstr = "could not resolve target host";
857 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
862 web_server_addr = htonl(web_server_addr);
866 web_server_addr = 0x00000001;
867 n = csiz + strlen(target_host) + 1;
871 errstr = "buffer cbuf too small.";
872 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
877 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
879 * What we forward to the socks4a server should have the
880 * size of socks_op, plus the length of the userid plus
881 * its \0 byte (which we don't have to add because the
882 * first byte of the userid is counted twice as it's also
883 * part of sock_op) minus the padding bytes (which are part
884 * of the userid as well), plus the length of the target_host
885 * (which is stored csiz bytes after the beginning of the buffer),
886 * plus another \0 byte.
888 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
893 /* Should never get here */
894 log_error(LOG_LEVEL_FATAL,
895 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
897 return(JB_INVALID_SOCKET);
902 csp->error_message = strdup(errstr);
903 return(JB_INVALID_SOCKET);
908 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
909 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
910 c->dstip[0] = (unsigned char)((web_server_addr >> 24) & 0xff);
911 c->dstip[1] = (unsigned char)((web_server_addr >> 16) & 0xff);
912 c->dstip[2] = (unsigned char)((web_server_addr >> 8) & 0xff);
913 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
918 /* pass the request to the socks server */
919 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
921 if (sfd == JB_INVALID_SOCKET)
923 /* The error an its reason have already been logged by connect_to() */
924 return(JB_INVALID_SOCKET);
926 else if (write_socket(sfd, (char *)c, csiz))
928 errstr = "SOCKS4 negotiation write failed.";
929 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
933 else if (!data_is_available(sfd, csp->config->socket_timeout))
935 if (socket_is_still_alive(sfd))
937 errstr = "SOCKS4 negotiation timed out";
941 errstr = "SOCKS4 negotiation got aborted by the server";
943 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
949 if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
951 errstr = "SOCKS4 negotiation read failed.";
952 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
959 csp->error_message = strdup(errstr);
960 return(JB_INVALID_SOCKET);
965 case SOCKS4_REQUEST_GRANTED:
967 case SOCKS4_REQUEST_REJECT:
968 errstr = "SOCKS request rejected or failed.";
971 case SOCKS4_REQUEST_IDENT_FAILED:
972 errstr = "SOCKS request rejected because "
973 "SOCKS server cannot connect to identd on the client.";
976 case SOCKS4_REQUEST_IDENT_CONFLICT:
977 errstr = "SOCKS request rejected because "
978 "the client program and identd report "
979 "different user-ids.";
984 snprintf(buf, sizeof(buf),
985 "SOCKS request rejected for reason code %d.", s->cd);
989 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
990 csp->error_message = strdup(errstr);
993 return(JB_INVALID_SOCKET);
997 /*********************************************************************
999 * Function : translate_socks5_error
1001 * Description : Translates a SOCKS errors to a string.
1004 * 1 : socks_error = The error code to translate.
1006 * Returns : The string translation.
1008 *********************************************************************/
1009 static const char *translate_socks5_error(int socks_error)
1011 switch (socks_error)
1013 /* XXX: these should be more descriptive */
1014 case SOCKS5_REQUEST_FAILED:
1015 return "SOCKS5 request failed";
1016 case SOCKS5_REQUEST_DENIED:
1017 return "SOCKS5 request denied";
1018 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1019 return "SOCKS5 network unreachable";
1020 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1021 return "SOCKS5 destination host unreachable";
1022 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1023 return "SOCKS5 connection refused";
1024 case SOCKS5_REQUEST_TTL_EXPIRED:
1025 return "SOCKS5 TTL expired";
1026 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1027 return "SOCKS5 client protocol error";
1028 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1029 return "SOCKS5 domain names unsupported";
1030 case SOCKS5_REQUEST_GRANTED:
1031 return "everything's peachy";
1033 return "SOCKS5 negotiation protocol error";
1038 /*********************************************************************
1040 * Function : convert_ipv4_address_to_bytes
1042 * Description : Converts an IPv4 address from string to bytes.
1045 * 1 : address = The IPv4 address string to convert.
1046 * 2 : buf = The buffer to write the bytes to.
1047 * Must be at least four bytes long.
1049 * Returns : JB_ERR_OK on success, JB_ERR_PARSE otherwise.
1051 *********************************************************************/
1052 static jb_err convert_ipv4_address_to_bytes(const char *address, char *buf)
1055 const char *p = address;
1057 for (i = 0; i < 4; i++)
1060 if (1 != sscanf(p, "%u", &byte))
1062 return JB_ERR_PARSE;
1066 return JB_ERR_PARSE;
1068 buf[i] = (char)byte;
1074 return JB_ERR_PARSE;
1085 /*********************************************************************
1087 * Function : read_socks_reply
1089 * Description : Read from a socket connected to a socks server.
1092 * 1 : sfd = file descriptor of the socket to read
1093 * 2 : buf = pointer to buffer where data will be written
1094 * Must be >= len bytes long.
1095 * 3 : len = maximum number of bytes to read
1096 * 4 : timeout = Number of seconds to wait.
1098 * Returns : On success, the number of bytes read is returned (zero
1099 * indicates end of file), and the file position is advanced
1100 * by this number. It is not an error if this number is
1101 * smaller than the number of bytes requested; this may hap-
1102 * pen for example because fewer bytes are actually available
1103 * right now (maybe because we were close to end-of-file, or
1104 * because we are reading from a pipe, or from a terminal,
1105 * or because read() was interrupted by a signal). On error,
1106 * -1 is returned, and errno is set appropriately. In this
1107 * case it is left unspecified whether the file position (if
1110 *********************************************************************/
1111 static int read_socks_reply(jb_socket sfd, char *buf, int len, int timeout)
1113 if (!data_is_available(sfd, timeout))
1115 if (socket_is_still_alive(sfd))
1117 log_error(LOG_LEVEL_ERROR,
1118 "The socks connection timed out after %d seconds.", timeout);
1122 log_error(LOG_LEVEL_ERROR, "The socks server hung "
1123 "up the connection without sending a response.");
1128 return read_socket(sfd, buf, len);
1133 /*********************************************************************
1135 * Function : socks5_connect
1137 * Description : Connect to the SOCKS server, and connect through
1138 * it to the specified server. This handles
1139 * all the SOCKS negotiation, and returns a file
1140 * descriptor for a socket which can be treated as a
1141 * normal (non-SOCKS) socket.
1144 * 1 : fwd = Specifies the SOCKS proxy to use.
1145 * 2 : target_host = The final server to connect to.
1146 * 3 : target_port = The final port to connect to.
1147 * 4 : csp = Current client state (buffers, headers, etc...)
1149 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1151 *********************************************************************/
1152 static jb_socket socks5_connect(const struct forward_spec *fwd,
1153 const char *target_host,
1155 struct client_state *csp)
1157 #define SIZE_SOCKS5_REPLY_IPV4 10
1158 #define SIZE_SOCKS5_REPLY_IPV6 22
1159 #define SIZE_SOCKS5_REPLY_DOMAIN 300
1160 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
1163 char sbuf[SIZE_SOCKS5_REPLY_DOMAIN];
1164 size_t client_pos = 0;
1165 int server_size = 0;
1168 const char *errstr = NULL;
1170 assert(fwd->gateway_host);
1171 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1173 errstr = "NULL gateway host specified";
1177 if (fwd->gateway_port <= 0)
1180 * XXX: currently this can't happen because in
1181 * case of invalid gateway ports we use the defaults.
1182 * Of course we really shouldn't do that.
1184 errstr = "invalid gateway port specified";
1188 hostlen = strlen(target_host);
1189 if (hostlen > (size_t)255)
1191 errstr = "target host name is longer than 255 characters";
1195 if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1197 /* Should never get here */
1198 log_error(LOG_LEVEL_FATAL,
1199 "SOCKS5 impossible internal error - bad SOCKS type");
1206 assert(errstr != NULL);
1207 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1208 csp->error_message = strdup(errstr);
1209 return(JB_INVALID_SOCKET);
1214 if (!err && read_socket(sfd, sbuf, 2) != 2)
1216 /* pass the request to the socks server */
1217 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1219 if (sfd == JB_INVALID_SOCKET)
1221 errstr = "socks5 server unreachable";
1222 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1223 /* Free the generic error message provided by connect_to() */
1224 freez(csp->error_message);
1225 csp->error_message = strdup(errstr);
1226 return(JB_INVALID_SOCKET);
1230 cbuf[client_pos++] = '\x05'; /* Version */
1232 if (fwd->auth_username && fwd->auth_password)
1234 cbuf[client_pos++] = '\x02'; /* Two authentication methods supported */
1235 cbuf[client_pos++] = '\x02'; /* Username/password */
1239 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1241 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1243 if (write_socket(sfd, cbuf, client_pos))
1245 errstr = "SOCKS5 negotiation write failed";
1246 csp->error_message = strdup(errstr);
1247 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1249 return(JB_INVALID_SOCKET);
1251 if (read_socks_reply(sfd, sbuf, sizeof(sbuf),
1252 csp->config->socket_timeout) != 2)
1255 errstr = "SOCKS5 negotiation read failed";
1259 if (!err && (sbuf[0] != '\x05'))
1261 errstr = "SOCKS5 negotiation protocol version error";
1265 if (!err && (sbuf[1] == '\xff'))
1267 errstr = "SOCKS5 authentication required";
1271 if (!err && (sbuf[1] == '\x02'))
1273 if (fwd->auth_username && fwd->auth_password)
1275 /* check cbuf overflow */
1276 size_t auth_len = strlen(fwd->auth_username) + strlen(fwd->auth_password) + 3;
1277 if (auth_len > sizeof(cbuf))
1279 errstr = "SOCKS5 username and/or password too long";
1285 errstr = "SOCKS5 server requested authentication while "
1286 "no credentials are configured";
1293 cbuf[client_pos++] = '\x01'; /* Version */
1294 cbuf[client_pos++] = (char)strlen(fwd->auth_username);
1296 memcpy(cbuf + client_pos, fwd->auth_username, strlen(fwd->auth_username));
1297 client_pos += strlen(fwd->auth_username);
1298 cbuf[client_pos++] = (char)strlen(fwd->auth_password);
1299 memcpy(cbuf + client_pos, fwd->auth_password, strlen(fwd->auth_password));
1300 client_pos += strlen(fwd->auth_password);
1302 if (write_socket(sfd, cbuf, client_pos))
1304 errstr = "SOCKS5 negotiation auth write failed";
1305 csp->error_message = strdup(errstr);
1306 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1308 return(JB_INVALID_SOCKET);
1311 if (read_socks_reply(sfd, sbuf, sizeof(sbuf),
1312 csp->config->socket_timeout) != 2)
1314 errstr = "SOCKS5 negotiation auth read failed";
1319 if (!err && (sbuf[1] != '\x00'))
1321 errstr = "SOCKS5 authentication failed";
1325 else if (!err && (sbuf[1] != '\x00'))
1327 errstr = "SOCKS5 negotiation protocol error";
1333 assert(errstr != NULL);
1334 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1335 csp->error_message = strdup(errstr);
1338 return(JB_INVALID_SOCKET);
1342 cbuf[client_pos++] = '\x05'; /* Version */
1343 cbuf[client_pos++] = '\x01'; /* TCP connect */
1344 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1345 if (host_is_ip_address(target_host) && NULL == strstr(target_host, ":"))
1347 cbuf[client_pos++] = '\x01'; /* Address is IPv4 address. */
1348 if (JB_ERR_OK != convert_ipv4_address_to_bytes(target_host, &cbuf[client_pos]))
1350 errstr = "SOCKS5 error. Failed to convert target address to IP address";
1351 csp->error_message = strdup(errstr);
1352 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1355 return(JB_INVALID_SOCKET);
1362 * XXX: This branch is currently also used for IPv6 addresses
1364 cbuf[client_pos++] = '\x03'; /* Address is domain name. */
1365 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1366 assert(sizeof(cbuf) - client_pos > (size_t)255);
1367 /* Using strncpy because we really want the nul byte padding. */
1368 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos - 1);
1369 client_pos += (hostlen & 0xffu);
1371 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1372 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1375 if (write_socket(sfd, cbuf, client_pos))
1377 errstr = "SOCKS5 negotiation write failed";
1378 csp->error_message = strdup(errstr);
1379 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1382 return(JB_INVALID_SOCKET);
1386 * Optimistically send the HTTP request with the initial
1387 * SOCKS request if the user enabled the use of Tor extensions,
1388 * the CONNECT method isn't being used (in which case the client
1389 * doesn't send data until it gets our 200 response) and the
1390 * client request has actually been completely read already.
1392 if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1393 && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1395 char *client_headers = list_to_text(csp->headers);
1396 size_t header_length;
1398 if (client_headers == NULL)
1400 log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers.");
1402 list_remove_all(csp->headers);
1403 header_length= strlen(client_headers);
1405 log_error(LOG_LEVEL_CONNECT,
1406 "Optimistically sending %lu bytes of client headers intended for %s.",
1407 header_length, csp->http->hostport);
1409 if (write_socket(sfd, client_headers, header_length))
1411 log_error(LOG_LEVEL_CONNECT,
1412 "optimistically writing header to: %s failed: %E", csp->http->hostport);
1413 freez(client_headers);
1414 return(JB_INVALID_SOCKET);
1416 freez(client_headers);
1417 if (csp->expected_client_content_length != 0)
1419 unsigned long long buffered_request_bytes =
1420 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1421 log_error(LOG_LEVEL_CONNECT,
1422 "Optimistically sending %llu bytes of client body. Expected %llu.",
1423 csp->expected_client_content_length, buffered_request_bytes);
1424 assert(csp->expected_client_content_length == buffered_request_bytes);
1425 if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1427 log_error(LOG_LEVEL_CONNECT,
1428 "optimistically writing %llu bytes of client body to: %s failed: %E",
1429 buffered_request_bytes, csp->http->hostport);
1430 return(JB_INVALID_SOCKET);
1432 clear_iob(csp->client_iob);
1437 server_size = read_socks_reply(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4,
1438 csp->config->socket_timeout);
1439 if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1441 errstr = "SOCKS5 negotiation read failed";
1445 if (sbuf[0] != '\x05')
1447 errstr = "SOCKS5 negotiation protocol version error";
1449 else if (sbuf[2] != '\x00')
1451 errstr = "SOCKS5 negotiation protocol error";
1453 else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1455 errstr = translate_socks5_error(sbuf[1]);
1459 if (sbuf[3] == '\x04')
1462 * The address field contains an IPv6 address
1463 * which means we didn't get the whole reply
1464 * yet. Read and discard the rest of it to make
1465 * sure it isn't treated as HTTP data later on.
1467 server_size = read_socks_reply(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE,
1468 csp->config->socket_timeout);
1469 if (server_size != SOCKS5_REPLY_DIFFERENCE)
1471 errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1474 else if (sbuf[3] == '\x03')
1477 * The address field contains a domain name
1478 * which means we didn't get the whole reply
1479 * yet. Read and discard the rest of it to make
1480 * sure it isn't treated as HTTP data later on.
1482 unsigned domain_length = (unsigned)sbuf[4];
1483 int bytes_left_to_read = 5 + (int)domain_length + 2 - SIZE_SOCKS5_REPLY_IPV4;
1484 if (bytes_left_to_read <= 0 || sizeof(sbuf) < bytes_left_to_read)
1486 errstr = "SOCKS5 negotiation read failed (Invalid domain length)";
1490 server_size = read_socks_reply(sfd, sbuf, bytes_left_to_read,
1491 csp->config->socket_timeout);
1492 if (server_size != bytes_left_to_read)
1494 errstr = "SOCKS5 negotiation read failed (Domain name)";
1498 else if (sbuf[3] != '\x01')
1500 errstr = "SOCKS5 reply contains unsupported address type";
1509 assert(errstr != NULL);
1510 csp->error_message = strdup(errstr);
1511 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1515 return(JB_INVALID_SOCKET);