1 const char gateway_rcs[] = "$Id: gateway.c,v 1.41 2008/11/08 15:29:58 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-2008 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.41 2008/11/08 15:29:58 fabiankeil
38 * Unify two debug messages.
40 * Revision 1.40 2008/11/08 15:14:05 fabiankeil
41 * Fix duplicated debugging check.
43 * Revision 1.39 2008/10/25 11:33:01 fabiankeil
44 * Remove already out-commented line left over from debugging.
46 * Revision 1.38 2008/10/24 17:33:00 fabiankeil
47 * - Tone the "keep-alive support is experimental" warning
48 * down a bit as hackish 0-chunk detection has been
49 * implemented recently.
50 * - Only show the "ndef HAVE_POLL" warning once on start-up.
52 * Revision 1.37 2008/10/23 17:40:53 fabiankeil
53 * Fix forget_connection() and mark_connection_unused(),
54 * which would both under certain circumstances access
55 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
57 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
58 * - Factor close_unusable_connections() out of
59 * get_reusable_connection() to make sure we really check
60 * all the remembered connections, not just the ones before
61 * the next reusable one.
62 * - Plug two file descriptor leaks. Internally marking
63 * connections as closed doesn't cut it.
65 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
66 * In socket_is_still_usable(), use select()
67 * and FD_ISSET() if poll() isn't available.
69 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
70 * Add preliminary timeout support.
72 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
73 * Fix two gcc44 warnings.
75 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
76 * Fix compiler warning.
78 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
79 * - Factor socket_is_still_usable() out of get_reusable_connection().
80 * - If poll() isn't available, show a warning and assume the socket
83 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
84 * If a remembered connection is no longer usable and
85 * has been marked closed, don't bother checking if the
86 * destination matches.
88 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
89 * Add missing dots for two log messages.
91 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
92 * Flush work-in-progress changes to keep outgoing connections
93 * alive where possible. Incomplete and mostly #ifdef'd out.
95 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
96 * Return only once in forwarded_connect().
98 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
99 * Fix typo in macro name.
101 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
103 * - make the buffers quite a bit smaller.
104 * - properly report "socks5 server unreachable" failures.
105 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
106 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
107 * - log a message if the socks5 server sends more data than expected.
108 * - add some assertions and comments.
110 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
111 * - Fix a compiler warning.
112 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
114 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
115 * Remember the cause of the SOCKS5 error for the CGI message.
117 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
118 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
120 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
121 * Modified patch from Song Weijia (#1762559) to
122 * fix socks requests on big-endian platforms.
124 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
125 * - Use strlcpy() instead of strcpy().
126 * - Use the same buffer for socks requests and socks responses.
127 * - Fix bogus warning about web_server_addr being used uninitialized.
129 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
130 * - Save errors in socks4_connect() to csp->error_message.
131 * - Silence some gcc43 warnings, hopefully the right way.
133 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
134 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
135 * with what was really the latest development (the v_3_0_branch branch)
137 * Revision 1.16 2002/05/12 21:36:29 jongfoster
138 * Correcting function comments
140 * Revision 1.15 2002/03/26 22:29:54 swa
141 * we have a new homepage!
143 * Revision 1.14 2002/03/24 13:25:43 swa
144 * name change related issues
146 * Revision 1.13 2002/03/13 00:29:59 jongfoster
149 * Revision 1.12 2002/03/09 20:03:52 jongfoster
150 * - Making various functions return int rather than size_t.
151 * (Undoing a recent change). Since size_t is unsigned on
152 * Windows, functions like read_socket that return -1 on
153 * error cannot return a size_t.
155 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
156 * crashes, and also frequently caused JB to jump to 100%
157 * CPU and stay there. (Because it thought it had just
158 * read ((unsigned)-1) == 4Gb of data...)
160 * - The signature of write_socket has changed, it now simply
161 * returns success=0/failure=nonzero.
163 * - Trying to get rid of a few warnings --with-debug on
164 * Windows, I've introduced a new type "jb_socket". This is
165 * used for the socket file descriptors. On Windows, this
166 * is SOCKET (a typedef for unsigned). Everywhere else, it's
167 * an int. The error value can't be -1 any more, so it's
168 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
169 * Windows it maps to the #define INVALID_SOCKET.)
171 * - The signature of bind_port has changed.
173 * Revision 1.11 2002/03/08 17:46:04 jongfoster
174 * Fixing int/size_t warnings
176 * Revision 1.10 2002/03/07 03:50:19 oes
177 * - Improved handling of failed DNS lookups
178 * - Fixed compiler warnings
180 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
181 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
182 * threads to call select() simultaneously. So, it's time to do a real, live,
183 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
184 * (native). Both versions will work, but using __OS2__ offers multi-threading.
186 * Revision 1.8 2001/09/13 20:10:12 jongfoster
187 * Fixing missing #include under Windows
189 * Revision 1.7 2001/09/12 17:58:26 steudten
191 * add #include <string.h>
193 * Revision 1.6 2001/09/10 10:41:16 oes
194 * Added #include in.h
196 * Revision 1.5 2001/07/29 18:47:57 jongfoster
197 * Adding missing #include project.h
199 * Revision 1.4 2001/07/24 12:47:06 oes
200 * Applied BeOS support update by Eugenia
202 * Revision 1.3 2001/06/09 10:55:28 jongfoster
203 * Changing BUFSIZ ==> BUFFER_SIZE
205 * Revision 1.2 2001/06/07 23:11:38 jongfoster
206 * Removing gateways[] list - no longer used.
207 * Replacing function pointer in struct gateway with a directly
208 * called function forwarded_connect(), which can do the common
209 * task of deciding whether to connect to the web server or HTTP
211 * Replacing struct gateway with struct forward_spec
212 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
213 * It was a bug which led to the connection being made to the web
214 * server rather than the HTTP proxy, and also a buffer overrun.
216 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
217 * Initial import of version 2.9.3 source tree
220 *********************************************************************/
226 #include <sys/types.h>
229 #include <netinet/in.h>
237 #include <winsock2.h>
238 #endif /* def _WIN32 */
242 #endif /* def __BEOS__ */
246 #endif /* def __OS2__ */
251 #include "jbsockets.h"
253 #include "miscutil.h"
254 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
257 #include <sys/poll.h>
260 #endif /* def __GLIBC__ */
261 #endif /* HAVE_POLL */
262 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
264 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
266 static jb_socket socks4_connect(const struct forward_spec * fwd,
267 const char * target_host,
269 struct client_state *csp);
271 static jb_socket socks5_connect(const struct forward_spec *fwd,
272 const char *target_host,
274 struct client_state *csp);
277 #define SOCKS_REQUEST_GRANTED 90
278 #define SOCKS_REQUEST_REJECT 91
279 #define SOCKS_REQUEST_IDENT_FAILED 92
280 #define SOCKS_REQUEST_IDENT_CONFLICT 93
282 #define SOCKS5_REQUEST_GRANTED 0
283 #define SOCKS5_REQUEST_FAILED 1
284 #define SOCKS5_REQUEST_DENIED 2
285 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
286 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
287 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
288 #define SOCKS5_REQUEST_TTL_EXPIRED 6
289 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
290 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
292 /* structure of a socks client operation */
294 unsigned char vn; /* socks version number */
295 unsigned char cd; /* command code */
296 unsigned char dstport[2]; /* destination port */
297 unsigned char dstip[4]; /* destination address */
298 char userid; /* first byte of userid */
299 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
300 /* more bytes of the userid follow, terminated by a NULL */
303 /* structure of a socks server reply */
305 unsigned char vn; /* socks version number */
306 unsigned char cd; /* command code */
307 unsigned char dstport[2]; /* destination port */
308 unsigned char dstip[4]; /* destination address */
311 static const char socks_userid[] = "anonymous";
313 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
315 #define MAX_REUSABLE_CONNECTIONS 100
316 int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
318 struct reusable_connection
333 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
335 static int mark_connection_unused(jb_socket sfd);
336 static void mark_connection_closed(struct reusable_connection *closed_connection);
337 static int socket_is_still_usable(jb_socket sfd);
340 /*********************************************************************
342 * Function : initialize_reusable_connections
344 * Description : Initializes the reusable_connection structures.
345 * Must be called with connection_reuse_mutex locked.
351 *********************************************************************/
352 extern void initialize_reusable_connections(void)
354 unsigned int slot = 0;
356 log_error(LOG_LEVEL_INFO,
357 "Support for 'Connection: keep-alive' is experimental."
359 " Detecting already dead connections might not work"
360 " correctly on your platform."
361 #endif /* ndef HAVE_POLL */
364 for (slot = 0; slot < SZ(reusable_connection); slot++)
366 mark_connection_closed(&reusable_connection[slot]);
369 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
373 /*********************************************************************
375 * Function : remember_connection
377 * Description : Remembers a connection for reuse later on.
380 * 1 : sfd = Open socket to remember.
381 * 2 : http = The destination for the connection.
382 * 3 : fwd = The forwarder settings used.
386 *********************************************************************/
387 void remember_connection(jb_socket sfd, const struct http_request *http,
388 const struct forward_spec *fwd)
390 unsigned int slot = 0;
391 int free_slot_found = FALSE;
393 assert(sfd != JB_INVALID_SOCKET);
395 if (mark_connection_unused(sfd))
400 privoxy_mutex_lock(&connection_reuse_mutex);
402 /* Find free socket slot. */
403 for (slot = 0; slot < SZ(reusable_connection); slot++)
405 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
407 assert(reusable_connection[slot].in_use == 0);
408 log_error(LOG_LEVEL_CONNECT,
409 "Remembering socket %d for %s:%d in slot %d.",
410 sfd, http->host, http->port, slot);
411 free_slot_found = TRUE;
416 if (!free_slot_found)
418 log_error(LOG_LEVEL_CONNECT,
419 "No free slots found to remembering socket for %s:%d. Last slot %d.",
420 http->host, http->port, slot);
421 privoxy_mutex_unlock(&connection_reuse_mutex);
426 assert(NULL != http->host);
427 reusable_connection[slot].host = strdup(http->host);
428 if (NULL == reusable_connection[slot].host)
430 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
432 reusable_connection[slot].sfd = sfd;
433 reusable_connection[slot].port = http->port;
434 reusable_connection[slot].in_use = 0;
435 reusable_connection[slot].timestamp = time(NULL);
438 assert(reusable_connection[slot].gateway_host == NULL);
439 assert(reusable_connection[slot].gateway_port == 0);
440 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
441 assert(reusable_connection[slot].forward_host == NULL);
442 assert(reusable_connection[slot].forward_port == 0);
444 reusable_connection[slot].forwarder_type = fwd->type;
445 if (NULL != fwd->gateway_host)
447 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
448 if (NULL == reusable_connection[slot].gateway_host)
450 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
455 reusable_connection[slot].gateway_host = NULL;
457 reusable_connection[slot].gateway_port = fwd->gateway_port;
459 if (NULL != fwd->forward_host)
461 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
462 if (NULL == reusable_connection[slot].forward_host)
464 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
469 reusable_connection[slot].forward_host = NULL;
471 reusable_connection[slot].forward_port = fwd->forward_port;
473 privoxy_mutex_unlock(&connection_reuse_mutex);
477 /*********************************************************************
479 * Function : mark_connection_closed
481 * Description : Marks a reused connection closed.
482 * Must be called with connection_reuse_mutex locked.
485 * 1 : closed_connection = The connection to mark as closed.
489 *********************************************************************/
490 static void mark_connection_closed(struct reusable_connection *closed_connection)
492 closed_connection->in_use = FALSE;
493 closed_connection->sfd = JB_INVALID_SOCKET;
494 freez(closed_connection->host);
495 closed_connection->port = 0;
496 closed_connection->timestamp = 0;
497 closed_connection->forwarder_type = SOCKS_NONE;
498 freez(closed_connection->gateway_host);
499 closed_connection->gateway_port = 0;
500 freez(closed_connection->forward_host);
501 closed_connection->forward_port = 0;
505 /*********************************************************************
507 * Function : forget_connection
509 * Description : Removes a previously remembered connection from
510 * the list of reusable connections.
513 * 1 : sfd = The socket belonging to the connection in question.
517 *********************************************************************/
518 void forget_connection(jb_socket sfd)
520 unsigned int slot = 0;
522 assert(sfd != JB_INVALID_SOCKET);
524 privoxy_mutex_lock(&connection_reuse_mutex);
526 for (slot = 0; slot < SZ(reusable_connection); slot++)
528 if (reusable_connection[slot].sfd == sfd)
530 assert(reusable_connection[slot].in_use);
532 log_error(LOG_LEVEL_CONNECT,
533 "Forgetting socket %d for %s:%d in slot %d.",
534 sfd, reusable_connection[slot].host,
535 reusable_connection[slot].port, slot);
536 mark_connection_closed(&reusable_connection[slot]);
537 privoxy_mutex_unlock(&connection_reuse_mutex);
543 log_error(LOG_LEVEL_CONNECT,
544 "Socket %d already forgotten or never remembered.", sfd);
546 privoxy_mutex_unlock(&connection_reuse_mutex);
550 /*********************************************************************
552 * Function : connection_destination_matches
554 * Description : Determines whether a remembered connection can
555 * be reused. That is whether the destination and
556 * the forwarding settings match.
559 * 1 : connection = The connection to check.
560 * 2 : http = The destination for the connection.
561 * 3 : fwd = The forwarder settings.
563 * Returns : TRUE for yes, FALSE otherwise.
565 *********************************************************************/
566 static int connection_destination_matches(const struct reusable_connection *connection,
567 const struct http_request *http,
568 const struct forward_spec *fwd)
570 /* XXX: Start of duplicated checks for debugging purposes. */
571 if (strcmpic(connection->host, http->host))
576 if (connection->forwarder_type != fwd->type)
578 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
579 connection->forwarder_type, fwd->type, http->host);
582 if (connection->gateway_port != fwd->gateway_port)
584 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
585 connection->gateway_port, fwd->gateway_port, http->host);
588 if (connection->forward_port != fwd->forward_port)
590 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
591 connection->forward_port, fwd->forward_port, http->host);
594 if (connection->port != http->port)
596 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
597 connection->port, http->port, http->host);
601 /* XXX: End of duplicated checks for debugging purposes. */
603 if ((connection->forwarder_type != fwd->type)
604 || (connection->gateway_port != fwd->gateway_port)
605 || (connection->forward_port != fwd->forward_port)
606 || (connection->port != http->port))
611 if (( (NULL != connection->gateway_host)
612 && (NULL != fwd->gateway_host)
613 && strcmpic(connection->gateway_host, fwd->gateway_host))
614 && (connection->gateway_host != fwd->gateway_host))
616 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
620 if (( (NULL != connection->forward_host)
621 && (NULL != fwd->forward_host)
622 && strcmpic(connection->forward_host, fwd->forward_host))
623 && (connection->forward_host != fwd->forward_host))
625 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
629 return (!strcmpic(connection->host, http->host));
634 /*********************************************************************
636 * Function : close_unusable_connections
638 * Description : Closes remembered connections that have timed
639 * out or have been closed on the other side.
645 *********************************************************************/
646 static void close_unusable_connections(void)
648 unsigned int slot = 0;
650 for (slot = 0; slot < SZ(reusable_connection); slot++)
652 if (!reusable_connection[slot].in_use
653 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
655 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
657 if (keep_alive_timeout < time_open)
659 log_error(LOG_LEVEL_CONNECT,
660 "The connection to %s:%d in slot %d timed out. "
661 "Closing socket %d. Timeout is: %d.",
662 reusable_connection[slot].host,
663 reusable_connection[slot].port, slot,
664 reusable_connection[slot].sfd, keep_alive_timeout);
665 close_socket(reusable_connection[slot].sfd);
666 mark_connection_closed(&reusable_connection[slot]);
670 if (!socket_is_still_usable(reusable_connection[slot].sfd))
672 log_error(LOG_LEVEL_CONNECT,
673 "The connection to %s:%d in slot %d is no longer usable. "
674 "Closing socket %d.", reusable_connection[slot].host,
675 reusable_connection[slot].port, slot,
676 reusable_connection[slot].sfd);
677 close_socket(reusable_connection[slot].sfd);
678 mark_connection_closed(&reusable_connection[slot]);
686 /*********************************************************************
688 * Function : socket_is_still_usable
690 * Description : Decides whether or not an open socket is still usable.
693 * 1 : sfd = The socket to check.
695 * Returns : TRUE for yes, otherwise FALSE.
697 *********************************************************************/
698 static int socket_is_still_usable(jb_socket sfd)
702 struct pollfd poll_fd[1];
704 memset(poll_fd, 0, sizeof(poll_fd));
706 poll_fd[0].events = POLLIN;
708 poll_result = poll(poll_fd, 1, 0);
710 if (-1 != poll_result)
712 return !(poll_fd[0].revents & POLLIN);
716 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
721 struct timeval timeout;
723 int socket_is_alive = 0;
725 memset(&timeout, '\0', sizeof(timeout));
726 FD_ZERO(&readable_fds);
727 FD_SET(sfd, &readable_fds);
729 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
732 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
736 * XXX: I'm not sure why !FD_ISSET() works,
737 * but apparently it does.
739 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
741 return socket_is_alive;
742 #endif /* def HAVE_POLL */
746 /*********************************************************************
748 * Function : get_reusable_connection
750 * Description : Returns an open socket to a previously remembered
751 * open connection (if there is one).
754 * 1 : http = The destination for the connection.
755 * 2 : fwd = The forwarder settings.
757 * Returns : JB_INVALID_SOCKET => No reusable connection found,
758 * otherwise a usable socket.
760 *********************************************************************/
761 static jb_socket get_reusable_connection(const struct http_request *http,
762 const struct forward_spec *fwd)
764 jb_socket sfd = JB_INVALID_SOCKET;
765 unsigned int slot = 0;
767 privoxy_mutex_lock(&connection_reuse_mutex);
769 close_unusable_connections();
771 for (slot = 0; slot < SZ(reusable_connection); slot++)
773 if (!reusable_connection[slot].in_use
774 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
776 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
778 reusable_connection[slot].in_use = TRUE;
779 sfd = reusable_connection[slot].sfd;
780 log_error(LOG_LEVEL_CONNECT,
781 "Found reusable socket %d for %s:%d in slot %d.",
782 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
788 privoxy_mutex_unlock(&connection_reuse_mutex);
795 /*********************************************************************
797 * Function : mark_connection_unused
799 * Description : Gives a remembered connection free for reuse.
802 * 1 : sfd = The socket belonging to the connection in question.
804 * Returns : TRUE => Socket found and marked as unused.
805 * FALSE => Socket not found.
807 *********************************************************************/
808 static int mark_connection_unused(jb_socket sfd)
810 unsigned int slot = 0;
811 int socket_found = FALSE;
813 assert(sfd != JB_INVALID_SOCKET);
815 privoxy_mutex_lock(&connection_reuse_mutex);
817 for (slot = 0; slot < SZ(reusable_connection); slot++)
819 if (reusable_connection[slot].sfd == sfd)
821 assert(reusable_connection[slot].in_use);
823 log_error(LOG_LEVEL_CONNECT,
824 "Marking open socket %d for %s:%d in slot %d as unused.",
825 sfd, reusable_connection[slot].host,
826 reusable_connection[slot].port, slot);
827 reusable_connection[slot].in_use = 0;
828 reusable_connection[slot].timestamp = time(NULL);
833 privoxy_mutex_unlock(&connection_reuse_mutex);
840 /*********************************************************************
842 * Function : set_keep_alive_timeout
844 * Description : Sets the timeout after which open
845 * connections will no longer be reused.
848 * 1 : timeout = The timeout in seconds.
852 *********************************************************************/
853 void set_keep_alive_timeout(int timeout)
855 keep_alive_timeout = timeout;
857 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
860 /*********************************************************************
862 * Function : forwarded_connect
864 * Description : Connect to a specified web server, possibly via
865 * a HTTP proxy and/or a SOCKS proxy.
868 * 1 : fwd = the proxies to use when connecting.
869 * 2 : http = the http request and apropos headers
870 * 3 : csp = Current client state (buffers, headers, etc...)
872 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
874 *********************************************************************/
875 jb_socket forwarded_connect(const struct forward_spec * fwd,
876 struct http_request *http,
877 struct client_state *csp)
879 const char * dest_host;
881 jb_socket sfd = JB_INVALID_SOCKET;
883 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
884 sfd = get_reusable_connection(http, fwd);
885 if (JB_INVALID_SOCKET == sfd)
887 log_error(LOG_LEVEL_CONNECT,
888 "No reusable socket for %s:%d found. Opening a new one.",
889 http->host, http->port);
895 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
897 /* Figure out if we need to connect to the web server or a HTTP proxy. */
898 if (fwd->forward_host)
901 dest_host = fwd->forward_host;
902 dest_port = fwd->forward_port;
907 dest_host = http->host;
908 dest_port = http->port;
911 /* Connect, maybe using a SOCKS proxy */
915 sfd = connect_to(dest_host, dest_port, csp);
919 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
922 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
925 /* Should never get here */
926 log_error(LOG_LEVEL_FATAL,
927 "SOCKS4 impossible internal error - bad SOCKS type.");
935 /*********************************************************************
937 * Function : socks4_connect
939 * Description : Connect to the SOCKS server, and connect through
940 * it to the specified server. This handles
941 * all the SOCKS negotiation, and returns a file
942 * descriptor for a socket which can be treated as a
943 * normal (non-SOCKS) socket.
945 * Logged error messages are saved to csp->error_message
946 * and later reused by error_response() for the CGI
947 * message. strdup allocation failures are handled there.
950 * 1 : fwd = Specifies the SOCKS proxy to use.
951 * 2 : target_host = The final server to connect to.
952 * 3 : target_port = The final port to connect to.
953 * 4 : csp = Current client state (buffers, headers, etc...)
955 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
957 *********************************************************************/
958 static jb_socket socks4_connect(const struct forward_spec * fwd,
959 const char * target_host,
961 struct client_state *csp)
963 unsigned int web_server_addr;
964 char buf[BUFFER_SIZE];
965 struct socks_op *c = (struct socks_op *)buf;
966 struct socks_reply *s = (struct socks_reply *)buf;
973 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
975 /* XXX: Shouldn't the config file parser prevent this? */
976 errstr = "NULL gateway host specified.";
980 if (fwd->gateway_port <= 0)
982 errstr = "invalid gateway port specified.";
988 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
989 csp->error_message = strdup(errstr);
991 return(JB_INVALID_SOCKET);
994 /* build a socks request for connection to the web server */
996 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
998 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
1003 web_server_addr = resolve_hostname_to_ip(target_host);
1004 if (web_server_addr == INADDR_NONE)
1006 errstr = "could not resolve target host";
1007 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
1012 web_server_addr = htonl(web_server_addr);
1016 web_server_addr = 0x00000001;
1017 n = csiz + strlen(target_host) + 1;
1018 if (n > sizeof(buf))
1021 errstr = "buffer cbuf too small.";
1022 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1027 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
1029 * What we forward to the socks4a server should have the
1030 * size of socks_op, plus the length of the userid plus
1031 * its \0 byte (which we don't have to add because the
1032 * first byte of the userid is counted twice as it's also
1033 * part of sock_op) minus the padding bytes (which are part
1034 * of the userid as well), plus the length of the target_host
1035 * (which is stored csiz bytes after the beginning of the buffer),
1036 * plus another \0 byte.
1038 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
1043 /* Should never get here */
1044 log_error(LOG_LEVEL_FATAL,
1045 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
1047 return(JB_INVALID_SOCKET);
1052 csp->error_message = strdup(errstr);
1053 return(JB_INVALID_SOCKET);
1058 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1059 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1060 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1061 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1062 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1063 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1065 /* pass the request to the socks server */
1066 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1068 if (sfd == JB_INVALID_SOCKET)
1071 * XXX: connect_to should fill in the exact reason.
1072 * Most likely resolving the IP of the forwarder failed.
1074 errstr = "connect_to failed: see logfile for details";
1077 else if (write_socket(sfd, (char *)c, csiz))
1079 errstr = "SOCKS4 negotiation write failed.";
1080 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1084 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1086 errstr = "SOCKS4 negotiation read failed.";
1087 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1094 csp->error_message = strdup(errstr);
1095 return(JB_INVALID_SOCKET);
1100 case SOCKS_REQUEST_GRANTED:
1103 case SOCKS_REQUEST_REJECT:
1104 errstr = "SOCKS request rejected or failed.";
1107 case SOCKS_REQUEST_IDENT_FAILED:
1108 errstr = "SOCKS request rejected because "
1109 "SOCKS server cannot connect to identd on the client.";
1112 case SOCKS_REQUEST_IDENT_CONFLICT:
1113 errstr = "SOCKS request rejected because "
1114 "the client program and identd report "
1115 "different user-ids.";
1120 snprintf(buf, sizeof(buf),
1121 "SOCKS request rejected for reason code %d.", s->cd);
1125 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1126 csp->error_message = strdup(errstr);
1129 return(JB_INVALID_SOCKET);
1133 /*********************************************************************
1135 * Function : translate_socks5_error
1137 * Description : Translates a SOCKS errors to a string.
1140 * 1 : socks_error = The error code to translate.
1142 * Returns : The string translation.
1144 *********************************************************************/
1145 static const char *translate_socks5_error(int socks_error)
1147 switch (socks_error)
1149 /* XXX: these should be more descriptive */
1150 case SOCKS5_REQUEST_FAILED:
1151 return "SOCKS5 request failed";
1152 case SOCKS5_REQUEST_DENIED:
1153 return "SOCKS5 request denied";
1154 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1155 return "SOCKS5 network unreachable";
1156 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1157 return "SOCKS5 host unreachable";
1158 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1159 return "SOCKS5 connection refused";
1160 case SOCKS5_REQUEST_TTL_EXPIRED:
1161 return "SOCKS5 TTL expired";
1162 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1163 return "SOCKS5 client protocol error";
1164 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1165 return "SOCKS5 domain names unsupported";
1166 case SOCKS5_REQUEST_GRANTED:
1167 return "everything's peachy";
1169 return "SOCKS5 negotiation protocol error";
1173 /*********************************************************************
1175 * Function : socks5_connect
1177 * Description : Connect to the SOCKS server, and connect through
1178 * it to the specified server. This handles
1179 * all the SOCKS negotiation, and returns a file
1180 * descriptor for a socket which can be treated as a
1181 * normal (non-SOCKS) socket.
1184 * 1 : fwd = Specifies the SOCKS proxy to use.
1185 * 2 : target_host = The final server to connect to.
1186 * 3 : target_port = The final port to connect to.
1187 * 4 : csp = Current client state (buffers, headers, etc...)
1189 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1191 *********************************************************************/
1192 static jb_socket socks5_connect(const struct forward_spec *fwd,
1193 const char *target_host,
1195 struct client_state *csp)
1200 size_t client_pos = 0;
1201 int server_size = 0;
1204 const char *errstr = NULL;
1206 assert(fwd->gateway_host);
1207 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1209 errstr = "NULL gateway host specified";
1213 if (fwd->gateway_port <= 0)
1216 * XXX: currently this can't happen because in
1217 * case of invalid gateway ports we use the defaults.
1218 * Of course we really shouldn't do that.
1220 errstr = "invalid gateway port specified";
1224 hostlen = strlen(target_host);
1227 errstr = "target host name is longer than 255 characters";
1231 if (fwd->type != SOCKS_5)
1233 /* Should never get here */
1234 log_error(LOG_LEVEL_FATAL,
1235 "SOCKS5 impossible internal error - bad SOCKS type");
1242 assert(errstr != NULL);
1243 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1244 csp->error_message = strdup(errstr);
1245 return(JB_INVALID_SOCKET);
1248 /* pass the request to the socks server */
1249 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1251 if (sfd == JB_INVALID_SOCKET)
1253 errstr = "socks5 server unreachable";
1254 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1255 csp->error_message = strdup(errstr);
1256 return(JB_INVALID_SOCKET);
1260 cbuf[client_pos++] = '\x05'; /* Version */
1261 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1262 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1264 if (write_socket(sfd, cbuf, client_pos))
1266 errstr = "SOCKS5 negotiation write failed";
1267 csp->error_message = strdup(errstr);
1268 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1270 return(JB_INVALID_SOCKET);
1273 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1275 errstr = "SOCKS5 negotiation read failed";
1279 if (!err && (sbuf[0] != '\x05'))
1281 errstr = "SOCKS5 negotiation protocol version error";
1285 if (!err && (sbuf[1] == '\xff'))
1287 errstr = "SOCKS5 authentication required";
1291 if (!err && (sbuf[1] != '\x00'))
1293 errstr = "SOCKS5 negotiation protocol error";
1299 assert(errstr != NULL);
1300 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1301 csp->error_message = strdup(errstr);
1304 return(JB_INVALID_SOCKET);
1308 cbuf[client_pos++] = '\x05'; /* Version */
1309 cbuf[client_pos++] = '\x01'; /* TCP connect */
1310 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1311 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1312 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1313 assert(sizeof(cbuf) - client_pos > 255);
1314 /* Using strncpy because we really want the nul byte padding. */
1315 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1316 client_pos += (hostlen & 0xffu);
1317 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1318 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1320 if (write_socket(sfd, cbuf, client_pos))
1322 errstr = "SOCKS5 negotiation read failed";
1323 csp->error_message = strdup(errstr);
1324 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1327 return(JB_INVALID_SOCKET);
1330 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1331 if (server_size < 3)
1333 errstr = "SOCKS5 negotiation read failed";
1336 else if (server_size > 20)
1338 /* This is somewhat unexpected but doesn't realy matter. */
1339 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1340 "from socks server. Would have accepted up to %d.",
1341 server_size, sizeof(sbuf));
1344 if (!err && (sbuf[0] != '\x05'))
1346 errstr = "SOCKS5 negotiation protocol version error";
1350 if (!err && (sbuf[2] != '\x00'))
1352 errstr = "SOCKS5 negotiation protocol error";
1358 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1362 errstr = translate_socks5_error(sbuf[1]);
1366 assert(errstr != NULL);
1367 csp->error_message = strdup(errstr);
1368 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1372 return(JB_INVALID_SOCKET);