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. http://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__ */
60 #endif /* def __OS2__ */
65 #include "jbsockets.h"
71 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
77 #endif /* def __GLIBC__ */
78 #endif /* HAVE_POLL */
79 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
81 static jb_socket socks4_connect(const struct forward_spec * fwd,
82 const char * target_host,
84 struct client_state *csp);
86 static jb_socket socks5_connect(const struct forward_spec *fwd,
87 const char *target_host,
89 struct client_state *csp);
92 SOCKS4_REQUEST_GRANTED = 90,
93 SOCKS4_REQUEST_REJECT = 91,
94 SOCKS4_REQUEST_IDENT_FAILED = 92,
95 SOCKS4_REQUEST_IDENT_CONFLICT = 93
99 SOCKS5_REQUEST_GRANTED = 0,
100 SOCKS5_REQUEST_FAILED = 1,
101 SOCKS5_REQUEST_DENIED = 2,
102 SOCKS5_REQUEST_NETWORK_UNREACHABLE = 3,
103 SOCKS5_REQUEST_HOST_UNREACHABLE = 4,
104 SOCKS5_REQUEST_CONNECTION_REFUSED = 5,
105 SOCKS5_REQUEST_TTL_EXPIRED = 6,
106 SOCKS5_REQUEST_PROTOCOL_ERROR = 7,
107 SOCKS5_REQUEST_BAD_ADDRESS_TYPE = 8
110 /* structure of a socks client operation */
112 unsigned char vn; /* socks version number */
113 unsigned char cd; /* command code */
114 unsigned char dstport[2]; /* destination port */
115 unsigned char dstip[4]; /* destination address */
116 char userid; /* first byte of userid */
117 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
118 /* more bytes of the userid follow, terminated by a NULL */
121 /* structure of a socks server reply */
123 unsigned char vn; /* socks version number */
124 unsigned char cd; /* command code */
125 unsigned char dstport[2]; /* destination port */
126 unsigned char dstip[4]; /* destination address */
129 static const char socks_userid[] = "anonymous";
131 #ifdef FEATURE_CONNECTION_SHARING
133 #define MAX_REUSABLE_CONNECTIONS 100
135 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
136 static int mark_connection_unused(const struct reusable_connection *connection);
138 /*********************************************************************
140 * Function : initialize_reusable_connections
142 * Description : Initializes the reusable_connection structures.
143 * Must be called with connection_reuse_mutex locked.
149 *********************************************************************/
150 extern void initialize_reusable_connections(void)
152 unsigned int slot = 0;
154 #if !defined(HAVE_POLL) && !defined(_WIN32)
155 log_error(LOG_LEVEL_INFO,
156 "Detecting already dead connections might not work "
157 "correctly on your platform. In case of problems, "
158 "unset the keep-alive-timeout option.");
161 for (slot = 0; slot < SZ(reusable_connection); slot++)
163 mark_connection_closed(&reusable_connection[slot]);
166 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
170 /*********************************************************************
172 * Function : remember_connection
174 * Description : Remembers a server connection for reuse later on.
177 * 1 : connection = The server connection to remember.
181 *********************************************************************/
182 void remember_connection(const struct reusable_connection *connection)
184 unsigned int slot = 0;
185 int free_slot_found = FALSE;
187 assert(NULL != connection);
188 assert(connection->sfd != JB_INVALID_SOCKET);
190 if (mark_connection_unused(connection))
195 privoxy_mutex_lock(&connection_reuse_mutex);
197 /* Find free socket slot. */
198 for (slot = 0; slot < SZ(reusable_connection); slot++)
200 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
202 assert(reusable_connection[slot].in_use == 0);
203 log_error(LOG_LEVEL_CONNECT,
204 "Remembering socket %d for %s:%d in slot %d.",
205 connection->sfd, connection->host, connection->port, slot);
206 free_slot_found = TRUE;
211 if (!free_slot_found)
213 log_error(LOG_LEVEL_CONNECT,
214 "No free slots found to remember socket for %s:%d. Last slot %d.",
215 connection->host, connection->port, slot);
216 privoxy_mutex_unlock(&connection_reuse_mutex);
217 close_socket(connection->sfd);
221 assert(NULL != connection->host);
222 reusable_connection[slot].host = strdup_or_die(connection->host);
223 reusable_connection[slot].sfd = connection->sfd;
224 reusable_connection[slot].port = connection->port;
225 reusable_connection[slot].in_use = 0;
226 reusable_connection[slot].timestamp = connection->timestamp;
227 reusable_connection[slot].request_sent = connection->request_sent;
228 reusable_connection[slot].response_received = connection->response_received;
229 reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
230 reusable_connection[slot].requests_sent_total = connection->requests_sent_total;
232 assert(reusable_connection[slot].gateway_host == NULL);
233 assert(reusable_connection[slot].gateway_port == 0);
234 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
235 assert(reusable_connection[slot].forward_host == NULL);
236 assert(reusable_connection[slot].forward_port == 0);
238 reusable_connection[slot].forwarder_type = connection->forwarder_type;
239 if (NULL != connection->gateway_host)
241 reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
245 reusable_connection[slot].gateway_host = NULL;
247 reusable_connection[slot].gateway_port = connection->gateway_port;
249 if (NULL != connection->forward_host)
251 reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
255 reusable_connection[slot].forward_host = NULL;
257 reusable_connection[slot].forward_port = connection->forward_port;
259 privoxy_mutex_unlock(&connection_reuse_mutex);
261 #endif /* def FEATURE_CONNECTION_SHARING */
264 /*********************************************************************
266 * Function : mark_connection_closed
268 * Description : Marks a reused connection closed.
271 * 1 : closed_connection = The connection to mark as closed.
275 *********************************************************************/
276 void mark_connection_closed(struct reusable_connection *closed_connection)
278 closed_connection->in_use = FALSE;
279 closed_connection->sfd = JB_INVALID_SOCKET;
280 freez(closed_connection->host);
281 closed_connection->port = 0;
282 closed_connection->timestamp = 0;
283 closed_connection->request_sent = 0;
284 closed_connection->response_received = 0;
285 closed_connection->keep_alive_timeout = 0;
286 closed_connection->requests_sent_total = 0;
287 closed_connection->forwarder_type = SOCKS_NONE;
288 freez(closed_connection->gateway_host);
289 closed_connection->gateway_port = 0;
290 freez(closed_connection->forward_host);
291 closed_connection->forward_port = 0;
295 #ifdef FEATURE_CONNECTION_SHARING
296 /*********************************************************************
298 * Function : forget_connection
300 * Description : Removes a previously remembered connection from
301 * the list of reusable connections.
304 * 1 : sfd = The socket belonging to the connection in question.
308 *********************************************************************/
309 void forget_connection(jb_socket sfd)
311 unsigned int slot = 0;
313 assert(sfd != JB_INVALID_SOCKET);
315 privoxy_mutex_lock(&connection_reuse_mutex);
317 for (slot = 0; slot < SZ(reusable_connection); slot++)
319 if (reusable_connection[slot].sfd == sfd)
321 assert(reusable_connection[slot].in_use);
323 log_error(LOG_LEVEL_CONNECT,
324 "Forgetting socket %d for %s:%d in slot %d.",
325 sfd, reusable_connection[slot].host,
326 reusable_connection[slot].port, slot);
327 mark_connection_closed(&reusable_connection[slot]);
332 privoxy_mutex_unlock(&connection_reuse_mutex);
335 #endif /* def FEATURE_CONNECTION_SHARING */
338 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
339 /*********************************************************************
341 * Function : connection_destination_matches
343 * Description : Determines whether a remembered connection can
344 * be reused. That is, whether the destination and
345 * the forwarding settings match.
348 * 1 : connection = The connection to check.
349 * 2 : http = The destination for the connection.
350 * 3 : fwd = The forwarder settings.
352 * Returns : TRUE for yes, FALSE otherwise.
354 *********************************************************************/
355 int connection_destination_matches(const struct reusable_connection *connection,
356 const struct http_request *http,
357 const struct forward_spec *fwd)
359 if ((connection->forwarder_type != fwd->type)
360 || (connection->gateway_port != fwd->gateway_port)
361 || (connection->forward_port != fwd->forward_port)
362 || (connection->port != http->port))
367 if (( (NULL != connection->gateway_host)
368 && (NULL != fwd->gateway_host)
369 && strcmpic(connection->gateway_host, fwd->gateway_host))
370 && (connection->gateway_host != fwd->gateway_host))
372 log_error(LOG_LEVEL_CONNECT,
373 "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
374 connection->gateway_host, fwd->gateway_host);
378 if (( (NULL != connection->forward_host)
379 && (NULL != fwd->forward_host)
380 && strcmpic(connection->forward_host, fwd->forward_host))
381 && (connection->forward_host != fwd->forward_host))
383 log_error(LOG_LEVEL_CONNECT,
384 "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
385 connection->forward_host, fwd->forward_host);
389 return (!strcmpic(connection->host, http->host));
392 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
395 #ifdef FEATURE_CONNECTION_SHARING
396 /*********************************************************************
398 * Function : close_unusable_connections
400 * Description : Closes remembered connections that have timed
401 * out or have been closed on the other side.
405 * Returns : Number of connections that are still alive.
407 *********************************************************************/
408 int close_unusable_connections(void)
410 unsigned int slot = 0;
411 int connections_alive = 0;
413 privoxy_mutex_lock(&connection_reuse_mutex);
415 for (slot = 0; slot < SZ(reusable_connection); slot++)
417 if (!reusable_connection[slot].in_use
418 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
420 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
421 time_t latency = (reusable_connection[slot].response_received -
422 reusable_connection[slot].request_sent) / 2;
424 if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
426 log_error(LOG_LEVEL_CONNECT,
427 "The connection to %s:%d in slot %d timed out. "
428 "Closing socket %d. Timeout is: %d. Assumed latency: %d.",
429 reusable_connection[slot].host,
430 reusable_connection[slot].port, slot,
431 reusable_connection[slot].sfd,
432 reusable_connection[slot].keep_alive_timeout,
434 close_socket(reusable_connection[slot].sfd);
435 mark_connection_closed(&reusable_connection[slot]);
437 else if (!socket_is_still_alive(reusable_connection[slot].sfd))
439 log_error(LOG_LEVEL_CONNECT,
440 "The connection to %s:%d in slot %d is no longer usable. "
441 "Closing socket %d.", reusable_connection[slot].host,
442 reusable_connection[slot].port, slot,
443 reusable_connection[slot].sfd);
444 close_socket(reusable_connection[slot].sfd);
445 mark_connection_closed(&reusable_connection[slot]);
454 privoxy_mutex_unlock(&connection_reuse_mutex);
456 return connections_alive;
461 /*********************************************************************
463 * Function : get_reusable_connection
465 * Description : Returns an open socket to a previously remembered
466 * open connection (if there is one).
469 * 1 : http = The destination for the connection.
470 * 2 : fwd = The forwarder settings.
472 * Returns : JB_INVALID_SOCKET => No reusable connection found,
473 * otherwise a usable socket.
475 *********************************************************************/
476 static jb_socket get_reusable_connection(const struct http_request *http,
477 const struct forward_spec *fwd)
479 jb_socket sfd = JB_INVALID_SOCKET;
480 unsigned int slot = 0;
482 close_unusable_connections();
484 privoxy_mutex_lock(&connection_reuse_mutex);
486 for (slot = 0; slot < SZ(reusable_connection); slot++)
488 if (!reusable_connection[slot].in_use
489 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
491 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
493 reusable_connection[slot].in_use = TRUE;
494 sfd = reusable_connection[slot].sfd;
495 log_error(LOG_LEVEL_CONNECT,
496 "Found reusable socket %d for %s:%d in slot %d. Timestamp made %d "
497 "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
498 sfd, reusable_connection[slot].host, reusable_connection[slot].port,
499 slot, time(NULL) - reusable_connection[slot].timestamp,
500 reusable_connection[slot].keep_alive_timeout,
501 (int)(reusable_connection[slot].response_received -
502 reusable_connection[slot].request_sent),
503 reusable_connection[slot].requests_sent_total);
509 privoxy_mutex_unlock(&connection_reuse_mutex);
516 /*********************************************************************
518 * Function : mark_connection_unused
520 * Description : Gives a remembered connection free for reuse.
523 * 1 : connection = The connection in question.
525 * Returns : TRUE => Socket found and marked as unused.
526 * FALSE => Socket not found.
528 *********************************************************************/
529 static int mark_connection_unused(const struct reusable_connection *connection)
531 unsigned int slot = 0;
532 int socket_found = FALSE;
534 assert(connection->sfd != JB_INVALID_SOCKET);
536 privoxy_mutex_lock(&connection_reuse_mutex);
538 for (slot = 0; slot < SZ(reusable_connection); slot++)
540 if (reusable_connection[slot].sfd == connection->sfd)
542 assert(reusable_connection[slot].in_use);
544 log_error(LOG_LEVEL_CONNECT,
545 "Marking open socket %d for %s:%d in slot %d as unused.",
546 connection->sfd, reusable_connection[slot].host,
547 reusable_connection[slot].port, slot);
548 reusable_connection[slot].in_use = 0;
549 reusable_connection[slot].timestamp = connection->timestamp;
554 privoxy_mutex_unlock(&connection_reuse_mutex);
559 #endif /* def FEATURE_CONNECTION_SHARING */
562 /*********************************************************************
564 * Function : forwarded_connect
566 * Description : Connect to a specified web server, possibly via
567 * a HTTP proxy and/or a SOCKS proxy.
570 * 1 : fwd = the proxies to use when connecting.
571 * 2 : http = the http request and apropos headers
572 * 3 : csp = Current client state (buffers, headers, etc...)
574 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
576 *********************************************************************/
577 jb_socket forwarded_connect(const struct forward_spec * fwd,
578 struct http_request *http,
579 struct client_state *csp)
581 const char * dest_host;
583 jb_socket sfd = JB_INVALID_SOCKET;
585 #ifdef FEATURE_CONNECTION_SHARING
586 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
587 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
589 sfd = get_reusable_connection(http, fwd);
590 if (JB_INVALID_SOCKET != sfd)
595 #endif /* def FEATURE_CONNECTION_SHARING */
597 /* Figure out if we need to connect to the web server or a HTTP proxy. */
598 if (fwd->forward_host)
601 dest_host = fwd->forward_host;
602 dest_port = fwd->forward_port;
607 dest_host = http->host;
608 dest_port = http->port;
611 /* Connect, maybe using a SOCKS proxy */
615 case FORWARD_WEBSERVER:
616 sfd = connect_to(dest_host, dest_port, csp);
620 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
624 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
627 /* Should never get here */
628 log_error(LOG_LEVEL_FATAL,
629 "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
632 if (JB_INVALID_SOCKET != sfd)
634 log_error(LOG_LEVEL_CONNECT,
635 "Created new connection to %s:%d on socket %d.",
636 http->host, http->port, sfd);
645 /*********************************************************************
647 * Function : socks_fuzz
649 * Description : Wrapper around socks[45]_connect() used for fuzzing.
652 * 1 : csp = Current client state (buffers, headers, etc...)
654 * Returns : JB_ERR_OK or JB_ERR_PARSE
656 *********************************************************************/
657 extern jb_err socks_fuzz(struct client_state *csp)
660 static struct forward_spec fwd;
661 char target_host[] = "fuzz.example.org";
662 int target_port = 12345;
664 fwd.gateway_host = strdup_or_die("fuzz.example.org");
665 fwd.gateway_port = 12345;
668 socket = socks4_connect(&fwd, target_host, target_port, csp);
670 if (JB_INVALID_SOCKET != socket)
673 socket = socks5_connect(&fwd, target_host, target_port, csp);
676 if (JB_INVALID_SOCKET == socket)
678 log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
682 log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
689 /*********************************************************************
691 * Function : socks4_connect
693 * Description : Connect to the SOCKS server, and connect through
694 * it to the specified server. This handles
695 * all the SOCKS negotiation, and returns a file
696 * descriptor for a socket which can be treated as a
697 * normal (non-SOCKS) socket.
699 * Logged error messages are saved to csp->error_message
700 * and later reused by error_response() for the CGI
701 * message. strdup allocation failures are handled there.
704 * 1 : fwd = Specifies the SOCKS proxy to use.
705 * 2 : target_host = The final server to connect to.
706 * 3 : target_port = The final port to connect to.
707 * 4 : csp = Current client state (buffers, headers, etc...)
709 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
711 *********************************************************************/
712 static jb_socket socks4_connect(const struct forward_spec * fwd,
713 const char * target_host,
715 struct client_state *csp)
717 unsigned long web_server_addr;
718 char buf[BUFFER_SIZE];
719 struct socks_op *c = (struct socks_op *)buf;
720 struct socks_reply *s = (struct socks_reply *)buf;
727 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
729 /* XXX: Shouldn't the config file parser prevent this? */
730 errstr = "NULL gateway host specified.";
734 if (fwd->gateway_port <= 0)
736 errstr = "invalid gateway port specified.";
742 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
743 csp->error_message = strdup(errstr);
745 return(JB_INVALID_SOCKET);
748 /* build a socks request for connection to the web server */
750 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
752 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
757 web_server_addr = resolve_hostname_to_ip(target_host);
758 if (web_server_addr == INADDR_NONE)
760 errstr = "could not resolve target host";
761 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
766 web_server_addr = htonl(web_server_addr);
770 web_server_addr = 0x00000001;
771 n = csiz + strlen(target_host) + 1;
775 errstr = "buffer cbuf too small.";
776 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
781 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
783 * What we forward to the socks4a server should have the
784 * size of socks_op, plus the length of the userid plus
785 * its \0 byte (which we don't have to add because the
786 * first byte of the userid is counted twice as it's also
787 * part of sock_op) minus the padding bytes (which are part
788 * of the userid as well), plus the length of the target_host
789 * (which is stored csiz bytes after the beginning of the buffer),
790 * plus another \0 byte.
792 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
797 /* Should never get here */
798 log_error(LOG_LEVEL_FATAL,
799 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
801 return(JB_INVALID_SOCKET);
806 csp->error_message = strdup(errstr);
807 return(JB_INVALID_SOCKET);
812 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
813 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
814 c->dstip[0] = (unsigned char)((web_server_addr >> 24) & 0xff);
815 c->dstip[1] = (unsigned char)((web_server_addr >> 16) & 0xff);
816 c->dstip[2] = (unsigned char)((web_server_addr >> 8) & 0xff);
817 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
822 /* pass the request to the socks server */
823 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
825 if (sfd == JB_INVALID_SOCKET)
827 /* The error an its reason have already been logged by connect_to() */
828 return(JB_INVALID_SOCKET);
830 else if (write_socket(sfd, (char *)c, csiz))
832 errstr = "SOCKS4 negotiation write failed.";
833 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
837 else if (!data_is_available(sfd, csp->config->socket_timeout))
839 if (socket_is_still_alive(sfd))
841 errstr = "SOCKS4 negotiation timed out";
845 errstr = "SOCKS4 negotiation got aborted by the server";
847 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
853 if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
855 errstr = "SOCKS4 negotiation read failed.";
856 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
863 csp->error_message = strdup(errstr);
864 return(JB_INVALID_SOCKET);
869 case SOCKS4_REQUEST_GRANTED:
871 case SOCKS4_REQUEST_REJECT:
872 errstr = "SOCKS request rejected or failed.";
875 case SOCKS4_REQUEST_IDENT_FAILED:
876 errstr = "SOCKS request rejected because "
877 "SOCKS server cannot connect to identd on the client.";
880 case SOCKS4_REQUEST_IDENT_CONFLICT:
881 errstr = "SOCKS request rejected because "
882 "the client program and identd report "
883 "different user-ids.";
888 snprintf(buf, sizeof(buf),
889 "SOCKS request rejected for reason code %d.", s->cd);
893 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
894 csp->error_message = strdup(errstr);
897 return(JB_INVALID_SOCKET);
901 /*********************************************************************
903 * Function : translate_socks5_error
905 * Description : Translates a SOCKS errors to a string.
908 * 1 : socks_error = The error code to translate.
910 * Returns : The string translation.
912 *********************************************************************/
913 static const char *translate_socks5_error(int socks_error)
917 /* XXX: these should be more descriptive */
918 case SOCKS5_REQUEST_FAILED:
919 return "SOCKS5 request failed";
920 case SOCKS5_REQUEST_DENIED:
921 return "SOCKS5 request denied";
922 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
923 return "SOCKS5 network unreachable";
924 case SOCKS5_REQUEST_HOST_UNREACHABLE:
925 return "SOCKS5 destination host unreachable";
926 case SOCKS5_REQUEST_CONNECTION_REFUSED:
927 return "SOCKS5 connection refused";
928 case SOCKS5_REQUEST_TTL_EXPIRED:
929 return "SOCKS5 TTL expired";
930 case SOCKS5_REQUEST_PROTOCOL_ERROR:
931 return "SOCKS5 client protocol error";
932 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
933 return "SOCKS5 domain names unsupported";
934 case SOCKS5_REQUEST_GRANTED:
935 return "everything's peachy";
937 return "SOCKS5 negotiation protocol error";
942 /*********************************************************************
944 * Function : socks5_connect
946 * Description : Connect to the SOCKS server, and connect through
947 * it to the specified server. This handles
948 * all the SOCKS negotiation, and returns a file
949 * descriptor for a socket which can be treated as a
950 * normal (non-SOCKS) socket.
953 * 1 : fwd = Specifies the SOCKS proxy to use.
954 * 2 : target_host = The final server to connect to.
955 * 3 : target_port = The final port to connect to.
956 * 4 : csp = Current client state (buffers, headers, etc...)
958 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
960 *********************************************************************/
961 static jb_socket socks5_connect(const struct forward_spec *fwd,
962 const char *target_host,
964 struct client_state *csp)
966 #define SIZE_SOCKS5_REPLY_IPV4 10
967 #define SIZE_SOCKS5_REPLY_IPV6 22
968 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
971 char sbuf[SIZE_SOCKS5_REPLY_IPV6];
972 size_t client_pos = 0;
976 const char *errstr = NULL;
978 assert(fwd->gateway_host);
979 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
981 errstr = "NULL gateway host specified";
985 if (fwd->gateway_port <= 0)
988 * XXX: currently this can't happen because in
989 * case of invalid gateway ports we use the defaults.
990 * Of course we really shouldn't do that.
992 errstr = "invalid gateway port specified";
996 hostlen = strlen(target_host);
997 if (hostlen > (size_t)255)
999 errstr = "target host name is longer than 255 characters";
1003 if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1005 /* Should never get here */
1006 log_error(LOG_LEVEL_FATAL,
1007 "SOCKS5 impossible internal error - bad SOCKS type");
1014 assert(errstr != NULL);
1015 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1016 csp->error_message = strdup(errstr);
1017 return(JB_INVALID_SOCKET);
1022 if (!err && read_socket(sfd, sbuf, 2) != 2)
1024 /* pass the request to the socks server */
1025 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1027 if (sfd == JB_INVALID_SOCKET)
1029 errstr = "socks5 server unreachable";
1030 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1031 /* Free the generic error message provided by connect_to() */
1032 freez(csp->error_message);
1033 csp->error_message = strdup(errstr);
1034 return(JB_INVALID_SOCKET);
1038 cbuf[client_pos++] = '\x05'; /* Version */
1039 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1040 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1042 if (write_socket(sfd, cbuf, client_pos))
1044 errstr = "SOCKS5 negotiation write failed";
1045 csp->error_message = strdup(errstr);
1046 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1048 return(JB_INVALID_SOCKET);
1050 if (!data_is_available(sfd, csp->config->socket_timeout))
1052 if (socket_is_still_alive(sfd))
1054 errstr = "SOCKS5 negotiation timed out";
1058 errstr = "SOCKS5 negotiation got aborted by the server";
1063 if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1066 errstr = "SOCKS5 negotiation read failed";
1070 if (!err && (sbuf[0] != '\x05'))
1072 errstr = "SOCKS5 negotiation protocol version error";
1076 if (!err && (sbuf[1] == '\xff'))
1078 errstr = "SOCKS5 authentication required";
1082 if (!err && (sbuf[1] != '\x00'))
1084 errstr = "SOCKS5 negotiation protocol error";
1090 assert(errstr != NULL);
1091 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1092 csp->error_message = strdup(errstr);
1095 return(JB_INVALID_SOCKET);
1099 cbuf[client_pos++] = '\x05'; /* Version */
1100 cbuf[client_pos++] = '\x01'; /* TCP connect */
1101 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1102 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1103 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1104 assert(sizeof(cbuf) - client_pos > (size_t)255);
1105 /* Using strncpy because we really want the nul byte padding. */
1106 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1107 client_pos += (hostlen & 0xffu);
1108 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1109 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1112 if (write_socket(sfd, cbuf, client_pos))
1114 errstr = "SOCKS5 negotiation write failed";
1115 csp->error_message = strdup(errstr);
1116 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1119 return(JB_INVALID_SOCKET);
1123 * Optimistically send the HTTP request with the initial
1124 * SOCKS request if the user enabled the use of Tor extensions,
1125 * the CONNECT method isn't being used (in which case the client
1126 * doesn't send data until it gets our 200 response) and the
1127 * client request has actually been completely read already.
1129 if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1130 && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1132 char *client_headers = list_to_text(csp->headers);
1133 size_t header_length;
1135 if (client_headers == NULL)
1137 log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1139 list_remove_all(csp->headers);
1140 header_length= strlen(client_headers);
1142 log_error(LOG_LEVEL_CONNECT,
1143 "Optimistically sending %d bytes of client headers intended for %s",
1144 header_length, csp->http->hostport);
1146 if (write_socket(sfd, client_headers, header_length))
1148 log_error(LOG_LEVEL_CONNECT,
1149 "optimistically writing header to: %s failed: %E", csp->http->hostport);
1150 freez(client_headers);
1151 return(JB_INVALID_SOCKET);
1153 freez(client_headers);
1154 if (csp->expected_client_content_length != 0)
1156 unsigned long long buffered_request_bytes =
1157 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1158 log_error(LOG_LEVEL_CONNECT,
1159 "Optimistically sending %llu bytes of client body. Expected %llu",
1160 csp->expected_client_content_length, buffered_request_bytes);
1161 assert(csp->expected_client_content_length == buffered_request_bytes);
1162 if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1164 log_error(LOG_LEVEL_CONNECT,
1165 "optimistically writing %llu bytes of client body to: %s failed: %E",
1166 buffered_request_bytes, csp->http->hostport);
1167 return(JB_INVALID_SOCKET);
1169 clear_iob(csp->client_iob);
1174 server_size = read_socket(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4);
1175 if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1177 errstr = "SOCKS5 negotiation read failed";
1181 if (sbuf[0] != '\x05')
1183 errstr = "SOCKS5 negotiation protocol version error";
1185 else if (sbuf[2] != '\x00')
1187 errstr = "SOCKS5 negotiation protocol error";
1189 else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1191 errstr = translate_socks5_error(sbuf[1]);
1195 if (sbuf[3] == '\x04')
1198 * The address field contains an IPv6 address
1199 * which means we didn't get the whole reply
1200 * yet. Read and discard the rest of it to make
1201 * sure it isn't treated as HTTP data later on.
1203 server_size = read_socket(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE);
1204 if (server_size != SOCKS5_REPLY_DIFFERENCE)
1206 errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1209 else if (sbuf[3] != '\x01')
1211 errstr = "SOCKS5 reply contains unsupported address type";
1220 assert(errstr != NULL);
1221 csp->error_message = strdup(errstr);
1222 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1226 return(JB_INVALID_SOCKET);