1 const char gateway_rcs[] = "$Id: gateway.c,v 1.92 2012/10/23 10:16:52 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/gateway.c,v $
6 * Purpose : Contains functions to connect to a server, possibly
7 * using a "forwarder" (i.e. HTTP proxy and/or a SOCKS4
10 * Copyright : Written by and Copyright (C) 2001-2009 the
11 * Privoxy team. http://www.privoxy.org/
13 * Based on the Internet Junkbuster originally written
14 * by and Copyright (C) 1997 Anonymous Coders and
15 * Junkbusters Corporation. http://www.junkbusters.com
17 * This program is free software; you can redistribute it
18 * and/or modify it under the terms of the GNU General
19 * Public License as published by the Free Software
20 * Foundation; either version 2 of the License, or (at
21 * your option) any later version.
23 * This program is distributed in the hope that it will
24 * be useful, but WITHOUT ANY WARRANTY; without even the
25 * implied warranty of MERCHANTABILITY or FITNESS FOR A
26 * PARTICULAR PURPOSE. See the GNU General Public
27 * License for more details.
29 * The GNU General Public License should be included with
30 * this file. If not, you can view it at
31 * http://www.gnu.org/copyleft/gpl.html
32 * or write to the Free Software Foundation, Inc., 59
33 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.
35 *********************************************************************/
41 #include <sys/types.h>
44 #include <netinet/in.h>
53 #endif /* def _WIN32 */
57 #endif /* def __BEOS__ */
61 #endif /* def __OS2__ */
66 #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 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
83 static jb_socket socks4_connect(const struct forward_spec * fwd,
84 const char * target_host,
86 struct client_state *csp);
88 static jb_socket socks5_connect(const struct forward_spec *fwd,
89 const char *target_host,
91 struct client_state *csp);
94 SOCKS4_REQUEST_GRANTED = 90,
95 SOCKS4_REQUEST_REJECT = 91,
96 SOCKS4_REQUEST_IDENT_FAILED = 92,
97 SOCKS4_REQUEST_IDENT_CONFLICT = 93
101 SOCKS5_REQUEST_GRANTED = 0,
102 SOCKS5_REQUEST_FAILED = 1,
103 SOCKS5_REQUEST_DENIED = 2,
104 SOCKS5_REQUEST_NETWORK_UNREACHABLE = 3,
105 SOCKS5_REQUEST_HOST_UNREACHABLE = 4,
106 SOCKS5_REQUEST_CONNECTION_REFUSED = 5,
107 SOCKS5_REQUEST_TTL_EXPIRED = 6,
108 SOCKS5_REQUEST_PROTOCOL_ERROR = 7,
109 SOCKS5_REQUEST_BAD_ADDRESS_TYPE = 8
112 /* structure of a socks client operation */
114 unsigned char vn; /* socks version number */
115 unsigned char cd; /* command code */
116 unsigned char dstport[2]; /* destination port */
117 unsigned char dstip[4]; /* destination address */
118 char userid; /* first byte of userid */
119 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
120 /* more bytes of the userid follow, terminated by a NULL */
123 /* structure of a socks server reply */
125 unsigned char vn; /* socks version number */
126 unsigned char cd; /* command code */
127 unsigned char dstport[2]; /* destination port */
128 unsigned char dstip[4]; /* destination address */
131 static const char socks_userid[] = "anonymous";
133 #ifdef FEATURE_CONNECTION_SHARING
135 #define MAX_REUSABLE_CONNECTIONS 100
136 static unsigned int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
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(NULL != connection->host);
225 reusable_connection[slot].host = strdup_or_die(connection->host);
226 reusable_connection[slot].sfd = connection->sfd;
227 reusable_connection[slot].port = connection->port;
228 reusable_connection[slot].in_use = 0;
229 reusable_connection[slot].timestamp = connection->timestamp;
230 reusable_connection[slot].request_sent = connection->request_sent;
231 reusable_connection[slot].response_received = connection->response_received;
232 reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
233 reusable_connection[slot].requests_sent_total = connection->requests_sent_total;
235 assert(reusable_connection[slot].gateway_host == NULL);
236 assert(reusable_connection[slot].gateway_port == 0);
237 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
238 assert(reusable_connection[slot].forward_host == NULL);
239 assert(reusable_connection[slot].forward_port == 0);
241 reusable_connection[slot].forwarder_type = connection->forwarder_type;
242 if (NULL != connection->gateway_host)
244 reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
248 reusable_connection[slot].gateway_host = NULL;
250 reusable_connection[slot].gateway_port = connection->gateway_port;
252 if (NULL != connection->forward_host)
254 reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
258 reusable_connection[slot].forward_host = NULL;
260 reusable_connection[slot].forward_port = connection->forward_port;
262 privoxy_mutex_unlock(&connection_reuse_mutex);
264 #endif /* def FEATURE_CONNECTION_SHARING */
267 /*********************************************************************
269 * Function : mark_connection_closed
271 * Description : Marks a reused connection closed.
274 * 1 : closed_connection = The connection to mark as closed.
278 *********************************************************************/
279 void mark_connection_closed(struct reusable_connection *closed_connection)
281 closed_connection->in_use = FALSE;
282 closed_connection->sfd = JB_INVALID_SOCKET;
283 freez(closed_connection->host);
284 closed_connection->port = 0;
285 closed_connection->timestamp = 0;
286 closed_connection->request_sent = 0;
287 closed_connection->response_received = 0;
288 closed_connection->keep_alive_timeout = 0;
289 closed_connection->requests_sent_total = 0;
290 closed_connection->forwarder_type = SOCKS_NONE;
291 freez(closed_connection->gateway_host);
292 closed_connection->gateway_port = 0;
293 freez(closed_connection->forward_host);
294 closed_connection->forward_port = 0;
298 #ifdef FEATURE_CONNECTION_SHARING
299 /*********************************************************************
301 * Function : forget_connection
303 * Description : Removes a previously remembered connection from
304 * the list of reusable connections.
307 * 1 : sfd = The socket belonging to the connection in question.
311 *********************************************************************/
312 void forget_connection(jb_socket sfd)
314 unsigned int slot = 0;
316 assert(sfd != JB_INVALID_SOCKET);
318 privoxy_mutex_lock(&connection_reuse_mutex);
320 for (slot = 0; slot < SZ(reusable_connection); slot++)
322 if (reusable_connection[slot].sfd == sfd)
324 assert(reusable_connection[slot].in_use);
326 log_error(LOG_LEVEL_CONNECT,
327 "Forgetting socket %d for %s:%d in slot %d.",
328 sfd, reusable_connection[slot].host,
329 reusable_connection[slot].port, slot);
330 mark_connection_closed(&reusable_connection[slot]);
335 privoxy_mutex_unlock(&connection_reuse_mutex);
338 #endif /* def FEATURE_CONNECTION_SHARING */
341 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
342 /*********************************************************************
344 * Function : connection_destination_matches
346 * Description : Determines whether a remembered connection can
347 * be reused. That is, whether the destination and
348 * the forwarding settings match.
351 * 1 : connection = The connection to check.
352 * 2 : http = The destination for the connection.
353 * 3 : fwd = The forwarder settings.
355 * Returns : TRUE for yes, FALSE otherwise.
357 *********************************************************************/
358 int connection_destination_matches(const struct reusable_connection *connection,
359 const struct http_request *http,
360 const struct forward_spec *fwd)
362 if ((connection->forwarder_type != fwd->type)
363 || (connection->gateway_port != fwd->gateway_port)
364 || (connection->forward_port != fwd->forward_port)
365 || (connection->port != http->port))
370 if (( (NULL != connection->gateway_host)
371 && (NULL != fwd->gateway_host)
372 && strcmpic(connection->gateway_host, fwd->gateway_host))
373 && (connection->gateway_host != fwd->gateway_host))
375 log_error(LOG_LEVEL_CONNECT,
376 "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
377 connection->gateway_host, fwd->gateway_host);
381 if (( (NULL != connection->forward_host)
382 && (NULL != fwd->forward_host)
383 && strcmpic(connection->forward_host, fwd->forward_host))
384 && (connection->forward_host != fwd->forward_host))
386 log_error(LOG_LEVEL_CONNECT,
387 "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
388 connection->forward_host, fwd->forward_host);
392 return (!strcmpic(connection->host, http->host));
395 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
398 #ifdef FEATURE_CONNECTION_SHARING
399 /*********************************************************************
401 * Function : close_unusable_connections
403 * Description : Closes remembered connections that have timed
404 * out or have been closed on the other side.
408 * Returns : Number of connections that are still alive.
410 *********************************************************************/
411 int close_unusable_connections(void)
413 unsigned int slot = 0;
414 int connections_alive = 0;
416 privoxy_mutex_lock(&connection_reuse_mutex);
418 for (slot = 0; slot < SZ(reusable_connection); slot++)
420 if (!reusable_connection[slot].in_use
421 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
423 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
424 time_t latency = (reusable_connection[slot].response_received -
425 reusable_connection[slot].request_sent) / 2;
427 if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
429 log_error(LOG_LEVEL_CONNECT,
430 "The connection to %s:%d in slot %d timed out. "
431 "Closing socket %d. Timeout is: %d. Assumed latency: %d.",
432 reusable_connection[slot].host,
433 reusable_connection[slot].port, slot,
434 reusable_connection[slot].sfd,
435 reusable_connection[slot].keep_alive_timeout,
437 close_socket(reusable_connection[slot].sfd);
438 mark_connection_closed(&reusable_connection[slot]);
440 else if (!socket_is_still_alive(reusable_connection[slot].sfd))
442 log_error(LOG_LEVEL_CONNECT,
443 "The connection to %s:%d in slot %d is no longer usable. "
444 "Closing socket %d.", reusable_connection[slot].host,
445 reusable_connection[slot].port, slot,
446 reusable_connection[slot].sfd);
447 close_socket(reusable_connection[slot].sfd);
448 mark_connection_closed(&reusable_connection[slot]);
457 privoxy_mutex_unlock(&connection_reuse_mutex);
459 return connections_alive;
464 /*********************************************************************
466 * Function : get_reusable_connection
468 * Description : Returns an open socket to a previously remembered
469 * open connection (if there is one).
472 * 1 : http = The destination for the connection.
473 * 2 : fwd = The forwarder settings.
475 * Returns : JB_INVALID_SOCKET => No reusable connection found,
476 * otherwise a usable socket.
478 *********************************************************************/
479 static jb_socket get_reusable_connection(const struct http_request *http,
480 const struct forward_spec *fwd)
482 jb_socket sfd = JB_INVALID_SOCKET;
483 unsigned int slot = 0;
485 close_unusable_connections();
487 privoxy_mutex_lock(&connection_reuse_mutex);
489 for (slot = 0; slot < SZ(reusable_connection); slot++)
491 if (!reusable_connection[slot].in_use
492 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
494 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
496 reusable_connection[slot].in_use = TRUE;
497 sfd = reusable_connection[slot].sfd;
498 log_error(LOG_LEVEL_CONNECT,
499 "Found reusable socket %d for %s:%d in slot %d. Timestamp made %d "
500 "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
501 sfd, reusable_connection[slot].host, reusable_connection[slot].port,
502 slot, time(NULL) - reusable_connection[slot].timestamp,
503 reusable_connection[slot].keep_alive_timeout,
504 (int)(reusable_connection[slot].response_received -
505 reusable_connection[slot].request_sent),
506 reusable_connection[slot].requests_sent_total);
512 privoxy_mutex_unlock(&connection_reuse_mutex);
519 /*********************************************************************
521 * Function : mark_connection_unused
523 * Description : Gives a remembered connection free for reuse.
526 * 1 : connection = The connection in question.
528 * Returns : TRUE => Socket found and marked as unused.
529 * FALSE => Socket not found.
531 *********************************************************************/
532 static int mark_connection_unused(const struct reusable_connection *connection)
534 unsigned int slot = 0;
535 int socket_found = FALSE;
537 assert(connection->sfd != JB_INVALID_SOCKET);
539 privoxy_mutex_lock(&connection_reuse_mutex);
541 for (slot = 0; slot < SZ(reusable_connection); slot++)
543 if (reusable_connection[slot].sfd == connection->sfd)
545 assert(reusable_connection[slot].in_use);
547 log_error(LOG_LEVEL_CONNECT,
548 "Marking open socket %d for %s:%d in slot %d as unused.",
549 connection->sfd, reusable_connection[slot].host,
550 reusable_connection[slot].port, slot);
551 reusable_connection[slot].in_use = 0;
552 reusable_connection[slot].timestamp = connection->timestamp;
557 privoxy_mutex_unlock(&connection_reuse_mutex);
564 /*********************************************************************
566 * Function : set_keep_alive_timeout
568 * Description : Sets the timeout after which open
569 * connections will no longer be reused.
572 * 1 : timeout = The timeout in seconds.
576 *********************************************************************/
577 void set_keep_alive_timeout(unsigned int timeout)
579 keep_alive_timeout = timeout;
581 #endif /* def FEATURE_CONNECTION_SHARING */
584 /*********************************************************************
586 * Function : forwarded_connect
588 * Description : Connect to a specified web server, possibly via
589 * a HTTP proxy and/or a SOCKS proxy.
592 * 1 : fwd = the proxies to use when connecting.
593 * 2 : http = the http request and apropos headers
594 * 3 : csp = Current client state (buffers, headers, etc...)
596 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
598 *********************************************************************/
599 jb_socket forwarded_connect(const struct forward_spec * fwd,
600 struct http_request *http,
601 struct client_state *csp)
603 const char * dest_host;
605 jb_socket sfd = JB_INVALID_SOCKET;
607 #ifdef FEATURE_CONNECTION_SHARING
608 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
609 && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
611 sfd = get_reusable_connection(http, fwd);
612 if (JB_INVALID_SOCKET != sfd)
617 #endif /* def FEATURE_CONNECTION_SHARING */
619 /* Figure out if we need to connect to the web server or a HTTP proxy. */
620 if (fwd->forward_host)
623 dest_host = fwd->forward_host;
624 dest_port = fwd->forward_port;
629 dest_host = http->host;
630 dest_port = http->port;
633 /* Connect, maybe using a SOCKS proxy */
637 sfd = connect_to(dest_host, dest_port, csp);
641 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
645 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
648 /* Should never get here */
649 log_error(LOG_LEVEL_FATAL,
650 "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
653 if (JB_INVALID_SOCKET != sfd)
655 log_error(LOG_LEVEL_CONNECT,
656 "Created new connection to %s:%d on socket %d.",
657 http->host, http->port, sfd);
665 /*********************************************************************
667 * Function : socks4_connect
669 * Description : Connect to the SOCKS server, and connect through
670 * it to the specified server. This handles
671 * all the SOCKS negotiation, and returns a file
672 * descriptor for a socket which can be treated as a
673 * normal (non-SOCKS) socket.
675 * Logged error messages are saved to csp->error_message
676 * and later reused by error_response() for the CGI
677 * message. strdup allocation failures are handled there.
680 * 1 : fwd = Specifies the SOCKS proxy to use.
681 * 2 : target_host = The final server to connect to.
682 * 3 : target_port = The final port to connect to.
683 * 4 : csp = Current client state (buffers, headers, etc...)
685 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
687 *********************************************************************/
688 static jb_socket socks4_connect(const struct forward_spec * fwd,
689 const char * target_host,
691 struct client_state *csp)
693 unsigned long web_server_addr;
694 char buf[BUFFER_SIZE];
695 struct socks_op *c = (struct socks_op *)buf;
696 struct socks_reply *s = (struct socks_reply *)buf;
703 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
705 /* XXX: Shouldn't the config file parser prevent this? */
706 errstr = "NULL gateway host specified.";
710 if (fwd->gateway_port <= 0)
712 errstr = "invalid gateway port specified.";
718 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
719 csp->error_message = strdup(errstr);
721 return(JB_INVALID_SOCKET);
724 /* build a socks request for connection to the web server */
726 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
728 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
733 web_server_addr = resolve_hostname_to_ip(target_host);
734 if (web_server_addr == INADDR_NONE)
736 errstr = "could not resolve target host";
737 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
742 web_server_addr = htonl(web_server_addr);
746 web_server_addr = 0x00000001;
747 n = csiz + strlen(target_host) + 1;
751 errstr = "buffer cbuf too small.";
752 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
757 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
759 * What we forward to the socks4a server should have the
760 * size of socks_op, plus the length of the userid plus
761 * its \0 byte (which we don't have to add because the
762 * first byte of the userid is counted twice as it's also
763 * part of sock_op) minus the padding bytes (which are part
764 * of the userid as well), plus the length of the target_host
765 * (which is stored csiz bytes after the beginning of the buffer),
766 * plus another \0 byte.
768 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
773 /* Should never get here */
774 log_error(LOG_LEVEL_FATAL,
775 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
777 return(JB_INVALID_SOCKET);
782 csp->error_message = strdup(errstr);
783 return(JB_INVALID_SOCKET);
788 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
789 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
790 c->dstip[0] = (unsigned char)((web_server_addr >> 24) & 0xff);
791 c->dstip[1] = (unsigned char)((web_server_addr >> 16) & 0xff);
792 c->dstip[2] = (unsigned char)((web_server_addr >> 8) & 0xff);
793 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
795 /* pass the request to the socks server */
796 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
798 if (sfd == JB_INVALID_SOCKET)
800 /* The error an its reason have already been logged by connect_to() */
801 return(JB_INVALID_SOCKET);
803 else if (write_socket(sfd, (char *)c, csiz))
805 errstr = "SOCKS4 negotiation write failed.";
806 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
810 else if (!data_is_available(sfd, csp->config->socket_timeout))
812 if (socket_is_still_alive(sfd))
814 errstr = "SOCKS4 negotiation timed out";
818 errstr = "SOCKS4 negotiation got aborted by the server";
820 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
824 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
826 errstr = "SOCKS4 negotiation read failed.";
827 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
834 csp->error_message = strdup(errstr);
835 return(JB_INVALID_SOCKET);
840 case SOCKS4_REQUEST_GRANTED:
842 case SOCKS4_REQUEST_REJECT:
843 errstr = "SOCKS request rejected or failed.";
846 case SOCKS4_REQUEST_IDENT_FAILED:
847 errstr = "SOCKS request rejected because "
848 "SOCKS server cannot connect to identd on the client.";
851 case SOCKS4_REQUEST_IDENT_CONFLICT:
852 errstr = "SOCKS request rejected because "
853 "the client program and identd report "
854 "different user-ids.";
859 snprintf(buf, sizeof(buf),
860 "SOCKS request rejected for reason code %d.", s->cd);
864 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
865 csp->error_message = strdup(errstr);
868 return(JB_INVALID_SOCKET);
872 /*********************************************************************
874 * Function : translate_socks5_error
876 * Description : Translates a SOCKS errors to a string.
879 * 1 : socks_error = The error code to translate.
881 * Returns : The string translation.
883 *********************************************************************/
884 static const char *translate_socks5_error(int socks_error)
888 /* XXX: these should be more descriptive */
889 case SOCKS5_REQUEST_FAILED:
890 return "SOCKS5 request failed";
891 case SOCKS5_REQUEST_DENIED:
892 return "SOCKS5 request denied";
893 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
894 return "SOCKS5 network unreachable";
895 case SOCKS5_REQUEST_HOST_UNREACHABLE:
896 return "SOCKS5 host unreachable";
897 case SOCKS5_REQUEST_CONNECTION_REFUSED:
898 return "SOCKS5 connection refused";
899 case SOCKS5_REQUEST_TTL_EXPIRED:
900 return "SOCKS5 TTL expired";
901 case SOCKS5_REQUEST_PROTOCOL_ERROR:
902 return "SOCKS5 client protocol error";
903 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
904 return "SOCKS5 domain names unsupported";
905 case SOCKS5_REQUEST_GRANTED:
906 return "everything's peachy";
908 return "SOCKS5 negotiation protocol error";
912 /*********************************************************************
914 * Function : socks5_connect
916 * Description : Connect to the SOCKS server, and connect through
917 * it to the specified server. This handles
918 * all the SOCKS negotiation, and returns a file
919 * descriptor for a socket which can be treated as a
920 * normal (non-SOCKS) socket.
923 * 1 : fwd = Specifies the SOCKS proxy to use.
924 * 2 : target_host = The final server to connect to.
925 * 3 : target_port = The final port to connect to.
926 * 4 : csp = Current client state (buffers, headers, etc...)
928 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
930 *********************************************************************/
931 static jb_socket socks5_connect(const struct forward_spec *fwd,
932 const char *target_host,
934 struct client_state *csp)
939 size_t client_pos = 0;
943 const char *errstr = NULL;
945 assert(fwd->gateway_host);
946 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
948 errstr = "NULL gateway host specified";
952 if (fwd->gateway_port <= 0)
955 * XXX: currently this can't happen because in
956 * case of invalid gateway ports we use the defaults.
957 * Of course we really shouldn't do that.
959 errstr = "invalid gateway port specified";
963 hostlen = strlen(target_host);
964 if (hostlen > (size_t)255)
966 errstr = "target host name is longer than 255 characters";
970 if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
972 /* Should never get here */
973 log_error(LOG_LEVEL_FATAL,
974 "SOCKS5 impossible internal error - bad SOCKS type");
981 assert(errstr != NULL);
982 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
983 csp->error_message = strdup(errstr);
984 return(JB_INVALID_SOCKET);
987 /* pass the request to the socks server */
988 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
990 if (sfd == JB_INVALID_SOCKET)
992 errstr = "socks5 server unreachable";
993 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
994 /* Free the generic error message provided by connect_to() */
995 freez(csp->error_message);
996 csp->error_message = strdup(errstr);
997 return(JB_INVALID_SOCKET);
1001 cbuf[client_pos++] = '\x05'; /* Version */
1002 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1003 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1005 if (write_socket(sfd, cbuf, client_pos))
1007 errstr = "SOCKS5 negotiation write failed";
1008 csp->error_message = strdup(errstr);
1009 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1011 return(JB_INVALID_SOCKET);
1014 if (!data_is_available(sfd, csp->config->socket_timeout))
1016 if (socket_is_still_alive(sfd))
1018 errstr = "SOCKS5 negotiation timed out";
1022 errstr = "SOCKS5 negotiation got aborted by the server";
1027 if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1029 errstr = "SOCKS5 negotiation read failed";
1033 if (!err && (sbuf[0] != '\x05'))
1035 errstr = "SOCKS5 negotiation protocol version error";
1039 if (!err && (sbuf[1] == '\xff'))
1041 errstr = "SOCKS5 authentication required";
1045 if (!err && (sbuf[1] != '\x00'))
1047 errstr = "SOCKS5 negotiation protocol error";
1053 assert(errstr != NULL);
1054 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1055 csp->error_message = strdup(errstr);
1058 return(JB_INVALID_SOCKET);
1062 cbuf[client_pos++] = '\x05'; /* Version */
1063 cbuf[client_pos++] = '\x01'; /* TCP connect */
1064 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1065 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1066 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1067 assert(sizeof(cbuf) - client_pos > (size_t)255);
1068 /* Using strncpy because we really want the nul byte padding. */
1069 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1070 client_pos += (hostlen & 0xffu);
1071 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1072 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1074 if (write_socket(sfd, cbuf, client_pos))
1076 errstr = "SOCKS5 negotiation write failed";
1077 csp->error_message = strdup(errstr);
1078 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1081 return(JB_INVALID_SOCKET);
1085 * Optimistically send the request headers with the initial
1086 * request if the user requested use of Tor extensions, the
1087 * CONNECT method isn't being used (in which case the client
1088 * doesn't send data until it gets our 200 response) and the
1089 * client request has been already read completely.
1091 * Not optimistically sending the request body (if there is one)
1092 * makes it easier to implement, but isn't an actual requirement.
1094 if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1095 && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1097 char *client_headers = list_to_text(csp->headers);
1098 size_t header_length;
1100 if (client_headers == NULL)
1102 log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1104 list_remove_all(csp->headers);
1105 header_length= strlen(client_headers);
1107 log_error(LOG_LEVEL_CONNECT,
1108 "Optimistically sending %d bytes of client headers intended for %s",
1109 header_length, csp->http->hostport);
1111 if (write_socket(sfd, client_headers, header_length))
1113 log_error(LOG_LEVEL_CONNECT,
1114 "optimistically writing header to: %s failed: %E", csp->http->hostport);
1115 freez(client_headers);
1116 return(JB_INVALID_SOCKET);
1118 freez(client_headers);
1121 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1122 if (server_size != sizeof(sbuf))
1124 errstr = "SOCKS5 negotiation read failed";
1128 if (sbuf[0] != '\x05')
1130 errstr = "SOCKS5 negotiation protocol version error";
1132 else if (sbuf[2] != '\x00')
1134 errstr = "SOCKS5 negotiation protocol error";
1136 else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1138 errstr = translate_socks5_error(sbuf[1]);
1146 assert(errstr != NULL);
1147 csp->error_message = strdup(errstr);
1148 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1152 return(JB_INVALID_SOCKET);