1 const char gateway_rcs[] = "$Id: gateway.c,v 1.45 2008/12/04 18:17:07 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.45 2008/12/04 18:17:07 fabiankeil
38 * Fix some cparser warnings.
40 * Revision 1.44 2008/11/22 11:54:04 fabiankeil
41 * Move log message around to include the socket number.
43 * Revision 1.43 2008/11/13 09:15:51 fabiankeil
44 * Make keep_alive_timeout static.
46 * Revision 1.42 2008/11/13 09:08:42 fabiankeil
47 * Add new config option: keep-alive-timeout.
49 * Revision 1.41 2008/11/08 15:29:58 fabiankeil
50 * Unify two debug messages.
52 * Revision 1.40 2008/11/08 15:14:05 fabiankeil
53 * Fix duplicated debugging check.
55 * Revision 1.39 2008/10/25 11:33:01 fabiankeil
56 * Remove already out-commented line left over from debugging.
58 * Revision 1.38 2008/10/24 17:33:00 fabiankeil
59 * - Tone the "keep-alive support is experimental" warning
60 * down a bit as hackish 0-chunk detection has been
61 * implemented recently.
62 * - Only show the "ndef HAVE_POLL" warning once on start-up.
64 * Revision 1.37 2008/10/23 17:40:53 fabiankeil
65 * Fix forget_connection() and mark_connection_unused(),
66 * which would both under certain circumstances access
67 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
69 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
70 * - Factor close_unusable_connections() out of
71 * get_reusable_connection() to make sure we really check
72 * all the remembered connections, not just the ones before
73 * the next reusable one.
74 * - Plug two file descriptor leaks. Internally marking
75 * connections as closed doesn't cut it.
77 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
78 * In socket_is_still_usable(), use select()
79 * and FD_ISSET() if poll() isn't available.
81 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
82 * Add preliminary timeout support.
84 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
85 * Fix two gcc44 warnings.
87 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
88 * Fix compiler warning.
90 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
91 * - Factor socket_is_still_usable() out of get_reusable_connection().
92 * - If poll() isn't available, show a warning and assume the socket
95 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
96 * If a remembered connection is no longer usable and
97 * has been marked closed, don't bother checking if the
98 * destination matches.
100 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
101 * Add missing dots for two log messages.
103 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
104 * Flush work-in-progress changes to keep outgoing connections
105 * alive where possible. Incomplete and mostly #ifdef'd out.
107 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
108 * Return only once in forwarded_connect().
110 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
111 * Fix typo in macro name.
113 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
115 * - make the buffers quite a bit smaller.
116 * - properly report "socks5 server unreachable" failures.
117 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
118 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
119 * - log a message if the socks5 server sends more data than expected.
120 * - add some assertions and comments.
122 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
123 * - Fix a compiler warning.
124 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
126 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
127 * Remember the cause of the SOCKS5 error for the CGI message.
129 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
130 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
132 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
133 * Modified patch from Song Weijia (#1762559) to
134 * fix socks requests on big-endian platforms.
136 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
137 * - Use strlcpy() instead of strcpy().
138 * - Use the same buffer for socks requests and socks responses.
139 * - Fix bogus warning about web_server_addr being used uninitialized.
141 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
142 * - Save errors in socks4_connect() to csp->error_message.
143 * - Silence some gcc43 warnings, hopefully the right way.
145 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
146 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
147 * with what was really the latest development (the v_3_0_branch branch)
149 * Revision 1.16 2002/05/12 21:36:29 jongfoster
150 * Correcting function comments
152 * Revision 1.15 2002/03/26 22:29:54 swa
153 * we have a new homepage!
155 * Revision 1.14 2002/03/24 13:25:43 swa
156 * name change related issues
158 * Revision 1.13 2002/03/13 00:29:59 jongfoster
161 * Revision 1.12 2002/03/09 20:03:52 jongfoster
162 * - Making various functions return int rather than size_t.
163 * (Undoing a recent change). Since size_t is unsigned on
164 * Windows, functions like read_socket that return -1 on
165 * error cannot return a size_t.
167 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
168 * crashes, and also frequently caused JB to jump to 100%
169 * CPU and stay there. (Because it thought it had just
170 * read ((unsigned)-1) == 4Gb of data...)
172 * - The signature of write_socket has changed, it now simply
173 * returns success=0/failure=nonzero.
175 * - Trying to get rid of a few warnings --with-debug on
176 * Windows, I've introduced a new type "jb_socket". This is
177 * used for the socket file descriptors. On Windows, this
178 * is SOCKET (a typedef for unsigned). Everywhere else, it's
179 * an int. The error value can't be -1 any more, so it's
180 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
181 * Windows it maps to the #define INVALID_SOCKET.)
183 * - The signature of bind_port has changed.
185 * Revision 1.11 2002/03/08 17:46:04 jongfoster
186 * Fixing int/size_t warnings
188 * Revision 1.10 2002/03/07 03:50:19 oes
189 * - Improved handling of failed DNS lookups
190 * - Fixed compiler warnings
192 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
193 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
194 * threads to call select() simultaneously. So, it's time to do a real, live,
195 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
196 * (native). Both versions will work, but using __OS2__ offers multi-threading.
198 * Revision 1.8 2001/09/13 20:10:12 jongfoster
199 * Fixing missing #include under Windows
201 * Revision 1.7 2001/09/12 17:58:26 steudten
203 * add #include <string.h>
205 * Revision 1.6 2001/09/10 10:41:16 oes
206 * Added #include in.h
208 * Revision 1.5 2001/07/29 18:47:57 jongfoster
209 * Adding missing #include project.h
211 * Revision 1.4 2001/07/24 12:47:06 oes
212 * Applied BeOS support update by Eugenia
214 * Revision 1.3 2001/06/09 10:55:28 jongfoster
215 * Changing BUFSIZ ==> BUFFER_SIZE
217 * Revision 1.2 2001/06/07 23:11:38 jongfoster
218 * Removing gateways[] list - no longer used.
219 * Replacing function pointer in struct gateway with a directly
220 * called function forwarded_connect(), which can do the common
221 * task of deciding whether to connect to the web server or HTTP
223 * Replacing struct gateway with struct forward_spec
224 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
225 * It was a bug which led to the connection being made to the web
226 * server rather than the HTTP proxy, and also a buffer overrun.
228 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
229 * Initial import of version 2.9.3 source tree
232 *********************************************************************/
238 #include <sys/types.h>
241 #include <netinet/in.h>
249 #include <winsock2.h>
250 #endif /* def _WIN32 */
254 #endif /* def __BEOS__ */
258 #endif /* def __OS2__ */
263 #include "jbsockets.h"
265 #include "miscutil.h"
266 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
269 #include <sys/poll.h>
272 #endif /* def __GLIBC__ */
273 #endif /* HAVE_POLL */
274 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
276 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
278 static jb_socket socks4_connect(const struct forward_spec * fwd,
279 const char * target_host,
281 struct client_state *csp);
283 static jb_socket socks5_connect(const struct forward_spec *fwd,
284 const char *target_host,
286 struct client_state *csp);
289 #define SOCKS_REQUEST_GRANTED 90
290 #define SOCKS_REQUEST_REJECT 91
291 #define SOCKS_REQUEST_IDENT_FAILED 92
292 #define SOCKS_REQUEST_IDENT_CONFLICT 93
294 #define SOCKS5_REQUEST_GRANTED 0
295 #define SOCKS5_REQUEST_FAILED 1
296 #define SOCKS5_REQUEST_DENIED 2
297 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
298 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
299 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
300 #define SOCKS5_REQUEST_TTL_EXPIRED 6
301 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
302 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
304 /* structure of a socks client operation */
306 unsigned char vn; /* socks version number */
307 unsigned char cd; /* command code */
308 unsigned char dstport[2]; /* destination port */
309 unsigned char dstip[4]; /* destination address */
310 char userid; /* first byte of userid */
311 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
312 /* more bytes of the userid follow, terminated by a NULL */
315 /* structure of a socks server reply */
317 unsigned char vn; /* socks version number */
318 unsigned char cd; /* command code */
319 unsigned char dstport[2]; /* destination port */
320 unsigned char dstip[4]; /* destination address */
323 static const char socks_userid[] = "anonymous";
325 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
327 #define MAX_REUSABLE_CONNECTIONS 100
328 static int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
330 struct reusable_connection
345 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
347 static int mark_connection_unused(jb_socket sfd);
348 static void mark_connection_closed(struct reusable_connection *closed_connection);
349 static int socket_is_still_usable(jb_socket sfd);
352 /*********************************************************************
354 * Function : initialize_reusable_connections
356 * Description : Initializes the reusable_connection structures.
357 * Must be called with connection_reuse_mutex locked.
363 *********************************************************************/
364 extern void initialize_reusable_connections(void)
366 unsigned int slot = 0;
368 log_error(LOG_LEVEL_INFO,
369 "Support for 'Connection: keep-alive' is experimental."
371 " Detecting already dead connections might not work"
372 " correctly on your platform."
373 #endif /* ndef HAVE_POLL */
376 for (slot = 0; slot < SZ(reusable_connection); slot++)
378 mark_connection_closed(&reusable_connection[slot]);
381 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
385 /*********************************************************************
387 * Function : remember_connection
389 * Description : Remembers a connection for reuse later on.
392 * 1 : sfd = Open socket to remember.
393 * 2 : http = The destination for the connection.
394 * 3 : fwd = The forwarder settings used.
398 *********************************************************************/
399 void remember_connection(jb_socket sfd, const struct http_request *http,
400 const struct forward_spec *fwd)
402 unsigned int slot = 0;
403 int free_slot_found = FALSE;
405 assert(sfd != JB_INVALID_SOCKET);
407 if (mark_connection_unused(sfd))
412 privoxy_mutex_lock(&connection_reuse_mutex);
414 /* Find free socket slot. */
415 for (slot = 0; slot < SZ(reusable_connection); slot++)
417 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
419 assert(reusable_connection[slot].in_use == 0);
420 log_error(LOG_LEVEL_CONNECT,
421 "Remembering socket %d for %s:%d in slot %d.",
422 sfd, http->host, http->port, slot);
423 free_slot_found = TRUE;
428 if (!free_slot_found)
430 log_error(LOG_LEVEL_CONNECT,
431 "No free slots found to remembering socket for %s:%d. Last slot %d.",
432 http->host, http->port, slot);
433 privoxy_mutex_unlock(&connection_reuse_mutex);
438 assert(NULL != http->host);
439 reusable_connection[slot].host = strdup(http->host);
440 if (NULL == reusable_connection[slot].host)
442 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
444 reusable_connection[slot].sfd = sfd;
445 reusable_connection[slot].port = http->port;
446 reusable_connection[slot].in_use = 0;
447 reusable_connection[slot].timestamp = time(NULL);
450 assert(reusable_connection[slot].gateway_host == NULL);
451 assert(reusable_connection[slot].gateway_port == 0);
452 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
453 assert(reusable_connection[slot].forward_host == NULL);
454 assert(reusable_connection[slot].forward_port == 0);
456 reusable_connection[slot].forwarder_type = fwd->type;
457 if (NULL != fwd->gateway_host)
459 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
460 if (NULL == reusable_connection[slot].gateway_host)
462 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
467 reusable_connection[slot].gateway_host = NULL;
469 reusable_connection[slot].gateway_port = fwd->gateway_port;
471 if (NULL != fwd->forward_host)
473 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
474 if (NULL == reusable_connection[slot].forward_host)
476 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
481 reusable_connection[slot].forward_host = NULL;
483 reusable_connection[slot].forward_port = fwd->forward_port;
485 privoxy_mutex_unlock(&connection_reuse_mutex);
489 /*********************************************************************
491 * Function : mark_connection_closed
493 * Description : Marks a reused connection closed.
494 * Must be called with connection_reuse_mutex locked.
497 * 1 : closed_connection = The connection to mark as closed.
501 *********************************************************************/
502 static void mark_connection_closed(struct reusable_connection *closed_connection)
504 closed_connection->in_use = FALSE;
505 closed_connection->sfd = JB_INVALID_SOCKET;
506 freez(closed_connection->host);
507 closed_connection->port = 0;
508 closed_connection->timestamp = 0;
509 closed_connection->forwarder_type = SOCKS_NONE;
510 freez(closed_connection->gateway_host);
511 closed_connection->gateway_port = 0;
512 freez(closed_connection->forward_host);
513 closed_connection->forward_port = 0;
517 /*********************************************************************
519 * Function : forget_connection
521 * Description : Removes a previously remembered connection from
522 * the list of reusable connections.
525 * 1 : sfd = The socket belonging to the connection in question.
529 *********************************************************************/
530 void forget_connection(jb_socket sfd)
532 unsigned int slot = 0;
534 assert(sfd != JB_INVALID_SOCKET);
536 privoxy_mutex_lock(&connection_reuse_mutex);
538 for (slot = 0; slot < SZ(reusable_connection); slot++)
540 if (reusable_connection[slot].sfd == sfd)
542 assert(reusable_connection[slot].in_use);
544 log_error(LOG_LEVEL_CONNECT,
545 "Forgetting socket %d for %s:%d in slot %d.",
546 sfd, reusable_connection[slot].host,
547 reusable_connection[slot].port, slot);
548 mark_connection_closed(&reusable_connection[slot]);
549 privoxy_mutex_unlock(&connection_reuse_mutex);
555 log_error(LOG_LEVEL_CONNECT,
556 "Socket %d already forgotten or never remembered.", sfd);
558 privoxy_mutex_unlock(&connection_reuse_mutex);
562 /*********************************************************************
564 * Function : connection_destination_matches
566 * Description : Determines whether a remembered connection can
567 * be reused. That is, whether the destination and
568 * the forwarding settings match.
571 * 1 : connection = The connection to check.
572 * 2 : http = The destination for the connection.
573 * 3 : fwd = The forwarder settings.
575 * Returns : TRUE for yes, FALSE otherwise.
577 *********************************************************************/
578 static int connection_destination_matches(const struct reusable_connection *connection,
579 const struct http_request *http,
580 const struct forward_spec *fwd)
582 if ((connection->forwarder_type != fwd->type)
583 || (connection->gateway_port != fwd->gateway_port)
584 || (connection->forward_port != fwd->forward_port)
585 || (connection->port != http->port))
590 if (( (NULL != connection->gateway_host)
591 && (NULL != fwd->gateway_host)
592 && strcmpic(connection->gateway_host, fwd->gateway_host))
593 && (connection->gateway_host != fwd->gateway_host))
595 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
599 if (( (NULL != connection->forward_host)
600 && (NULL != fwd->forward_host)
601 && strcmpic(connection->forward_host, fwd->forward_host))
602 && (connection->forward_host != fwd->forward_host))
604 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
608 return (!strcmpic(connection->host, http->host));
613 /*********************************************************************
615 * Function : close_unusable_connections
617 * Description : Closes remembered connections that have timed
618 * out or have been closed on the other side.
624 *********************************************************************/
625 static void close_unusable_connections(void)
627 unsigned int slot = 0;
629 for (slot = 0; slot < SZ(reusable_connection); slot++)
631 if (!reusable_connection[slot].in_use
632 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
634 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
636 if (keep_alive_timeout < time_open)
638 log_error(LOG_LEVEL_CONNECT,
639 "The connection to %s:%d in slot %d timed out. "
640 "Closing socket %d. Timeout is: %d.",
641 reusable_connection[slot].host,
642 reusable_connection[slot].port, slot,
643 reusable_connection[slot].sfd, keep_alive_timeout);
644 close_socket(reusable_connection[slot].sfd);
645 mark_connection_closed(&reusable_connection[slot]);
649 if (!socket_is_still_usable(reusable_connection[slot].sfd))
651 log_error(LOG_LEVEL_CONNECT,
652 "The connection to %s:%d in slot %d is no longer usable. "
653 "Closing socket %d.", reusable_connection[slot].host,
654 reusable_connection[slot].port, slot,
655 reusable_connection[slot].sfd);
656 close_socket(reusable_connection[slot].sfd);
657 mark_connection_closed(&reusable_connection[slot]);
665 /*********************************************************************
667 * Function : socket_is_still_usable
669 * Description : Decides whether or not an open socket is still usable.
672 * 1 : sfd = The socket to check.
674 * Returns : TRUE for yes, otherwise FALSE.
676 *********************************************************************/
677 static int socket_is_still_usable(jb_socket sfd)
681 struct pollfd poll_fd[1];
683 memset(poll_fd, 0, sizeof(poll_fd));
685 poll_fd[0].events = POLLIN;
687 poll_result = poll(poll_fd, 1, 0);
689 if (-1 != poll_result)
691 return !(poll_fd[0].revents & POLLIN);
695 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
700 struct timeval timeout;
702 int socket_is_alive = 0;
704 memset(&timeout, '\0', sizeof(timeout));
705 FD_ZERO(&readable_fds);
706 FD_SET(sfd, &readable_fds);
708 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
711 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
715 * XXX: I'm not sure why !FD_ISSET() works,
716 * but apparently it does.
718 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
720 return socket_is_alive;
721 #endif /* def HAVE_POLL */
725 /*********************************************************************
727 * Function : get_reusable_connection
729 * Description : Returns an open socket to a previously remembered
730 * open connection (if there is one).
733 * 1 : http = The destination for the connection.
734 * 2 : fwd = The forwarder settings.
736 * Returns : JB_INVALID_SOCKET => No reusable connection found,
737 * otherwise a usable socket.
739 *********************************************************************/
740 static jb_socket get_reusable_connection(const struct http_request *http,
741 const struct forward_spec *fwd)
743 jb_socket sfd = JB_INVALID_SOCKET;
744 unsigned int slot = 0;
746 privoxy_mutex_lock(&connection_reuse_mutex);
748 close_unusable_connections();
750 for (slot = 0; slot < SZ(reusable_connection); slot++)
752 if (!reusable_connection[slot].in_use
753 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
755 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
757 reusable_connection[slot].in_use = TRUE;
758 sfd = reusable_connection[slot].sfd;
759 log_error(LOG_LEVEL_CONNECT,
760 "Found reusable socket %d for %s:%d in slot %d.",
761 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
767 privoxy_mutex_unlock(&connection_reuse_mutex);
774 /*********************************************************************
776 * Function : mark_connection_unused
778 * Description : Gives a remembered connection free for reuse.
781 * 1 : sfd = The socket belonging to the connection in question.
783 * Returns : TRUE => Socket found and marked as unused.
784 * FALSE => Socket not found.
786 *********************************************************************/
787 static int mark_connection_unused(jb_socket sfd)
789 unsigned int slot = 0;
790 int socket_found = FALSE;
792 assert(sfd != JB_INVALID_SOCKET);
794 privoxy_mutex_lock(&connection_reuse_mutex);
796 for (slot = 0; slot < SZ(reusable_connection); slot++)
798 if (reusable_connection[slot].sfd == sfd)
800 assert(reusable_connection[slot].in_use);
802 log_error(LOG_LEVEL_CONNECT,
803 "Marking open socket %d for %s:%d in slot %d as unused.",
804 sfd, reusable_connection[slot].host,
805 reusable_connection[slot].port, slot);
806 reusable_connection[slot].in_use = 0;
807 reusable_connection[slot].timestamp = time(NULL);
812 privoxy_mutex_unlock(&connection_reuse_mutex);
819 /*********************************************************************
821 * Function : set_keep_alive_timeout
823 * Description : Sets the timeout after which open
824 * connections will no longer be reused.
827 * 1 : timeout = The timeout in seconds.
831 *********************************************************************/
832 void set_keep_alive_timeout(int timeout)
834 keep_alive_timeout = timeout;
836 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
839 /*********************************************************************
841 * Function : forwarded_connect
843 * Description : Connect to a specified web server, possibly via
844 * a HTTP proxy and/or a SOCKS proxy.
847 * 1 : fwd = the proxies to use when connecting.
848 * 2 : http = the http request and apropos headers
849 * 3 : csp = Current client state (buffers, headers, etc...)
851 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
853 *********************************************************************/
854 jb_socket forwarded_connect(const struct forward_spec * fwd,
855 struct http_request *http,
856 struct client_state *csp)
858 const char * dest_host;
860 jb_socket sfd = JB_INVALID_SOCKET;
862 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
863 sfd = get_reusable_connection(http, fwd);
864 if (JB_INVALID_SOCKET != sfd)
868 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
870 /* Figure out if we need to connect to the web server or a HTTP proxy. */
871 if (fwd->forward_host)
874 dest_host = fwd->forward_host;
875 dest_port = fwd->forward_port;
880 dest_host = http->host;
881 dest_port = http->port;
884 /* Connect, maybe using a SOCKS proxy */
888 sfd = connect_to(dest_host, dest_port, csp);
892 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
895 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
898 /* Should never get here */
899 log_error(LOG_LEVEL_FATAL,
900 "SOCKS4 impossible internal error - bad SOCKS type.");
903 if (JB_INVALID_SOCKET != sfd)
905 log_error(LOG_LEVEL_CONNECT,
906 "Created new connection to %s:%d on socket %d.",
907 http->host, http->port, sfd);
915 /*********************************************************************
917 * Function : socks4_connect
919 * Description : Connect to the SOCKS server, and connect through
920 * it to the specified server. This handles
921 * all the SOCKS negotiation, and returns a file
922 * descriptor for a socket which can be treated as a
923 * normal (non-SOCKS) socket.
925 * Logged error messages are saved to csp->error_message
926 * and later reused by error_response() for the CGI
927 * message. strdup allocation failures are handled there.
930 * 1 : fwd = Specifies the SOCKS proxy to use.
931 * 2 : target_host = The final server to connect to.
932 * 3 : target_port = The final port to connect to.
933 * 4 : csp = Current client state (buffers, headers, etc...)
935 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
937 *********************************************************************/
938 static jb_socket socks4_connect(const struct forward_spec * fwd,
939 const char * target_host,
941 struct client_state *csp)
943 unsigned int web_server_addr;
944 char buf[BUFFER_SIZE];
945 struct socks_op *c = (struct socks_op *)buf;
946 struct socks_reply *s = (struct socks_reply *)buf;
953 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
955 /* XXX: Shouldn't the config file parser prevent this? */
956 errstr = "NULL gateway host specified.";
960 if (fwd->gateway_port <= 0)
962 errstr = "invalid gateway port specified.";
968 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
969 csp->error_message = strdup(errstr);
971 return(JB_INVALID_SOCKET);
974 /* build a socks request for connection to the web server */
976 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
978 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
983 web_server_addr = resolve_hostname_to_ip(target_host);
984 if (web_server_addr == INADDR_NONE)
986 errstr = "could not resolve target host";
987 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
992 web_server_addr = htonl(web_server_addr);
996 web_server_addr = 0x00000001;
997 n = csiz + strlen(target_host) + 1;
1001 errstr = "buffer cbuf too small.";
1002 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1007 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
1009 * What we forward to the socks4a server should have the
1010 * size of socks_op, plus the length of the userid plus
1011 * its \0 byte (which we don't have to add because the
1012 * first byte of the userid is counted twice as it's also
1013 * part of sock_op) minus the padding bytes (which are part
1014 * of the userid as well), plus the length of the target_host
1015 * (which is stored csiz bytes after the beginning of the buffer),
1016 * plus another \0 byte.
1018 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
1023 /* Should never get here */
1024 log_error(LOG_LEVEL_FATAL,
1025 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
1027 return(JB_INVALID_SOCKET);
1032 csp->error_message = strdup(errstr);
1033 return(JB_INVALID_SOCKET);
1038 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1039 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1040 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1041 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1042 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1043 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1045 /* pass the request to the socks server */
1046 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1048 if (sfd == JB_INVALID_SOCKET)
1051 * XXX: connect_to should fill in the exact reason.
1052 * Most likely resolving the IP of the forwarder failed.
1054 errstr = "connect_to failed: see logfile for details";
1057 else if (write_socket(sfd, (char *)c, csiz))
1059 errstr = "SOCKS4 negotiation write failed.";
1060 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1064 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1066 errstr = "SOCKS4 negotiation read failed.";
1067 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1074 csp->error_message = strdup(errstr);
1075 return(JB_INVALID_SOCKET);
1080 case SOCKS_REQUEST_GRANTED:
1082 case SOCKS_REQUEST_REJECT:
1083 errstr = "SOCKS request rejected or failed.";
1086 case SOCKS_REQUEST_IDENT_FAILED:
1087 errstr = "SOCKS request rejected because "
1088 "SOCKS server cannot connect to identd on the client.";
1091 case SOCKS_REQUEST_IDENT_CONFLICT:
1092 errstr = "SOCKS request rejected because "
1093 "the client program and identd report "
1094 "different user-ids.";
1099 snprintf(buf, sizeof(buf),
1100 "SOCKS request rejected for reason code %d.", s->cd);
1104 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1105 csp->error_message = strdup(errstr);
1108 return(JB_INVALID_SOCKET);
1112 /*********************************************************************
1114 * Function : translate_socks5_error
1116 * Description : Translates a SOCKS errors to a string.
1119 * 1 : socks_error = The error code to translate.
1121 * Returns : The string translation.
1123 *********************************************************************/
1124 static const char *translate_socks5_error(int socks_error)
1126 switch (socks_error)
1128 /* XXX: these should be more descriptive */
1129 case SOCKS5_REQUEST_FAILED:
1130 return "SOCKS5 request failed";
1131 case SOCKS5_REQUEST_DENIED:
1132 return "SOCKS5 request denied";
1133 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1134 return "SOCKS5 network unreachable";
1135 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1136 return "SOCKS5 host unreachable";
1137 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1138 return "SOCKS5 connection refused";
1139 case SOCKS5_REQUEST_TTL_EXPIRED:
1140 return "SOCKS5 TTL expired";
1141 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1142 return "SOCKS5 client protocol error";
1143 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1144 return "SOCKS5 domain names unsupported";
1145 case SOCKS5_REQUEST_GRANTED:
1146 return "everything's peachy";
1148 return "SOCKS5 negotiation protocol error";
1152 /*********************************************************************
1154 * Function : socks5_connect
1156 * Description : Connect to the SOCKS server, and connect through
1157 * it to the specified server. This handles
1158 * all the SOCKS negotiation, and returns a file
1159 * descriptor for a socket which can be treated as a
1160 * normal (non-SOCKS) socket.
1163 * 1 : fwd = Specifies the SOCKS proxy to use.
1164 * 2 : target_host = The final server to connect to.
1165 * 3 : target_port = The final port to connect to.
1166 * 4 : csp = Current client state (buffers, headers, etc...)
1168 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1170 *********************************************************************/
1171 static jb_socket socks5_connect(const struct forward_spec *fwd,
1172 const char *target_host,
1174 struct client_state *csp)
1179 size_t client_pos = 0;
1180 int server_size = 0;
1183 const char *errstr = NULL;
1185 assert(fwd->gateway_host);
1186 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1188 errstr = "NULL gateway host specified";
1192 if (fwd->gateway_port <= 0)
1195 * XXX: currently this can't happen because in
1196 * case of invalid gateway ports we use the defaults.
1197 * Of course we really shouldn't do that.
1199 errstr = "invalid gateway port specified";
1203 hostlen = strlen(target_host);
1204 if (hostlen > (size_t)255)
1206 errstr = "target host name is longer than 255 characters";
1210 if (fwd->type != SOCKS_5)
1212 /* Should never get here */
1213 log_error(LOG_LEVEL_FATAL,
1214 "SOCKS5 impossible internal error - bad SOCKS type");
1221 assert(errstr != NULL);
1222 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1223 csp->error_message = strdup(errstr);
1224 return(JB_INVALID_SOCKET);
1227 /* pass the request to the socks server */
1228 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1230 if (sfd == JB_INVALID_SOCKET)
1232 errstr = "socks5 server unreachable";
1233 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1234 csp->error_message = strdup(errstr);
1235 return(JB_INVALID_SOCKET);
1239 cbuf[client_pos++] = '\x05'; /* Version */
1240 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1241 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1243 if (write_socket(sfd, cbuf, client_pos))
1245 errstr = "SOCKS5 negotiation write failed";
1246 csp->error_message = strdup(errstr);
1247 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1249 return(JB_INVALID_SOCKET);
1252 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1254 errstr = "SOCKS5 negotiation read failed";
1258 if (!err && (sbuf[0] != '\x05'))
1260 errstr = "SOCKS5 negotiation protocol version error";
1264 if (!err && (sbuf[1] == '\xff'))
1266 errstr = "SOCKS5 authentication required";
1270 if (!err && (sbuf[1] != '\x00'))
1272 errstr = "SOCKS5 negotiation protocol error";
1278 assert(errstr != NULL);
1279 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1280 csp->error_message = strdup(errstr);
1283 return(JB_INVALID_SOCKET);
1287 cbuf[client_pos++] = '\x05'; /* Version */
1288 cbuf[client_pos++] = '\x01'; /* TCP connect */
1289 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1290 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1291 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1292 assert(sizeof(cbuf) - client_pos > (size_t)255);
1293 /* Using strncpy because we really want the nul byte padding. */
1294 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1295 client_pos += (hostlen & 0xffu);
1296 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1297 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1299 if (write_socket(sfd, cbuf, client_pos))
1301 errstr = "SOCKS5 negotiation read failed";
1302 csp->error_message = strdup(errstr);
1303 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1306 return(JB_INVALID_SOCKET);
1309 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1310 if (server_size < 3)
1312 errstr = "SOCKS5 negotiation read failed";
1315 else if (server_size > 20)
1317 /* This is somewhat unexpected but doesn't realy matter. */
1318 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1319 "from socks server. Would have accepted up to %d.",
1320 server_size, sizeof(sbuf));
1323 if (!err && (sbuf[0] != '\x05'))
1325 errstr = "SOCKS5 negotiation protocol version error";
1329 if (!err && (sbuf[2] != '\x00'))
1331 errstr = "SOCKS5 negotiation protocol error";
1337 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1341 errstr = translate_socks5_error(sbuf[1]);
1345 assert(errstr != NULL);
1346 csp->error_message = strdup(errstr);
1347 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1351 return(JB_INVALID_SOCKET);