1 const char gateway_rcs[] = "$Id: gateway.c,v 1.46 2008/12/13 11:07:23 fabiankeil Exp $";
2 /*********************************************************************
4 * File : $Source: /cvsroot/ijbswa/current/gateway.c,v $
6 * Purpose : Contains functions to connect to a server, possibly
7 * using a "forwarder" (i.e. HTTP proxy and/or a SOCKS4
10 * Copyright : Written by and Copyright (C) 2001-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.46 2008/12/13 11:07:23 fabiankeil
38 * Remove duplicated debugging checks
39 * in connection_destination_matches().
41 * Revision 1.45 2008/12/04 18:17:07 fabiankeil
42 * Fix some cparser warnings.
44 * Revision 1.44 2008/11/22 11:54:04 fabiankeil
45 * Move log message around to include the socket number.
47 * Revision 1.43 2008/11/13 09:15:51 fabiankeil
48 * Make keep_alive_timeout static.
50 * Revision 1.42 2008/11/13 09:08:42 fabiankeil
51 * Add new config option: keep-alive-timeout.
53 * Revision 1.41 2008/11/08 15:29:58 fabiankeil
54 * Unify two debug messages.
56 * Revision 1.40 2008/11/08 15:14:05 fabiankeil
57 * Fix duplicated debugging check.
59 * Revision 1.39 2008/10/25 11:33:01 fabiankeil
60 * Remove already out-commented line left over from debugging.
62 * Revision 1.38 2008/10/24 17:33:00 fabiankeil
63 * - Tone the "keep-alive support is experimental" warning
64 * down a bit as hackish 0-chunk detection has been
65 * implemented recently.
66 * - Only show the "ndef HAVE_POLL" warning once on start-up.
68 * Revision 1.37 2008/10/23 17:40:53 fabiankeil
69 * Fix forget_connection() and mark_connection_unused(),
70 * which would both under certain circumstances access
71 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
73 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
74 * - Factor close_unusable_connections() out of
75 * get_reusable_connection() to make sure we really check
76 * all the remembered connections, not just the ones before
77 * the next reusable one.
78 * - Plug two file descriptor leaks. Internally marking
79 * connections as closed doesn't cut it.
81 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
82 * In socket_is_still_usable(), use select()
83 * and FD_ISSET() if poll() isn't available.
85 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
86 * Add preliminary timeout support.
88 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
89 * Fix two gcc44 warnings.
91 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
92 * Fix compiler warning.
94 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
95 * - Factor socket_is_still_usable() out of get_reusable_connection().
96 * - If poll() isn't available, show a warning and assume the socket
99 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
100 * If a remembered connection is no longer usable and
101 * has been marked closed, don't bother checking if the
102 * destination matches.
104 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
105 * Add missing dots for two log messages.
107 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
108 * Flush work-in-progress changes to keep outgoing connections
109 * alive where possible. Incomplete and mostly #ifdef'd out.
111 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
112 * Return only once in forwarded_connect().
114 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
115 * Fix typo in macro name.
117 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
119 * - make the buffers quite a bit smaller.
120 * - properly report "socks5 server unreachable" failures.
121 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
122 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
123 * - log a message if the socks5 server sends more data than expected.
124 * - add some assertions and comments.
126 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
127 * - Fix a compiler warning.
128 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
130 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
131 * Remember the cause of the SOCKS5 error for the CGI message.
133 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
134 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
136 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
137 * Modified patch from Song Weijia (#1762559) to
138 * fix socks requests on big-endian platforms.
140 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
141 * - Use strlcpy() instead of strcpy().
142 * - Use the same buffer for socks requests and socks responses.
143 * - Fix bogus warning about web_server_addr being used uninitialized.
145 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
146 * - Save errors in socks4_connect() to csp->error_message.
147 * - Silence some gcc43 warnings, hopefully the right way.
149 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
150 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
151 * with what was really the latest development (the v_3_0_branch branch)
153 * Revision 1.16 2002/05/12 21:36:29 jongfoster
154 * Correcting function comments
156 * Revision 1.15 2002/03/26 22:29:54 swa
157 * we have a new homepage!
159 * Revision 1.14 2002/03/24 13:25:43 swa
160 * name change related issues
162 * Revision 1.13 2002/03/13 00:29:59 jongfoster
165 * Revision 1.12 2002/03/09 20:03:52 jongfoster
166 * - Making various functions return int rather than size_t.
167 * (Undoing a recent change). Since size_t is unsigned on
168 * Windows, functions like read_socket that return -1 on
169 * error cannot return a size_t.
171 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
172 * crashes, and also frequently caused JB to jump to 100%
173 * CPU and stay there. (Because it thought it had just
174 * read ((unsigned)-1) == 4Gb of data...)
176 * - The signature of write_socket has changed, it now simply
177 * returns success=0/failure=nonzero.
179 * - Trying to get rid of a few warnings --with-debug on
180 * Windows, I've introduced a new type "jb_socket". This is
181 * used for the socket file descriptors. On Windows, this
182 * is SOCKET (a typedef for unsigned). Everywhere else, it's
183 * an int. The error value can't be -1 any more, so it's
184 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
185 * Windows it maps to the #define INVALID_SOCKET.)
187 * - The signature of bind_port has changed.
189 * Revision 1.11 2002/03/08 17:46:04 jongfoster
190 * Fixing int/size_t warnings
192 * Revision 1.10 2002/03/07 03:50:19 oes
193 * - Improved handling of failed DNS lookups
194 * - Fixed compiler warnings
196 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
197 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
198 * threads to call select() simultaneously. So, it's time to do a real, live,
199 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
200 * (native). Both versions will work, but using __OS2__ offers multi-threading.
202 * Revision 1.8 2001/09/13 20:10:12 jongfoster
203 * Fixing missing #include under Windows
205 * Revision 1.7 2001/09/12 17:58:26 steudten
207 * add #include <string.h>
209 * Revision 1.6 2001/09/10 10:41:16 oes
210 * Added #include in.h
212 * Revision 1.5 2001/07/29 18:47:57 jongfoster
213 * Adding missing #include project.h
215 * Revision 1.4 2001/07/24 12:47:06 oes
216 * Applied BeOS support update by Eugenia
218 * Revision 1.3 2001/06/09 10:55:28 jongfoster
219 * Changing BUFSIZ ==> BUFFER_SIZE
221 * Revision 1.2 2001/06/07 23:11:38 jongfoster
222 * Removing gateways[] list - no longer used.
223 * Replacing function pointer in struct gateway with a directly
224 * called function forwarded_connect(), which can do the common
225 * task of deciding whether to connect to the web server or HTTP
227 * Replacing struct gateway with struct forward_spec
228 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
229 * It was a bug which led to the connection being made to the web
230 * server rather than the HTTP proxy, and also a buffer overrun.
232 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
233 * Initial import of version 2.9.3 source tree
236 *********************************************************************/
242 #include <sys/types.h>
245 #include <netinet/in.h>
253 #include <winsock2.h>
254 #endif /* def _WIN32 */
258 #endif /* def __BEOS__ */
262 #endif /* def __OS2__ */
267 #include "jbsockets.h"
269 #include "miscutil.h"
270 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
273 #include <sys/poll.h>
276 #endif /* def __GLIBC__ */
277 #endif /* HAVE_POLL */
278 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
280 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
282 static jb_socket socks4_connect(const struct forward_spec * fwd,
283 const char * target_host,
285 struct client_state *csp);
287 static jb_socket socks5_connect(const struct forward_spec *fwd,
288 const char *target_host,
290 struct client_state *csp);
293 #define SOCKS_REQUEST_GRANTED 90
294 #define SOCKS_REQUEST_REJECT 91
295 #define SOCKS_REQUEST_IDENT_FAILED 92
296 #define SOCKS_REQUEST_IDENT_CONFLICT 93
298 #define SOCKS5_REQUEST_GRANTED 0
299 #define SOCKS5_REQUEST_FAILED 1
300 #define SOCKS5_REQUEST_DENIED 2
301 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
302 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
303 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
304 #define SOCKS5_REQUEST_TTL_EXPIRED 6
305 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
306 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
308 /* structure of a socks client operation */
310 unsigned char vn; /* socks version number */
311 unsigned char cd; /* command code */
312 unsigned char dstport[2]; /* destination port */
313 unsigned char dstip[4]; /* destination address */
314 char userid; /* first byte of userid */
315 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
316 /* more bytes of the userid follow, terminated by a NULL */
319 /* structure of a socks server reply */
321 unsigned char vn; /* socks version number */
322 unsigned char cd; /* command code */
323 unsigned char dstport[2]; /* destination port */
324 unsigned char dstip[4]; /* destination address */
327 static const char socks_userid[] = "anonymous";
329 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
331 #define MAX_REUSABLE_CONNECTIONS 100
332 static int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
334 struct reusable_connection
349 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
351 static int mark_connection_unused(jb_socket sfd);
352 static void mark_connection_closed(struct reusable_connection *closed_connection);
353 static int socket_is_still_usable(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 log_error(LOG_LEVEL_INFO,
373 "Support for 'Connection: keep-alive' is experimental."
375 " Detecting already dead connections might not work"
376 " correctly on your platform."
377 #endif /* ndef HAVE_POLL */
380 for (slot = 0; slot < SZ(reusable_connection); slot++)
382 mark_connection_closed(&reusable_connection[slot]);
385 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
389 /*********************************************************************
391 * Function : remember_connection
393 * Description : Remembers a connection for reuse later on.
396 * 1 : sfd = Open socket to remember.
397 * 2 : http = The destination for the connection.
398 * 3 : fwd = The forwarder settings used.
402 *********************************************************************/
403 void remember_connection(jb_socket sfd, const struct http_request *http,
404 const struct forward_spec *fwd)
406 unsigned int slot = 0;
407 int free_slot_found = FALSE;
409 assert(sfd != JB_INVALID_SOCKET);
411 if (mark_connection_unused(sfd))
416 privoxy_mutex_lock(&connection_reuse_mutex);
418 /* Find free socket slot. */
419 for (slot = 0; slot < SZ(reusable_connection); slot++)
421 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
423 assert(reusable_connection[slot].in_use == 0);
424 log_error(LOG_LEVEL_CONNECT,
425 "Remembering socket %d for %s:%d in slot %d.",
426 sfd, http->host, http->port, slot);
427 free_slot_found = TRUE;
432 if (!free_slot_found)
434 log_error(LOG_LEVEL_CONNECT,
435 "No free slots found to remembering socket for %s:%d. Last slot %d.",
436 http->host, http->port, slot);
437 privoxy_mutex_unlock(&connection_reuse_mutex);
442 assert(NULL != http->host);
443 reusable_connection[slot].host = strdup(http->host);
444 if (NULL == reusable_connection[slot].host)
446 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
448 reusable_connection[slot].sfd = sfd;
449 reusable_connection[slot].port = http->port;
450 reusable_connection[slot].in_use = 0;
451 reusable_connection[slot].timestamp = time(NULL);
454 assert(reusable_connection[slot].gateway_host == NULL);
455 assert(reusable_connection[slot].gateway_port == 0);
456 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
457 assert(reusable_connection[slot].forward_host == NULL);
458 assert(reusable_connection[slot].forward_port == 0);
460 reusable_connection[slot].forwarder_type = fwd->type;
461 if (NULL != fwd->gateway_host)
463 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
464 if (NULL == reusable_connection[slot].gateway_host)
466 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
471 reusable_connection[slot].gateway_host = NULL;
473 reusable_connection[slot].gateway_port = fwd->gateway_port;
475 if (NULL != fwd->forward_host)
477 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
478 if (NULL == reusable_connection[slot].forward_host)
480 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
485 reusable_connection[slot].forward_host = NULL;
487 reusable_connection[slot].forward_port = fwd->forward_port;
489 privoxy_mutex_unlock(&connection_reuse_mutex);
493 /*********************************************************************
495 * Function : mark_connection_closed
497 * Description : Marks a reused connection closed.
498 * Must be called with connection_reuse_mutex locked.
501 * 1 : closed_connection = The connection to mark as closed.
505 *********************************************************************/
506 static void mark_connection_closed(struct reusable_connection *closed_connection)
508 closed_connection->in_use = FALSE;
509 closed_connection->sfd = JB_INVALID_SOCKET;
510 freez(closed_connection->host);
511 closed_connection->port = 0;
512 closed_connection->timestamp = 0;
513 closed_connection->forwarder_type = SOCKS_NONE;
514 freez(closed_connection->gateway_host);
515 closed_connection->gateway_port = 0;
516 freez(closed_connection->forward_host);
517 closed_connection->forward_port = 0;
521 /*********************************************************************
523 * Function : forget_connection
525 * Description : Removes a previously remembered connection from
526 * the list of reusable connections.
529 * 1 : sfd = The socket belonging to the connection in question.
533 *********************************************************************/
534 void forget_connection(jb_socket sfd)
536 unsigned int slot = 0;
538 assert(sfd != JB_INVALID_SOCKET);
540 privoxy_mutex_lock(&connection_reuse_mutex);
542 for (slot = 0; slot < SZ(reusable_connection); slot++)
544 if (reusable_connection[slot].sfd == sfd)
546 assert(reusable_connection[slot].in_use);
548 log_error(LOG_LEVEL_CONNECT,
549 "Forgetting socket %d for %s:%d in slot %d.",
550 sfd, reusable_connection[slot].host,
551 reusable_connection[slot].port, slot);
552 mark_connection_closed(&reusable_connection[slot]);
553 privoxy_mutex_unlock(&connection_reuse_mutex);
559 log_error(LOG_LEVEL_CONNECT,
560 "Socket %d already forgotten or never remembered.", sfd);
562 privoxy_mutex_unlock(&connection_reuse_mutex);
566 /*********************************************************************
568 * Function : connection_destination_matches
570 * Description : Determines whether a remembered connection can
571 * be reused. That is, whether the destination and
572 * the forwarding settings match.
575 * 1 : connection = The connection to check.
576 * 2 : http = The destination for the connection.
577 * 3 : fwd = The forwarder settings.
579 * Returns : TRUE for yes, FALSE otherwise.
581 *********************************************************************/
582 static int connection_destination_matches(const struct reusable_connection *connection,
583 const struct http_request *http,
584 const struct forward_spec *fwd)
586 if ((connection->forwarder_type != fwd->type)
587 || (connection->gateway_port != fwd->gateway_port)
588 || (connection->forward_port != fwd->forward_port)
589 || (connection->port != http->port))
594 if (( (NULL != connection->gateway_host)
595 && (NULL != fwd->gateway_host)
596 && strcmpic(connection->gateway_host, fwd->gateway_host))
597 && (connection->gateway_host != fwd->gateway_host))
599 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
603 if (( (NULL != connection->forward_host)
604 && (NULL != fwd->forward_host)
605 && strcmpic(connection->forward_host, fwd->forward_host))
606 && (connection->forward_host != fwd->forward_host))
608 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
612 return (!strcmpic(connection->host, http->host));
617 /*********************************************************************
619 * Function : close_unusable_connections
621 * Description : Closes remembered connections that have timed
622 * out or have been closed on the other side.
626 * Returns : Number of connections that are still alive.
628 *********************************************************************/
629 int close_unusable_connections(void)
631 unsigned int slot = 0;
632 int connections_alive = 0;
634 privoxy_mutex_lock(&connection_reuse_mutex);
636 for (slot = 0; slot < SZ(reusable_connection); slot++)
638 if (!reusable_connection[slot].in_use
639 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
641 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
643 if (keep_alive_timeout < time_open)
645 log_error(LOG_LEVEL_CONNECT,
646 "The connection to %s:%d in slot %d timed out. "
647 "Closing socket %d. Timeout is: %d.",
648 reusable_connection[slot].host,
649 reusable_connection[slot].port, slot,
650 reusable_connection[slot].sfd, keep_alive_timeout);
651 close_socket(reusable_connection[slot].sfd);
652 mark_connection_closed(&reusable_connection[slot]);
654 else if (!socket_is_still_usable(reusable_connection[slot].sfd))
656 log_error(LOG_LEVEL_CONNECT,
657 "The connection to %s:%d in slot %d is no longer usable. "
658 "Closing socket %d.", reusable_connection[slot].host,
659 reusable_connection[slot].port, slot,
660 reusable_connection[slot].sfd);
661 close_socket(reusable_connection[slot].sfd);
662 mark_connection_closed(&reusable_connection[slot]);
671 privoxy_mutex_unlock(&connection_reuse_mutex);
673 return connections_alive;
678 /*********************************************************************
680 * Function : socket_is_still_usable
682 * Description : Decides whether or not an open socket is still usable.
685 * 1 : sfd = The socket to check.
687 * Returns : TRUE for yes, otherwise FALSE.
689 *********************************************************************/
690 static int socket_is_still_usable(jb_socket sfd)
694 struct pollfd poll_fd[1];
696 memset(poll_fd, 0, sizeof(poll_fd));
698 poll_fd[0].events = POLLIN;
700 poll_result = poll(poll_fd, 1, 0);
702 if (-1 != poll_result)
704 return !(poll_fd[0].revents & POLLIN);
708 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
713 struct timeval timeout;
715 int socket_is_alive = 0;
717 memset(&timeout, '\0', sizeof(timeout));
718 FD_ZERO(&readable_fds);
719 FD_SET(sfd, &readable_fds);
721 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
724 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
728 * XXX: I'm not sure why !FD_ISSET() works,
729 * but apparently it does.
731 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
733 return socket_is_alive;
734 #endif /* def HAVE_POLL */
738 /*********************************************************************
740 * Function : get_reusable_connection
742 * Description : Returns an open socket to a previously remembered
743 * open connection (if there is one).
746 * 1 : http = The destination for the connection.
747 * 2 : fwd = The forwarder settings.
749 * Returns : JB_INVALID_SOCKET => No reusable connection found,
750 * otherwise a usable socket.
752 *********************************************************************/
753 static jb_socket get_reusable_connection(const struct http_request *http,
754 const struct forward_spec *fwd)
756 jb_socket sfd = JB_INVALID_SOCKET;
757 unsigned int slot = 0;
759 close_unusable_connections();
761 privoxy_mutex_lock(&connection_reuse_mutex);
763 for (slot = 0; slot < SZ(reusable_connection); slot++)
765 if (!reusable_connection[slot].in_use
766 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
768 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
770 reusable_connection[slot].in_use = TRUE;
771 sfd = reusable_connection[slot].sfd;
772 log_error(LOG_LEVEL_CONNECT,
773 "Found reusable socket %d for %s:%d in slot %d.",
774 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
780 privoxy_mutex_unlock(&connection_reuse_mutex);
787 /*********************************************************************
789 * Function : mark_connection_unused
791 * Description : Gives a remembered connection free for reuse.
794 * 1 : sfd = The socket belonging to the connection in question.
796 * Returns : TRUE => Socket found and marked as unused.
797 * FALSE => Socket not found.
799 *********************************************************************/
800 static int mark_connection_unused(jb_socket sfd)
802 unsigned int slot = 0;
803 int socket_found = FALSE;
805 assert(sfd != JB_INVALID_SOCKET);
807 privoxy_mutex_lock(&connection_reuse_mutex);
809 for (slot = 0; slot < SZ(reusable_connection); slot++)
811 if (reusable_connection[slot].sfd == sfd)
813 assert(reusable_connection[slot].in_use);
815 log_error(LOG_LEVEL_CONNECT,
816 "Marking open socket %d for %s:%d in slot %d as unused.",
817 sfd, reusable_connection[slot].host,
818 reusable_connection[slot].port, slot);
819 reusable_connection[slot].in_use = 0;
820 reusable_connection[slot].timestamp = time(NULL);
825 privoxy_mutex_unlock(&connection_reuse_mutex);
832 /*********************************************************************
834 * Function : set_keep_alive_timeout
836 * Description : Sets the timeout after which open
837 * connections will no longer be reused.
840 * 1 : timeout = The timeout in seconds.
844 *********************************************************************/
845 void set_keep_alive_timeout(int timeout)
847 keep_alive_timeout = timeout;
849 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
852 /*********************************************************************
854 * Function : forwarded_connect
856 * Description : Connect to a specified web server, possibly via
857 * a HTTP proxy and/or a SOCKS proxy.
860 * 1 : fwd = the proxies to use when connecting.
861 * 2 : http = the http request and apropos headers
862 * 3 : csp = Current client state (buffers, headers, etc...)
864 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
866 *********************************************************************/
867 jb_socket forwarded_connect(const struct forward_spec * fwd,
868 struct http_request *http,
869 struct client_state *csp)
871 const char * dest_host;
873 jb_socket sfd = JB_INVALID_SOCKET;
875 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
876 sfd = get_reusable_connection(http, fwd);
877 if (JB_INVALID_SOCKET != sfd)
881 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
883 /* Figure out if we need to connect to the web server or a HTTP proxy. */
884 if (fwd->forward_host)
887 dest_host = fwd->forward_host;
888 dest_port = fwd->forward_port;
893 dest_host = http->host;
894 dest_port = http->port;
897 /* Connect, maybe using a SOCKS proxy */
901 sfd = connect_to(dest_host, dest_port, csp);
905 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
908 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
911 /* Should never get here */
912 log_error(LOG_LEVEL_FATAL,
913 "SOCKS4 impossible internal error - bad SOCKS type.");
916 if (JB_INVALID_SOCKET != sfd)
918 log_error(LOG_LEVEL_CONNECT,
919 "Created new connection to %s:%d on socket %d.",
920 http->host, http->port, sfd);
928 /*********************************************************************
930 * Function : socks4_connect
932 * Description : Connect to the SOCKS server, and connect through
933 * it to the specified server. This handles
934 * all the SOCKS negotiation, and returns a file
935 * descriptor for a socket which can be treated as a
936 * normal (non-SOCKS) socket.
938 * Logged error messages are saved to csp->error_message
939 * and later reused by error_response() for the CGI
940 * message. strdup allocation failures are handled there.
943 * 1 : fwd = Specifies the SOCKS proxy to use.
944 * 2 : target_host = The final server to connect to.
945 * 3 : target_port = The final port to connect to.
946 * 4 : csp = Current client state (buffers, headers, etc...)
948 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
950 *********************************************************************/
951 static jb_socket socks4_connect(const struct forward_spec * fwd,
952 const char * target_host,
954 struct client_state *csp)
956 unsigned int web_server_addr;
957 char buf[BUFFER_SIZE];
958 struct socks_op *c = (struct socks_op *)buf;
959 struct socks_reply *s = (struct socks_reply *)buf;
966 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
968 /* XXX: Shouldn't the config file parser prevent this? */
969 errstr = "NULL gateway host specified.";
973 if (fwd->gateway_port <= 0)
975 errstr = "invalid gateway port specified.";
981 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
982 csp->error_message = strdup(errstr);
984 return(JB_INVALID_SOCKET);
987 /* build a socks request for connection to the web server */
989 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
991 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
996 web_server_addr = resolve_hostname_to_ip(target_host);
997 if (web_server_addr == INADDR_NONE)
999 errstr = "could not resolve target host";
1000 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
1005 web_server_addr = htonl(web_server_addr);
1009 web_server_addr = 0x00000001;
1010 n = csiz + strlen(target_host) + 1;
1011 if (n > sizeof(buf))
1014 errstr = "buffer cbuf too small.";
1015 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1020 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
1022 * What we forward to the socks4a server should have the
1023 * size of socks_op, plus the length of the userid plus
1024 * its \0 byte (which we don't have to add because the
1025 * first byte of the userid is counted twice as it's also
1026 * part of sock_op) minus the padding bytes (which are part
1027 * of the userid as well), plus the length of the target_host
1028 * (which is stored csiz bytes after the beginning of the buffer),
1029 * plus another \0 byte.
1031 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
1036 /* Should never get here */
1037 log_error(LOG_LEVEL_FATAL,
1038 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
1040 return(JB_INVALID_SOCKET);
1045 csp->error_message = strdup(errstr);
1046 return(JB_INVALID_SOCKET);
1051 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1052 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1053 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1054 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1055 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1056 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1058 /* pass the request to the socks server */
1059 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1061 if (sfd == JB_INVALID_SOCKET)
1064 * XXX: connect_to should fill in the exact reason.
1065 * Most likely resolving the IP of the forwarder failed.
1067 errstr = "connect_to failed: see logfile for details";
1070 else if (write_socket(sfd, (char *)c, csiz))
1072 errstr = "SOCKS4 negotiation write failed.";
1073 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1077 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1079 errstr = "SOCKS4 negotiation read failed.";
1080 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1087 csp->error_message = strdup(errstr);
1088 return(JB_INVALID_SOCKET);
1093 case SOCKS_REQUEST_GRANTED:
1095 case SOCKS_REQUEST_REJECT:
1096 errstr = "SOCKS request rejected or failed.";
1099 case SOCKS_REQUEST_IDENT_FAILED:
1100 errstr = "SOCKS request rejected because "
1101 "SOCKS server cannot connect to identd on the client.";
1104 case SOCKS_REQUEST_IDENT_CONFLICT:
1105 errstr = "SOCKS request rejected because "
1106 "the client program and identd report "
1107 "different user-ids.";
1112 snprintf(buf, sizeof(buf),
1113 "SOCKS request rejected for reason code %d.", s->cd);
1117 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1118 csp->error_message = strdup(errstr);
1121 return(JB_INVALID_SOCKET);
1125 /*********************************************************************
1127 * Function : translate_socks5_error
1129 * Description : Translates a SOCKS errors to a string.
1132 * 1 : socks_error = The error code to translate.
1134 * Returns : The string translation.
1136 *********************************************************************/
1137 static const char *translate_socks5_error(int socks_error)
1139 switch (socks_error)
1141 /* XXX: these should be more descriptive */
1142 case SOCKS5_REQUEST_FAILED:
1143 return "SOCKS5 request failed";
1144 case SOCKS5_REQUEST_DENIED:
1145 return "SOCKS5 request denied";
1146 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1147 return "SOCKS5 network unreachable";
1148 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1149 return "SOCKS5 host unreachable";
1150 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1151 return "SOCKS5 connection refused";
1152 case SOCKS5_REQUEST_TTL_EXPIRED:
1153 return "SOCKS5 TTL expired";
1154 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1155 return "SOCKS5 client protocol error";
1156 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1157 return "SOCKS5 domain names unsupported";
1158 case SOCKS5_REQUEST_GRANTED:
1159 return "everything's peachy";
1161 return "SOCKS5 negotiation protocol error";
1165 /*********************************************************************
1167 * Function : socks5_connect
1169 * Description : Connect to the SOCKS server, and connect through
1170 * it to the specified server. This handles
1171 * all the SOCKS negotiation, and returns a file
1172 * descriptor for a socket which can be treated as a
1173 * normal (non-SOCKS) socket.
1176 * 1 : fwd = Specifies the SOCKS proxy to use.
1177 * 2 : target_host = The final server to connect to.
1178 * 3 : target_port = The final port to connect to.
1179 * 4 : csp = Current client state (buffers, headers, etc...)
1181 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1183 *********************************************************************/
1184 static jb_socket socks5_connect(const struct forward_spec *fwd,
1185 const char *target_host,
1187 struct client_state *csp)
1192 size_t client_pos = 0;
1193 int server_size = 0;
1196 const char *errstr = NULL;
1198 assert(fwd->gateway_host);
1199 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1201 errstr = "NULL gateway host specified";
1205 if (fwd->gateway_port <= 0)
1208 * XXX: currently this can't happen because in
1209 * case of invalid gateway ports we use the defaults.
1210 * Of course we really shouldn't do that.
1212 errstr = "invalid gateway port specified";
1216 hostlen = strlen(target_host);
1217 if (hostlen > (size_t)255)
1219 errstr = "target host name is longer than 255 characters";
1223 if (fwd->type != SOCKS_5)
1225 /* Should never get here */
1226 log_error(LOG_LEVEL_FATAL,
1227 "SOCKS5 impossible internal error - bad SOCKS type");
1234 assert(errstr != NULL);
1235 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1236 csp->error_message = strdup(errstr);
1237 return(JB_INVALID_SOCKET);
1240 /* pass the request to the socks server */
1241 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1243 if (sfd == JB_INVALID_SOCKET)
1245 errstr = "socks5 server unreachable";
1246 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1247 csp->error_message = strdup(errstr);
1248 return(JB_INVALID_SOCKET);
1252 cbuf[client_pos++] = '\x05'; /* Version */
1253 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1254 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1256 if (write_socket(sfd, cbuf, client_pos))
1258 errstr = "SOCKS5 negotiation write failed";
1259 csp->error_message = strdup(errstr);
1260 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1262 return(JB_INVALID_SOCKET);
1265 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1267 errstr = "SOCKS5 negotiation read failed";
1271 if (!err && (sbuf[0] != '\x05'))
1273 errstr = "SOCKS5 negotiation protocol version error";
1277 if (!err && (sbuf[1] == '\xff'))
1279 errstr = "SOCKS5 authentication required";
1283 if (!err && (sbuf[1] != '\x00'))
1285 errstr = "SOCKS5 negotiation protocol error";
1291 assert(errstr != NULL);
1292 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1293 csp->error_message = strdup(errstr);
1296 return(JB_INVALID_SOCKET);
1300 cbuf[client_pos++] = '\x05'; /* Version */
1301 cbuf[client_pos++] = '\x01'; /* TCP connect */
1302 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1303 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1304 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1305 assert(sizeof(cbuf) - client_pos > (size_t)255);
1306 /* Using strncpy because we really want the nul byte padding. */
1307 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1308 client_pos += (hostlen & 0xffu);
1309 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1310 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1312 if (write_socket(sfd, cbuf, client_pos))
1314 errstr = "SOCKS5 negotiation read failed";
1315 csp->error_message = strdup(errstr);
1316 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1319 return(JB_INVALID_SOCKET);
1322 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1323 if (server_size < 3)
1325 errstr = "SOCKS5 negotiation read failed";
1328 else if (server_size > 20)
1330 /* This is somewhat unexpected but doesn't realy matter. */
1331 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1332 "from socks server. Would have accepted up to %d.",
1333 server_size, sizeof(sbuf));
1336 if (!err && (sbuf[0] != '\x05'))
1338 errstr = "SOCKS5 negotiation protocol version error";
1342 if (!err && (sbuf[2] != '\x00'))
1344 errstr = "SOCKS5 negotiation protocol error";
1350 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1354 errstr = translate_socks5_error(sbuf[1]);
1358 assert(errstr != NULL);
1359 csp->error_message = strdup(errstr);
1360 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1364 return(JB_INVALID_SOCKET);