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_detail_matches
343 * Description : Helper function for connection_destination_matches().
344 * Compares strings which can be NULL.
347 * 1 : connection_detail = The connection detail to compare.
348 * 2 : fowarder_detail = The forwarder detail to compare.
350 * Returns : TRUE for yes, FALSE otherwise.
352 *********************************************************************/
353 static int connection_detail_matches(const char *connection_detail,
354 const char *forwarder_detail)
356 if (connection_detail == NULL && forwarder_detail == NULL)
358 /* Both details are unset. */
362 if ((connection_detail == NULL && forwarder_detail != NULL)
363 || (connection_detail != NULL && forwarder_detail == NULL))
365 /* Only one detail isn't set. */
369 /* Both details are set, but do they match? */
370 return(!strcmpic(connection_detail, forwarder_detail));
375 /*********************************************************************
377 * Function : connection_destination_matches
379 * Description : Determines whether a remembered connection can
380 * be reused. That is, whether the destination and
381 * the forwarding settings match.
384 * 1 : connection = The connection to check.
385 * 2 : http = The destination for the connection.
386 * 3 : fwd = The forwarder settings.
388 * Returns : TRUE for yes, FALSE otherwise.
390 *********************************************************************/
391 int connection_destination_matches(const struct reusable_connection *connection,
392 const struct http_request *http,
393 const struct forward_spec *fwd)
395 if ((connection->forwarder_type != fwd->type)
396 || (connection->gateway_port != fwd->gateway_port)
397 || (connection->forward_port != fwd->forward_port)
398 || (connection->port != http->port))
403 if (!connection_detail_matches(connection->gateway_host, fwd->gateway_host))
405 log_error(LOG_LEVEL_CONNECT,
406 "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
407 connection->gateway_host != NULL ? connection->gateway_host : "none",
408 fwd->gateway_host != NULL ? fwd->gateway_host : "none");
412 if (!connection_detail_matches(connection->forward_host, fwd->forward_host))
414 log_error(LOG_LEVEL_CONNECT,
415 "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
416 connection->forward_host != NULL ? connection->forward_host : "none",
417 fwd->forward_host != NULL ? fwd->forward_host : "none");
421 return (!strcmpic(connection->host, http->host));
424 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
427 #ifdef FEATURE_CONNECTION_SHARING
428 /*********************************************************************
430 * Function : close_unusable_connections
432 * Description : Closes remembered connections that have timed
433 * out or have been closed on the other side.
437 * Returns : Number of connections that are still alive.
439 *********************************************************************/
440 int close_unusable_connections(void)
442 unsigned int slot = 0;
443 int connections_alive = 0;
445 privoxy_mutex_lock(&connection_reuse_mutex);
447 for (slot = 0; slot < SZ(reusable_connection); slot++)
449 if (!reusable_connection[slot].in_use
450 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
452 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
453 time_t latency = (reusable_connection[slot].response_received -
454 reusable_connection[slot].request_sent) / 2;
456 if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
458 log_error(LOG_LEVEL_CONNECT,
459 "The connection to %s:%d in slot %d timed out. "
460 "Closing socket %d. Timeout is: %d. Assumed latency: %ld.",
461 reusable_connection[slot].host,
462 reusable_connection[slot].port, slot,
463 reusable_connection[slot].sfd,
464 reusable_connection[slot].keep_alive_timeout,
466 close_socket(reusable_connection[slot].sfd);
467 mark_connection_closed(&reusable_connection[slot]);
469 else if (!socket_is_still_alive(reusable_connection[slot].sfd))
471 log_error(LOG_LEVEL_CONNECT,
472 "The connection to %s:%d in slot %d is no longer usable. "
473 "Closing socket %d.", reusable_connection[slot].host,
474 reusable_connection[slot].port, slot,
475 reusable_connection[slot].sfd);
476 close_socket(reusable_connection[slot].sfd);
477 mark_connection_closed(&reusable_connection[slot]);
486 privoxy_mutex_unlock(&connection_reuse_mutex);
488 return connections_alive;
493 /*********************************************************************
495 * Function : get_reusable_connection
497 * Description : Returns an open socket to a previously remembered
498 * open connection (if there is one).
501 * 1 : http = The destination for the connection.
502 * 2 : fwd = The forwarder settings.
504 * Returns : JB_INVALID_SOCKET => No reusable connection found,
505 * otherwise a usable socket.
507 *********************************************************************/
508 static jb_socket get_reusable_connection(const struct http_request *http,
509 const struct forward_spec *fwd)
511 jb_socket sfd = JB_INVALID_SOCKET;
512 unsigned int slot = 0;
514 close_unusable_connections();
516 privoxy_mutex_lock(&connection_reuse_mutex);
518 for (slot = 0; slot < SZ(reusable_connection); slot++)
520 if (!reusable_connection[slot].in_use
521 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
523 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
525 reusable_connection[slot].in_use = TRUE;
526 sfd = reusable_connection[slot].sfd;
527 log_error(LOG_LEVEL_CONNECT,
528 "Found reusable socket %d for %s:%d in slot %d. Timestamp made %ld "
529 "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
530 sfd, reusable_connection[slot].host, reusable_connection[slot].port,
531 slot, time(NULL) - reusable_connection[slot].timestamp,
532 reusable_connection[slot].keep_alive_timeout,
533 (int)(reusable_connection[slot].response_received -
534 reusable_connection[slot].request_sent),
535 reusable_connection[slot].requests_sent_total);
541 privoxy_mutex_unlock(&connection_reuse_mutex);
548 /*********************************************************************
550 * Function : mark_connection_unused
552 * Description : Gives a remembered connection free for reuse.
555 * 1 : connection = The connection in question.
557 * Returns : TRUE => Socket found and marked as unused.
558 * FALSE => Socket not found.
560 *********************************************************************/
561 static int mark_connection_unused(const struct reusable_connection *connection)
563 unsigned int slot = 0;
564 int socket_found = FALSE;
566 assert(connection->sfd != JB_INVALID_SOCKET);
568 privoxy_mutex_lock(&connection_reuse_mutex);
570 for (slot = 0; slot < SZ(reusable_connection); slot++)
572 if (reusable_connection[slot].sfd == connection->sfd)
574 assert(reusable_connection[slot].in_use);
576 log_error(LOG_LEVEL_CONNECT,
577 "Marking open socket %d for %s:%d in slot %d as unused.",
578 connection->sfd, reusable_connection[slot].host,
579 reusable_connection[slot].port, slot);
580 reusable_connection[slot].in_use = 0;
581 reusable_connection[slot].timestamp = connection->timestamp;
586 privoxy_mutex_unlock(&connection_reuse_mutex);
591 #endif /* def FEATURE_CONNECTION_SHARING */
594 /*********************************************************************
596 * Function : forwarded_connect
598 * Description : Connect to a specified web server, possibly via
599 * a HTTP proxy and/or a SOCKS proxy.
602 * 1 : fwd = the proxies to use when connecting.
603 * 2 : http = the http request and apropos headers
604 * 3 : csp = Current client state (buffers, headers, etc...)
606 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
608 *********************************************************************/
609 jb_socket forwarded_connect(const struct forward_spec *fwd,
610 struct http_request *http,
611 struct client_state *csp)
613 const char *dest_host;
615 jb_socket sfd = JB_INVALID_SOCKET;
617 #ifdef FEATURE_CONNECTION_SHARING
618 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
619 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
621 sfd = get_reusable_connection(http, fwd);
622 if (JB_INVALID_SOCKET != sfd)
627 #endif /* def FEATURE_CONNECTION_SHARING */
629 /* Figure out if we need to connect to the web server or a HTTP proxy. */
630 if (fwd->forward_host)
633 dest_host = fwd->forward_host;
634 dest_port = fwd->forward_port;
639 dest_host = http->host;
640 dest_port = http->port;
643 /* Connect, maybe using a SOCKS proxy */
647 case FORWARD_WEBSERVER:
648 sfd = connect_to(dest_host, dest_port, csp);
652 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
656 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
659 /* Should never get here */
660 log_error(LOG_LEVEL_FATAL,
661 "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
664 if (JB_INVALID_SOCKET != sfd)
666 log_error(LOG_LEVEL_CONNECT,
667 "Created new connection to %s:%d on socket %d.",
668 http->host, http->port, sfd);
677 /*********************************************************************
679 * Function : socks_fuzz
681 * Description : Wrapper around socks[45]_connect() used for fuzzing.
684 * 1 : csp = Current client state (buffers, headers, etc...)
686 * Returns : JB_ERR_OK or JB_ERR_PARSE
688 *********************************************************************/
689 extern jb_err socks_fuzz(struct client_state *csp)
692 static struct forward_spec fwd;
693 char target_host[] = "fuzz.example.org";
694 int target_port = 12345;
696 fwd.gateway_host = strdup_or_die("fuzz.example.org");
697 fwd.gateway_port = 12345;
700 socket = socks4_connect(&fwd, target_host, target_port, csp);
702 if (JB_INVALID_SOCKET != socket)
705 socket = socks5_connect(&fwd, target_host, target_port, csp);
708 if (JB_INVALID_SOCKET == socket)
710 log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
714 log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
721 /*********************************************************************
723 * Function : socks4_connect
725 * Description : Connect to the SOCKS server, and connect through
726 * it to the specified server. This handles
727 * all the SOCKS negotiation, and returns a file
728 * descriptor for a socket which can be treated as a
729 * normal (non-SOCKS) socket.
731 * Logged error messages are saved to csp->error_message
732 * and later reused by error_response() for the CGI
733 * message. strdup allocation failures are handled there.
736 * 1 : fwd = Specifies the SOCKS proxy to use.
737 * 2 : target_host = The final server to connect to.
738 * 3 : target_port = The final port to connect to.
739 * 4 : csp = Current client state (buffers, headers, etc...)
741 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
743 *********************************************************************/
744 static jb_socket socks4_connect(const struct forward_spec *fwd,
745 const char *target_host,
747 struct client_state *csp)
749 unsigned long web_server_addr;
750 char buf[BUFFER_SIZE];
751 struct socks_op *c = (struct socks_op *)buf;
752 struct socks_reply *s = (struct socks_reply *)buf;
759 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
761 /* XXX: Shouldn't the config file parser prevent this? */
762 errstr = "NULL gateway host specified.";
766 if (fwd->gateway_port <= 0)
768 errstr = "invalid gateway port specified.";
774 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
775 csp->error_message = strdup(errstr);
777 return(JB_INVALID_SOCKET);
780 /* build a socks request for connection to the web server */
782 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
784 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
789 web_server_addr = resolve_hostname_to_ip(target_host);
790 if (web_server_addr == INADDR_NONE)
792 errstr = "could not resolve target host";
793 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
798 web_server_addr = htonl(web_server_addr);
802 web_server_addr = 0x00000001;
803 n = csiz + strlen(target_host) + 1;
807 errstr = "buffer cbuf too small.";
808 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
813 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
815 * What we forward to the socks4a server should have the
816 * size of socks_op, plus the length of the userid plus
817 * its \0 byte (which we don't have to add because the
818 * first byte of the userid is counted twice as it's also
819 * part of sock_op) minus the padding bytes (which are part
820 * of the userid as well), plus the length of the target_host
821 * (which is stored csiz bytes after the beginning of the buffer),
822 * plus another \0 byte.
824 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
829 /* Should never get here */
830 log_error(LOG_LEVEL_FATAL,
831 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
833 return(JB_INVALID_SOCKET);
838 csp->error_message = strdup(errstr);
839 return(JB_INVALID_SOCKET);
844 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
845 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
846 c->dstip[0] = (unsigned char)((web_server_addr >> 24) & 0xff);
847 c->dstip[1] = (unsigned char)((web_server_addr >> 16) & 0xff);
848 c->dstip[2] = (unsigned char)((web_server_addr >> 8) & 0xff);
849 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
854 /* pass the request to the socks server */
855 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
857 if (sfd == JB_INVALID_SOCKET)
859 /* The error an its reason have already been logged by connect_to() */
860 return(JB_INVALID_SOCKET);
862 else if (write_socket(sfd, (char *)c, csiz))
864 errstr = "SOCKS4 negotiation write failed.";
865 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
869 else if (!data_is_available(sfd, csp->config->socket_timeout))
871 if (socket_is_still_alive(sfd))
873 errstr = "SOCKS4 negotiation timed out";
877 errstr = "SOCKS4 negotiation got aborted by the server";
879 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
885 if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
887 errstr = "SOCKS4 negotiation read failed.";
888 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
895 csp->error_message = strdup(errstr);
896 return(JB_INVALID_SOCKET);
901 case SOCKS4_REQUEST_GRANTED:
903 case SOCKS4_REQUEST_REJECT:
904 errstr = "SOCKS request rejected or failed.";
907 case SOCKS4_REQUEST_IDENT_FAILED:
908 errstr = "SOCKS request rejected because "
909 "SOCKS server cannot connect to identd on the client.";
912 case SOCKS4_REQUEST_IDENT_CONFLICT:
913 errstr = "SOCKS request rejected because "
914 "the client program and identd report "
915 "different user-ids.";
920 snprintf(buf, sizeof(buf),
921 "SOCKS request rejected for reason code %d.", s->cd);
925 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
926 csp->error_message = strdup(errstr);
929 return(JB_INVALID_SOCKET);
933 /*********************************************************************
935 * Function : translate_socks5_error
937 * Description : Translates a SOCKS errors to a string.
940 * 1 : socks_error = The error code to translate.
942 * Returns : The string translation.
944 *********************************************************************/
945 static const char *translate_socks5_error(int socks_error)
949 /* XXX: these should be more descriptive */
950 case SOCKS5_REQUEST_FAILED:
951 return "SOCKS5 request failed";
952 case SOCKS5_REQUEST_DENIED:
953 return "SOCKS5 request denied";
954 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
955 return "SOCKS5 network unreachable";
956 case SOCKS5_REQUEST_HOST_UNREACHABLE:
957 return "SOCKS5 destination host unreachable";
958 case SOCKS5_REQUEST_CONNECTION_REFUSED:
959 return "SOCKS5 connection refused";
960 case SOCKS5_REQUEST_TTL_EXPIRED:
961 return "SOCKS5 TTL expired";
962 case SOCKS5_REQUEST_PROTOCOL_ERROR:
963 return "SOCKS5 client protocol error";
964 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
965 return "SOCKS5 domain names unsupported";
966 case SOCKS5_REQUEST_GRANTED:
967 return "everything's peachy";
969 return "SOCKS5 negotiation protocol error";
974 /*********************************************************************
976 * Function : socks5_connect
978 * Description : Connect to the SOCKS server, and connect through
979 * it to the specified server. This handles
980 * all the SOCKS negotiation, and returns a file
981 * descriptor for a socket which can be treated as a
982 * normal (non-SOCKS) socket.
985 * 1 : fwd = Specifies the SOCKS proxy to use.
986 * 2 : target_host = The final server to connect to.
987 * 3 : target_port = The final port to connect to.
988 * 4 : csp = Current client state (buffers, headers, etc...)
990 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
992 *********************************************************************/
993 static jb_socket socks5_connect(const struct forward_spec *fwd,
994 const char *target_host,
996 struct client_state *csp)
998 #define SIZE_SOCKS5_REPLY_IPV4 10
999 #define SIZE_SOCKS5_REPLY_IPV6 22
1000 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
1003 char sbuf[SIZE_SOCKS5_REPLY_IPV6];
1004 size_t client_pos = 0;
1005 int server_size = 0;
1008 const char *errstr = NULL;
1010 assert(fwd->gateway_host);
1011 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1013 errstr = "NULL gateway host specified";
1017 if (fwd->gateway_port <= 0)
1020 * XXX: currently this can't happen because in
1021 * case of invalid gateway ports we use the defaults.
1022 * Of course we really shouldn't do that.
1024 errstr = "invalid gateway port specified";
1028 hostlen = strlen(target_host);
1029 if (hostlen > (size_t)255)
1031 errstr = "target host name is longer than 255 characters";
1035 if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1037 /* Should never get here */
1038 log_error(LOG_LEVEL_FATAL,
1039 "SOCKS5 impossible internal error - bad SOCKS type");
1046 assert(errstr != NULL);
1047 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1048 csp->error_message = strdup(errstr);
1049 return(JB_INVALID_SOCKET);
1054 if (!err && read_socket(sfd, sbuf, 2) != 2)
1056 /* pass the request to the socks server */
1057 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1059 if (sfd == JB_INVALID_SOCKET)
1061 errstr = "socks5 server unreachable";
1062 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1063 /* Free the generic error message provided by connect_to() */
1064 freez(csp->error_message);
1065 csp->error_message = strdup(errstr);
1066 return(JB_INVALID_SOCKET);
1070 cbuf[client_pos++] = '\x05'; /* Version */
1072 if (fwd->auth_username && fwd->auth_password)
1074 cbuf[client_pos++] = '\x02'; /* Two authentication methods supported */
1075 cbuf[client_pos++] = '\x02'; /* Username/password */
1079 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1081 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1083 if (write_socket(sfd, cbuf, client_pos))
1085 errstr = "SOCKS5 negotiation write failed";
1086 csp->error_message = strdup(errstr);
1087 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1089 return(JB_INVALID_SOCKET);
1091 if (!data_is_available(sfd, csp->config->socket_timeout))
1093 if (socket_is_still_alive(sfd))
1095 errstr = "SOCKS5 negotiation timed out";
1099 errstr = "SOCKS5 negotiation got aborted by the server";
1104 if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1107 errstr = "SOCKS5 negotiation read failed";
1111 if (!err && (sbuf[0] != '\x05'))
1113 errstr = "SOCKS5 negotiation protocol version error";
1117 if (!err && (sbuf[1] == '\xff'))
1119 errstr = "SOCKS5 authentication required";
1123 if (!err && (sbuf[1] == '\x02'))
1125 /* check cbuf overflow */
1126 size_t auth_len = strlen(fwd->auth_username) + strlen(fwd->auth_password) + 3;
1127 if (auth_len > sizeof(cbuf))
1129 errstr = "SOCKS5 username and/or password too long";
1136 cbuf[client_pos++] = '\x01'; /* Version */
1137 cbuf[client_pos++] = (char)strlen(fwd->auth_username);
1139 memcpy(cbuf + client_pos, fwd->auth_username, strlen(fwd->auth_username));
1140 client_pos += strlen(fwd->auth_username);
1141 cbuf[client_pos++] = (char)strlen(fwd->auth_password);
1142 memcpy(cbuf + client_pos, fwd->auth_password, strlen(fwd->auth_password));
1143 client_pos += strlen(fwd->auth_password);
1145 if (write_socket(sfd, cbuf, client_pos))
1147 errstr = "SOCKS5 negotiation auth write failed";
1148 csp->error_message = strdup(errstr);
1149 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1151 return(JB_INVALID_SOCKET);
1154 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1156 errstr = "SOCKS5 negotiation auth read failed";
1161 if (!err && (sbuf[1] != '\x00'))
1163 errstr = "SOCKS5 authentication failed";
1167 else if (!err && (sbuf[1] != '\x00'))
1169 errstr = "SOCKS5 negotiation protocol error";
1175 assert(errstr != NULL);
1176 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1177 csp->error_message = strdup(errstr);
1180 return(JB_INVALID_SOCKET);
1184 cbuf[client_pos++] = '\x05'; /* Version */
1185 cbuf[client_pos++] = '\x01'; /* TCP connect */
1186 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1187 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1188 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1189 assert(sizeof(cbuf) - client_pos > (size_t)255);
1190 /* Using strncpy because we really want the nul byte padding. */
1191 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1192 client_pos += (hostlen & 0xffu);
1193 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1194 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1197 if (write_socket(sfd, cbuf, client_pos))
1199 errstr = "SOCKS5 negotiation write failed";
1200 csp->error_message = strdup(errstr);
1201 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1204 return(JB_INVALID_SOCKET);
1208 * Optimistically send the HTTP request with the initial
1209 * SOCKS request if the user enabled the use of Tor extensions,
1210 * the CONNECT method isn't being used (in which case the client
1211 * doesn't send data until it gets our 200 response) and the
1212 * client request has actually been completely read already.
1214 if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1215 && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1217 char *client_headers = list_to_text(csp->headers);
1218 size_t header_length;
1220 if (client_headers == NULL)
1222 log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1224 list_remove_all(csp->headers);
1225 header_length= strlen(client_headers);
1227 log_error(LOG_LEVEL_CONNECT,
1228 "Optimistically sending %lu bytes of client headers intended for %s",
1229 header_length, csp->http->hostport);
1231 if (write_socket(sfd, client_headers, header_length))
1233 log_error(LOG_LEVEL_CONNECT,
1234 "optimistically writing header to: %s failed: %E", csp->http->hostport);
1235 freez(client_headers);
1236 return(JB_INVALID_SOCKET);
1238 freez(client_headers);
1239 if (csp->expected_client_content_length != 0)
1241 unsigned long long buffered_request_bytes =
1242 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1243 log_error(LOG_LEVEL_CONNECT,
1244 "Optimistically sending %llu bytes of client body. Expected %llu",
1245 csp->expected_client_content_length, buffered_request_bytes);
1246 assert(csp->expected_client_content_length == buffered_request_bytes);
1247 if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1249 log_error(LOG_LEVEL_CONNECT,
1250 "optimistically writing %llu bytes of client body to: %s failed: %E",
1251 buffered_request_bytes, csp->http->hostport);
1252 return(JB_INVALID_SOCKET);
1254 clear_iob(csp->client_iob);
1259 server_size = read_socket(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4);
1260 if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1262 errstr = "SOCKS5 negotiation read failed";
1266 if (sbuf[0] != '\x05')
1268 errstr = "SOCKS5 negotiation protocol version error";
1270 else if (sbuf[2] != '\x00')
1272 errstr = "SOCKS5 negotiation protocol error";
1274 else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1276 errstr = translate_socks5_error(sbuf[1]);
1280 if (sbuf[3] == '\x04')
1283 * The address field contains an IPv6 address
1284 * which means we didn't get the whole reply
1285 * yet. Read and discard the rest of it to make
1286 * sure it isn't treated as HTTP data later on.
1288 server_size = read_socket(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE);
1289 if (server_size != SOCKS5_REPLY_DIFFERENCE)
1291 errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1294 else if (sbuf[3] != '\x01')
1296 errstr = "SOCKS5 reply contains unsupported address type";
1305 assert(errstr != NULL);
1306 csp->error_message = strdup(errstr);
1307 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1311 return(JB_INVALID_SOCKET);