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__ */
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(slot < SZ(reusable_connection));
222 assert(NULL != connection->host);
223 reusable_connection[slot].host = strdup_or_die(connection->host);
224 reusable_connection[slot].sfd = connection->sfd;
225 reusable_connection[slot].port = connection->port;
226 reusable_connection[slot].in_use = 0;
227 reusable_connection[slot].timestamp = connection->timestamp;
228 reusable_connection[slot].request_sent = connection->request_sent;
229 reusable_connection[slot].response_received = connection->response_received;
230 reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
231 reusable_connection[slot].requests_sent_total = connection->requests_sent_total;
233 assert(reusable_connection[slot].gateway_host == NULL);
234 assert(reusable_connection[slot].gateway_port == 0);
235 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
236 assert(reusable_connection[slot].forward_host == NULL);
237 assert(reusable_connection[slot].forward_port == 0);
239 reusable_connection[slot].forwarder_type = connection->forwarder_type;
240 if (NULL != connection->gateway_host)
242 reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
246 reusable_connection[slot].gateway_host = NULL;
248 reusable_connection[slot].gateway_port = connection->gateway_port;
250 if (NULL != connection->forward_host)
252 reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
256 reusable_connection[slot].forward_host = NULL;
258 reusable_connection[slot].forward_port = connection->forward_port;
260 privoxy_mutex_unlock(&connection_reuse_mutex);
262 #endif /* def FEATURE_CONNECTION_SHARING */
265 /*********************************************************************
267 * Function : mark_connection_closed
269 * Description : Marks a reused connection closed.
272 * 1 : closed_connection = The connection to mark as closed.
276 *********************************************************************/
277 void mark_connection_closed(struct reusable_connection *closed_connection)
279 closed_connection->in_use = FALSE;
280 closed_connection->sfd = JB_INVALID_SOCKET;
281 freez(closed_connection->host);
282 closed_connection->port = 0;
283 closed_connection->timestamp = 0;
284 closed_connection->request_sent = 0;
285 closed_connection->response_received = 0;
286 closed_connection->keep_alive_timeout = 0;
287 closed_connection->requests_sent_total = 0;
288 closed_connection->forwarder_type = SOCKS_NONE;
289 freez(closed_connection->gateway_host);
290 closed_connection->gateway_port = 0;
291 freez(closed_connection->forward_host);
292 closed_connection->forward_port = 0;
296 #ifdef FEATURE_CONNECTION_SHARING
297 /*********************************************************************
299 * Function : forget_connection
301 * Description : Removes a previously remembered connection from
302 * the list of reusable connections.
305 * 1 : sfd = The socket belonging to the connection in question.
309 *********************************************************************/
310 void forget_connection(jb_socket sfd)
312 unsigned int slot = 0;
314 assert(sfd != JB_INVALID_SOCKET);
316 privoxy_mutex_lock(&connection_reuse_mutex);
318 for (slot = 0; slot < SZ(reusable_connection); slot++)
320 if (reusable_connection[slot].sfd == sfd)
322 assert(reusable_connection[slot].in_use);
324 log_error(LOG_LEVEL_CONNECT,
325 "Forgetting socket %d for %s:%d in slot %d.",
326 sfd, reusable_connection[slot].host,
327 reusable_connection[slot].port, slot);
328 mark_connection_closed(&reusable_connection[slot]);
333 privoxy_mutex_unlock(&connection_reuse_mutex);
336 #endif /* def FEATURE_CONNECTION_SHARING */
339 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
340 /*********************************************************************
342 * Function : connection_destination_matches
344 * Description : Determines whether a remembered connection can
345 * be reused. That is, whether the destination and
346 * the forwarding settings match.
349 * 1 : connection = The connection to check.
350 * 2 : http = The destination for the connection.
351 * 3 : fwd = The forwarder settings.
353 * Returns : TRUE for yes, FALSE otherwise.
355 *********************************************************************/
356 int connection_destination_matches(const struct reusable_connection *connection,
357 const struct http_request *http,
358 const struct forward_spec *fwd)
360 if ((connection->forwarder_type != fwd->type)
361 || (connection->gateway_port != fwd->gateway_port)
362 || (connection->forward_port != fwd->forward_port)
363 || (connection->port != http->port))
368 if (( (NULL != connection->gateway_host)
369 && (NULL != fwd->gateway_host)
370 && strcmpic(connection->gateway_host, fwd->gateway_host))
371 && (connection->gateway_host != fwd->gateway_host))
373 log_error(LOG_LEVEL_CONNECT,
374 "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
375 connection->gateway_host, fwd->gateway_host);
379 if (( (NULL != connection->forward_host)
380 && (NULL != fwd->forward_host)
381 && strcmpic(connection->forward_host, fwd->forward_host))
382 && (connection->forward_host != fwd->forward_host))
384 log_error(LOG_LEVEL_CONNECT,
385 "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
386 connection->forward_host, fwd->forward_host);
390 return (!strcmpic(connection->host, http->host));
393 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
396 #ifdef FEATURE_CONNECTION_SHARING
397 /*********************************************************************
399 * Function : close_unusable_connections
401 * Description : Closes remembered connections that have timed
402 * out or have been closed on the other side.
406 * Returns : Number of connections that are still alive.
408 *********************************************************************/
409 int close_unusable_connections(void)
411 unsigned int slot = 0;
412 int connections_alive = 0;
414 privoxy_mutex_lock(&connection_reuse_mutex);
416 for (slot = 0; slot < SZ(reusable_connection); slot++)
418 if (!reusable_connection[slot].in_use
419 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
421 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
422 time_t latency = (reusable_connection[slot].response_received -
423 reusable_connection[slot].request_sent) / 2;
425 if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
427 log_error(LOG_LEVEL_CONNECT,
428 "The connection to %s:%d in slot %d timed out. "
429 "Closing socket %d. Timeout is: %d. Assumed latency: %d.",
430 reusable_connection[slot].host,
431 reusable_connection[slot].port, slot,
432 reusable_connection[slot].sfd,
433 reusable_connection[slot].keep_alive_timeout,
435 close_socket(reusable_connection[slot].sfd);
436 mark_connection_closed(&reusable_connection[slot]);
438 else if (!socket_is_still_alive(reusable_connection[slot].sfd))
440 log_error(LOG_LEVEL_CONNECT,
441 "The connection to %s:%d in slot %d is no longer usable. "
442 "Closing socket %d.", reusable_connection[slot].host,
443 reusable_connection[slot].port, slot,
444 reusable_connection[slot].sfd);
445 close_socket(reusable_connection[slot].sfd);
446 mark_connection_closed(&reusable_connection[slot]);
455 privoxy_mutex_unlock(&connection_reuse_mutex);
457 return connections_alive;
462 /*********************************************************************
464 * Function : get_reusable_connection
466 * Description : Returns an open socket to a previously remembered
467 * open connection (if there is one).
470 * 1 : http = The destination for the connection.
471 * 2 : fwd = The forwarder settings.
473 * Returns : JB_INVALID_SOCKET => No reusable connection found,
474 * otherwise a usable socket.
476 *********************************************************************/
477 static jb_socket get_reusable_connection(const struct http_request *http,
478 const struct forward_spec *fwd)
480 jb_socket sfd = JB_INVALID_SOCKET;
481 unsigned int slot = 0;
483 close_unusable_connections();
485 privoxy_mutex_lock(&connection_reuse_mutex);
487 for (slot = 0; slot < SZ(reusable_connection); slot++)
489 if (!reusable_connection[slot].in_use
490 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
492 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
494 reusable_connection[slot].in_use = TRUE;
495 sfd = reusable_connection[slot].sfd;
496 log_error(LOG_LEVEL_CONNECT,
497 "Found reusable socket %d for %s:%d in slot %d. Timestamp made %d "
498 "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
499 sfd, reusable_connection[slot].host, reusable_connection[slot].port,
500 slot, time(NULL) - reusable_connection[slot].timestamp,
501 reusable_connection[slot].keep_alive_timeout,
502 (int)(reusable_connection[slot].response_received -
503 reusable_connection[slot].request_sent),
504 reusable_connection[slot].requests_sent_total);
510 privoxy_mutex_unlock(&connection_reuse_mutex);
517 /*********************************************************************
519 * Function : mark_connection_unused
521 * Description : Gives a remembered connection free for reuse.
524 * 1 : connection = The connection in question.
526 * Returns : TRUE => Socket found and marked as unused.
527 * FALSE => Socket not found.
529 *********************************************************************/
530 static int mark_connection_unused(const struct reusable_connection *connection)
532 unsigned int slot = 0;
533 int socket_found = FALSE;
535 assert(connection->sfd != JB_INVALID_SOCKET);
537 privoxy_mutex_lock(&connection_reuse_mutex);
539 for (slot = 0; slot < SZ(reusable_connection); slot++)
541 if (reusable_connection[slot].sfd == connection->sfd)
543 assert(reusable_connection[slot].in_use);
545 log_error(LOG_LEVEL_CONNECT,
546 "Marking open socket %d for %s:%d in slot %d as unused.",
547 connection->sfd, reusable_connection[slot].host,
548 reusable_connection[slot].port, slot);
549 reusable_connection[slot].in_use = 0;
550 reusable_connection[slot].timestamp = connection->timestamp;
555 privoxy_mutex_unlock(&connection_reuse_mutex);
560 #endif /* def FEATURE_CONNECTION_SHARING */
563 /*********************************************************************
565 * Function : forwarded_connect
567 * Description : Connect to a specified web server, possibly via
568 * a HTTP proxy and/or a SOCKS proxy.
571 * 1 : fwd = the proxies to use when connecting.
572 * 2 : http = the http request and apropos headers
573 * 3 : csp = Current client state (buffers, headers, etc...)
575 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
577 *********************************************************************/
578 jb_socket forwarded_connect(const struct forward_spec * fwd,
579 struct http_request *http,
580 struct client_state *csp)
582 const char * dest_host;
584 jb_socket sfd = JB_INVALID_SOCKET;
586 #ifdef FEATURE_CONNECTION_SHARING
587 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
588 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
590 sfd = get_reusable_connection(http, fwd);
591 if (JB_INVALID_SOCKET != sfd)
596 #endif /* def FEATURE_CONNECTION_SHARING */
598 /* Figure out if we need to connect to the web server or a HTTP proxy. */
599 if (fwd->forward_host)
602 dest_host = fwd->forward_host;
603 dest_port = fwd->forward_port;
608 dest_host = http->host;
609 dest_port = http->port;
612 /* Connect, maybe using a SOCKS proxy */
616 case FORWARD_WEBSERVER:
617 sfd = connect_to(dest_host, dest_port, csp);
621 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
625 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
628 /* Should never get here */
629 log_error(LOG_LEVEL_FATAL,
630 "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
633 if (JB_INVALID_SOCKET != sfd)
635 log_error(LOG_LEVEL_CONNECT,
636 "Created new connection to %s:%d on socket %d.",
637 http->host, http->port, sfd);
646 /*********************************************************************
648 * Function : socks_fuzz
650 * Description : Wrapper around socks[45]_connect() used for fuzzing.
653 * 1 : csp = Current client state (buffers, headers, etc...)
655 * Returns : JB_ERR_OK or JB_ERR_PARSE
657 *********************************************************************/
658 extern jb_err socks_fuzz(struct client_state *csp)
661 static struct forward_spec fwd;
662 char target_host[] = "fuzz.example.org";
663 int target_port = 12345;
665 fwd.gateway_host = strdup_or_die("fuzz.example.org");
666 fwd.gateway_port = 12345;
669 socket = socks4_connect(&fwd, target_host, target_port, csp);
671 if (JB_INVALID_SOCKET != socket)
674 socket = socks5_connect(&fwd, target_host, target_port, csp);
677 if (JB_INVALID_SOCKET == socket)
679 log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
683 log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
690 /*********************************************************************
692 * Function : socks4_connect
694 * Description : Connect to the SOCKS server, and connect through
695 * it to the specified server. This handles
696 * all the SOCKS negotiation, and returns a file
697 * descriptor for a socket which can be treated as a
698 * normal (non-SOCKS) socket.
700 * Logged error messages are saved to csp->error_message
701 * and later reused by error_response() for the CGI
702 * message. strdup allocation failures are handled there.
705 * 1 : fwd = Specifies the SOCKS proxy to use.
706 * 2 : target_host = The final server to connect to.
707 * 3 : target_port = The final port to connect to.
708 * 4 : csp = Current client state (buffers, headers, etc...)
710 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
712 *********************************************************************/
713 static jb_socket socks4_connect(const struct forward_spec * fwd,
714 const char * target_host,
716 struct client_state *csp)
718 unsigned long web_server_addr;
719 char buf[BUFFER_SIZE];
720 struct socks_op *c = (struct socks_op *)buf;
721 struct socks_reply *s = (struct socks_reply *)buf;
728 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
730 /* XXX: Shouldn't the config file parser prevent this? */
731 errstr = "NULL gateway host specified.";
735 if (fwd->gateway_port <= 0)
737 errstr = "invalid gateway port specified.";
743 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
744 csp->error_message = strdup(errstr);
746 return(JB_INVALID_SOCKET);
749 /* build a socks request for connection to the web server */
751 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
753 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
758 web_server_addr = resolve_hostname_to_ip(target_host);
759 if (web_server_addr == INADDR_NONE)
761 errstr = "could not resolve target host";
762 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
767 web_server_addr = htonl(web_server_addr);
771 web_server_addr = 0x00000001;
772 n = csiz + strlen(target_host) + 1;
776 errstr = "buffer cbuf too small.";
777 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
782 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
784 * What we forward to the socks4a server should have the
785 * size of socks_op, plus the length of the userid plus
786 * its \0 byte (which we don't have to add because the
787 * first byte of the userid is counted twice as it's also
788 * part of sock_op) minus the padding bytes (which are part
789 * of the userid as well), plus the length of the target_host
790 * (which is stored csiz bytes after the beginning of the buffer),
791 * plus another \0 byte.
793 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
798 /* Should never get here */
799 log_error(LOG_LEVEL_FATAL,
800 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
802 return(JB_INVALID_SOCKET);
807 csp->error_message = strdup(errstr);
808 return(JB_INVALID_SOCKET);
813 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
814 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
815 c->dstip[0] = (unsigned char)((web_server_addr >> 24) & 0xff);
816 c->dstip[1] = (unsigned char)((web_server_addr >> 16) & 0xff);
817 c->dstip[2] = (unsigned char)((web_server_addr >> 8) & 0xff);
818 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
823 /* pass the request to the socks server */
824 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
826 if (sfd == JB_INVALID_SOCKET)
828 /* The error an its reason have already been logged by connect_to() */
829 return(JB_INVALID_SOCKET);
831 else if (write_socket(sfd, (char *)c, csiz))
833 errstr = "SOCKS4 negotiation write failed.";
834 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
838 else if (!data_is_available(sfd, csp->config->socket_timeout))
840 if (socket_is_still_alive(sfd))
842 errstr = "SOCKS4 negotiation timed out";
846 errstr = "SOCKS4 negotiation got aborted by the server";
848 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
854 if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
856 errstr = "SOCKS4 negotiation read failed.";
857 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
864 csp->error_message = strdup(errstr);
865 return(JB_INVALID_SOCKET);
870 case SOCKS4_REQUEST_GRANTED:
872 case SOCKS4_REQUEST_REJECT:
873 errstr = "SOCKS request rejected or failed.";
876 case SOCKS4_REQUEST_IDENT_FAILED:
877 errstr = "SOCKS request rejected because "
878 "SOCKS server cannot connect to identd on the client.";
881 case SOCKS4_REQUEST_IDENT_CONFLICT:
882 errstr = "SOCKS request rejected because "
883 "the client program and identd report "
884 "different user-ids.";
889 snprintf(buf, sizeof(buf),
890 "SOCKS request rejected for reason code %d.", s->cd);
894 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
895 csp->error_message = strdup(errstr);
898 return(JB_INVALID_SOCKET);
902 /*********************************************************************
904 * Function : translate_socks5_error
906 * Description : Translates a SOCKS errors to a string.
909 * 1 : socks_error = The error code to translate.
911 * Returns : The string translation.
913 *********************************************************************/
914 static const char *translate_socks5_error(int socks_error)
918 /* XXX: these should be more descriptive */
919 case SOCKS5_REQUEST_FAILED:
920 return "SOCKS5 request failed";
921 case SOCKS5_REQUEST_DENIED:
922 return "SOCKS5 request denied";
923 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
924 return "SOCKS5 network unreachable";
925 case SOCKS5_REQUEST_HOST_UNREACHABLE:
926 return "SOCKS5 destination host unreachable";
927 case SOCKS5_REQUEST_CONNECTION_REFUSED:
928 return "SOCKS5 connection refused";
929 case SOCKS5_REQUEST_TTL_EXPIRED:
930 return "SOCKS5 TTL expired";
931 case SOCKS5_REQUEST_PROTOCOL_ERROR:
932 return "SOCKS5 client protocol error";
933 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
934 return "SOCKS5 domain names unsupported";
935 case SOCKS5_REQUEST_GRANTED:
936 return "everything's peachy";
938 return "SOCKS5 negotiation protocol error";
943 /*********************************************************************
945 * Function : socks5_connect
947 * Description : Connect to the SOCKS server, and connect through
948 * it to the specified server. This handles
949 * all the SOCKS negotiation, and returns a file
950 * descriptor for a socket which can be treated as a
951 * normal (non-SOCKS) socket.
954 * 1 : fwd = Specifies the SOCKS proxy to use.
955 * 2 : target_host = The final server to connect to.
956 * 3 : target_port = The final port to connect to.
957 * 4 : csp = Current client state (buffers, headers, etc...)
959 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
961 *********************************************************************/
962 static jb_socket socks5_connect(const struct forward_spec *fwd,
963 const char *target_host,
965 struct client_state *csp)
967 #define SIZE_SOCKS5_REPLY_IPV4 10
968 #define SIZE_SOCKS5_REPLY_IPV6 22
969 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
972 char sbuf[SIZE_SOCKS5_REPLY_IPV6];
973 size_t client_pos = 0;
977 const char *errstr = NULL;
979 assert(fwd->gateway_host);
980 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
982 errstr = "NULL gateway host specified";
986 if (fwd->gateway_port <= 0)
989 * XXX: currently this can't happen because in
990 * case of invalid gateway ports we use the defaults.
991 * Of course we really shouldn't do that.
993 errstr = "invalid gateway port specified";
997 hostlen = strlen(target_host);
998 if (hostlen > (size_t)255)
1000 errstr = "target host name is longer than 255 characters";
1004 if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1006 /* Should never get here */
1007 log_error(LOG_LEVEL_FATAL,
1008 "SOCKS5 impossible internal error - bad SOCKS type");
1015 assert(errstr != NULL);
1016 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1017 csp->error_message = strdup(errstr);
1018 return(JB_INVALID_SOCKET);
1023 if (!err && read_socket(sfd, sbuf, 2) != 2)
1025 /* pass the request to the socks server */
1026 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1028 if (sfd == JB_INVALID_SOCKET)
1030 errstr = "socks5 server unreachable";
1031 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1032 /* Free the generic error message provided by connect_to() */
1033 freez(csp->error_message);
1034 csp->error_message = strdup(errstr);
1035 return(JB_INVALID_SOCKET);
1039 cbuf[client_pos++] = '\x05'; /* Version */
1041 if (fwd->auth_username && fwd->auth_password)
1043 cbuf[client_pos++] = '\x02'; /* Two authentication methods supported */
1044 cbuf[client_pos++] = '\x02'; /* Username/password */
1048 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1050 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1052 if (write_socket(sfd, cbuf, client_pos))
1054 errstr = "SOCKS5 negotiation write failed";
1055 csp->error_message = strdup(errstr);
1056 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1058 return(JB_INVALID_SOCKET);
1060 if (!data_is_available(sfd, csp->config->socket_timeout))
1062 if (socket_is_still_alive(sfd))
1064 errstr = "SOCKS5 negotiation timed out";
1068 errstr = "SOCKS5 negotiation got aborted by the server";
1073 if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1076 errstr = "SOCKS5 negotiation read failed";
1080 if (!err && (sbuf[0] != '\x05'))
1082 errstr = "SOCKS5 negotiation protocol version error";
1086 if (!err && (sbuf[1] == '\xff'))
1088 errstr = "SOCKS5 authentication required";
1092 if (!err && (sbuf[1] == '\x02'))
1094 /* check cbuf overflow */
1095 size_t auth_len = strlen(fwd->auth_username) + strlen(fwd->auth_password) + 3;
1096 if (auth_len > sizeof(cbuf))
1098 errstr = "SOCKS5 username and/or password too long";
1105 cbuf[client_pos++] = '\x01'; /* Version */
1106 cbuf[client_pos++] = (char)strlen(fwd->auth_username);
1108 memcpy(cbuf + client_pos, fwd->auth_username, strlen(fwd->auth_username));
1109 client_pos += strlen(fwd->auth_username);
1110 cbuf[client_pos++] = (char)strlen(fwd->auth_password);
1111 memcpy(cbuf + client_pos, fwd->auth_password, strlen(fwd->auth_password));
1112 client_pos += strlen(fwd->auth_password);
1114 if (write_socket(sfd, cbuf, client_pos))
1116 errstr = "SOCKS5 negotiation auth write failed";
1117 csp->error_message = strdup(errstr);
1118 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1120 return(JB_INVALID_SOCKET);
1123 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1125 errstr = "SOCKS5 negotiation auth read failed";
1130 if (!err && (sbuf[1] != '\x00'))
1132 errstr = "SOCKS5 authentication failed";
1136 else if (!err && (sbuf[1] != '\x00'))
1138 errstr = "SOCKS5 negotiation protocol error";
1144 assert(errstr != NULL);
1145 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1146 csp->error_message = strdup(errstr);
1149 return(JB_INVALID_SOCKET);
1153 cbuf[client_pos++] = '\x05'; /* Version */
1154 cbuf[client_pos++] = '\x01'; /* TCP connect */
1155 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1156 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1157 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1158 assert(sizeof(cbuf) - client_pos > (size_t)255);
1159 /* Using strncpy because we really want the nul byte padding. */
1160 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1161 client_pos += (hostlen & 0xffu);
1162 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1163 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1166 if (write_socket(sfd, cbuf, client_pos))
1168 errstr = "SOCKS5 negotiation write failed";
1169 csp->error_message = strdup(errstr);
1170 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1173 return(JB_INVALID_SOCKET);
1177 * Optimistically send the HTTP request with the initial
1178 * SOCKS request if the user enabled the use of Tor extensions,
1179 * the CONNECT method isn't being used (in which case the client
1180 * doesn't send data until it gets our 200 response) and the
1181 * client request has actually been completely read already.
1183 if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1184 && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1186 char *client_headers = list_to_text(csp->headers);
1187 size_t header_length;
1189 if (client_headers == NULL)
1191 log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1193 list_remove_all(csp->headers);
1194 header_length= strlen(client_headers);
1196 log_error(LOG_LEVEL_CONNECT,
1197 "Optimistically sending %d bytes of client headers intended for %s",
1198 header_length, csp->http->hostport);
1200 if (write_socket(sfd, client_headers, header_length))
1202 log_error(LOG_LEVEL_CONNECT,
1203 "optimistically writing header to: %s failed: %E", csp->http->hostport);
1204 freez(client_headers);
1205 return(JB_INVALID_SOCKET);
1207 freez(client_headers);
1208 if (csp->expected_client_content_length != 0)
1210 unsigned long long buffered_request_bytes =
1211 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1212 log_error(LOG_LEVEL_CONNECT,
1213 "Optimistically sending %llu bytes of client body. Expected %llu",
1214 csp->expected_client_content_length, buffered_request_bytes);
1215 assert(csp->expected_client_content_length == buffered_request_bytes);
1216 if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1218 log_error(LOG_LEVEL_CONNECT,
1219 "optimistically writing %llu bytes of client body to: %s failed: %E",
1220 buffered_request_bytes, csp->http->hostport);
1221 return(JB_INVALID_SOCKET);
1223 clear_iob(csp->client_iob);
1228 server_size = read_socket(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4);
1229 if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1231 errstr = "SOCKS5 negotiation read failed";
1235 if (sbuf[0] != '\x05')
1237 errstr = "SOCKS5 negotiation protocol version error";
1239 else if (sbuf[2] != '\x00')
1241 errstr = "SOCKS5 negotiation protocol error";
1243 else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1245 errstr = translate_socks5_error(sbuf[1]);
1249 if (sbuf[3] == '\x04')
1252 * The address field contains an IPv6 address
1253 * which means we didn't get the whole reply
1254 * yet. Read and discard the rest of it to make
1255 * sure it isn't treated as HTTP data later on.
1257 server_size = read_socket(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE);
1258 if (server_size != SOCKS5_REPLY_DIFFERENCE)
1260 errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1263 else if (sbuf[3] != '\x01')
1265 errstr = "SOCKS5 reply contains unsupported address type";
1274 assert(errstr != NULL);
1275 csp->error_message = strdup(errstr);
1276 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1280 return(JB_INVALID_SOCKET);