1 const char gateway_rcs[] = "$Id: gateway.c,v 1.50 2009/05/10 10:19:23 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 SourceForge
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.
37 * Revision 1.50 2009/05/10 10:19:23 fabiankeil
38 * Reenable server-side-only keep-alive support, but only share
39 * outgoing connections if the connection-sharing option is set.
41 * Revision 1.49 2009/05/10 10:12:30 fabiankeil
42 * Initial keep-alive support for the client socket.
43 * Temporarily disable the server-side-only keep-alive code.
45 * Revision 1.48 2009/02/13 17:20:36 fabiankeil
46 * Reword keep-alive support warning and only show
47 * it #if !defined(HAVE_POLL) && !defined(_WIN32).
49 * Revision 1.47 2008/12/24 17:06:19 fabiankeil
50 * Keep a thread around to timeout alive connections
51 * even if no new requests are coming in.
53 * Revision 1.46 2008/12/13 11:07:23 fabiankeil
54 * Remove duplicated debugging checks
55 * in connection_destination_matches().
57 * Revision 1.45 2008/12/04 18:17:07 fabiankeil
58 * Fix some cparser warnings.
60 * Revision 1.44 2008/11/22 11:54:04 fabiankeil
61 * Move log message around to include the socket number.
63 * Revision 1.43 2008/11/13 09:15:51 fabiankeil
64 * Make keep_alive_timeout static.
66 * Revision 1.42 2008/11/13 09:08:42 fabiankeil
67 * Add new config option: keep-alive-timeout.
69 * Revision 1.41 2008/11/08 15:29:58 fabiankeil
70 * Unify two debug messages.
72 * Revision 1.40 2008/11/08 15:14:05 fabiankeil
73 * Fix duplicated debugging check.
75 * Revision 1.39 2008/10/25 11:33:01 fabiankeil
76 * Remove already out-commented line left over from debugging.
78 * Revision 1.38 2008/10/24 17:33:00 fabiankeil
79 * - Tone the "keep-alive support is experimental" warning
80 * down a bit as hackish 0-chunk detection has been
81 * implemented recently.
82 * - Only show the "ndef HAVE_POLL" warning once on start-up.
84 * Revision 1.37 2008/10/23 17:40:53 fabiankeil
85 * Fix forget_connection() and mark_connection_unused(),
86 * which would both under certain circumstances access
87 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
89 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
90 * - Factor close_unusable_connections() out of
91 * get_reusable_connection() to make sure we really check
92 * all the remembered connections, not just the ones before
93 * the next reusable one.
94 * - Plug two file descriptor leaks. Internally marking
95 * connections as closed doesn't cut it.
97 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
98 * In socket_is_still_usable(), use select()
99 * and FD_ISSET() if poll() isn't available.
101 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
102 * Add preliminary timeout support.
104 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
105 * Fix two gcc44 warnings.
107 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
108 * Fix compiler warning.
110 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
111 * - Factor socket_is_still_usable() out of get_reusable_connection().
112 * - If poll() isn't available, show a warning and assume the socket
115 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
116 * If a remembered connection is no longer usable and
117 * has been marked closed, don't bother checking if the
118 * destination matches.
120 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
121 * Add missing dots for two log messages.
123 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
124 * Flush work-in-progress changes to keep outgoing connections
125 * alive where possible. Incomplete and mostly #ifdef'd out.
127 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
128 * Return only once in forwarded_connect().
130 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
131 * Fix typo in macro name.
133 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
135 * - make the buffers quite a bit smaller.
136 * - properly report "socks5 server unreachable" failures.
137 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
138 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
139 * - log a message if the socks5 server sends more data than expected.
140 * - add some assertions and comments.
142 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
143 * - Fix a compiler warning.
144 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
146 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
147 * Remember the cause of the SOCKS5 error for the CGI message.
149 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
150 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
152 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
153 * Modified patch from Song Weijia (#1762559) to
154 * fix socks requests on big-endian platforms.
156 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
157 * - Use strlcpy() instead of strcpy().
158 * - Use the same buffer for socks requests and socks responses.
159 * - Fix bogus warning about web_server_addr being used uninitialized.
161 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
162 * - Save errors in socks4_connect() to csp->error_message.
163 * - Silence some gcc43 warnings, hopefully the right way.
165 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
166 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
167 * with what was really the latest development (the v_3_0_branch branch)
169 * Revision 1.16 2002/05/12 21:36:29 jongfoster
170 * Correcting function comments
172 * Revision 1.15 2002/03/26 22:29:54 swa
173 * we have a new homepage!
175 * Revision 1.14 2002/03/24 13:25:43 swa
176 * name change related issues
178 * Revision 1.13 2002/03/13 00:29:59 jongfoster
181 * Revision 1.12 2002/03/09 20:03:52 jongfoster
182 * - Making various functions return int rather than size_t.
183 * (Undoing a recent change). Since size_t is unsigned on
184 * Windows, functions like read_socket that return -1 on
185 * error cannot return a size_t.
187 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
188 * crashes, and also frequently caused JB to jump to 100%
189 * CPU and stay there. (Because it thought it had just
190 * read ((unsigned)-1) == 4Gb of data...)
192 * - The signature of write_socket has changed, it now simply
193 * returns success=0/failure=nonzero.
195 * - Trying to get rid of a few warnings --with-debug on
196 * Windows, I've introduced a new type "jb_socket". This is
197 * used for the socket file descriptors. On Windows, this
198 * is SOCKET (a typedef for unsigned). Everywhere else, it's
199 * an int. The error value can't be -1 any more, so it's
200 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
201 * Windows it maps to the #define INVALID_SOCKET.)
203 * - The signature of bind_port has changed.
205 * Revision 1.11 2002/03/08 17:46:04 jongfoster
206 * Fixing int/size_t warnings
208 * Revision 1.10 2002/03/07 03:50:19 oes
209 * - Improved handling of failed DNS lookups
210 * - Fixed compiler warnings
212 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
213 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
214 * threads to call select() simultaneously. So, it's time to do a real, live,
215 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
216 * (native). Both versions will work, but using __OS2__ offers multi-threading.
218 * Revision 1.8 2001/09/13 20:10:12 jongfoster
219 * Fixing missing #include under Windows
221 * Revision 1.7 2001/09/12 17:58:26 steudten
223 * add #include <string.h>
225 * Revision 1.6 2001/09/10 10:41:16 oes
226 * Added #include in.h
228 * Revision 1.5 2001/07/29 18:47:57 jongfoster
229 * Adding missing #include project.h
231 * Revision 1.4 2001/07/24 12:47:06 oes
232 * Applied BeOS support update by Eugenia
234 * Revision 1.3 2001/06/09 10:55:28 jongfoster
235 * Changing BUFSIZ ==> BUFFER_SIZE
237 * Revision 1.2 2001/06/07 23:11:38 jongfoster
238 * Removing gateways[] list - no longer used.
239 * Replacing function pointer in struct gateway with a directly
240 * called function forwarded_connect(), which can do the common
241 * task of deciding whether to connect to the web server or HTTP
243 * Replacing struct gateway with struct forward_spec
244 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
245 * It was a bug which led to the connection being made to the web
246 * server rather than the HTTP proxy, and also a buffer overrun.
248 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
249 * Initial import of version 2.9.3 source tree
252 *********************************************************************/
258 #include <sys/types.h>
261 #include <netinet/in.h>
269 #include <winsock2.h>
270 #endif /* def _WIN32 */
274 #endif /* def __BEOS__ */
278 #endif /* def __OS2__ */
283 #include "jbsockets.h"
285 #include "miscutil.h"
286 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
289 #include <sys/poll.h>
292 #endif /* def __GLIBC__ */
293 #endif /* HAVE_POLL */
294 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
296 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
298 static jb_socket socks4_connect(const struct forward_spec * fwd,
299 const char * target_host,
301 struct client_state *csp);
303 static jb_socket socks5_connect(const struct forward_spec *fwd,
304 const char *target_host,
306 struct client_state *csp);
309 #define SOCKS_REQUEST_GRANTED 90
310 #define SOCKS_REQUEST_REJECT 91
311 #define SOCKS_REQUEST_IDENT_FAILED 92
312 #define SOCKS_REQUEST_IDENT_CONFLICT 93
314 #define SOCKS5_REQUEST_GRANTED 0
315 #define SOCKS5_REQUEST_FAILED 1
316 #define SOCKS5_REQUEST_DENIED 2
317 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
318 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
319 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
320 #define SOCKS5_REQUEST_TTL_EXPIRED 6
321 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
322 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
324 /* structure of a socks client operation */
326 unsigned char vn; /* socks version number */
327 unsigned char cd; /* command code */
328 unsigned char dstport[2]; /* destination port */
329 unsigned char dstip[4]; /* destination address */
330 char userid; /* first byte of userid */
331 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
332 /* more bytes of the userid follow, terminated by a NULL */
335 /* structure of a socks server reply */
337 unsigned char vn; /* socks version number */
338 unsigned char cd; /* command code */
339 unsigned char dstport[2]; /* destination port */
340 unsigned char dstip[4]; /* destination address */
343 static const char socks_userid[] = "anonymous";
345 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
347 #define MAX_REUSABLE_CONNECTIONS 100
348 static unsigned int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
350 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
351 static int mark_connection_unused(jb_socket sfd);
353 /*********************************************************************
355 * Function : initialize_reusable_connections
357 * Description : Initializes the reusable_connection structures.
358 * Must be called with connection_reuse_mutex locked.
364 *********************************************************************/
365 extern void initialize_reusable_connections(void)
367 unsigned int slot = 0;
369 #if !defined(HAVE_POLL) && !defined(_WIN32)
370 log_error(LOG_LEVEL_INFO,
371 "Detecting already dead connections might not work "
372 "correctly on your platform. In case of problems, "
373 "unset the keep-alive-timeout option.");
376 for (slot = 0; slot < SZ(reusable_connection); slot++)
378 mark_connection_closed(&reusable_connection[slot]);
381 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
385 /*********************************************************************
387 * Function : remember_connection
389 * Description : Remembers a connection for reuse later on.
392 * 1 : sfd = Open socket to remember.
393 * 2 : http = The destination for the connection.
394 * 3 : fwd = The forwarder settings used.
398 *********************************************************************/
399 void remember_connection(jb_socket sfd, const struct http_request *http,
400 const struct forward_spec *fwd)
402 unsigned int slot = 0;
403 int free_slot_found = FALSE;
405 assert(sfd != JB_INVALID_SOCKET);
407 if (mark_connection_unused(sfd))
412 privoxy_mutex_lock(&connection_reuse_mutex);
414 /* Find free socket slot. */
415 for (slot = 0; slot < SZ(reusable_connection); slot++)
417 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
419 assert(reusable_connection[slot].in_use == 0);
420 log_error(LOG_LEVEL_CONNECT,
421 "Remembering socket %d for %s:%d in slot %d.",
422 sfd, http->host, http->port, slot);
423 free_slot_found = TRUE;
428 if (!free_slot_found)
430 log_error(LOG_LEVEL_CONNECT,
431 "No free slots found to remembering socket for %s:%d. Last slot %d.",
432 http->host, http->port, slot);
433 privoxy_mutex_unlock(&connection_reuse_mutex);
438 assert(NULL != http->host);
439 reusable_connection[slot].host = strdup(http->host);
440 if (NULL == reusable_connection[slot].host)
442 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
444 reusable_connection[slot].sfd = sfd;
445 reusable_connection[slot].port = http->port;
446 reusable_connection[slot].in_use = 0;
447 reusable_connection[slot].timestamp = time(NULL);
450 assert(reusable_connection[slot].gateway_host == NULL);
451 assert(reusable_connection[slot].gateway_port == 0);
452 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
453 assert(reusable_connection[slot].forward_host == NULL);
454 assert(reusable_connection[slot].forward_port == 0);
456 reusable_connection[slot].forwarder_type = fwd->type;
457 if (NULL != fwd->gateway_host)
459 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
460 if (NULL == reusable_connection[slot].gateway_host)
462 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
467 reusable_connection[slot].gateway_host = NULL;
469 reusable_connection[slot].gateway_port = fwd->gateway_port;
471 if (NULL != fwd->forward_host)
473 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
474 if (NULL == reusable_connection[slot].forward_host)
476 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
481 reusable_connection[slot].forward_host = NULL;
483 reusable_connection[slot].forward_port = fwd->forward_port;
485 privoxy_mutex_unlock(&connection_reuse_mutex);
489 /*********************************************************************
491 * Function : mark_connection_closed
493 * Description : Marks a reused connection closed.
496 * 1 : closed_connection = The connection to mark as closed.
500 *********************************************************************/
501 void mark_connection_closed(struct reusable_connection *closed_connection)
503 closed_connection->in_use = FALSE;
504 closed_connection->sfd = JB_INVALID_SOCKET;
505 freez(closed_connection->host);
506 closed_connection->port = 0;
507 closed_connection->timestamp = 0;
508 closed_connection->forwarder_type = SOCKS_NONE;
509 freez(closed_connection->gateway_host);
510 closed_connection->gateway_port = 0;
511 freez(closed_connection->forward_host);
512 closed_connection->forward_port = 0;
516 /*********************************************************************
518 * Function : forget_connection
520 * Description : Removes a previously remembered connection from
521 * the list of reusable connections.
524 * 1 : sfd = The socket belonging to the connection in question.
528 *********************************************************************/
529 void forget_connection(jb_socket sfd)
531 unsigned int slot = 0;
533 assert(sfd != JB_INVALID_SOCKET);
535 privoxy_mutex_lock(&connection_reuse_mutex);
537 for (slot = 0; slot < SZ(reusable_connection); slot++)
539 if (reusable_connection[slot].sfd == sfd)
541 assert(reusable_connection[slot].in_use);
543 log_error(LOG_LEVEL_CONNECT,
544 "Forgetting socket %d for %s:%d in slot %d.",
545 sfd, reusable_connection[slot].host,
546 reusable_connection[slot].port, slot);
547 mark_connection_closed(&reusable_connection[slot]);
548 privoxy_mutex_unlock(&connection_reuse_mutex);
554 log_error(LOG_LEVEL_CONNECT,
555 "Socket %d already forgotten or never remembered.", sfd);
557 privoxy_mutex_unlock(&connection_reuse_mutex);
561 /*********************************************************************
563 * Function : connection_destination_matches
565 * Description : Determines whether a remembered connection can
566 * be reused. That is, whether the destination and
567 * the forwarding settings match.
570 * 1 : connection = The connection to check.
571 * 2 : http = The destination for the connection.
572 * 3 : fwd = The forwarder settings.
574 * Returns : TRUE for yes, FALSE otherwise.
576 *********************************************************************/
577 int connection_destination_matches(const struct reusable_connection *connection,
578 const struct http_request *http,
579 const struct forward_spec *fwd)
581 if ((connection->forwarder_type != fwd->type)
582 || (connection->gateway_port != fwd->gateway_port)
583 || (connection->forward_port != fwd->forward_port)
584 || (connection->port != http->port))
589 if (( (NULL != connection->gateway_host)
590 && (NULL != fwd->gateway_host)
591 && strcmpic(connection->gateway_host, fwd->gateway_host))
592 && (connection->gateway_host != fwd->gateway_host))
594 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
598 if (( (NULL != connection->forward_host)
599 && (NULL != fwd->forward_host)
600 && strcmpic(connection->forward_host, fwd->forward_host))
601 && (connection->forward_host != fwd->forward_host))
603 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
607 return (!strcmpic(connection->host, http->host));
612 /*********************************************************************
614 * Function : close_unusable_connections
616 * Description : Closes remembered connections that have timed
617 * out or have been closed on the other side.
621 * Returns : Number of connections that are still alive.
623 *********************************************************************/
624 int close_unusable_connections(void)
626 unsigned int slot = 0;
627 int connections_alive = 0;
629 privoxy_mutex_lock(&connection_reuse_mutex);
631 for (slot = 0; slot < SZ(reusable_connection); slot++)
633 if (!reusable_connection[slot].in_use
634 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
636 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
638 if (keep_alive_timeout < time_open)
640 log_error(LOG_LEVEL_CONNECT,
641 "The connection to %s:%d in slot %d timed out. "
642 "Closing socket %d. Timeout is: %d.",
643 reusable_connection[slot].host,
644 reusable_connection[slot].port, slot,
645 reusable_connection[slot].sfd, keep_alive_timeout);
646 close_socket(reusable_connection[slot].sfd);
647 mark_connection_closed(&reusable_connection[slot]);
649 else if (!socket_is_still_usable(reusable_connection[slot].sfd))
651 log_error(LOG_LEVEL_CONNECT,
652 "The connection to %s:%d in slot %d is no longer usable. "
653 "Closing socket %d.", reusable_connection[slot].host,
654 reusable_connection[slot].port, slot,
655 reusable_connection[slot].sfd);
656 close_socket(reusable_connection[slot].sfd);
657 mark_connection_closed(&reusable_connection[slot]);
666 privoxy_mutex_unlock(&connection_reuse_mutex);
668 return connections_alive;
673 /*********************************************************************
675 * Function : get_reusable_connection
677 * Description : Returns an open socket to a previously remembered
678 * open connection (if there is one).
681 * 1 : http = The destination for the connection.
682 * 2 : fwd = The forwarder settings.
684 * Returns : JB_INVALID_SOCKET => No reusable connection found,
685 * otherwise a usable socket.
687 *********************************************************************/
688 static jb_socket get_reusable_connection(const struct http_request *http,
689 const struct forward_spec *fwd)
691 jb_socket sfd = JB_INVALID_SOCKET;
692 unsigned int slot = 0;
694 close_unusable_connections();
696 privoxy_mutex_lock(&connection_reuse_mutex);
698 for (slot = 0; slot < SZ(reusable_connection); slot++)
700 if (!reusable_connection[slot].in_use
701 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
703 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
705 reusable_connection[slot].in_use = TRUE;
706 sfd = reusable_connection[slot].sfd;
707 log_error(LOG_LEVEL_CONNECT,
708 "Found reusable socket %d for %s:%d in slot %d.",
709 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
715 privoxy_mutex_unlock(&connection_reuse_mutex);
722 /*********************************************************************
724 * Function : mark_connection_unused
726 * Description : Gives a remembered connection free for reuse.
729 * 1 : sfd = The socket belonging to the connection in question.
731 * Returns : TRUE => Socket found and marked as unused.
732 * FALSE => Socket not found.
734 *********************************************************************/
735 static int mark_connection_unused(jb_socket sfd)
737 unsigned int slot = 0;
738 int socket_found = FALSE;
740 assert(sfd != JB_INVALID_SOCKET);
742 privoxy_mutex_lock(&connection_reuse_mutex);
744 for (slot = 0; slot < SZ(reusable_connection); slot++)
746 if (reusable_connection[slot].sfd == sfd)
748 assert(reusable_connection[slot].in_use);
750 log_error(LOG_LEVEL_CONNECT,
751 "Marking open socket %d for %s:%d in slot %d as unused.",
752 sfd, reusable_connection[slot].host,
753 reusable_connection[slot].port, slot);
754 reusable_connection[slot].in_use = 0;
755 reusable_connection[slot].timestamp = time(NULL);
760 privoxy_mutex_unlock(&connection_reuse_mutex);
767 /*********************************************************************
769 * Function : set_keep_alive_timeout
771 * Description : Sets the timeout after which open
772 * connections will no longer be reused.
775 * 1 : timeout = The timeout in seconds.
779 *********************************************************************/
780 void set_keep_alive_timeout(unsigned int timeout)
782 keep_alive_timeout = timeout;
784 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
787 /*********************************************************************
789 * Function : forwarded_connect
791 * Description : Connect to a specified web server, possibly via
792 * a HTTP proxy and/or a SOCKS proxy.
795 * 1 : fwd = the proxies to use when connecting.
796 * 2 : http = the http request and apropos headers
797 * 3 : csp = Current client state (buffers, headers, etc...)
799 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
801 *********************************************************************/
802 jb_socket forwarded_connect(const struct forward_spec * fwd,
803 struct http_request *http,
804 struct client_state *csp)
806 const char * dest_host;
808 jb_socket sfd = JB_INVALID_SOCKET;
810 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
811 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
813 sfd = get_reusable_connection(http, fwd);
814 if (JB_INVALID_SOCKET != sfd)
819 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
821 /* Figure out if we need to connect to the web server or a HTTP proxy. */
822 if (fwd->forward_host)
825 dest_host = fwd->forward_host;
826 dest_port = fwd->forward_port;
831 dest_host = http->host;
832 dest_port = http->port;
835 /* Connect, maybe using a SOCKS proxy */
839 sfd = connect_to(dest_host, dest_port, csp);
843 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
846 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
849 /* Should never get here */
850 log_error(LOG_LEVEL_FATAL,
851 "SOCKS4 impossible internal error - bad SOCKS type.");
854 if (JB_INVALID_SOCKET != sfd)
856 log_error(LOG_LEVEL_CONNECT,
857 "Created new connection to %s:%d on socket %d.",
858 http->host, http->port, sfd);
866 /*********************************************************************
868 * Function : socks4_connect
870 * Description : Connect to the SOCKS server, and connect through
871 * it to the specified server. This handles
872 * all the SOCKS negotiation, and returns a file
873 * descriptor for a socket which can be treated as a
874 * normal (non-SOCKS) socket.
876 * Logged error messages are saved to csp->error_message
877 * and later reused by error_response() for the CGI
878 * message. strdup allocation failures are handled there.
881 * 1 : fwd = Specifies the SOCKS proxy to use.
882 * 2 : target_host = The final server to connect to.
883 * 3 : target_port = The final port to connect to.
884 * 4 : csp = Current client state (buffers, headers, etc...)
886 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
888 *********************************************************************/
889 static jb_socket socks4_connect(const struct forward_spec * fwd,
890 const char * target_host,
892 struct client_state *csp)
894 unsigned int web_server_addr;
895 char buf[BUFFER_SIZE];
896 struct socks_op *c = (struct socks_op *)buf;
897 struct socks_reply *s = (struct socks_reply *)buf;
904 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
906 /* XXX: Shouldn't the config file parser prevent this? */
907 errstr = "NULL gateway host specified.";
911 if (fwd->gateway_port <= 0)
913 errstr = "invalid gateway port specified.";
919 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
920 csp->error_message = strdup(errstr);
922 return(JB_INVALID_SOCKET);
925 /* build a socks request for connection to the web server */
927 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
929 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
934 web_server_addr = resolve_hostname_to_ip(target_host);
935 if (web_server_addr == INADDR_NONE)
937 errstr = "could not resolve target host";
938 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
943 web_server_addr = htonl(web_server_addr);
947 web_server_addr = 0x00000001;
948 n = csiz + strlen(target_host) + 1;
952 errstr = "buffer cbuf too small.";
953 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
958 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
960 * What we forward to the socks4a server should have the
961 * size of socks_op, plus the length of the userid plus
962 * its \0 byte (which we don't have to add because the
963 * first byte of the userid is counted twice as it's also
964 * part of sock_op) minus the padding bytes (which are part
965 * of the userid as well), plus the length of the target_host
966 * (which is stored csiz bytes after the beginning of the buffer),
967 * plus another \0 byte.
969 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
974 /* Should never get here */
975 log_error(LOG_LEVEL_FATAL,
976 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
978 return(JB_INVALID_SOCKET);
983 csp->error_message = strdup(errstr);
984 return(JB_INVALID_SOCKET);
989 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
990 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
991 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
992 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
993 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
994 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
996 /* pass the request to the socks server */
997 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
999 if (sfd == JB_INVALID_SOCKET)
1002 * XXX: connect_to should fill in the exact reason.
1003 * Most likely resolving the IP of the forwarder failed.
1005 errstr = "connect_to failed: see logfile for details";
1008 else if (write_socket(sfd, (char *)c, csiz))
1010 errstr = "SOCKS4 negotiation write failed.";
1011 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1015 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1017 errstr = "SOCKS4 negotiation read failed.";
1018 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1025 csp->error_message = strdup(errstr);
1026 return(JB_INVALID_SOCKET);
1031 case SOCKS_REQUEST_GRANTED:
1033 case SOCKS_REQUEST_REJECT:
1034 errstr = "SOCKS request rejected or failed.";
1037 case SOCKS_REQUEST_IDENT_FAILED:
1038 errstr = "SOCKS request rejected because "
1039 "SOCKS server cannot connect to identd on the client.";
1042 case SOCKS_REQUEST_IDENT_CONFLICT:
1043 errstr = "SOCKS request rejected because "
1044 "the client program and identd report "
1045 "different user-ids.";
1050 snprintf(buf, sizeof(buf),
1051 "SOCKS request rejected for reason code %d.", s->cd);
1055 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1056 csp->error_message = strdup(errstr);
1059 return(JB_INVALID_SOCKET);
1063 /*********************************************************************
1065 * Function : translate_socks5_error
1067 * Description : Translates a SOCKS errors to a string.
1070 * 1 : socks_error = The error code to translate.
1072 * Returns : The string translation.
1074 *********************************************************************/
1075 static const char *translate_socks5_error(int socks_error)
1077 switch (socks_error)
1079 /* XXX: these should be more descriptive */
1080 case SOCKS5_REQUEST_FAILED:
1081 return "SOCKS5 request failed";
1082 case SOCKS5_REQUEST_DENIED:
1083 return "SOCKS5 request denied";
1084 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1085 return "SOCKS5 network unreachable";
1086 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1087 return "SOCKS5 host unreachable";
1088 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1089 return "SOCKS5 connection refused";
1090 case SOCKS5_REQUEST_TTL_EXPIRED:
1091 return "SOCKS5 TTL expired";
1092 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1093 return "SOCKS5 client protocol error";
1094 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1095 return "SOCKS5 domain names unsupported";
1096 case SOCKS5_REQUEST_GRANTED:
1097 return "everything's peachy";
1099 return "SOCKS5 negotiation protocol error";
1103 /*********************************************************************
1105 * Function : socks5_connect
1107 * Description : Connect to the SOCKS server, and connect through
1108 * it to the specified server. This handles
1109 * all the SOCKS negotiation, and returns a file
1110 * descriptor for a socket which can be treated as a
1111 * normal (non-SOCKS) socket.
1114 * 1 : fwd = Specifies the SOCKS proxy to use.
1115 * 2 : target_host = The final server to connect to.
1116 * 3 : target_port = The final port to connect to.
1117 * 4 : csp = Current client state (buffers, headers, etc...)
1119 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1121 *********************************************************************/
1122 static jb_socket socks5_connect(const struct forward_spec *fwd,
1123 const char *target_host,
1125 struct client_state *csp)
1130 size_t client_pos = 0;
1131 int server_size = 0;
1134 const char *errstr = NULL;
1136 assert(fwd->gateway_host);
1137 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1139 errstr = "NULL gateway host specified";
1143 if (fwd->gateway_port <= 0)
1146 * XXX: currently this can't happen because in
1147 * case of invalid gateway ports we use the defaults.
1148 * Of course we really shouldn't do that.
1150 errstr = "invalid gateway port specified";
1154 hostlen = strlen(target_host);
1155 if (hostlen > (size_t)255)
1157 errstr = "target host name is longer than 255 characters";
1161 if (fwd->type != SOCKS_5)
1163 /* Should never get here */
1164 log_error(LOG_LEVEL_FATAL,
1165 "SOCKS5 impossible internal error - bad SOCKS type");
1172 assert(errstr != NULL);
1173 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1174 csp->error_message = strdup(errstr);
1175 return(JB_INVALID_SOCKET);
1178 /* pass the request to the socks server */
1179 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1181 if (sfd == JB_INVALID_SOCKET)
1183 errstr = "socks5 server unreachable";
1184 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1185 csp->error_message = strdup(errstr);
1186 return(JB_INVALID_SOCKET);
1190 cbuf[client_pos++] = '\x05'; /* Version */
1191 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1192 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1194 if (write_socket(sfd, cbuf, client_pos))
1196 errstr = "SOCKS5 negotiation write failed";
1197 csp->error_message = strdup(errstr);
1198 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1200 return(JB_INVALID_SOCKET);
1203 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1205 errstr = "SOCKS5 negotiation read failed";
1209 if (!err && (sbuf[0] != '\x05'))
1211 errstr = "SOCKS5 negotiation protocol version error";
1215 if (!err && (sbuf[1] == '\xff'))
1217 errstr = "SOCKS5 authentication required";
1221 if (!err && (sbuf[1] != '\x00'))
1223 errstr = "SOCKS5 negotiation protocol error";
1229 assert(errstr != NULL);
1230 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1231 csp->error_message = strdup(errstr);
1234 return(JB_INVALID_SOCKET);
1238 cbuf[client_pos++] = '\x05'; /* Version */
1239 cbuf[client_pos++] = '\x01'; /* TCP connect */
1240 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1241 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1242 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1243 assert(sizeof(cbuf) - client_pos > (size_t)255);
1244 /* Using strncpy because we really want the nul byte padding. */
1245 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1246 client_pos += (hostlen & 0xffu);
1247 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1248 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1250 if (write_socket(sfd, cbuf, client_pos))
1252 errstr = "SOCKS5 negotiation read failed";
1253 csp->error_message = strdup(errstr);
1254 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1257 return(JB_INVALID_SOCKET);
1260 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1261 if (server_size < 3)
1263 errstr = "SOCKS5 negotiation read failed";
1266 else if (server_size > 20)
1268 /* This is somewhat unexpected but doesn't realy matter. */
1269 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1270 "from socks server. Would have accepted up to %d.",
1271 server_size, sizeof(sbuf));
1274 if (!err && (sbuf[0] != '\x05'))
1276 errstr = "SOCKS5 negotiation protocol version error";
1280 if (!err && (sbuf[2] != '\x00'))
1282 errstr = "SOCKS5 negotiation protocol error";
1288 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1292 errstr = translate_socks5_error(sbuf[1]);
1296 assert(errstr != NULL);
1297 csp->error_message = strdup(errstr);
1298 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1302 return(JB_INVALID_SOCKET);