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
132 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
133 #error Using FEATURE_CONNECTION_SHARING without FEATURE_CONNECTION_KEEP_ALIVE is impossible
136 #define MAX_REUSABLE_CONNECTIONS 100
138 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
139 static int mark_connection_unused(const struct reusable_connection *connection);
141 /*********************************************************************
143 * Function : initialize_reusable_connections
145 * Description : Initializes the reusable_connection structures.
146 * Must be called with connection_reuse_mutex locked.
152 *********************************************************************/
153 extern void initialize_reusable_connections(void)
155 unsigned int slot = 0;
157 #if !defined(HAVE_POLL) && !defined(_WIN32)
158 log_error(LOG_LEVEL_INFO,
159 "Detecting already dead connections might not work "
160 "correctly on your platform. In case of problems, "
161 "unset the keep-alive-timeout option.");
164 for (slot = 0; slot < SZ(reusable_connection); slot++)
166 mark_connection_closed(&reusable_connection[slot]);
169 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
173 /*********************************************************************
175 * Function : remember_connection
177 * Description : Remembers a server connection for reuse later on.
180 * 1 : connection = The server connection to remember.
184 *********************************************************************/
185 void remember_connection(const struct reusable_connection *connection)
187 unsigned int slot = 0;
188 int free_slot_found = FALSE;
190 assert(NULL != connection);
191 assert(connection->sfd != JB_INVALID_SOCKET);
193 if (mark_connection_unused(connection))
198 privoxy_mutex_lock(&connection_reuse_mutex);
200 /* Find free socket slot. */
201 for (slot = 0; slot < SZ(reusable_connection); slot++)
203 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
205 assert(reusable_connection[slot].in_use == 0);
206 log_error(LOG_LEVEL_CONNECT,
207 "Remembering socket %d for %s:%d in slot %d.",
208 connection->sfd, connection->host, connection->port, slot);
209 free_slot_found = TRUE;
214 if (!free_slot_found)
216 log_error(LOG_LEVEL_CONNECT,
217 "No free slots found to remember socket for %s:%d. Last slot %d.",
218 connection->host, connection->port, slot);
219 privoxy_mutex_unlock(&connection_reuse_mutex);
220 close_socket(connection->sfd);
224 assert(slot < SZ(reusable_connection));
225 assert(NULL != connection->host);
226 reusable_connection[slot].host = strdup_or_die(connection->host);
227 reusable_connection[slot].sfd = connection->sfd;
228 reusable_connection[slot].port = connection->port;
229 reusable_connection[slot].in_use = 0;
230 reusable_connection[slot].timestamp = connection->timestamp;
231 reusable_connection[slot].request_sent = connection->request_sent;
232 reusable_connection[slot].response_received = connection->response_received;
233 reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
234 reusable_connection[slot].requests_sent_total = connection->requests_sent_total;
236 assert(reusable_connection[slot].gateway_host == NULL);
237 assert(reusable_connection[slot].gateway_port == 0);
238 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
239 assert(reusable_connection[slot].forward_host == NULL);
240 assert(reusable_connection[slot].forward_port == 0);
242 reusable_connection[slot].forwarder_type = connection->forwarder_type;
243 if (NULL != connection->gateway_host)
245 reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
249 reusable_connection[slot].gateway_host = NULL;
251 reusable_connection[slot].gateway_port = connection->gateway_port;
253 if (NULL != connection->forward_host)
255 reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
259 reusable_connection[slot].forward_host = NULL;
261 reusable_connection[slot].forward_port = connection->forward_port;
263 privoxy_mutex_unlock(&connection_reuse_mutex);
265 #endif /* def FEATURE_CONNECTION_SHARING */
268 /*********************************************************************
270 * Function : mark_connection_closed
272 * Description : Marks a reused connection closed.
275 * 1 : closed_connection = The connection to mark as closed.
279 *********************************************************************/
280 void mark_connection_closed(struct reusable_connection *closed_connection)
282 closed_connection->in_use = FALSE;
283 closed_connection->sfd = JB_INVALID_SOCKET;
284 freez(closed_connection->host);
285 closed_connection->port = 0;
286 closed_connection->timestamp = 0;
287 closed_connection->request_sent = 0;
288 closed_connection->response_received = 0;
289 closed_connection->keep_alive_timeout = 0;
290 closed_connection->requests_sent_total = 0;
291 closed_connection->forwarder_type = SOCKS_NONE;
292 freez(closed_connection->gateway_host);
293 closed_connection->gateway_port = 0;
294 freez(closed_connection->forward_host);
295 closed_connection->forward_port = 0;
299 #ifdef FEATURE_CONNECTION_SHARING
300 /*********************************************************************
302 * Function : forget_connection
304 * Description : Removes a previously remembered connection from
305 * the list of reusable connections.
308 * 1 : sfd = The socket belonging to the connection in question.
312 *********************************************************************/
313 void forget_connection(jb_socket sfd)
315 unsigned int slot = 0;
317 assert(sfd != JB_INVALID_SOCKET);
319 privoxy_mutex_lock(&connection_reuse_mutex);
321 for (slot = 0; slot < SZ(reusable_connection); slot++)
323 if (reusable_connection[slot].sfd == sfd)
325 assert(reusable_connection[slot].in_use);
327 log_error(LOG_LEVEL_CONNECT,
328 "Forgetting socket %d for %s:%d in slot %d.",
329 sfd, reusable_connection[slot].host,
330 reusable_connection[slot].port, slot);
331 mark_connection_closed(&reusable_connection[slot]);
336 privoxy_mutex_unlock(&connection_reuse_mutex);
339 #endif /* def FEATURE_CONNECTION_SHARING */
342 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
343 /*********************************************************************
345 * Function : connection_destination_matches
347 * Description : Determines whether a remembered connection can
348 * be reused. That is, whether the destination and
349 * the forwarding settings match.
352 * 1 : connection = The connection to check.
353 * 2 : http = The destination for the connection.
354 * 3 : fwd = The forwarder settings.
356 * Returns : TRUE for yes, FALSE otherwise.
358 *********************************************************************/
359 int connection_destination_matches(const struct reusable_connection *connection,
360 const struct http_request *http,
361 const struct forward_spec *fwd)
363 if ((connection->forwarder_type != fwd->type)
364 || (connection->gateway_port != fwd->gateway_port)
365 || (connection->forward_port != fwd->forward_port)
366 || (connection->port != http->port))
371 if (( (NULL != connection->gateway_host)
372 && (NULL != fwd->gateway_host)
373 && strcmpic(connection->gateway_host, fwd->gateway_host))
374 && (connection->gateway_host != fwd->gateway_host))
376 log_error(LOG_LEVEL_CONNECT,
377 "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
378 connection->gateway_host, fwd->gateway_host);
382 if (( (NULL != connection->forward_host)
383 && (NULL != fwd->forward_host)
384 && strcmpic(connection->forward_host, fwd->forward_host))
385 && (connection->forward_host != fwd->forward_host))
387 log_error(LOG_LEVEL_CONNECT,
388 "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
389 connection->forward_host, fwd->forward_host);
393 return (!strcmpic(connection->host, http->host));
396 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
399 #ifdef FEATURE_CONNECTION_SHARING
400 /*********************************************************************
402 * Function : close_unusable_connections
404 * Description : Closes remembered connections that have timed
405 * out or have been closed on the other side.
409 * Returns : Number of connections that are still alive.
411 *********************************************************************/
412 int close_unusable_connections(void)
414 unsigned int slot = 0;
415 int connections_alive = 0;
417 privoxy_mutex_lock(&connection_reuse_mutex);
419 for (slot = 0; slot < SZ(reusable_connection); slot++)
421 if (!reusable_connection[slot].in_use
422 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
424 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
425 time_t latency = (reusable_connection[slot].response_received -
426 reusable_connection[slot].request_sent) / 2;
428 if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
430 log_error(LOG_LEVEL_CONNECT,
431 "The connection to %s:%d in slot %d timed out. "
432 "Closing socket %d. Timeout is: %d. Assumed latency: %d.",
433 reusable_connection[slot].host,
434 reusable_connection[slot].port, slot,
435 reusable_connection[slot].sfd,
436 reusable_connection[slot].keep_alive_timeout,
438 close_socket(reusable_connection[slot].sfd);
439 mark_connection_closed(&reusable_connection[slot]);
441 else if (!socket_is_still_alive(reusable_connection[slot].sfd))
443 log_error(LOG_LEVEL_CONNECT,
444 "The connection to %s:%d in slot %d is no longer usable. "
445 "Closing socket %d.", reusable_connection[slot].host,
446 reusable_connection[slot].port, slot,
447 reusable_connection[slot].sfd);
448 close_socket(reusable_connection[slot].sfd);
449 mark_connection_closed(&reusable_connection[slot]);
458 privoxy_mutex_unlock(&connection_reuse_mutex);
460 return connections_alive;
465 /*********************************************************************
467 * Function : get_reusable_connection
469 * Description : Returns an open socket to a previously remembered
470 * open connection (if there is one).
473 * 1 : http = The destination for the connection.
474 * 2 : fwd = The forwarder settings.
476 * Returns : JB_INVALID_SOCKET => No reusable connection found,
477 * otherwise a usable socket.
479 *********************************************************************/
480 static jb_socket get_reusable_connection(const struct http_request *http,
481 const struct forward_spec *fwd)
483 jb_socket sfd = JB_INVALID_SOCKET;
484 unsigned int slot = 0;
486 close_unusable_connections();
488 privoxy_mutex_lock(&connection_reuse_mutex);
490 for (slot = 0; slot < SZ(reusable_connection); slot++)
492 if (!reusable_connection[slot].in_use
493 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
495 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
497 reusable_connection[slot].in_use = TRUE;
498 sfd = reusable_connection[slot].sfd;
499 log_error(LOG_LEVEL_CONNECT,
500 "Found reusable socket %d for %s:%d in slot %d. Timestamp made %d "
501 "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
502 sfd, reusable_connection[slot].host, reusable_connection[slot].port,
503 slot, time(NULL) - reusable_connection[slot].timestamp,
504 reusable_connection[slot].keep_alive_timeout,
505 (int)(reusable_connection[slot].response_received -
506 reusable_connection[slot].request_sent),
507 reusable_connection[slot].requests_sent_total);
513 privoxy_mutex_unlock(&connection_reuse_mutex);
520 /*********************************************************************
522 * Function : mark_connection_unused
524 * Description : Gives a remembered connection free for reuse.
527 * 1 : connection = The connection in question.
529 * Returns : TRUE => Socket found and marked as unused.
530 * FALSE => Socket not found.
532 *********************************************************************/
533 static int mark_connection_unused(const struct reusable_connection *connection)
535 unsigned int slot = 0;
536 int socket_found = FALSE;
538 assert(connection->sfd != JB_INVALID_SOCKET);
540 privoxy_mutex_lock(&connection_reuse_mutex);
542 for (slot = 0; slot < SZ(reusable_connection); slot++)
544 if (reusable_connection[slot].sfd == connection->sfd)
546 assert(reusable_connection[slot].in_use);
548 log_error(LOG_LEVEL_CONNECT,
549 "Marking open socket %d for %s:%d in slot %d as unused.",
550 connection->sfd, reusable_connection[slot].host,
551 reusable_connection[slot].port, slot);
552 reusable_connection[slot].in_use = 0;
553 reusable_connection[slot].timestamp = connection->timestamp;
558 privoxy_mutex_unlock(&connection_reuse_mutex);
563 #endif /* def FEATURE_CONNECTION_SHARING */
566 /*********************************************************************
568 * Function : forwarded_connect
570 * Description : Connect to a specified web server, possibly via
571 * a HTTP proxy and/or a SOCKS proxy.
574 * 1 : fwd = the proxies to use when connecting.
575 * 2 : http = the http request and apropos headers
576 * 3 : csp = Current client state (buffers, headers, etc...)
578 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
580 *********************************************************************/
581 jb_socket forwarded_connect(const struct forward_spec *fwd,
582 struct http_request *http,
583 struct client_state *csp)
585 const char *dest_host;
587 jb_socket sfd = JB_INVALID_SOCKET;
589 #ifdef FEATURE_CONNECTION_SHARING
590 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
591 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
593 sfd = get_reusable_connection(http, fwd);
594 if (JB_INVALID_SOCKET != sfd)
599 #endif /* def FEATURE_CONNECTION_SHARING */
601 /* Figure out if we need to connect to the web server or a HTTP proxy. */
602 if (fwd->forward_host)
605 dest_host = fwd->forward_host;
606 dest_port = fwd->forward_port;
611 dest_host = http->host;
612 dest_port = http->port;
615 /* Connect, maybe using a SOCKS proxy */
619 case FORWARD_WEBSERVER:
620 sfd = connect_to(dest_host, dest_port, csp);
624 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
628 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
631 /* Should never get here */
632 log_error(LOG_LEVEL_FATAL,
633 "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
636 if (JB_INVALID_SOCKET != sfd)
638 log_error(LOG_LEVEL_CONNECT,
639 "Created new connection to %s:%d on socket %d.",
640 http->host, http->port, sfd);
649 /*********************************************************************
651 * Function : socks_fuzz
653 * Description : Wrapper around socks[45]_connect() used for fuzzing.
656 * 1 : csp = Current client state (buffers, headers, etc...)
658 * Returns : JB_ERR_OK or JB_ERR_PARSE
660 *********************************************************************/
661 extern jb_err socks_fuzz(struct client_state *csp)
664 static struct forward_spec fwd;
665 char target_host[] = "fuzz.example.org";
666 int target_port = 12345;
668 fwd.gateway_host = strdup_or_die("fuzz.example.org");
669 fwd.gateway_port = 12345;
672 socket = socks4_connect(&fwd, target_host, target_port, csp);
674 if (JB_INVALID_SOCKET != socket)
677 socket = socks5_connect(&fwd, target_host, target_port, csp);
680 if (JB_INVALID_SOCKET == socket)
682 log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
686 log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
693 /*********************************************************************
695 * Function : socks4_connect
697 * Description : Connect to the SOCKS server, and connect through
698 * it to the specified server. This handles
699 * all the SOCKS negotiation, and returns a file
700 * descriptor for a socket which can be treated as a
701 * normal (non-SOCKS) socket.
703 * Logged error messages are saved to csp->error_message
704 * and later reused by error_response() for the CGI
705 * message. strdup allocation failures are handled there.
708 * 1 : fwd = Specifies the SOCKS proxy to use.
709 * 2 : target_host = The final server to connect to.
710 * 3 : target_port = The final port to connect to.
711 * 4 : csp = Current client state (buffers, headers, etc...)
713 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
715 *********************************************************************/
716 static jb_socket socks4_connect(const struct forward_spec *fwd,
717 const char *target_host,
719 struct client_state *csp)
721 unsigned long web_server_addr;
722 char buf[BUFFER_SIZE];
723 struct socks_op *c = (struct socks_op *)buf;
724 struct socks_reply *s = (struct socks_reply *)buf;
731 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
733 /* XXX: Shouldn't the config file parser prevent this? */
734 errstr = "NULL gateway host specified.";
738 if (fwd->gateway_port <= 0)
740 errstr = "invalid gateway port specified.";
746 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
747 csp->error_message = strdup(errstr);
749 return(JB_INVALID_SOCKET);
752 /* build a socks request for connection to the web server */
754 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
756 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
761 web_server_addr = resolve_hostname_to_ip(target_host);
762 if (web_server_addr == INADDR_NONE)
764 errstr = "could not resolve target host";
765 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
770 web_server_addr = htonl(web_server_addr);
774 web_server_addr = 0x00000001;
775 n = csiz + strlen(target_host) + 1;
779 errstr = "buffer cbuf too small.";
780 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
785 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
787 * What we forward to the socks4a server should have the
788 * size of socks_op, plus the length of the userid plus
789 * its \0 byte (which we don't have to add because the
790 * first byte of the userid is counted twice as it's also
791 * part of sock_op) minus the padding bytes (which are part
792 * of the userid as well), plus the length of the target_host
793 * (which is stored csiz bytes after the beginning of the buffer),
794 * plus another \0 byte.
796 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
801 /* Should never get here */
802 log_error(LOG_LEVEL_FATAL,
803 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
805 return(JB_INVALID_SOCKET);
810 csp->error_message = strdup(errstr);
811 return(JB_INVALID_SOCKET);
816 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
817 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
818 c->dstip[0] = (unsigned char)((web_server_addr >> 24) & 0xff);
819 c->dstip[1] = (unsigned char)((web_server_addr >> 16) & 0xff);
820 c->dstip[2] = (unsigned char)((web_server_addr >> 8) & 0xff);
821 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
826 /* pass the request to the socks server */
827 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
829 if (sfd == JB_INVALID_SOCKET)
831 /* The error an its reason have already been logged by connect_to() */
832 return(JB_INVALID_SOCKET);
834 else if (write_socket(sfd, (char *)c, csiz))
836 errstr = "SOCKS4 negotiation write failed.";
837 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
841 else if (!data_is_available(sfd, csp->config->socket_timeout))
843 if (socket_is_still_alive(sfd))
845 errstr = "SOCKS4 negotiation timed out";
849 errstr = "SOCKS4 negotiation got aborted by the server";
851 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
857 if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
859 errstr = "SOCKS4 negotiation read failed.";
860 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
867 csp->error_message = strdup(errstr);
868 return(JB_INVALID_SOCKET);
873 case SOCKS4_REQUEST_GRANTED:
875 case SOCKS4_REQUEST_REJECT:
876 errstr = "SOCKS request rejected or failed.";
879 case SOCKS4_REQUEST_IDENT_FAILED:
880 errstr = "SOCKS request rejected because "
881 "SOCKS server cannot connect to identd on the client.";
884 case SOCKS4_REQUEST_IDENT_CONFLICT:
885 errstr = "SOCKS request rejected because "
886 "the client program and identd report "
887 "different user-ids.";
892 snprintf(buf, sizeof(buf),
893 "SOCKS request rejected for reason code %d.", s->cd);
897 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
898 csp->error_message = strdup(errstr);
901 return(JB_INVALID_SOCKET);
905 /*********************************************************************
907 * Function : translate_socks5_error
909 * Description : Translates a SOCKS errors to a string.
912 * 1 : socks_error = The error code to translate.
914 * Returns : The string translation.
916 *********************************************************************/
917 static const char *translate_socks5_error(int socks_error)
921 /* XXX: these should be more descriptive */
922 case SOCKS5_REQUEST_FAILED:
923 return "SOCKS5 request failed";
924 case SOCKS5_REQUEST_DENIED:
925 return "SOCKS5 request denied";
926 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
927 return "SOCKS5 network unreachable";
928 case SOCKS5_REQUEST_HOST_UNREACHABLE:
929 return "SOCKS5 destination host unreachable";
930 case SOCKS5_REQUEST_CONNECTION_REFUSED:
931 return "SOCKS5 connection refused";
932 case SOCKS5_REQUEST_TTL_EXPIRED:
933 return "SOCKS5 TTL expired";
934 case SOCKS5_REQUEST_PROTOCOL_ERROR:
935 return "SOCKS5 client protocol error";
936 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
937 return "SOCKS5 domain names unsupported";
938 case SOCKS5_REQUEST_GRANTED:
939 return "everything's peachy";
941 return "SOCKS5 negotiation protocol error";
946 /*********************************************************************
948 * Function : socks5_connect
950 * Description : Connect to the SOCKS server, and connect through
951 * it to the specified server. This handles
952 * all the SOCKS negotiation, and returns a file
953 * descriptor for a socket which can be treated as a
954 * normal (non-SOCKS) socket.
957 * 1 : fwd = Specifies the SOCKS proxy to use.
958 * 2 : target_host = The final server to connect to.
959 * 3 : target_port = The final port to connect to.
960 * 4 : csp = Current client state (buffers, headers, etc...)
962 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
964 *********************************************************************/
965 static jb_socket socks5_connect(const struct forward_spec *fwd,
966 const char *target_host,
968 struct client_state *csp)
970 #define SIZE_SOCKS5_REPLY_IPV4 10
971 #define SIZE_SOCKS5_REPLY_IPV6 22
972 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
975 char sbuf[SIZE_SOCKS5_REPLY_IPV6];
976 size_t client_pos = 0;
980 const char *errstr = NULL;
982 assert(fwd->gateway_host);
983 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
985 errstr = "NULL gateway host specified";
989 if (fwd->gateway_port <= 0)
992 * XXX: currently this can't happen because in
993 * case of invalid gateway ports we use the defaults.
994 * Of course we really shouldn't do that.
996 errstr = "invalid gateway port specified";
1000 hostlen = strlen(target_host);
1001 if (hostlen > (size_t)255)
1003 errstr = "target host name is longer than 255 characters";
1007 if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1009 /* Should never get here */
1010 log_error(LOG_LEVEL_FATAL,
1011 "SOCKS5 impossible internal error - bad SOCKS type");
1018 assert(errstr != NULL);
1019 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1020 csp->error_message = strdup(errstr);
1021 return(JB_INVALID_SOCKET);
1026 if (!err && read_socket(sfd, sbuf, 2) != 2)
1028 /* pass the request to the socks server */
1029 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1031 if (sfd == JB_INVALID_SOCKET)
1033 errstr = "socks5 server unreachable";
1034 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1035 /* Free the generic error message provided by connect_to() */
1036 freez(csp->error_message);
1037 csp->error_message = strdup(errstr);
1038 return(JB_INVALID_SOCKET);
1042 cbuf[client_pos++] = '\x05'; /* Version */
1044 if (fwd->auth_username && fwd->auth_password)
1046 cbuf[client_pos++] = '\x02'; /* Two authentication methods supported */
1047 cbuf[client_pos++] = '\x02'; /* Username/password */
1051 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1053 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1055 if (write_socket(sfd, cbuf, client_pos))
1057 errstr = "SOCKS5 negotiation write failed";
1058 csp->error_message = strdup(errstr);
1059 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1061 return(JB_INVALID_SOCKET);
1063 if (!data_is_available(sfd, csp->config->socket_timeout))
1065 if (socket_is_still_alive(sfd))
1067 errstr = "SOCKS5 negotiation timed out";
1071 errstr = "SOCKS5 negotiation got aborted by the server";
1076 if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1079 errstr = "SOCKS5 negotiation read failed";
1083 if (!err && (sbuf[0] != '\x05'))
1085 errstr = "SOCKS5 negotiation protocol version error";
1089 if (!err && (sbuf[1] == '\xff'))
1091 errstr = "SOCKS5 authentication required";
1095 if (!err && (sbuf[1] == '\x02'))
1097 /* check cbuf overflow */
1098 size_t auth_len = strlen(fwd->auth_username) + strlen(fwd->auth_password) + 3;
1099 if (auth_len > sizeof(cbuf))
1101 errstr = "SOCKS5 username and/or password too long";
1108 cbuf[client_pos++] = '\x01'; /* Version */
1109 cbuf[client_pos++] = (char)strlen(fwd->auth_username);
1111 memcpy(cbuf + client_pos, fwd->auth_username, strlen(fwd->auth_username));
1112 client_pos += strlen(fwd->auth_username);
1113 cbuf[client_pos++] = (char)strlen(fwd->auth_password);
1114 memcpy(cbuf + client_pos, fwd->auth_password, strlen(fwd->auth_password));
1115 client_pos += strlen(fwd->auth_password);
1117 if (write_socket(sfd, cbuf, client_pos))
1119 errstr = "SOCKS5 negotiation auth write failed";
1120 csp->error_message = strdup(errstr);
1121 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1123 return(JB_INVALID_SOCKET);
1126 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1128 errstr = "SOCKS5 negotiation auth read failed";
1133 if (!err && (sbuf[1] != '\x00'))
1135 errstr = "SOCKS5 authentication failed";
1139 else if (!err && (sbuf[1] != '\x00'))
1141 errstr = "SOCKS5 negotiation protocol error";
1147 assert(errstr != NULL);
1148 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1149 csp->error_message = strdup(errstr);
1152 return(JB_INVALID_SOCKET);
1156 cbuf[client_pos++] = '\x05'; /* Version */
1157 cbuf[client_pos++] = '\x01'; /* TCP connect */
1158 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1159 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1160 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1161 assert(sizeof(cbuf) - client_pos > (size_t)255);
1162 /* Using strncpy because we really want the nul byte padding. */
1163 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1164 client_pos += (hostlen & 0xffu);
1165 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1166 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1169 if (write_socket(sfd, cbuf, client_pos))
1171 errstr = "SOCKS5 negotiation write failed";
1172 csp->error_message = strdup(errstr);
1173 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1176 return(JB_INVALID_SOCKET);
1180 * Optimistically send the HTTP request with the initial
1181 * SOCKS request if the user enabled the use of Tor extensions,
1182 * the CONNECT method isn't being used (in which case the client
1183 * doesn't send data until it gets our 200 response) and the
1184 * client request has actually been completely read already.
1186 if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1187 && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1189 char *client_headers = list_to_text(csp->headers);
1190 size_t header_length;
1192 if (client_headers == NULL)
1194 log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1196 list_remove_all(csp->headers);
1197 header_length= strlen(client_headers);
1199 log_error(LOG_LEVEL_CONNECT,
1200 "Optimistically sending %d bytes of client headers intended for %s",
1201 header_length, csp->http->hostport);
1203 if (write_socket(sfd, client_headers, header_length))
1205 log_error(LOG_LEVEL_CONNECT,
1206 "optimistically writing header to: %s failed: %E", csp->http->hostport);
1207 freez(client_headers);
1208 return(JB_INVALID_SOCKET);
1210 freez(client_headers);
1211 if (csp->expected_client_content_length != 0)
1213 unsigned long long buffered_request_bytes =
1214 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1215 log_error(LOG_LEVEL_CONNECT,
1216 "Optimistically sending %llu bytes of client body. Expected %llu",
1217 csp->expected_client_content_length, buffered_request_bytes);
1218 assert(csp->expected_client_content_length == buffered_request_bytes);
1219 if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1221 log_error(LOG_LEVEL_CONNECT,
1222 "optimistically writing %llu bytes of client body to: %s failed: %E",
1223 buffered_request_bytes, csp->http->hostport);
1224 return(JB_INVALID_SOCKET);
1226 clear_iob(csp->client_iob);
1231 server_size = read_socket(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4);
1232 if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1234 errstr = "SOCKS5 negotiation read failed";
1238 if (sbuf[0] != '\x05')
1240 errstr = "SOCKS5 negotiation protocol version error";
1242 else if (sbuf[2] != '\x00')
1244 errstr = "SOCKS5 negotiation protocol error";
1246 else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1248 errstr = translate_socks5_error(sbuf[1]);
1252 if (sbuf[3] == '\x04')
1255 * The address field contains an IPv6 address
1256 * which means we didn't get the whole reply
1257 * yet. Read and discard the rest of it to make
1258 * sure it isn't treated as HTTP data later on.
1260 server_size = read_socket(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE);
1261 if (server_size != SOCKS5_REPLY_DIFFERENCE)
1263 errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1266 else if (sbuf[3] != '\x01')
1268 errstr = "SOCKS5 reply contains unsupported address type";
1277 assert(errstr != NULL);
1278 csp->error_message = strdup(errstr);
1279 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1283 return(JB_INVALID_SOCKET);