1 /*********************************************************************
3 * File : $Source: /cvsroot/ijbswa/current/gateway.c,v $
5 * Purpose : Contains functions to connect to a server, possibly
6 * using a "forwarder" (i.e. HTTP proxy and/or a SOCKS4
9 * Copyright : Written by and Copyright (C) 2001-2017 the
10 * Privoxy team. https://www.privoxy.org/
12 * Based on the Internet Junkbuster originally written
13 * by and Copyright (C) 1997 Anonymous Coders and
14 * Junkbusters Corporation. http://www.junkbusters.com
16 * This program is free software; you can redistribute it
17 * and/or modify it under the terms of the GNU General
18 * Public License as published by the Free Software
19 * Foundation; either version 2 of the License, or (at
20 * your option) any later version.
22 * This program is distributed in the hope that it will
23 * be useful, but WITHOUT ANY WARRANTY; without even the
24 * implied warranty of MERCHANTABILITY or FITNESS FOR A
25 * PARTICULAR PURPOSE. See the GNU General Public
26 * License for more details.
28 * The GNU General Public License should be included with
29 * this file. If not, you can view it at
30 * http://www.gnu.org/copyleft/gpl.html
31 * or write to the Free Software Foundation, Inc., 59
32 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
34 *********************************************************************/
40 #include <sys/types.h>
43 #include <netinet/in.h>
52 #endif /* def _WIN32 */
56 #endif /* def __BEOS__ */
61 #include "jbsockets.h"
67 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
73 #endif /* def __GLIBC__ */
74 #endif /* HAVE_POLL */
75 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
77 static jb_socket socks4_connect(const struct forward_spec *fwd,
78 const char *target_host,
80 struct client_state *csp);
82 static jb_socket socks5_connect(const struct forward_spec *fwd,
83 const char *target_host,
85 struct client_state *csp);
88 SOCKS4_REQUEST_GRANTED = 90,
89 SOCKS4_REQUEST_REJECT = 91,
90 SOCKS4_REQUEST_IDENT_FAILED = 92,
91 SOCKS4_REQUEST_IDENT_CONFLICT = 93
95 SOCKS5_REQUEST_GRANTED = 0,
96 SOCKS5_REQUEST_FAILED = 1,
97 SOCKS5_REQUEST_DENIED = 2,
98 SOCKS5_REQUEST_NETWORK_UNREACHABLE = 3,
99 SOCKS5_REQUEST_HOST_UNREACHABLE = 4,
100 SOCKS5_REQUEST_CONNECTION_REFUSED = 5,
101 SOCKS5_REQUEST_TTL_EXPIRED = 6,
102 SOCKS5_REQUEST_PROTOCOL_ERROR = 7,
103 SOCKS5_REQUEST_BAD_ADDRESS_TYPE = 8
106 /* structure of a socks client operation */
108 unsigned char vn; /* socks version number */
109 unsigned char cd; /* command code */
110 unsigned char dstport[2]; /* destination port */
111 unsigned char dstip[4]; /* destination address */
112 char userid; /* first byte of userid */
113 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
114 /* more bytes of the userid follow, terminated by a NULL */
117 /* structure of a socks server reply */
119 unsigned char vn; /* socks version number */
120 unsigned char cd; /* command code */
121 unsigned char dstport[2]; /* destination port */
122 unsigned char dstip[4]; /* destination address */
125 static const char socks_userid[] = "anonymous";
127 #ifdef FEATURE_CONNECTION_SHARING
128 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
129 #error Using FEATURE_CONNECTION_SHARING without FEATURE_CONNECTION_KEEP_ALIVE is impossible
132 #define MAX_REUSABLE_CONNECTIONS 100
134 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
135 static int mark_connection_unused(const struct reusable_connection *connection);
137 /*********************************************************************
139 * Function : initialize_reusable_connections
141 * Description : Initializes the reusable_connection structures.
142 * Must be called with connection_reuse_mutex locked.
148 *********************************************************************/
149 extern void initialize_reusable_connections(void)
151 unsigned int slot = 0;
153 #if !defined(HAVE_POLL) && !defined(_WIN32)
154 log_error(LOG_LEVEL_INFO,
155 "Detecting already dead connections might not work "
156 "correctly on your platform. In case of problems, "
157 "unset the keep-alive-timeout option.");
160 for (slot = 0; slot < SZ(reusable_connection); slot++)
162 mark_connection_closed(&reusable_connection[slot]);
165 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
169 /*********************************************************************
171 * Function : remember_connection
173 * Description : Remembers a server connection for reuse later on.
176 * 1 : connection = The server connection to remember.
180 *********************************************************************/
181 void remember_connection(const struct reusable_connection *connection)
183 unsigned int slot = 0;
184 int free_slot_found = FALSE;
186 assert(NULL != connection);
187 assert(connection->sfd != JB_INVALID_SOCKET);
189 if (mark_connection_unused(connection))
194 privoxy_mutex_lock(&connection_reuse_mutex);
196 /* Find free socket slot. */
197 for (slot = 0; slot < SZ(reusable_connection); slot++)
199 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
201 assert(reusable_connection[slot].in_use == 0);
202 log_error(LOG_LEVEL_CONNECT,
203 "Remembering socket %d for %s:%d in slot %d.",
204 connection->sfd, connection->host, connection->port, slot);
205 free_slot_found = TRUE;
210 if (!free_slot_found)
212 log_error(LOG_LEVEL_CONNECT,
213 "No free slots found to remember socket for %s:%d. Last slot %d.",
214 connection->host, connection->port, slot);
215 privoxy_mutex_unlock(&connection_reuse_mutex);
216 close_socket(connection->sfd);
220 assert(slot < SZ(reusable_connection));
221 assert(NULL != connection->host);
222 reusable_connection[slot].host = strdup_or_die(connection->host);
223 reusable_connection[slot].sfd = connection->sfd;
224 reusable_connection[slot].port = connection->port;
225 reusable_connection[slot].in_use = 0;
226 reusable_connection[slot].timestamp = connection->timestamp;
227 reusable_connection[slot].request_sent = connection->request_sent;
228 reusable_connection[slot].response_received = connection->response_received;
229 reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
230 reusable_connection[slot].requests_sent_total = connection->requests_sent_total;
232 assert(reusable_connection[slot].gateway_host == NULL);
233 assert(reusable_connection[slot].gateway_port == 0);
234 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
235 assert(reusable_connection[slot].forward_host == NULL);
236 assert(reusable_connection[slot].forward_port == 0);
238 reusable_connection[slot].forwarder_type = connection->forwarder_type;
239 if (NULL != connection->gateway_host)
241 reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
245 reusable_connection[slot].gateway_host = NULL;
247 reusable_connection[slot].gateway_port = connection->gateway_port;
249 if (NULL != connection->forward_host)
251 reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
255 reusable_connection[slot].forward_host = NULL;
257 reusable_connection[slot].forward_port = connection->forward_port;
259 privoxy_mutex_unlock(&connection_reuse_mutex);
261 #endif /* def FEATURE_CONNECTION_SHARING */
264 /*********************************************************************
266 * Function : mark_connection_closed
268 * Description : Marks a reused connection closed.
271 * 1 : closed_connection = The connection to mark as closed.
275 *********************************************************************/
276 void mark_connection_closed(struct reusable_connection *closed_connection)
278 closed_connection->in_use = FALSE;
279 closed_connection->sfd = JB_INVALID_SOCKET;
280 freez(closed_connection->host);
281 closed_connection->port = 0;
282 closed_connection->timestamp = 0;
283 closed_connection->request_sent = 0;
284 closed_connection->response_received = 0;
285 closed_connection->keep_alive_timeout = 0;
286 closed_connection->requests_sent_total = 0;
287 closed_connection->forwarder_type = SOCKS_NONE;
288 freez(closed_connection->gateway_host);
289 closed_connection->gateway_port = 0;
290 freez(closed_connection->auth_username);
291 freez(closed_connection->auth_password);
292 freez(closed_connection->forward_host);
293 closed_connection->forward_port = 0;
297 #ifdef FEATURE_CONNECTION_SHARING
298 /*********************************************************************
300 * Function : forget_connection
302 * Description : Removes a previously remembered connection from
303 * the list of reusable connections.
306 * 1 : sfd = The socket belonging to the connection in question.
310 *********************************************************************/
311 void forget_connection(jb_socket sfd)
313 unsigned int slot = 0;
315 assert(sfd != JB_INVALID_SOCKET);
317 privoxy_mutex_lock(&connection_reuse_mutex);
319 for (slot = 0; slot < SZ(reusable_connection); slot++)
321 if (reusable_connection[slot].sfd == sfd)
323 assert(reusable_connection[slot].in_use);
325 log_error(LOG_LEVEL_CONNECT,
326 "Forgetting socket %d for %s:%d in slot %d.",
327 sfd, reusable_connection[slot].host,
328 reusable_connection[slot].port, slot);
329 mark_connection_closed(&reusable_connection[slot]);
334 privoxy_mutex_unlock(&connection_reuse_mutex);
337 #endif /* def FEATURE_CONNECTION_SHARING */
340 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
341 /*********************************************************************
343 * Function : connection_detail_matches
345 * Description : Helper function for connection_destination_matches().
346 * Compares strings which can be NULL.
349 * 1 : connection_detail = The connection detail to compare.
350 * 2 : fowarder_detail = The forwarder detail to compare.
352 * Returns : TRUE for yes, FALSE otherwise.
354 *********************************************************************/
355 static int connection_detail_matches(const char *connection_detail,
356 const char *forwarder_detail)
358 if (connection_detail == NULL && forwarder_detail == NULL)
360 /* Both details are unset. */
364 if ((connection_detail == NULL && forwarder_detail != NULL)
365 || (connection_detail != NULL && forwarder_detail == NULL))
367 /* Only one detail isn't set. */
371 /* Both details are set, but do they match? */
372 return(!strcmpic(connection_detail, forwarder_detail));
377 /*********************************************************************
379 * Function : connection_destination_matches
381 * Description : Determines whether a remembered connection can
382 * be reused. That is, whether the destination and
383 * the forwarding settings match.
386 * 1 : connection = The connection to check.
387 * 2 : http = The destination for the connection.
388 * 3 : fwd = The forwarder settings.
390 * Returns : TRUE for yes, FALSE otherwise.
392 *********************************************************************/
393 int connection_destination_matches(const struct reusable_connection *connection,
394 const struct http_request *http,
395 const struct forward_spec *fwd)
397 if ((connection->forwarder_type != fwd->type)
398 || (connection->gateway_port != fwd->gateway_port)
399 || (connection->forward_port != fwd->forward_port)
400 || (connection->port != http->port))
405 if (!connection_detail_matches(connection->gateway_host, fwd->gateway_host))
407 log_error(LOG_LEVEL_CONNECT,
408 "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
409 connection->gateway_host != NULL ? connection->gateway_host : "none",
410 fwd->gateway_host != NULL ? fwd->gateway_host : "none");
414 if (!connection_detail_matches(connection->auth_username, fwd->auth_username))
416 log_error(LOG_LEVEL_CONNECT, "Socks user name mismatch. "
417 "Previous user name: %s. Current user name: %s",
418 connection->auth_username != NULL ? connection->auth_username : "none",
419 fwd->auth_username != NULL ? fwd->auth_username : "none");
423 if (!connection_detail_matches(connection->auth_password, fwd->auth_password))
425 log_error(LOG_LEVEL_CONNECT, "Socks user name mismatch. "
426 "Previous password: %s. Current password: %s",
427 connection->auth_password != NULL ? connection->auth_password : "none",
428 fwd->auth_password != NULL ? fwd->auth_password : "none");
432 if (!connection_detail_matches(connection->forward_host, fwd->forward_host))
434 log_error(LOG_LEVEL_CONNECT,
435 "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
436 connection->forward_host != NULL ? connection->forward_host : "none",
437 fwd->forward_host != NULL ? fwd->forward_host : "none");
441 return (!strcmpic(connection->host, http->host));
444 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
447 #ifdef FEATURE_CONNECTION_SHARING
448 /*********************************************************************
450 * Function : close_unusable_connections
452 * Description : Closes remembered connections that have timed
453 * out or have been closed on the other side.
457 * Returns : Number of connections that are still alive.
459 *********************************************************************/
460 int close_unusable_connections(void)
462 unsigned int slot = 0;
463 int connections_alive = 0;
465 privoxy_mutex_lock(&connection_reuse_mutex);
467 for (slot = 0; slot < SZ(reusable_connection); slot++)
469 if (!reusable_connection[slot].in_use
470 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
472 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
473 time_t latency = (reusable_connection[slot].response_received -
474 reusable_connection[slot].request_sent) / 2;
476 if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
478 log_error(LOG_LEVEL_CONNECT,
479 "The connection to %s:%d in slot %d timed out. "
480 "Closing socket %d. Timeout is: %d. Assumed latency: %ld.",
481 reusable_connection[slot].host,
482 reusable_connection[slot].port, slot,
483 reusable_connection[slot].sfd,
484 reusable_connection[slot].keep_alive_timeout,
486 close_socket(reusable_connection[slot].sfd);
487 mark_connection_closed(&reusable_connection[slot]);
489 else if (!socket_is_still_alive(reusable_connection[slot].sfd))
491 log_error(LOG_LEVEL_CONNECT,
492 "The connection to %s:%d in slot %d is no longer usable. "
493 "Closing socket %d.", reusable_connection[slot].host,
494 reusable_connection[slot].port, slot,
495 reusable_connection[slot].sfd);
496 close_socket(reusable_connection[slot].sfd);
497 mark_connection_closed(&reusable_connection[slot]);
506 privoxy_mutex_unlock(&connection_reuse_mutex);
508 return connections_alive;
513 /*********************************************************************
515 * Function : get_reusable_connection
517 * Description : Returns an open socket to a previously remembered
518 * open connection (if there is one).
521 * 1 : http = The destination for the connection.
522 * 2 : fwd = The forwarder settings.
524 * Returns : JB_INVALID_SOCKET => No reusable connection found,
525 * otherwise a usable socket.
527 *********************************************************************/
528 static jb_socket get_reusable_connection(const struct http_request *http,
529 const struct forward_spec *fwd)
531 jb_socket sfd = JB_INVALID_SOCKET;
532 unsigned int slot = 0;
534 close_unusable_connections();
536 privoxy_mutex_lock(&connection_reuse_mutex);
538 for (slot = 0; slot < SZ(reusable_connection); slot++)
540 if (!reusable_connection[slot].in_use
541 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
543 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
545 reusable_connection[slot].in_use = TRUE;
546 sfd = reusable_connection[slot].sfd;
547 log_error(LOG_LEVEL_CONNECT,
548 "Found reusable socket %d for %s:%d in slot %d. Timestamp made %ld "
549 "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
550 sfd, reusable_connection[slot].host, reusable_connection[slot].port,
551 slot, time(NULL) - reusable_connection[slot].timestamp,
552 reusable_connection[slot].keep_alive_timeout,
553 (int)(reusable_connection[slot].response_received -
554 reusable_connection[slot].request_sent),
555 reusable_connection[slot].requests_sent_total);
561 privoxy_mutex_unlock(&connection_reuse_mutex);
568 /*********************************************************************
570 * Function : mark_connection_unused
572 * Description : Gives a remembered connection free for reuse.
575 * 1 : connection = The connection in question.
577 * Returns : TRUE => Socket found and marked as unused.
578 * FALSE => Socket not found.
580 *********************************************************************/
581 static int mark_connection_unused(const struct reusable_connection *connection)
583 unsigned int slot = 0;
584 int socket_found = FALSE;
586 assert(connection->sfd != JB_INVALID_SOCKET);
588 privoxy_mutex_lock(&connection_reuse_mutex);
590 for (slot = 0; slot < SZ(reusable_connection); slot++)
592 if (reusable_connection[slot].sfd == connection->sfd)
594 assert(reusable_connection[slot].in_use);
596 log_error(LOG_LEVEL_CONNECT,
597 "Marking open socket %d for %s:%d in slot %d as unused.",
598 connection->sfd, reusable_connection[slot].host,
599 reusable_connection[slot].port, slot);
600 reusable_connection[slot].in_use = 0;
601 reusable_connection[slot].timestamp = connection->timestamp;
606 privoxy_mutex_unlock(&connection_reuse_mutex);
611 #endif /* def FEATURE_CONNECTION_SHARING */
614 /*********************************************************************
616 * Function : forwarded_connect
618 * Description : Connect to a specified web server, possibly via
619 * a HTTP proxy and/or a SOCKS proxy.
622 * 1 : fwd = the proxies to use when connecting.
623 * 2 : http = the http request and apropos headers
624 * 3 : csp = Current client state (buffers, headers, etc...)
626 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
628 *********************************************************************/
629 jb_socket forwarded_connect(const struct forward_spec *fwd,
630 struct http_request *http,
631 struct client_state *csp)
633 const char *dest_host;
635 jb_socket sfd = JB_INVALID_SOCKET;
637 #ifdef FEATURE_CONNECTION_SHARING
638 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
639 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
641 sfd = get_reusable_connection(http, fwd);
642 if (JB_INVALID_SOCKET != sfd)
647 #endif /* def FEATURE_CONNECTION_SHARING */
649 /* Figure out if we need to connect to the web server or a HTTP proxy. */
650 if (fwd->forward_host)
653 dest_host = fwd->forward_host;
654 dest_port = fwd->forward_port;
659 dest_host = http->host;
660 dest_port = http->port;
663 /* Connect, maybe using a SOCKS proxy */
667 case FORWARD_WEBSERVER:
668 sfd = connect_to(dest_host, dest_port, csp);
672 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
676 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
679 /* Should never get here */
680 log_error(LOG_LEVEL_FATAL,
681 "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
684 if (JB_INVALID_SOCKET != sfd)
686 log_error(LOG_LEVEL_CONNECT,
687 "Created new connection to %s:%d on socket %d.",
688 http->host, http->port, sfd);
697 /*********************************************************************
699 * Function : socks_fuzz
701 * Description : Wrapper around socks[45]_connect() used for fuzzing.
704 * 1 : csp = Current client state (buffers, headers, etc...)
706 * Returns : JB_ERR_OK or JB_ERR_PARSE
708 *********************************************************************/
709 extern jb_err socks_fuzz(struct client_state *csp)
712 static struct forward_spec fwd;
713 char target_host[] = "fuzz.example.org";
714 int target_port = 12345;
716 fwd.gateway_host = strdup_or_die("fuzz.example.org");
717 fwd.gateway_port = 12345;
720 socket = socks4_connect(&fwd, target_host, target_port, csp);
722 if (JB_INVALID_SOCKET != socket)
725 socket = socks5_connect(&fwd, target_host, target_port, csp);
728 if (JB_INVALID_SOCKET == socket)
730 log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
734 log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
741 /*********************************************************************
743 * Function : socks4_connect
745 * Description : Connect to the SOCKS server, and connect through
746 * it to the specified server. This handles
747 * all the SOCKS negotiation, and returns a file
748 * descriptor for a socket which can be treated as a
749 * normal (non-SOCKS) socket.
751 * Logged error messages are saved to csp->error_message
752 * and later reused by error_response() for the CGI
753 * message. strdup allocation failures are handled there.
756 * 1 : fwd = Specifies the SOCKS proxy to use.
757 * 2 : target_host = The final server to connect to.
758 * 3 : target_port = The final port to connect to.
759 * 4 : csp = Current client state (buffers, headers, etc...)
761 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
763 *********************************************************************/
764 static jb_socket socks4_connect(const struct forward_spec *fwd,
765 const char *target_host,
767 struct client_state *csp)
769 unsigned long web_server_addr;
770 char buf[BUFFER_SIZE];
771 struct socks_op *c = (struct socks_op *)buf;
772 struct socks_reply *s = (struct socks_reply *)buf;
779 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
781 /* XXX: Shouldn't the config file parser prevent this? */
782 errstr = "NULL gateway host specified.";
786 if (fwd->gateway_port <= 0)
788 errstr = "invalid gateway port specified.";
794 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
795 csp->error_message = strdup(errstr);
797 return(JB_INVALID_SOCKET);
800 /* build a socks request for connection to the web server */
802 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
804 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
809 web_server_addr = resolve_hostname_to_ip(target_host);
810 if (web_server_addr == INADDR_NONE)
812 errstr = "could not resolve target host";
813 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
818 web_server_addr = htonl(web_server_addr);
822 web_server_addr = 0x00000001;
823 n = csiz + strlen(target_host) + 1;
827 errstr = "buffer cbuf too small.";
828 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
833 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
835 * What we forward to the socks4a server should have the
836 * size of socks_op, plus the length of the userid plus
837 * its \0 byte (which we don't have to add because the
838 * first byte of the userid is counted twice as it's also
839 * part of sock_op) minus the padding bytes (which are part
840 * of the userid as well), plus the length of the target_host
841 * (which is stored csiz bytes after the beginning of the buffer),
842 * plus another \0 byte.
844 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
849 /* Should never get here */
850 log_error(LOG_LEVEL_FATAL,
851 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
853 return(JB_INVALID_SOCKET);
858 csp->error_message = strdup(errstr);
859 return(JB_INVALID_SOCKET);
864 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
865 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
866 c->dstip[0] = (unsigned char)((web_server_addr >> 24) & 0xff);
867 c->dstip[1] = (unsigned char)((web_server_addr >> 16) & 0xff);
868 c->dstip[2] = (unsigned char)((web_server_addr >> 8) & 0xff);
869 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
874 /* pass the request to the socks server */
875 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
877 if (sfd == JB_INVALID_SOCKET)
879 /* The error an its reason have already been logged by connect_to() */
880 return(JB_INVALID_SOCKET);
882 else if (write_socket(sfd, (char *)c, csiz))
884 errstr = "SOCKS4 negotiation write failed.";
885 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
889 else if (!data_is_available(sfd, csp->config->socket_timeout))
891 if (socket_is_still_alive(sfd))
893 errstr = "SOCKS4 negotiation timed out";
897 errstr = "SOCKS4 negotiation got aborted by the server";
899 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
905 if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
907 errstr = "SOCKS4 negotiation read failed.";
908 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
915 csp->error_message = strdup(errstr);
916 return(JB_INVALID_SOCKET);
921 case SOCKS4_REQUEST_GRANTED:
923 case SOCKS4_REQUEST_REJECT:
924 errstr = "SOCKS request rejected or failed.";
927 case SOCKS4_REQUEST_IDENT_FAILED:
928 errstr = "SOCKS request rejected because "
929 "SOCKS server cannot connect to identd on the client.";
932 case SOCKS4_REQUEST_IDENT_CONFLICT:
933 errstr = "SOCKS request rejected because "
934 "the client program and identd report "
935 "different user-ids.";
940 snprintf(buf, sizeof(buf),
941 "SOCKS request rejected for reason code %d.", s->cd);
945 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
946 csp->error_message = strdup(errstr);
949 return(JB_INVALID_SOCKET);
953 /*********************************************************************
955 * Function : translate_socks5_error
957 * Description : Translates a SOCKS errors to a string.
960 * 1 : socks_error = The error code to translate.
962 * Returns : The string translation.
964 *********************************************************************/
965 static const char *translate_socks5_error(int socks_error)
969 /* XXX: these should be more descriptive */
970 case SOCKS5_REQUEST_FAILED:
971 return "SOCKS5 request failed";
972 case SOCKS5_REQUEST_DENIED:
973 return "SOCKS5 request denied";
974 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
975 return "SOCKS5 network unreachable";
976 case SOCKS5_REQUEST_HOST_UNREACHABLE:
977 return "SOCKS5 destination host unreachable";
978 case SOCKS5_REQUEST_CONNECTION_REFUSED:
979 return "SOCKS5 connection refused";
980 case SOCKS5_REQUEST_TTL_EXPIRED:
981 return "SOCKS5 TTL expired";
982 case SOCKS5_REQUEST_PROTOCOL_ERROR:
983 return "SOCKS5 client protocol error";
984 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
985 return "SOCKS5 domain names unsupported";
986 case SOCKS5_REQUEST_GRANTED:
987 return "everything's peachy";
989 return "SOCKS5 negotiation protocol error";
994 /*********************************************************************
996 * Function : socks5_connect
998 * Description : Connect to the SOCKS server, and connect through
999 * it to the specified server. This handles
1000 * all the SOCKS negotiation, and returns a file
1001 * descriptor for a socket which can be treated as a
1002 * normal (non-SOCKS) socket.
1005 * 1 : fwd = Specifies the SOCKS proxy to use.
1006 * 2 : target_host = The final server to connect to.
1007 * 3 : target_port = The final port to connect to.
1008 * 4 : csp = Current client state (buffers, headers, etc...)
1010 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1012 *********************************************************************/
1013 static jb_socket socks5_connect(const struct forward_spec *fwd,
1014 const char *target_host,
1016 struct client_state *csp)
1018 #define SIZE_SOCKS5_REPLY_IPV4 10
1019 #define SIZE_SOCKS5_REPLY_IPV6 22
1020 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
1023 char sbuf[SIZE_SOCKS5_REPLY_IPV6];
1024 size_t client_pos = 0;
1025 int server_size = 0;
1028 const char *errstr = NULL;
1030 assert(fwd->gateway_host);
1031 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1033 errstr = "NULL gateway host specified";
1037 if (fwd->gateway_port <= 0)
1040 * XXX: currently this can't happen because in
1041 * case of invalid gateway ports we use the defaults.
1042 * Of course we really shouldn't do that.
1044 errstr = "invalid gateway port specified";
1048 hostlen = strlen(target_host);
1049 if (hostlen > (size_t)255)
1051 errstr = "target host name is longer than 255 characters";
1055 if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1057 /* Should never get here */
1058 log_error(LOG_LEVEL_FATAL,
1059 "SOCKS5 impossible internal error - bad SOCKS type");
1066 assert(errstr != NULL);
1067 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1068 csp->error_message = strdup(errstr);
1069 return(JB_INVALID_SOCKET);
1074 if (!err && read_socket(sfd, sbuf, 2) != 2)
1076 /* pass the request to the socks server */
1077 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1079 if (sfd == JB_INVALID_SOCKET)
1081 errstr = "socks5 server unreachable";
1082 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1083 /* Free the generic error message provided by connect_to() */
1084 freez(csp->error_message);
1085 csp->error_message = strdup(errstr);
1086 return(JB_INVALID_SOCKET);
1090 cbuf[client_pos++] = '\x05'; /* Version */
1092 if (fwd->auth_username && fwd->auth_password)
1094 cbuf[client_pos++] = '\x02'; /* Two authentication methods supported */
1095 cbuf[client_pos++] = '\x02'; /* Username/password */
1099 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1101 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1103 if (write_socket(sfd, cbuf, client_pos))
1105 errstr = "SOCKS5 negotiation write failed";
1106 csp->error_message = strdup(errstr);
1107 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1109 return(JB_INVALID_SOCKET);
1111 if (!data_is_available(sfd, csp->config->socket_timeout))
1113 if (socket_is_still_alive(sfd))
1115 errstr = "SOCKS5 negotiation timed out";
1119 errstr = "SOCKS5 negotiation got aborted by the server";
1124 if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1127 errstr = "SOCKS5 negotiation read failed";
1131 if (!err && (sbuf[0] != '\x05'))
1133 errstr = "SOCKS5 negotiation protocol version error";
1137 if (!err && (sbuf[1] == '\xff'))
1139 errstr = "SOCKS5 authentication required";
1143 if (!err && (sbuf[1] == '\x02'))
1145 /* check cbuf overflow */
1146 size_t auth_len = strlen(fwd->auth_username) + strlen(fwd->auth_password) + 3;
1147 if (auth_len > sizeof(cbuf))
1149 errstr = "SOCKS5 username and/or password too long";
1156 cbuf[client_pos++] = '\x01'; /* Version */
1157 cbuf[client_pos++] = (char)strlen(fwd->auth_username);
1159 memcpy(cbuf + client_pos, fwd->auth_username, strlen(fwd->auth_username));
1160 client_pos += strlen(fwd->auth_username);
1161 cbuf[client_pos++] = (char)strlen(fwd->auth_password);
1162 memcpy(cbuf + client_pos, fwd->auth_password, strlen(fwd->auth_password));
1163 client_pos += strlen(fwd->auth_password);
1165 if (write_socket(sfd, cbuf, client_pos))
1167 errstr = "SOCKS5 negotiation auth write failed";
1168 csp->error_message = strdup(errstr);
1169 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1171 return(JB_INVALID_SOCKET);
1174 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1176 errstr = "SOCKS5 negotiation auth read failed";
1181 if (!err && (sbuf[1] != '\x00'))
1183 errstr = "SOCKS5 authentication failed";
1187 else if (!err && (sbuf[1] != '\x00'))
1189 errstr = "SOCKS5 negotiation protocol error";
1195 assert(errstr != NULL);
1196 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1197 csp->error_message = strdup(errstr);
1200 return(JB_INVALID_SOCKET);
1204 cbuf[client_pos++] = '\x05'; /* Version */
1205 cbuf[client_pos++] = '\x01'; /* TCP connect */
1206 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1207 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1208 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1209 assert(sizeof(cbuf) - client_pos > (size_t)255);
1210 /* Using strncpy because we really want the nul byte padding. */
1211 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1212 client_pos += (hostlen & 0xffu);
1213 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1214 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1217 if (write_socket(sfd, cbuf, client_pos))
1219 errstr = "SOCKS5 negotiation write failed";
1220 csp->error_message = strdup(errstr);
1221 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1224 return(JB_INVALID_SOCKET);
1228 * Optimistically send the HTTP request with the initial
1229 * SOCKS request if the user enabled the use of Tor extensions,
1230 * the CONNECT method isn't being used (in which case the client
1231 * doesn't send data until it gets our 200 response) and the
1232 * client request has actually been completely read already.
1234 if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1235 && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1237 char *client_headers = list_to_text(csp->headers);
1238 size_t header_length;
1240 if (client_headers == NULL)
1242 log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1244 list_remove_all(csp->headers);
1245 header_length= strlen(client_headers);
1247 log_error(LOG_LEVEL_CONNECT,
1248 "Optimistically sending %lu bytes of client headers intended for %s",
1249 header_length, csp->http->hostport);
1251 if (write_socket(sfd, client_headers, header_length))
1253 log_error(LOG_LEVEL_CONNECT,
1254 "optimistically writing header to: %s failed: %E", csp->http->hostport);
1255 freez(client_headers);
1256 return(JB_INVALID_SOCKET);
1258 freez(client_headers);
1259 if (csp->expected_client_content_length != 0)
1261 unsigned long long buffered_request_bytes =
1262 (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1263 log_error(LOG_LEVEL_CONNECT,
1264 "Optimistically sending %llu bytes of client body. Expected %llu",
1265 csp->expected_client_content_length, buffered_request_bytes);
1266 assert(csp->expected_client_content_length == buffered_request_bytes);
1267 if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1269 log_error(LOG_LEVEL_CONNECT,
1270 "optimistically writing %llu bytes of client body to: %s failed: %E",
1271 buffered_request_bytes, csp->http->hostport);
1272 return(JB_INVALID_SOCKET);
1274 clear_iob(csp->client_iob);
1279 server_size = read_socket(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4);
1280 if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1282 errstr = "SOCKS5 negotiation read failed";
1286 if (sbuf[0] != '\x05')
1288 errstr = "SOCKS5 negotiation protocol version error";
1290 else if (sbuf[2] != '\x00')
1292 errstr = "SOCKS5 negotiation protocol error";
1294 else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1296 errstr = translate_socks5_error(sbuf[1]);
1300 if (sbuf[3] == '\x04')
1303 * The address field contains an IPv6 address
1304 * which means we didn't get the whole reply
1305 * yet. Read and discard the rest of it to make
1306 * sure it isn't treated as HTTP data later on.
1308 server_size = read_socket(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE);
1309 if (server_size != SOCKS5_REPLY_DIFFERENCE)
1311 errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1314 else if (sbuf[3] != '\x01')
1316 errstr = "SOCKS5 reply contains unsupported address type";
1325 assert(errstr != NULL);
1326 csp->error_message = strdup(errstr);
1327 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1331 return(JB_INVALID_SOCKET);