1 const char gateway_rcs[] = "$Id: gateway.c,v 1.47 2008/12/24 17:06:19 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.47 2008/12/24 17:06:19 fabiankeil
38 * Keep a thread around to timeout alive connections
39 * even if no new requests are coming in.
41 * Revision 1.46 2008/12/13 11:07:23 fabiankeil
42 * Remove duplicated debugging checks
43 * in connection_destination_matches().
45 * Revision 1.45 2008/12/04 18:17:07 fabiankeil
46 * Fix some cparser warnings.
48 * Revision 1.44 2008/11/22 11:54:04 fabiankeil
49 * Move log message around to include the socket number.
51 * Revision 1.43 2008/11/13 09:15:51 fabiankeil
52 * Make keep_alive_timeout static.
54 * Revision 1.42 2008/11/13 09:08:42 fabiankeil
55 * Add new config option: keep-alive-timeout.
57 * Revision 1.41 2008/11/08 15:29:58 fabiankeil
58 * Unify two debug messages.
60 * Revision 1.40 2008/11/08 15:14:05 fabiankeil
61 * Fix duplicated debugging check.
63 * Revision 1.39 2008/10/25 11:33:01 fabiankeil
64 * Remove already out-commented line left over from debugging.
66 * Revision 1.38 2008/10/24 17:33:00 fabiankeil
67 * - Tone the "keep-alive support is experimental" warning
68 * down a bit as hackish 0-chunk detection has been
69 * implemented recently.
70 * - Only show the "ndef HAVE_POLL" warning once on start-up.
72 * Revision 1.37 2008/10/23 17:40:53 fabiankeil
73 * Fix forget_connection() and mark_connection_unused(),
74 * which would both under certain circumstances access
75 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
77 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
78 * - Factor close_unusable_connections() out of
79 * get_reusable_connection() to make sure we really check
80 * all the remembered connections, not just the ones before
81 * the next reusable one.
82 * - Plug two file descriptor leaks. Internally marking
83 * connections as closed doesn't cut it.
85 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
86 * In socket_is_still_usable(), use select()
87 * and FD_ISSET() if poll() isn't available.
89 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
90 * Add preliminary timeout support.
92 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
93 * Fix two gcc44 warnings.
95 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
96 * Fix compiler warning.
98 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
99 * - Factor socket_is_still_usable() out of get_reusable_connection().
100 * - If poll() isn't available, show a warning and assume the socket
103 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
104 * If a remembered connection is no longer usable and
105 * has been marked closed, don't bother checking if the
106 * destination matches.
108 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
109 * Add missing dots for two log messages.
111 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
112 * Flush work-in-progress changes to keep outgoing connections
113 * alive where possible. Incomplete and mostly #ifdef'd out.
115 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
116 * Return only once in forwarded_connect().
118 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
119 * Fix typo in macro name.
121 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
123 * - make the buffers quite a bit smaller.
124 * - properly report "socks5 server unreachable" failures.
125 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
126 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
127 * - log a message if the socks5 server sends more data than expected.
128 * - add some assertions and comments.
130 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
131 * - Fix a compiler warning.
132 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
134 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
135 * Remember the cause of the SOCKS5 error for the CGI message.
137 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
138 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
140 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
141 * Modified patch from Song Weijia (#1762559) to
142 * fix socks requests on big-endian platforms.
144 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
145 * - Use strlcpy() instead of strcpy().
146 * - Use the same buffer for socks requests and socks responses.
147 * - Fix bogus warning about web_server_addr being used uninitialized.
149 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
150 * - Save errors in socks4_connect() to csp->error_message.
151 * - Silence some gcc43 warnings, hopefully the right way.
153 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
154 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
155 * with what was really the latest development (the v_3_0_branch branch)
157 * Revision 1.16 2002/05/12 21:36:29 jongfoster
158 * Correcting function comments
160 * Revision 1.15 2002/03/26 22:29:54 swa
161 * we have a new homepage!
163 * Revision 1.14 2002/03/24 13:25:43 swa
164 * name change related issues
166 * Revision 1.13 2002/03/13 00:29:59 jongfoster
169 * Revision 1.12 2002/03/09 20:03:52 jongfoster
170 * - Making various functions return int rather than size_t.
171 * (Undoing a recent change). Since size_t is unsigned on
172 * Windows, functions like read_socket that return -1 on
173 * error cannot return a size_t.
175 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
176 * crashes, and also frequently caused JB to jump to 100%
177 * CPU and stay there. (Because it thought it had just
178 * read ((unsigned)-1) == 4Gb of data...)
180 * - The signature of write_socket has changed, it now simply
181 * returns success=0/failure=nonzero.
183 * - Trying to get rid of a few warnings --with-debug on
184 * Windows, I've introduced a new type "jb_socket". This is
185 * used for the socket file descriptors. On Windows, this
186 * is SOCKET (a typedef for unsigned). Everywhere else, it's
187 * an int. The error value can't be -1 any more, so it's
188 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
189 * Windows it maps to the #define INVALID_SOCKET.)
191 * - The signature of bind_port has changed.
193 * Revision 1.11 2002/03/08 17:46:04 jongfoster
194 * Fixing int/size_t warnings
196 * Revision 1.10 2002/03/07 03:50:19 oes
197 * - Improved handling of failed DNS lookups
198 * - Fixed compiler warnings
200 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
201 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
202 * threads to call select() simultaneously. So, it's time to do a real, live,
203 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
204 * (native). Both versions will work, but using __OS2__ offers multi-threading.
206 * Revision 1.8 2001/09/13 20:10:12 jongfoster
207 * Fixing missing #include under Windows
209 * Revision 1.7 2001/09/12 17:58:26 steudten
211 * add #include <string.h>
213 * Revision 1.6 2001/09/10 10:41:16 oes
214 * Added #include in.h
216 * Revision 1.5 2001/07/29 18:47:57 jongfoster
217 * Adding missing #include project.h
219 * Revision 1.4 2001/07/24 12:47:06 oes
220 * Applied BeOS support update by Eugenia
222 * Revision 1.3 2001/06/09 10:55:28 jongfoster
223 * Changing BUFSIZ ==> BUFFER_SIZE
225 * Revision 1.2 2001/06/07 23:11:38 jongfoster
226 * Removing gateways[] list - no longer used.
227 * Replacing function pointer in struct gateway with a directly
228 * called function forwarded_connect(), which can do the common
229 * task of deciding whether to connect to the web server or HTTP
231 * Replacing struct gateway with struct forward_spec
232 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
233 * It was a bug which led to the connection being made to the web
234 * server rather than the HTTP proxy, and also a buffer overrun.
236 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
237 * Initial import of version 2.9.3 source tree
240 *********************************************************************/
246 #include <sys/types.h>
249 #include <netinet/in.h>
257 #include <winsock2.h>
258 #endif /* def _WIN32 */
262 #endif /* def __BEOS__ */
266 #endif /* def __OS2__ */
271 #include "jbsockets.h"
273 #include "miscutil.h"
274 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
277 #include <sys/poll.h>
280 #endif /* def __GLIBC__ */
281 #endif /* HAVE_POLL */
282 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
284 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
286 static jb_socket socks4_connect(const struct forward_spec * fwd,
287 const char * target_host,
289 struct client_state *csp);
291 static jb_socket socks5_connect(const struct forward_spec *fwd,
292 const char *target_host,
294 struct client_state *csp);
297 #define SOCKS_REQUEST_GRANTED 90
298 #define SOCKS_REQUEST_REJECT 91
299 #define SOCKS_REQUEST_IDENT_FAILED 92
300 #define SOCKS_REQUEST_IDENT_CONFLICT 93
302 #define SOCKS5_REQUEST_GRANTED 0
303 #define SOCKS5_REQUEST_FAILED 1
304 #define SOCKS5_REQUEST_DENIED 2
305 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
306 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
307 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
308 #define SOCKS5_REQUEST_TTL_EXPIRED 6
309 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
310 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
312 /* structure of a socks client operation */
314 unsigned char vn; /* socks version number */
315 unsigned char cd; /* command code */
316 unsigned char dstport[2]; /* destination port */
317 unsigned char dstip[4]; /* destination address */
318 char userid; /* first byte of userid */
319 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
320 /* more bytes of the userid follow, terminated by a NULL */
323 /* structure of a socks server reply */
325 unsigned char vn; /* socks version number */
326 unsigned char cd; /* command code */
327 unsigned char dstport[2]; /* destination port */
328 unsigned char dstip[4]; /* destination address */
331 static const char socks_userid[] = "anonymous";
333 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
335 #define MAX_REUSABLE_CONNECTIONS 100
336 static int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
338 struct reusable_connection
353 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
355 static int mark_connection_unused(jb_socket sfd);
356 static void mark_connection_closed(struct reusable_connection *closed_connection);
357 static int socket_is_still_usable(jb_socket sfd);
360 /*********************************************************************
362 * Function : initialize_reusable_connections
364 * Description : Initializes the reusable_connection structures.
365 * Must be called with connection_reuse_mutex locked.
371 *********************************************************************/
372 extern void initialize_reusable_connections(void)
374 unsigned int slot = 0;
376 #if !defined(HAVE_POLL) && !defined(_WIN32)
377 log_error(LOG_LEVEL_INFO,
378 "Detecting already dead connections might not work "
379 "correctly on your platform. In case of problems, "
380 "unset the keep-alive-timeout option.");
383 for (slot = 0; slot < SZ(reusable_connection); slot++)
385 mark_connection_closed(&reusable_connection[slot]);
388 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
392 /*********************************************************************
394 * Function : remember_connection
396 * Description : Remembers a connection for reuse later on.
399 * 1 : sfd = Open socket to remember.
400 * 2 : http = The destination for the connection.
401 * 3 : fwd = The forwarder settings used.
405 *********************************************************************/
406 void remember_connection(jb_socket sfd, const struct http_request *http,
407 const struct forward_spec *fwd)
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);
457 assert(reusable_connection[slot].gateway_host == NULL);
458 assert(reusable_connection[slot].gateway_port == 0);
459 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
460 assert(reusable_connection[slot].forward_host == NULL);
461 assert(reusable_connection[slot].forward_port == 0);
463 reusable_connection[slot].forwarder_type = fwd->type;
464 if (NULL != fwd->gateway_host)
466 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
467 if (NULL == reusable_connection[slot].gateway_host)
469 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
474 reusable_connection[slot].gateway_host = NULL;
476 reusable_connection[slot].gateway_port = fwd->gateway_port;
478 if (NULL != fwd->forward_host)
480 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
481 if (NULL == reusable_connection[slot].forward_host)
483 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
488 reusable_connection[slot].forward_host = NULL;
490 reusable_connection[slot].forward_port = fwd->forward_port;
492 privoxy_mutex_unlock(&connection_reuse_mutex);
496 /*********************************************************************
498 * Function : mark_connection_closed
500 * Description : Marks a reused connection closed.
501 * Must be called with connection_reuse_mutex locked.
504 * 1 : closed_connection = The connection to mark as closed.
508 *********************************************************************/
509 static 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->forwarder_type = SOCKS_NONE;
517 freez(closed_connection->gateway_host);
518 closed_connection->gateway_port = 0;
519 freez(closed_connection->forward_host);
520 closed_connection->forward_port = 0;
524 /*********************************************************************
526 * Function : forget_connection
528 * Description : Removes a previously remembered connection from
529 * the list of reusable connections.
532 * 1 : sfd = The socket belonging to the connection in question.
536 *********************************************************************/
537 void forget_connection(jb_socket sfd)
539 unsigned int slot = 0;
541 assert(sfd != JB_INVALID_SOCKET);
543 privoxy_mutex_lock(&connection_reuse_mutex);
545 for (slot = 0; slot < SZ(reusable_connection); slot++)
547 if (reusable_connection[slot].sfd == sfd)
549 assert(reusable_connection[slot].in_use);
551 log_error(LOG_LEVEL_CONNECT,
552 "Forgetting socket %d for %s:%d in slot %d.",
553 sfd, reusable_connection[slot].host,
554 reusable_connection[slot].port, slot);
555 mark_connection_closed(&reusable_connection[slot]);
556 privoxy_mutex_unlock(&connection_reuse_mutex);
562 log_error(LOG_LEVEL_CONNECT,
563 "Socket %d already forgotten or never remembered.", sfd);
565 privoxy_mutex_unlock(&connection_reuse_mutex);
569 /*********************************************************************
571 * Function : connection_destination_matches
573 * Description : Determines whether a remembered connection can
574 * be reused. That is, whether the destination and
575 * the forwarding settings match.
578 * 1 : connection = The connection to check.
579 * 2 : http = The destination for the connection.
580 * 3 : fwd = The forwarder settings.
582 * Returns : TRUE for yes, FALSE otherwise.
584 *********************************************************************/
585 static int connection_destination_matches(const struct reusable_connection *connection,
586 const struct http_request *http,
587 const struct forward_spec *fwd)
589 if ((connection->forwarder_type != fwd->type)
590 || (connection->gateway_port != fwd->gateway_port)
591 || (connection->forward_port != fwd->forward_port)
592 || (connection->port != http->port))
597 if (( (NULL != connection->gateway_host)
598 && (NULL != fwd->gateway_host)
599 && strcmpic(connection->gateway_host, fwd->gateway_host))
600 && (connection->gateway_host != fwd->gateway_host))
602 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
606 if (( (NULL != connection->forward_host)
607 && (NULL != fwd->forward_host)
608 && strcmpic(connection->forward_host, fwd->forward_host))
609 && (connection->forward_host != fwd->forward_host))
611 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
615 return (!strcmpic(connection->host, http->host));
620 /*********************************************************************
622 * Function : close_unusable_connections
624 * Description : Closes remembered connections that have timed
625 * out or have been closed on the other side.
629 * Returns : Number of connections that are still alive.
631 *********************************************************************/
632 int close_unusable_connections(void)
634 unsigned int slot = 0;
635 int connections_alive = 0;
637 privoxy_mutex_lock(&connection_reuse_mutex);
639 for (slot = 0; slot < SZ(reusable_connection); slot++)
641 if (!reusable_connection[slot].in_use
642 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
644 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
646 if (keep_alive_timeout < time_open)
648 log_error(LOG_LEVEL_CONNECT,
649 "The connection to %s:%d in slot %d timed out. "
650 "Closing socket %d. Timeout is: %d.",
651 reusable_connection[slot].host,
652 reusable_connection[slot].port, slot,
653 reusable_connection[slot].sfd, keep_alive_timeout);
654 close_socket(reusable_connection[slot].sfd);
655 mark_connection_closed(&reusable_connection[slot]);
657 else if (!socket_is_still_usable(reusable_connection[slot].sfd))
659 log_error(LOG_LEVEL_CONNECT,
660 "The connection to %s:%d in slot %d is no longer usable. "
661 "Closing socket %d.", reusable_connection[slot].host,
662 reusable_connection[slot].port, slot,
663 reusable_connection[slot].sfd);
664 close_socket(reusable_connection[slot].sfd);
665 mark_connection_closed(&reusable_connection[slot]);
674 privoxy_mutex_unlock(&connection_reuse_mutex);
676 return connections_alive;
681 /*********************************************************************
683 * Function : socket_is_still_usable
685 * Description : Decides whether or not an open socket is still usable.
688 * 1 : sfd = The socket to check.
690 * Returns : TRUE for yes, otherwise FALSE.
692 *********************************************************************/
693 static int socket_is_still_usable(jb_socket sfd)
697 struct pollfd poll_fd[1];
699 memset(poll_fd, 0, sizeof(poll_fd));
701 poll_fd[0].events = POLLIN;
703 poll_result = poll(poll_fd, 1, 0);
705 if (-1 != poll_result)
707 return !(poll_fd[0].revents & POLLIN);
711 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
716 struct timeval timeout;
718 int socket_is_alive = 0;
720 memset(&timeout, '\0', sizeof(timeout));
721 FD_ZERO(&readable_fds);
722 FD_SET(sfd, &readable_fds);
724 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
727 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
731 * XXX: I'm not sure why !FD_ISSET() works,
732 * but apparently it does.
734 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
736 return socket_is_alive;
737 #endif /* def HAVE_POLL */
741 /*********************************************************************
743 * Function : get_reusable_connection
745 * Description : Returns an open socket to a previously remembered
746 * open connection (if there is one).
749 * 1 : http = The destination for the connection.
750 * 2 : fwd = The forwarder settings.
752 * Returns : JB_INVALID_SOCKET => No reusable connection found,
753 * otherwise a usable socket.
755 *********************************************************************/
756 static jb_socket get_reusable_connection(const struct http_request *http,
757 const struct forward_spec *fwd)
759 jb_socket sfd = JB_INVALID_SOCKET;
760 unsigned int slot = 0;
762 close_unusable_connections();
764 privoxy_mutex_lock(&connection_reuse_mutex);
766 for (slot = 0; slot < SZ(reusable_connection); slot++)
768 if (!reusable_connection[slot].in_use
769 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
771 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
773 reusable_connection[slot].in_use = TRUE;
774 sfd = reusable_connection[slot].sfd;
775 log_error(LOG_LEVEL_CONNECT,
776 "Found reusable socket %d for %s:%d in slot %d.",
777 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
783 privoxy_mutex_unlock(&connection_reuse_mutex);
790 /*********************************************************************
792 * Function : mark_connection_unused
794 * Description : Gives a remembered connection free for reuse.
797 * 1 : sfd = The socket belonging to the connection in question.
799 * Returns : TRUE => Socket found and marked as unused.
800 * FALSE => Socket not found.
802 *********************************************************************/
803 static int mark_connection_unused(jb_socket sfd)
805 unsigned int slot = 0;
806 int socket_found = FALSE;
808 assert(sfd != JB_INVALID_SOCKET);
810 privoxy_mutex_lock(&connection_reuse_mutex);
812 for (slot = 0; slot < SZ(reusable_connection); slot++)
814 if (reusable_connection[slot].sfd == sfd)
816 assert(reusable_connection[slot].in_use);
818 log_error(LOG_LEVEL_CONNECT,
819 "Marking open socket %d for %s:%d in slot %d as unused.",
820 sfd, reusable_connection[slot].host,
821 reusable_connection[slot].port, slot);
822 reusable_connection[slot].in_use = 0;
823 reusable_connection[slot].timestamp = time(NULL);
828 privoxy_mutex_unlock(&connection_reuse_mutex);
835 /*********************************************************************
837 * Function : set_keep_alive_timeout
839 * Description : Sets the timeout after which open
840 * connections will no longer be reused.
843 * 1 : timeout = The timeout in seconds.
847 *********************************************************************/
848 void set_keep_alive_timeout(int timeout)
850 keep_alive_timeout = timeout;
852 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
855 /*********************************************************************
857 * Function : forwarded_connect
859 * Description : Connect to a specified web server, possibly via
860 * a HTTP proxy and/or a SOCKS proxy.
863 * 1 : fwd = the proxies to use when connecting.
864 * 2 : http = the http request and apropos headers
865 * 3 : csp = Current client state (buffers, headers, etc...)
867 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
869 *********************************************************************/
870 jb_socket forwarded_connect(const struct forward_spec * fwd,
871 struct http_request *http,
872 struct client_state *csp)
874 const char * dest_host;
876 jb_socket sfd = JB_INVALID_SOCKET;
878 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
879 sfd = get_reusable_connection(http, fwd);
880 if (JB_INVALID_SOCKET != sfd)
884 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
886 /* Figure out if we need to connect to the web server or a HTTP proxy. */
887 if (fwd->forward_host)
890 dest_host = fwd->forward_host;
891 dest_port = fwd->forward_port;
896 dest_host = http->host;
897 dest_port = http->port;
900 /* Connect, maybe using a SOCKS proxy */
904 sfd = connect_to(dest_host, dest_port, csp);
908 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
911 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
914 /* Should never get here */
915 log_error(LOG_LEVEL_FATAL,
916 "SOCKS4 impossible internal error - bad SOCKS type.");
919 if (JB_INVALID_SOCKET != sfd)
921 log_error(LOG_LEVEL_CONNECT,
922 "Created new connection to %s:%d on socket %d.",
923 http->host, http->port, sfd);
931 /*********************************************************************
933 * Function : socks4_connect
935 * Description : Connect to the SOCKS server, and connect through
936 * it to the specified server. This handles
937 * all the SOCKS negotiation, and returns a file
938 * descriptor for a socket which can be treated as a
939 * normal (non-SOCKS) socket.
941 * Logged error messages are saved to csp->error_message
942 * and later reused by error_response() for the CGI
943 * message. strdup allocation failures are handled there.
946 * 1 : fwd = Specifies the SOCKS proxy to use.
947 * 2 : target_host = The final server to connect to.
948 * 3 : target_port = The final port to connect to.
949 * 4 : csp = Current client state (buffers, headers, etc...)
951 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
953 *********************************************************************/
954 static jb_socket socks4_connect(const struct forward_spec * fwd,
955 const char * target_host,
957 struct client_state *csp)
959 unsigned int web_server_addr;
960 char buf[BUFFER_SIZE];
961 struct socks_op *c = (struct socks_op *)buf;
962 struct socks_reply *s = (struct socks_reply *)buf;
969 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
971 /* XXX: Shouldn't the config file parser prevent this? */
972 errstr = "NULL gateway host specified.";
976 if (fwd->gateway_port <= 0)
978 errstr = "invalid gateway port specified.";
984 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
985 csp->error_message = strdup(errstr);
987 return(JB_INVALID_SOCKET);
990 /* build a socks request for connection to the web server */
992 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
994 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
999 web_server_addr = resolve_hostname_to_ip(target_host);
1000 if (web_server_addr == INADDR_NONE)
1002 errstr = "could not resolve target host";
1003 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
1008 web_server_addr = htonl(web_server_addr);
1012 web_server_addr = 0x00000001;
1013 n = csiz + strlen(target_host) + 1;
1014 if (n > sizeof(buf))
1017 errstr = "buffer cbuf too small.";
1018 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1023 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
1025 * What we forward to the socks4a server should have the
1026 * size of socks_op, plus the length of the userid plus
1027 * its \0 byte (which we don't have to add because the
1028 * first byte of the userid is counted twice as it's also
1029 * part of sock_op) minus the padding bytes (which are part
1030 * of the userid as well), plus the length of the target_host
1031 * (which is stored csiz bytes after the beginning of the buffer),
1032 * plus another \0 byte.
1034 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
1039 /* Should never get here */
1040 log_error(LOG_LEVEL_FATAL,
1041 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
1043 return(JB_INVALID_SOCKET);
1048 csp->error_message = strdup(errstr);
1049 return(JB_INVALID_SOCKET);
1054 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1055 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1056 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1057 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1058 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1059 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1061 /* pass the request to the socks server */
1062 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1064 if (sfd == JB_INVALID_SOCKET)
1067 * XXX: connect_to should fill in the exact reason.
1068 * Most likely resolving the IP of the forwarder failed.
1070 errstr = "connect_to failed: see logfile for details";
1073 else if (write_socket(sfd, (char *)c, csiz))
1075 errstr = "SOCKS4 negotiation write failed.";
1076 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1080 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1082 errstr = "SOCKS4 negotiation read failed.";
1083 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1090 csp->error_message = strdup(errstr);
1091 return(JB_INVALID_SOCKET);
1096 case SOCKS_REQUEST_GRANTED:
1098 case SOCKS_REQUEST_REJECT:
1099 errstr = "SOCKS request rejected or failed.";
1102 case SOCKS_REQUEST_IDENT_FAILED:
1103 errstr = "SOCKS request rejected because "
1104 "SOCKS server cannot connect to identd on the client.";
1107 case SOCKS_REQUEST_IDENT_CONFLICT:
1108 errstr = "SOCKS request rejected because "
1109 "the client program and identd report "
1110 "different user-ids.";
1115 snprintf(buf, sizeof(buf),
1116 "SOCKS request rejected for reason code %d.", s->cd);
1120 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1121 csp->error_message = strdup(errstr);
1124 return(JB_INVALID_SOCKET);
1128 /*********************************************************************
1130 * Function : translate_socks5_error
1132 * Description : Translates a SOCKS errors to a string.
1135 * 1 : socks_error = The error code to translate.
1137 * Returns : The string translation.
1139 *********************************************************************/
1140 static const char *translate_socks5_error(int socks_error)
1142 switch (socks_error)
1144 /* XXX: these should be more descriptive */
1145 case SOCKS5_REQUEST_FAILED:
1146 return "SOCKS5 request failed";
1147 case SOCKS5_REQUEST_DENIED:
1148 return "SOCKS5 request denied";
1149 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1150 return "SOCKS5 network unreachable";
1151 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1152 return "SOCKS5 host unreachable";
1153 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1154 return "SOCKS5 connection refused";
1155 case SOCKS5_REQUEST_TTL_EXPIRED:
1156 return "SOCKS5 TTL expired";
1157 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1158 return "SOCKS5 client protocol error";
1159 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1160 return "SOCKS5 domain names unsupported";
1161 case SOCKS5_REQUEST_GRANTED:
1162 return "everything's peachy";
1164 return "SOCKS5 negotiation protocol error";
1168 /*********************************************************************
1170 * Function : socks5_connect
1172 * Description : Connect to the SOCKS server, and connect through
1173 * it to the specified server. This handles
1174 * all the SOCKS negotiation, and returns a file
1175 * descriptor for a socket which can be treated as a
1176 * normal (non-SOCKS) socket.
1179 * 1 : fwd = Specifies the SOCKS proxy to use.
1180 * 2 : target_host = The final server to connect to.
1181 * 3 : target_port = The final port to connect to.
1182 * 4 : csp = Current client state (buffers, headers, etc...)
1184 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1186 *********************************************************************/
1187 static jb_socket socks5_connect(const struct forward_spec *fwd,
1188 const char *target_host,
1190 struct client_state *csp)
1195 size_t client_pos = 0;
1196 int server_size = 0;
1199 const char *errstr = NULL;
1201 assert(fwd->gateway_host);
1202 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1204 errstr = "NULL gateway host specified";
1208 if (fwd->gateway_port <= 0)
1211 * XXX: currently this can't happen because in
1212 * case of invalid gateway ports we use the defaults.
1213 * Of course we really shouldn't do that.
1215 errstr = "invalid gateway port specified";
1219 hostlen = strlen(target_host);
1220 if (hostlen > (size_t)255)
1222 errstr = "target host name is longer than 255 characters";
1226 if (fwd->type != SOCKS_5)
1228 /* Should never get here */
1229 log_error(LOG_LEVEL_FATAL,
1230 "SOCKS5 impossible internal error - bad SOCKS type");
1237 assert(errstr != NULL);
1238 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1239 csp->error_message = strdup(errstr);
1240 return(JB_INVALID_SOCKET);
1243 /* pass the request to the socks server */
1244 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1246 if (sfd == JB_INVALID_SOCKET)
1248 errstr = "socks5 server unreachable";
1249 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1250 csp->error_message = strdup(errstr);
1251 return(JB_INVALID_SOCKET);
1255 cbuf[client_pos++] = '\x05'; /* Version */
1256 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1257 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1259 if (write_socket(sfd, cbuf, client_pos))
1261 errstr = "SOCKS5 negotiation write failed";
1262 csp->error_message = strdup(errstr);
1263 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1265 return(JB_INVALID_SOCKET);
1268 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1270 errstr = "SOCKS5 negotiation read failed";
1274 if (!err && (sbuf[0] != '\x05'))
1276 errstr = "SOCKS5 negotiation protocol version error";
1280 if (!err && (sbuf[1] == '\xff'))
1282 errstr = "SOCKS5 authentication required";
1286 if (!err && (sbuf[1] != '\x00'))
1288 errstr = "SOCKS5 negotiation protocol error";
1294 assert(errstr != NULL);
1295 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1296 csp->error_message = strdup(errstr);
1299 return(JB_INVALID_SOCKET);
1303 cbuf[client_pos++] = '\x05'; /* Version */
1304 cbuf[client_pos++] = '\x01'; /* TCP connect */
1305 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1306 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1307 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1308 assert(sizeof(cbuf) - client_pos > (size_t)255);
1309 /* Using strncpy because we really want the nul byte padding. */
1310 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1311 client_pos += (hostlen & 0xffu);
1312 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1313 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1315 if (write_socket(sfd, cbuf, client_pos))
1317 errstr = "SOCKS5 negotiation read failed";
1318 csp->error_message = strdup(errstr);
1319 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1322 return(JB_INVALID_SOCKET);
1325 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1326 if (server_size < 3)
1328 errstr = "SOCKS5 negotiation read failed";
1331 else if (server_size > 20)
1333 /* This is somewhat unexpected but doesn't realy matter. */
1334 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1335 "from socks server. Would have accepted up to %d.",
1336 server_size, sizeof(sbuf));
1339 if (!err && (sbuf[0] != '\x05'))
1341 errstr = "SOCKS5 negotiation protocol version error";
1345 if (!err && (sbuf[2] != '\x00'))
1347 errstr = "SOCKS5 negotiation protocol error";
1353 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1357 errstr = translate_socks5_error(sbuf[1]);
1361 assert(errstr != NULL);
1362 csp->error_message = strdup(errstr);
1363 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1367 return(JB_INVALID_SOCKET);