1 const char gateway_rcs[] = "$Id: gateway.c,v 1.51 2009/05/13 18:20:54 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.51 2009/05/13 18:20:54 fabiankeil
38 * There's no reason for keep_alive_timeout to be signed.
40 * Revision 1.50 2009/05/10 10:19:23 fabiankeil
41 * Reenable server-side-only keep-alive support, but only share
42 * outgoing connections if the connection-sharing option is set.
44 * Revision 1.49 2009/05/10 10:12:30 fabiankeil
45 * Initial keep-alive support for the client socket.
46 * Temporarily disable the server-side-only keep-alive code.
48 * Revision 1.48 2009/02/13 17:20:36 fabiankeil
49 * Reword keep-alive support warning and only show
50 * it #if !defined(HAVE_POLL) && !defined(_WIN32).
52 * Revision 1.47 2008/12/24 17:06:19 fabiankeil
53 * Keep a thread around to timeout alive connections
54 * even if no new requests are coming in.
56 * Revision 1.46 2008/12/13 11:07:23 fabiankeil
57 * Remove duplicated debugging checks
58 * in connection_destination_matches().
60 * Revision 1.45 2008/12/04 18:17:07 fabiankeil
61 * Fix some cparser warnings.
63 * Revision 1.44 2008/11/22 11:54:04 fabiankeil
64 * Move log message around to include the socket number.
66 * Revision 1.43 2008/11/13 09:15:51 fabiankeil
67 * Make keep_alive_timeout static.
69 * Revision 1.42 2008/11/13 09:08:42 fabiankeil
70 * Add new config option: keep-alive-timeout.
72 * Revision 1.41 2008/11/08 15:29:58 fabiankeil
73 * Unify two debug messages.
75 * Revision 1.40 2008/11/08 15:14:05 fabiankeil
76 * Fix duplicated debugging check.
78 * Revision 1.39 2008/10/25 11:33:01 fabiankeil
79 * Remove already out-commented line left over from debugging.
81 * Revision 1.38 2008/10/24 17:33:00 fabiankeil
82 * - Tone the "keep-alive support is experimental" warning
83 * down a bit as hackish 0-chunk detection has been
84 * implemented recently.
85 * - Only show the "ndef HAVE_POLL" warning once on start-up.
87 * Revision 1.37 2008/10/23 17:40:53 fabiankeil
88 * Fix forget_connection() and mark_connection_unused(),
89 * which would both under certain circumstances access
90 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
92 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
93 * - Factor close_unusable_connections() out of
94 * get_reusable_connection() to make sure we really check
95 * all the remembered connections, not just the ones before
96 * the next reusable one.
97 * - Plug two file descriptor leaks. Internally marking
98 * connections as closed doesn't cut it.
100 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
101 * In socket_is_still_usable(), use select()
102 * and FD_ISSET() if poll() isn't available.
104 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
105 * Add preliminary timeout support.
107 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
108 * Fix two gcc44 warnings.
110 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
111 * Fix compiler warning.
113 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
114 * - Factor socket_is_still_usable() out of get_reusable_connection().
115 * - If poll() isn't available, show a warning and assume the socket
118 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
119 * If a remembered connection is no longer usable and
120 * has been marked closed, don't bother checking if the
121 * destination matches.
123 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
124 * Add missing dots for two log messages.
126 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
127 * Flush work-in-progress changes to keep outgoing connections
128 * alive where possible. Incomplete and mostly #ifdef'd out.
130 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
131 * Return only once in forwarded_connect().
133 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
134 * Fix typo in macro name.
136 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
138 * - make the buffers quite a bit smaller.
139 * - properly report "socks5 server unreachable" failures.
140 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
141 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
142 * - log a message if the socks5 server sends more data than expected.
143 * - add some assertions and comments.
145 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
146 * - Fix a compiler warning.
147 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
149 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
150 * Remember the cause of the SOCKS5 error for the CGI message.
152 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
153 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
155 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
156 * Modified patch from Song Weijia (#1762559) to
157 * fix socks requests on big-endian platforms.
159 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
160 * - Use strlcpy() instead of strcpy().
161 * - Use the same buffer for socks requests and socks responses.
162 * - Fix bogus warning about web_server_addr being used uninitialized.
164 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
165 * - Save errors in socks4_connect() to csp->error_message.
166 * - Silence some gcc43 warnings, hopefully the right way.
168 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
169 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
170 * with what was really the latest development (the v_3_0_branch branch)
172 * Revision 1.16 2002/05/12 21:36:29 jongfoster
173 * Correcting function comments
175 * Revision 1.15 2002/03/26 22:29:54 swa
176 * we have a new homepage!
178 * Revision 1.14 2002/03/24 13:25:43 swa
179 * name change related issues
181 * Revision 1.13 2002/03/13 00:29:59 jongfoster
184 * Revision 1.12 2002/03/09 20:03:52 jongfoster
185 * - Making various functions return int rather than size_t.
186 * (Undoing a recent change). Since size_t is unsigned on
187 * Windows, functions like read_socket that return -1 on
188 * error cannot return a size_t.
190 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
191 * crashes, and also frequently caused JB to jump to 100%
192 * CPU and stay there. (Because it thought it had just
193 * read ((unsigned)-1) == 4Gb of data...)
195 * - The signature of write_socket has changed, it now simply
196 * returns success=0/failure=nonzero.
198 * - Trying to get rid of a few warnings --with-debug on
199 * Windows, I've introduced a new type "jb_socket". This is
200 * used for the socket file descriptors. On Windows, this
201 * is SOCKET (a typedef for unsigned). Everywhere else, it's
202 * an int. The error value can't be -1 any more, so it's
203 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
204 * Windows it maps to the #define INVALID_SOCKET.)
206 * - The signature of bind_port has changed.
208 * Revision 1.11 2002/03/08 17:46:04 jongfoster
209 * Fixing int/size_t warnings
211 * Revision 1.10 2002/03/07 03:50:19 oes
212 * - Improved handling of failed DNS lookups
213 * - Fixed compiler warnings
215 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
216 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
217 * threads to call select() simultaneously. So, it's time to do a real, live,
218 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
219 * (native). Both versions will work, but using __OS2__ offers multi-threading.
221 * Revision 1.8 2001/09/13 20:10:12 jongfoster
222 * Fixing missing #include under Windows
224 * Revision 1.7 2001/09/12 17:58:26 steudten
226 * add #include <string.h>
228 * Revision 1.6 2001/09/10 10:41:16 oes
229 * Added #include in.h
231 * Revision 1.5 2001/07/29 18:47:57 jongfoster
232 * Adding missing #include project.h
234 * Revision 1.4 2001/07/24 12:47:06 oes
235 * Applied BeOS support update by Eugenia
237 * Revision 1.3 2001/06/09 10:55:28 jongfoster
238 * Changing BUFSIZ ==> BUFFER_SIZE
240 * Revision 1.2 2001/06/07 23:11:38 jongfoster
241 * Removing gateways[] list - no longer used.
242 * Replacing function pointer in struct gateway with a directly
243 * called function forwarded_connect(), which can do the common
244 * task of deciding whether to connect to the web server or HTTP
246 * Replacing struct gateway with struct forward_spec
247 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
248 * It was a bug which led to the connection being made to the web
249 * server rather than the HTTP proxy, and also a buffer overrun.
251 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
252 * Initial import of version 2.9.3 source tree
255 *********************************************************************/
261 #include <sys/types.h>
264 #include <netinet/in.h>
272 #include <winsock2.h>
273 #endif /* def _WIN32 */
277 #endif /* def __BEOS__ */
281 #endif /* def __OS2__ */
286 #include "jbsockets.h"
288 #include "miscutil.h"
289 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
292 #include <sys/poll.h>
295 #endif /* def __GLIBC__ */
296 #endif /* HAVE_POLL */
297 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
299 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
301 static jb_socket socks4_connect(const struct forward_spec * fwd,
302 const char * target_host,
304 struct client_state *csp);
306 static jb_socket socks5_connect(const struct forward_spec *fwd,
307 const char *target_host,
309 struct client_state *csp);
312 #define SOCKS_REQUEST_GRANTED 90
313 #define SOCKS_REQUEST_REJECT 91
314 #define SOCKS_REQUEST_IDENT_FAILED 92
315 #define SOCKS_REQUEST_IDENT_CONFLICT 93
317 #define SOCKS5_REQUEST_GRANTED 0
318 #define SOCKS5_REQUEST_FAILED 1
319 #define SOCKS5_REQUEST_DENIED 2
320 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
321 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
322 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
323 #define SOCKS5_REQUEST_TTL_EXPIRED 6
324 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
325 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
327 /* structure of a socks client operation */
329 unsigned char vn; /* socks version number */
330 unsigned char cd; /* command code */
331 unsigned char dstport[2]; /* destination port */
332 unsigned char dstip[4]; /* destination address */
333 char userid; /* first byte of userid */
334 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
335 /* more bytes of the userid follow, terminated by a NULL */
338 /* structure of a socks server reply */
340 unsigned char vn; /* socks version number */
341 unsigned char cd; /* command code */
342 unsigned char dstport[2]; /* destination port */
343 unsigned char dstip[4]; /* destination address */
346 static const char socks_userid[] = "anonymous";
348 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
350 #define MAX_REUSABLE_CONNECTIONS 100
351 static unsigned int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
353 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
354 static int mark_connection_unused(jb_socket sfd);
356 /*********************************************************************
358 * Function : initialize_reusable_connections
360 * Description : Initializes the reusable_connection structures.
361 * Must be called with connection_reuse_mutex locked.
367 *********************************************************************/
368 extern void initialize_reusable_connections(void)
370 unsigned int slot = 0;
372 #if !defined(HAVE_POLL) && !defined(_WIN32)
373 log_error(LOG_LEVEL_INFO,
374 "Detecting already dead connections might not work "
375 "correctly on your platform. In case of problems, "
376 "unset the keep-alive-timeout option.");
379 for (slot = 0; slot < SZ(reusable_connection); slot++)
381 mark_connection_closed(&reusable_connection[slot]);
384 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
388 /*********************************************************************
390 * Function : remember_connection
392 * Description : Remembers a connection for reuse later on.
395 * 1 : sfd = Open socket to remember.
396 * 2 : http = The destination for the connection.
397 * 3 : fwd = The forwarder settings used.
398 * 4 : timeout = Number of seconds after which the
399 * connection shouldn't be reused.
403 *********************************************************************/
404 void remember_connection(jb_socket sfd,
405 const struct http_request *http,
406 const struct forward_spec *fwd,
407 unsigned int timeout)
409 unsigned int slot = 0;
410 int free_slot_found = FALSE;
412 assert(sfd != JB_INVALID_SOCKET);
414 if (mark_connection_unused(sfd))
419 privoxy_mutex_lock(&connection_reuse_mutex);
421 /* Find free socket slot. */
422 for (slot = 0; slot < SZ(reusable_connection); slot++)
424 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
426 assert(reusable_connection[slot].in_use == 0);
427 log_error(LOG_LEVEL_CONNECT,
428 "Remembering socket %d for %s:%d in slot %d.",
429 sfd, http->host, http->port, slot);
430 free_slot_found = TRUE;
435 if (!free_slot_found)
437 log_error(LOG_LEVEL_CONNECT,
438 "No free slots found to remembering socket for %s:%d. Last slot %d.",
439 http->host, http->port, slot);
440 privoxy_mutex_unlock(&connection_reuse_mutex);
445 assert(NULL != http->host);
446 reusable_connection[slot].host = strdup(http->host);
447 if (NULL == reusable_connection[slot].host)
449 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
451 reusable_connection[slot].sfd = sfd;
452 reusable_connection[slot].port = http->port;
453 reusable_connection[slot].in_use = 0;
454 reusable_connection[slot].timestamp = time(NULL);
455 reusable_connection[slot].keep_alive_timeout = timeout;
458 assert(reusable_connection[slot].gateway_host == NULL);
459 assert(reusable_connection[slot].gateway_port == 0);
460 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
461 assert(reusable_connection[slot].forward_host == NULL);
462 assert(reusable_connection[slot].forward_port == 0);
464 reusable_connection[slot].forwarder_type = fwd->type;
465 if (NULL != fwd->gateway_host)
467 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
468 if (NULL == reusable_connection[slot].gateway_host)
470 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
475 reusable_connection[slot].gateway_host = NULL;
477 reusable_connection[slot].gateway_port = fwd->gateway_port;
479 if (NULL != fwd->forward_host)
481 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
482 if (NULL == reusable_connection[slot].forward_host)
484 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
489 reusable_connection[slot].forward_host = NULL;
491 reusable_connection[slot].forward_port = fwd->forward_port;
493 privoxy_mutex_unlock(&connection_reuse_mutex);
497 /*********************************************************************
499 * Function : mark_connection_closed
501 * Description : Marks a reused connection closed.
504 * 1 : closed_connection = The connection to mark as closed.
508 *********************************************************************/
509 void mark_connection_closed(struct reusable_connection *closed_connection)
511 closed_connection->in_use = FALSE;
512 closed_connection->sfd = JB_INVALID_SOCKET;
513 freez(closed_connection->host);
514 closed_connection->port = 0;
515 closed_connection->timestamp = 0;
516 closed_connection->keep_alive_timeout = 0;
517 closed_connection->forwarder_type = SOCKS_NONE;
518 freez(closed_connection->gateway_host);
519 closed_connection->gateway_port = 0;
520 freez(closed_connection->forward_host);
521 closed_connection->forward_port = 0;
525 /*********************************************************************
527 * Function : forget_connection
529 * Description : Removes a previously remembered connection from
530 * the list of reusable connections.
533 * 1 : sfd = The socket belonging to the connection in question.
537 *********************************************************************/
538 void forget_connection(jb_socket sfd)
540 unsigned int slot = 0;
542 assert(sfd != JB_INVALID_SOCKET);
544 privoxy_mutex_lock(&connection_reuse_mutex);
546 for (slot = 0; slot < SZ(reusable_connection); slot++)
548 if (reusable_connection[slot].sfd == sfd)
550 assert(reusable_connection[slot].in_use);
552 log_error(LOG_LEVEL_CONNECT,
553 "Forgetting socket %d for %s:%d in slot %d.",
554 sfd, reusable_connection[slot].host,
555 reusable_connection[slot].port, slot);
556 mark_connection_closed(&reusable_connection[slot]);
557 privoxy_mutex_unlock(&connection_reuse_mutex);
563 log_error(LOG_LEVEL_CONNECT,
564 "Socket %d already forgotten or never remembered.", sfd);
566 privoxy_mutex_unlock(&connection_reuse_mutex);
570 /*********************************************************************
572 * Function : connection_destination_matches
574 * Description : Determines whether a remembered connection can
575 * be reused. That is, whether the destination and
576 * the forwarding settings match.
579 * 1 : connection = The connection to check.
580 * 2 : http = The destination for the connection.
581 * 3 : fwd = The forwarder settings.
583 * Returns : TRUE for yes, FALSE otherwise.
585 *********************************************************************/
586 int connection_destination_matches(const struct reusable_connection *connection,
587 const struct http_request *http,
588 const struct forward_spec *fwd)
590 if ((connection->forwarder_type != fwd->type)
591 || (connection->gateway_port != fwd->gateway_port)
592 || (connection->forward_port != fwd->forward_port)
593 || (connection->port != http->port))
598 if (( (NULL != connection->gateway_host)
599 && (NULL != fwd->gateway_host)
600 && strcmpic(connection->gateway_host, fwd->gateway_host))
601 && (connection->gateway_host != fwd->gateway_host))
603 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
607 if (( (NULL != connection->forward_host)
608 && (NULL != fwd->forward_host)
609 && strcmpic(connection->forward_host, fwd->forward_host))
610 && (connection->forward_host != fwd->forward_host))
612 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
616 return (!strcmpic(connection->host, http->host));
621 /*********************************************************************
623 * Function : close_unusable_connections
625 * Description : Closes remembered connections that have timed
626 * out or have been closed on the other side.
630 * Returns : Number of connections that are still alive.
632 *********************************************************************/
633 int close_unusable_connections(void)
635 unsigned int slot = 0;
636 int connections_alive = 0;
638 privoxy_mutex_lock(&connection_reuse_mutex);
640 for (slot = 0; slot < SZ(reusable_connection); slot++)
642 if (!reusable_connection[slot].in_use
643 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
645 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
647 if (reusable_connection[slot].keep_alive_timeout < time_open)
649 log_error(LOG_LEVEL_CONNECT,
650 "The connection to %s:%d in slot %d timed out. "
651 "Closing socket %d. Timeout is: %d.",
652 reusable_connection[slot].host,
653 reusable_connection[slot].port, slot,
654 reusable_connection[slot].sfd,
655 reusable_connection[slot].keep_alive_timeout);
656 close_socket(reusable_connection[slot].sfd);
657 mark_connection_closed(&reusable_connection[slot]);
659 else if (!socket_is_still_usable(reusable_connection[slot].sfd))
661 log_error(LOG_LEVEL_CONNECT,
662 "The connection to %s:%d in slot %d is no longer usable. "
663 "Closing socket %d.", reusable_connection[slot].host,
664 reusable_connection[slot].port, slot,
665 reusable_connection[slot].sfd);
666 close_socket(reusable_connection[slot].sfd);
667 mark_connection_closed(&reusable_connection[slot]);
676 privoxy_mutex_unlock(&connection_reuse_mutex);
678 return connections_alive;
683 /*********************************************************************
685 * Function : get_reusable_connection
687 * Description : Returns an open socket to a previously remembered
688 * open connection (if there is one).
691 * 1 : http = The destination for the connection.
692 * 2 : fwd = The forwarder settings.
694 * Returns : JB_INVALID_SOCKET => No reusable connection found,
695 * otherwise a usable socket.
697 *********************************************************************/
698 static jb_socket get_reusable_connection(const struct http_request *http,
699 const struct forward_spec *fwd)
701 jb_socket sfd = JB_INVALID_SOCKET;
702 unsigned int slot = 0;
704 close_unusable_connections();
706 privoxy_mutex_lock(&connection_reuse_mutex);
708 for (slot = 0; slot < SZ(reusable_connection); slot++)
710 if (!reusable_connection[slot].in_use
711 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
713 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
715 reusable_connection[slot].in_use = TRUE;
716 sfd = reusable_connection[slot].sfd;
717 log_error(LOG_LEVEL_CONNECT,
718 "Found reusable socket %d for %s:%d in slot %d.",
719 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
725 privoxy_mutex_unlock(&connection_reuse_mutex);
732 /*********************************************************************
734 * Function : mark_connection_unused
736 * Description : Gives a remembered connection free for reuse.
739 * 1 : sfd = The socket belonging to the connection in question.
741 * Returns : TRUE => Socket found and marked as unused.
742 * FALSE => Socket not found.
744 *********************************************************************/
745 static int mark_connection_unused(jb_socket sfd)
747 unsigned int slot = 0;
748 int socket_found = FALSE;
750 assert(sfd != JB_INVALID_SOCKET);
752 privoxy_mutex_lock(&connection_reuse_mutex);
754 for (slot = 0; slot < SZ(reusable_connection); slot++)
756 if (reusable_connection[slot].sfd == sfd)
758 assert(reusable_connection[slot].in_use);
760 log_error(LOG_LEVEL_CONNECT,
761 "Marking open socket %d for %s:%d in slot %d as unused.",
762 sfd, reusable_connection[slot].host,
763 reusable_connection[slot].port, slot);
764 reusable_connection[slot].in_use = 0;
765 reusable_connection[slot].timestamp = time(NULL);
770 privoxy_mutex_unlock(&connection_reuse_mutex);
777 /*********************************************************************
779 * Function : set_keep_alive_timeout
781 * Description : Sets the timeout after which open
782 * connections will no longer be reused.
785 * 1 : timeout = The timeout in seconds.
789 *********************************************************************/
790 void set_keep_alive_timeout(unsigned int timeout)
792 keep_alive_timeout = timeout;
794 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
797 /*********************************************************************
799 * Function : forwarded_connect
801 * Description : Connect to a specified web server, possibly via
802 * a HTTP proxy and/or a SOCKS proxy.
805 * 1 : fwd = the proxies to use when connecting.
806 * 2 : http = the http request and apropos headers
807 * 3 : csp = Current client state (buffers, headers, etc...)
809 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
811 *********************************************************************/
812 jb_socket forwarded_connect(const struct forward_spec * fwd,
813 struct http_request *http,
814 struct client_state *csp)
816 const char * dest_host;
818 jb_socket sfd = JB_INVALID_SOCKET;
820 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
821 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
823 sfd = get_reusable_connection(http, fwd);
824 if (JB_INVALID_SOCKET != sfd)
829 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
831 /* Figure out if we need to connect to the web server or a HTTP proxy. */
832 if (fwd->forward_host)
835 dest_host = fwd->forward_host;
836 dest_port = fwd->forward_port;
841 dest_host = http->host;
842 dest_port = http->port;
845 /* Connect, maybe using a SOCKS proxy */
849 sfd = connect_to(dest_host, dest_port, csp);
853 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
856 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
859 /* Should never get here */
860 log_error(LOG_LEVEL_FATAL,
861 "SOCKS4 impossible internal error - bad SOCKS type.");
864 if (JB_INVALID_SOCKET != sfd)
866 log_error(LOG_LEVEL_CONNECT,
867 "Created new connection to %s:%d on socket %d.",
868 http->host, http->port, sfd);
876 /*********************************************************************
878 * Function : socks4_connect
880 * Description : Connect to the SOCKS server, and connect through
881 * it to the specified server. This handles
882 * all the SOCKS negotiation, and returns a file
883 * descriptor for a socket which can be treated as a
884 * normal (non-SOCKS) socket.
886 * Logged error messages are saved to csp->error_message
887 * and later reused by error_response() for the CGI
888 * message. strdup allocation failures are handled there.
891 * 1 : fwd = Specifies the SOCKS proxy to use.
892 * 2 : target_host = The final server to connect to.
893 * 3 : target_port = The final port to connect to.
894 * 4 : csp = Current client state (buffers, headers, etc...)
896 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
898 *********************************************************************/
899 static jb_socket socks4_connect(const struct forward_spec * fwd,
900 const char * target_host,
902 struct client_state *csp)
904 unsigned int web_server_addr;
905 char buf[BUFFER_SIZE];
906 struct socks_op *c = (struct socks_op *)buf;
907 struct socks_reply *s = (struct socks_reply *)buf;
914 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
916 /* XXX: Shouldn't the config file parser prevent this? */
917 errstr = "NULL gateway host specified.";
921 if (fwd->gateway_port <= 0)
923 errstr = "invalid gateway port specified.";
929 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
930 csp->error_message = strdup(errstr);
932 return(JB_INVALID_SOCKET);
935 /* build a socks request for connection to the web server */
937 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
939 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
944 web_server_addr = resolve_hostname_to_ip(target_host);
945 if (web_server_addr == INADDR_NONE)
947 errstr = "could not resolve target host";
948 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
953 web_server_addr = htonl(web_server_addr);
957 web_server_addr = 0x00000001;
958 n = csiz + strlen(target_host) + 1;
962 errstr = "buffer cbuf too small.";
963 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
968 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
970 * What we forward to the socks4a server should have the
971 * size of socks_op, plus the length of the userid plus
972 * its \0 byte (which we don't have to add because the
973 * first byte of the userid is counted twice as it's also
974 * part of sock_op) minus the padding bytes (which are part
975 * of the userid as well), plus the length of the target_host
976 * (which is stored csiz bytes after the beginning of the buffer),
977 * plus another \0 byte.
979 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
984 /* Should never get here */
985 log_error(LOG_LEVEL_FATAL,
986 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
988 return(JB_INVALID_SOCKET);
993 csp->error_message = strdup(errstr);
994 return(JB_INVALID_SOCKET);
999 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1000 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1001 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1002 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1003 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1004 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1006 /* pass the request to the socks server */
1007 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1009 if (sfd == JB_INVALID_SOCKET)
1012 * XXX: connect_to should fill in the exact reason.
1013 * Most likely resolving the IP of the forwarder failed.
1015 errstr = "connect_to failed: see logfile for details";
1018 else if (write_socket(sfd, (char *)c, csiz))
1020 errstr = "SOCKS4 negotiation write failed.";
1021 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1025 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1027 errstr = "SOCKS4 negotiation read failed.";
1028 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1035 csp->error_message = strdup(errstr);
1036 return(JB_INVALID_SOCKET);
1041 case SOCKS_REQUEST_GRANTED:
1043 case SOCKS_REQUEST_REJECT:
1044 errstr = "SOCKS request rejected or failed.";
1047 case SOCKS_REQUEST_IDENT_FAILED:
1048 errstr = "SOCKS request rejected because "
1049 "SOCKS server cannot connect to identd on the client.";
1052 case SOCKS_REQUEST_IDENT_CONFLICT:
1053 errstr = "SOCKS request rejected because "
1054 "the client program and identd report "
1055 "different user-ids.";
1060 snprintf(buf, sizeof(buf),
1061 "SOCKS request rejected for reason code %d.", s->cd);
1065 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1066 csp->error_message = strdup(errstr);
1069 return(JB_INVALID_SOCKET);
1073 /*********************************************************************
1075 * Function : translate_socks5_error
1077 * Description : Translates a SOCKS errors to a string.
1080 * 1 : socks_error = The error code to translate.
1082 * Returns : The string translation.
1084 *********************************************************************/
1085 static const char *translate_socks5_error(int socks_error)
1087 switch (socks_error)
1089 /* XXX: these should be more descriptive */
1090 case SOCKS5_REQUEST_FAILED:
1091 return "SOCKS5 request failed";
1092 case SOCKS5_REQUEST_DENIED:
1093 return "SOCKS5 request denied";
1094 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1095 return "SOCKS5 network unreachable";
1096 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1097 return "SOCKS5 host unreachable";
1098 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1099 return "SOCKS5 connection refused";
1100 case SOCKS5_REQUEST_TTL_EXPIRED:
1101 return "SOCKS5 TTL expired";
1102 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1103 return "SOCKS5 client protocol error";
1104 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1105 return "SOCKS5 domain names unsupported";
1106 case SOCKS5_REQUEST_GRANTED:
1107 return "everything's peachy";
1109 return "SOCKS5 negotiation protocol error";
1113 /*********************************************************************
1115 * Function : socks5_connect
1117 * Description : Connect to the SOCKS server, and connect through
1118 * it to the specified server. This handles
1119 * all the SOCKS negotiation, and returns a file
1120 * descriptor for a socket which can be treated as a
1121 * normal (non-SOCKS) socket.
1124 * 1 : fwd = Specifies the SOCKS proxy to use.
1125 * 2 : target_host = The final server to connect to.
1126 * 3 : target_port = The final port to connect to.
1127 * 4 : csp = Current client state (buffers, headers, etc...)
1129 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1131 *********************************************************************/
1132 static jb_socket socks5_connect(const struct forward_spec *fwd,
1133 const char *target_host,
1135 struct client_state *csp)
1140 size_t client_pos = 0;
1141 int server_size = 0;
1144 const char *errstr = NULL;
1146 assert(fwd->gateway_host);
1147 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1149 errstr = "NULL gateway host specified";
1153 if (fwd->gateway_port <= 0)
1156 * XXX: currently this can't happen because in
1157 * case of invalid gateway ports we use the defaults.
1158 * Of course we really shouldn't do that.
1160 errstr = "invalid gateway port specified";
1164 hostlen = strlen(target_host);
1165 if (hostlen > (size_t)255)
1167 errstr = "target host name is longer than 255 characters";
1171 if (fwd->type != SOCKS_5)
1173 /* Should never get here */
1174 log_error(LOG_LEVEL_FATAL,
1175 "SOCKS5 impossible internal error - bad SOCKS type");
1182 assert(errstr != NULL);
1183 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1184 csp->error_message = strdup(errstr);
1185 return(JB_INVALID_SOCKET);
1188 /* pass the request to the socks server */
1189 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1191 if (sfd == JB_INVALID_SOCKET)
1193 errstr = "socks5 server unreachable";
1194 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1195 csp->error_message = strdup(errstr);
1196 return(JB_INVALID_SOCKET);
1200 cbuf[client_pos++] = '\x05'; /* Version */
1201 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1202 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1204 if (write_socket(sfd, cbuf, client_pos))
1206 errstr = "SOCKS5 negotiation write failed";
1207 csp->error_message = strdup(errstr);
1208 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1210 return(JB_INVALID_SOCKET);
1213 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1215 errstr = "SOCKS5 negotiation read failed";
1219 if (!err && (sbuf[0] != '\x05'))
1221 errstr = "SOCKS5 negotiation protocol version error";
1225 if (!err && (sbuf[1] == '\xff'))
1227 errstr = "SOCKS5 authentication required";
1231 if (!err && (sbuf[1] != '\x00'))
1233 errstr = "SOCKS5 negotiation protocol error";
1239 assert(errstr != NULL);
1240 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1241 csp->error_message = strdup(errstr);
1244 return(JB_INVALID_SOCKET);
1248 cbuf[client_pos++] = '\x05'; /* Version */
1249 cbuf[client_pos++] = '\x01'; /* TCP connect */
1250 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1251 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1252 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1253 assert(sizeof(cbuf) - client_pos > (size_t)255);
1254 /* Using strncpy because we really want the nul byte padding. */
1255 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1256 client_pos += (hostlen & 0xffu);
1257 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1258 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1260 if (write_socket(sfd, cbuf, client_pos))
1262 errstr = "SOCKS5 negotiation read failed";
1263 csp->error_message = strdup(errstr);
1264 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1267 return(JB_INVALID_SOCKET);
1270 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1271 if (server_size < 3)
1273 errstr = "SOCKS5 negotiation read failed";
1276 else if (server_size > 20)
1278 /* This is somewhat unexpected but doesn't realy matter. */
1279 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1280 "from socks server. Would have accepted up to %d.",
1281 server_size, sizeof(sbuf));
1284 if (!err && (sbuf[0] != '\x05'))
1286 errstr = "SOCKS5 negotiation protocol version error";
1290 if (!err && (sbuf[2] != '\x00'))
1292 errstr = "SOCKS5 negotiation protocol error";
1298 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1302 errstr = translate_socks5_error(sbuf[1]);
1306 assert(errstr != NULL);
1307 csp->error_message = strdup(errstr);
1308 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1312 return(JB_INVALID_SOCKET);