1 const char gateway_rcs[] = "$Id: gateway.c,v 1.39 2008/10/25 11:33:01 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.39 2008/10/25 11:33:01 fabiankeil
38 * Remove already out-commented line left over from debugging.
40 * Revision 1.38 2008/10/24 17:33:00 fabiankeil
41 * - Tone the "keep-alive support is experimental" warning
42 * down a bit as hackish 0-chunk detection has been
43 * implemented recently.
44 * - Only show the "ndef HAVE_POLL" warning once on start-up.
46 * Revision 1.37 2008/10/23 17:40:53 fabiankeil
47 * Fix forget_connection() and mark_connection_unused(),
48 * which would both under certain circumstances access
49 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
51 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
52 * - Factor close_unusable_connections() out of
53 * get_reusable_connection() to make sure we really check
54 * all the remembered connections, not just the ones before
55 * the next reusable one.
56 * - Plug two file descriptor leaks. Internally marking
57 * connections as closed doesn't cut it.
59 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
60 * In socket_is_still_usable(), use select()
61 * and FD_ISSET() if poll() isn't available.
63 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
64 * Add preliminary timeout support.
66 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
67 * Fix two gcc44 warnings.
69 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
70 * Fix compiler warning.
72 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
73 * - Factor socket_is_still_usable() out of get_reusable_connection().
74 * - If poll() isn't available, show a warning and assume the socket
77 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
78 * If a remembered connection is no longer usable and
79 * has been marked closed, don't bother checking if the
80 * destination matches.
82 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
83 * Add missing dots for two log messages.
85 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
86 * Flush work-in-progress changes to keep outgoing connections
87 * alive where possible. Incomplete and mostly #ifdef'd out.
89 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
90 * Return only once in forwarded_connect().
92 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
93 * Fix typo in macro name.
95 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
97 * - make the buffers quite a bit smaller.
98 * - properly report "socks5 server unreachable" failures.
99 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
100 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
101 * - log a message if the socks5 server sends more data than expected.
102 * - add some assertions and comments.
104 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
105 * - Fix a compiler warning.
106 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
108 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
109 * Remember the cause of the SOCKS5 error for the CGI message.
111 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
112 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
114 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
115 * Modified patch from Song Weijia (#1762559) to
116 * fix socks requests on big-endian platforms.
118 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
119 * - Use strlcpy() instead of strcpy().
120 * - Use the same buffer for socks requests and socks responses.
121 * - Fix bogus warning about web_server_addr being used uninitialized.
123 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
124 * - Save errors in socks4_connect() to csp->error_message.
125 * - Silence some gcc43 warnings, hopefully the right way.
127 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
128 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
129 * with what was really the latest development (the v_3_0_branch branch)
131 * Revision 1.16 2002/05/12 21:36:29 jongfoster
132 * Correcting function comments
134 * Revision 1.15 2002/03/26 22:29:54 swa
135 * we have a new homepage!
137 * Revision 1.14 2002/03/24 13:25:43 swa
138 * name change related issues
140 * Revision 1.13 2002/03/13 00:29:59 jongfoster
143 * Revision 1.12 2002/03/09 20:03:52 jongfoster
144 * - Making various functions return int rather than size_t.
145 * (Undoing a recent change). Since size_t is unsigned on
146 * Windows, functions like read_socket that return -1 on
147 * error cannot return a size_t.
149 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
150 * crashes, and also frequently caused JB to jump to 100%
151 * CPU and stay there. (Because it thought it had just
152 * read ((unsigned)-1) == 4Gb of data...)
154 * - The signature of write_socket has changed, it now simply
155 * returns success=0/failure=nonzero.
157 * - Trying to get rid of a few warnings --with-debug on
158 * Windows, I've introduced a new type "jb_socket". This is
159 * used for the socket file descriptors. On Windows, this
160 * is SOCKET (a typedef for unsigned). Everywhere else, it's
161 * an int. The error value can't be -1 any more, so it's
162 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
163 * Windows it maps to the #define INVALID_SOCKET.)
165 * - The signature of bind_port has changed.
167 * Revision 1.11 2002/03/08 17:46:04 jongfoster
168 * Fixing int/size_t warnings
170 * Revision 1.10 2002/03/07 03:50:19 oes
171 * - Improved handling of failed DNS lookups
172 * - Fixed compiler warnings
174 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
175 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
176 * threads to call select() simultaneously. So, it's time to do a real, live,
177 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
178 * (native). Both versions will work, but using __OS2__ offers multi-threading.
180 * Revision 1.8 2001/09/13 20:10:12 jongfoster
181 * Fixing missing #include under Windows
183 * Revision 1.7 2001/09/12 17:58:26 steudten
185 * add #include <string.h>
187 * Revision 1.6 2001/09/10 10:41:16 oes
188 * Added #include in.h
190 * Revision 1.5 2001/07/29 18:47:57 jongfoster
191 * Adding missing #include project.h
193 * Revision 1.4 2001/07/24 12:47:06 oes
194 * Applied BeOS support update by Eugenia
196 * Revision 1.3 2001/06/09 10:55:28 jongfoster
197 * Changing BUFSIZ ==> BUFFER_SIZE
199 * Revision 1.2 2001/06/07 23:11:38 jongfoster
200 * Removing gateways[] list - no longer used.
201 * Replacing function pointer in struct gateway with a directly
202 * called function forwarded_connect(), which can do the common
203 * task of deciding whether to connect to the web server or HTTP
205 * Replacing struct gateway with struct forward_spec
206 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
207 * It was a bug which led to the connection being made to the web
208 * server rather than the HTTP proxy, and also a buffer overrun.
210 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
211 * Initial import of version 2.9.3 source tree
214 *********************************************************************/
220 #include <sys/types.h>
223 #include <netinet/in.h>
231 #include <winsock2.h>
232 #endif /* def _WIN32 */
236 #endif /* def __BEOS__ */
240 #endif /* def __OS2__ */
245 #include "jbsockets.h"
247 #include "miscutil.h"
248 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
251 #include <sys/poll.h>
254 #endif /* def __GLIBC__ */
255 #endif /* HAVE_POLL */
256 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
258 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
260 static jb_socket socks4_connect(const struct forward_spec * fwd,
261 const char * target_host,
263 struct client_state *csp);
265 static jb_socket socks5_connect(const struct forward_spec *fwd,
266 const char *target_host,
268 struct client_state *csp);
271 #define SOCKS_REQUEST_GRANTED 90
272 #define SOCKS_REQUEST_REJECT 91
273 #define SOCKS_REQUEST_IDENT_FAILED 92
274 #define SOCKS_REQUEST_IDENT_CONFLICT 93
276 #define SOCKS5_REQUEST_GRANTED 0
277 #define SOCKS5_REQUEST_FAILED 1
278 #define SOCKS5_REQUEST_DENIED 2
279 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
280 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
281 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
282 #define SOCKS5_REQUEST_TTL_EXPIRED 6
283 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
284 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
286 /* structure of a socks client operation */
288 unsigned char vn; /* socks version number */
289 unsigned char cd; /* command code */
290 unsigned char dstport[2]; /* destination port */
291 unsigned char dstip[4]; /* destination address */
292 char userid; /* first byte of userid */
293 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
294 /* more bytes of the userid follow, terminated by a NULL */
297 /* structure of a socks server reply */
299 unsigned char vn; /* socks version number */
300 unsigned char cd; /* command code */
301 unsigned char dstport[2]; /* destination port */
302 unsigned char dstip[4]; /* destination address */
305 static const char socks_userid[] = "anonymous";
307 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
309 #define MAX_REUSABLE_CONNECTIONS 100
310 /* XXX: should be a config option. */
311 #define CONNECTION_KEEP_ALIVE_TIMEOUT 3 * 60
313 struct reusable_connection
328 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
330 static int mark_connection_unused(jb_socket sfd);
331 static void mark_connection_closed(struct reusable_connection *closed_connection);
332 static int socket_is_still_usable(jb_socket sfd);
335 /*********************************************************************
337 * Function : initialize_reusable_connections
339 * Description : Initializes the reusable_connection structures.
340 * Must be called with connection_reuse_mutex locked.
346 *********************************************************************/
347 extern void initialize_reusable_connections(void)
349 unsigned int slot = 0;
351 log_error(LOG_LEVEL_INFO,
352 "Support for 'Connection: keep-alive' is experimental."
354 " Detecting already dead connections might not work"
355 " correctly on your platform."
356 #endif /* ndef HAVE_POLL */
359 for (slot = 0; slot < SZ(reusable_connection); slot++)
361 mark_connection_closed(&reusable_connection[slot]);
364 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
368 /*********************************************************************
370 * Function : remember_connection
372 * Description : Remembers a connection for reuse later on.
375 * 1 : sfd = Open socket to remember.
376 * 2 : http = The destination for the connection.
377 * 3 : fwd = The forwarder settings used.
381 *********************************************************************/
382 void remember_connection(jb_socket sfd, const struct http_request *http,
383 const struct forward_spec *fwd)
385 unsigned int slot = 0;
386 int free_slot_found = FALSE;
388 assert(sfd != JB_INVALID_SOCKET);
390 if (mark_connection_unused(sfd))
395 privoxy_mutex_lock(&connection_reuse_mutex);
397 /* Find free socket slot. */
398 for (slot = 0; slot < SZ(reusable_connection); slot++)
400 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
402 assert(reusable_connection[slot].in_use == 0);
403 log_error(LOG_LEVEL_CONNECT,
404 "Remembering socket %d for %s:%d in slot %d.",
405 sfd, http->host, http->port, slot);
406 free_slot_found = TRUE;
411 if (!free_slot_found)
413 log_error(LOG_LEVEL_CONNECT,
414 "No free slots found to remembering socket for %s:%d. Last slot %d.",
415 http->host, http->port, slot);
416 privoxy_mutex_unlock(&connection_reuse_mutex);
421 assert(NULL != http->host);
422 reusable_connection[slot].host = strdup(http->host);
423 if (NULL == reusable_connection[slot].host)
425 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
427 reusable_connection[slot].sfd = sfd;
428 reusable_connection[slot].port = http->port;
429 reusable_connection[slot].in_use = 0;
430 reusable_connection[slot].timestamp = time(NULL);
433 assert(reusable_connection[slot].gateway_host == NULL);
434 assert(reusable_connection[slot].gateway_port == 0);
435 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
436 assert(reusable_connection[slot].forward_host == NULL);
437 assert(reusable_connection[slot].forward_port == 0);
439 reusable_connection[slot].forwarder_type = fwd->type;
440 if (NULL != fwd->gateway_host)
442 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
443 if (NULL == reusable_connection[slot].gateway_host)
445 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
450 reusable_connection[slot].gateway_host = NULL;
452 reusable_connection[slot].gateway_port = fwd->gateway_port;
454 if (NULL != fwd->forward_host)
456 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
457 if (NULL == reusable_connection[slot].forward_host)
459 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
464 reusable_connection[slot].forward_host = NULL;
466 reusable_connection[slot].forward_port = fwd->forward_port;
468 privoxy_mutex_unlock(&connection_reuse_mutex);
472 /*********************************************************************
474 * Function : mark_connection_closed
476 * Description : Marks a reused connection closed.
477 * Must be called with connection_reuse_mutex locked.
480 * 1 : closed_connection = The connection to mark as closed.
484 *********************************************************************/
485 static void mark_connection_closed(struct reusable_connection *closed_connection)
487 closed_connection->in_use = FALSE;
488 closed_connection->sfd = JB_INVALID_SOCKET;
489 freez(closed_connection->host);
490 closed_connection->port = 0;
491 closed_connection->timestamp = 0;
492 closed_connection->forwarder_type = SOCKS_NONE;
493 freez(closed_connection->gateway_host);
494 closed_connection->gateway_port = 0;
495 freez(closed_connection->forward_host);
496 closed_connection->forward_port = 0;
500 /*********************************************************************
502 * Function : forget_connection
504 * Description : Removes a previously remembered connection from
505 * the list of reusable connections.
508 * 1 : sfd = The socket belonging to the connection in question.
512 *********************************************************************/
513 void forget_connection(jb_socket sfd)
515 unsigned int slot = 0;
517 assert(sfd != JB_INVALID_SOCKET);
519 privoxy_mutex_lock(&connection_reuse_mutex);
521 for (slot = 0; slot < SZ(reusable_connection); slot++)
523 if (reusable_connection[slot].sfd == sfd)
525 assert(reusable_connection[slot].in_use);
527 log_error(LOG_LEVEL_CONNECT,
528 "Forgetting socket %d for %s:%d in slot %d.",
529 sfd, reusable_connection[slot].host,
530 reusable_connection[slot].port, slot);
531 mark_connection_closed(&reusable_connection[slot]);
532 privoxy_mutex_unlock(&connection_reuse_mutex);
538 log_error(LOG_LEVEL_CONNECT,
539 "Socket %d already forgotten or never remembered.", sfd);
541 privoxy_mutex_unlock(&connection_reuse_mutex);
545 /*********************************************************************
547 * Function : connection_destination_matches
549 * Description : Determines whether a remembered connection can
550 * be reused. That is whether the destination and
551 * the forwarding settings match.
554 * 1 : connection = The connection to check.
555 * 2 : http = The destination for the connection.
556 * 3 : fwd = The forwarder settings.
558 * Returns : TRUE for yes, FALSE otherwise.
560 *********************************************************************/
561 static int connection_destination_matches(const struct reusable_connection *connection,
562 const struct http_request *http,
563 const struct forward_spec *fwd)
565 /* XXX: Start of duplicated checks for debugging purposes. */
566 if (strcmpic(connection->host, http->host))
571 if (connection->forwarder_type != fwd->type)
573 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
574 connection->forwarder_type, fwd->type, http->host);
577 if (connection->gateway_port != fwd->gateway_port)
579 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
580 connection->gateway_port, fwd->gateway_port, http->host);
583 if (connection->forward_port != fwd->forward_port)
585 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
586 connection->forward_port, fwd->forward_port, http->host);
589 if (connection->port != http->port)
591 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
592 connection->port, http->port, http->host);
596 /* XXX: End of duplicated checks for debugging purposes. */
598 if ((connection->forwarder_type != fwd->type)
599 || (connection->gateway_port != fwd->gateway_port)
600 || (connection->forward_port != fwd->forward_port)
601 || (connection->port != http->port))
606 if (( (NULL != connection->gateway_host)
607 && (NULL != fwd->gateway_host)
608 && strcmpic(connection->gateway_host, fwd->gateway_host))
609 && (connection->gateway_host != fwd->gateway_host))
611 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
615 if (( (NULL != connection->forward_host)
616 && (NULL != fwd->forward_host)
617 && strcmpic(connection->forward_host, fwd->forward_host))
618 && (connection->forward_host != fwd->forward_host))
620 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
624 return (!strcmpic(connection->host, http->host));
629 /*********************************************************************
631 * Function : close_unusable_connections
633 * Description : Closes remembered connections that have timed
634 * out or have been closed on the other side.
640 *********************************************************************/
641 static void close_unusable_connections(void)
643 unsigned int slot = 0;
645 for (slot = 0; slot < SZ(reusable_connection); slot++)
647 if (!reusable_connection[slot].in_use
648 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
650 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
652 if (CONNECTION_KEEP_ALIVE_TIMEOUT < time_open)
654 log_error(LOG_LEVEL_CONNECT,
655 "The connection to %s:%d in slot %d timed out. Closing.",
656 reusable_connection[slot].host, reusable_connection[slot].port,
658 close_socket(reusable_connection[slot].sfd);
659 mark_connection_closed(&reusable_connection[slot]);
663 if (!socket_is_still_usable(reusable_connection[slot].sfd))
665 log_error(LOG_LEVEL_CONNECT,
666 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
667 reusable_connection[slot].sfd, reusable_connection[slot].host,
668 reusable_connection[slot].port, slot);
669 close_socket(reusable_connection[slot].sfd);
670 mark_connection_closed(&reusable_connection[slot]);
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 privoxy_mutex_lock(&connection_reuse_mutex);
761 close_unusable_connections();
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);
830 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
833 /*********************************************************************
835 * Function : forwarded_connect
837 * Description : Connect to a specified web server, possibly via
838 * a HTTP proxy and/or a SOCKS proxy.
841 * 1 : fwd = the proxies to use when connecting.
842 * 2 : http = the http request and apropos headers
843 * 3 : csp = Current client state (buffers, headers, etc...)
845 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
847 *********************************************************************/
848 jb_socket forwarded_connect(const struct forward_spec * fwd,
849 struct http_request *http,
850 struct client_state *csp)
852 const char * dest_host;
854 jb_socket sfd = JB_INVALID_SOCKET;
856 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
857 sfd = get_reusable_connection(http, fwd);
858 if (JB_INVALID_SOCKET == sfd)
860 log_error(LOG_LEVEL_CONNECT,
861 "No reusable socket for %s:%d found. Opening a new one.",
862 http->host, http->port);
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.");
908 /*********************************************************************
910 * Function : socks4_connect
912 * Description : Connect to the SOCKS server, and connect through
913 * it to the specified server. This handles
914 * all the SOCKS negotiation, and returns a file
915 * descriptor for a socket which can be treated as a
916 * normal (non-SOCKS) socket.
918 * Logged error messages are saved to csp->error_message
919 * and later reused by error_response() for the CGI
920 * message. strdup allocation failures are handled there.
923 * 1 : fwd = Specifies the SOCKS proxy to use.
924 * 2 : target_host = The final server to connect to.
925 * 3 : target_port = The final port to connect to.
926 * 4 : csp = Current client state (buffers, headers, etc...)
928 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
930 *********************************************************************/
931 static jb_socket socks4_connect(const struct forward_spec * fwd,
932 const char * target_host,
934 struct client_state *csp)
936 unsigned int web_server_addr;
937 char buf[BUFFER_SIZE];
938 struct socks_op *c = (struct socks_op *)buf;
939 struct socks_reply *s = (struct socks_reply *)buf;
946 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
948 /* XXX: Shouldn't the config file parser prevent this? */
949 errstr = "NULL gateway host specified.";
953 if (fwd->gateway_port <= 0)
955 errstr = "invalid gateway port specified.";
961 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
962 csp->error_message = strdup(errstr);
964 return(JB_INVALID_SOCKET);
967 /* build a socks request for connection to the web server */
969 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
971 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
976 web_server_addr = resolve_hostname_to_ip(target_host);
977 if (web_server_addr == INADDR_NONE)
979 errstr = "could not resolve target host";
980 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
985 web_server_addr = htonl(web_server_addr);
989 web_server_addr = 0x00000001;
990 n = csiz + strlen(target_host) + 1;
994 errstr = "buffer cbuf too small.";
995 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1000 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
1002 * What we forward to the socks4a server should have the
1003 * size of socks_op, plus the length of the userid plus
1004 * its \0 byte (which we don't have to add because the
1005 * first byte of the userid is counted twice as it's also
1006 * part of sock_op) minus the padding bytes (which are part
1007 * of the userid as well), plus the length of the target_host
1008 * (which is stored csiz bytes after the beginning of the buffer),
1009 * plus another \0 byte.
1011 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
1016 /* Should never get here */
1017 log_error(LOG_LEVEL_FATAL,
1018 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
1020 return(JB_INVALID_SOCKET);
1025 csp->error_message = strdup(errstr);
1026 return(JB_INVALID_SOCKET);
1031 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1032 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1033 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1034 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1035 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1036 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1038 /* pass the request to the socks server */
1039 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1041 if (sfd == JB_INVALID_SOCKET)
1044 * XXX: connect_to should fill in the exact reason.
1045 * Most likely resolving the IP of the forwarder failed.
1047 errstr = "connect_to failed: see logfile for details";
1050 else if (write_socket(sfd, (char *)c, csiz))
1052 errstr = "SOCKS4 negotiation write failed.";
1053 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1057 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1059 errstr = "SOCKS4 negotiation read failed.";
1060 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1067 csp->error_message = strdup(errstr);
1068 return(JB_INVALID_SOCKET);
1073 case SOCKS_REQUEST_GRANTED:
1076 case SOCKS_REQUEST_REJECT:
1077 errstr = "SOCKS request rejected or failed.";
1080 case SOCKS_REQUEST_IDENT_FAILED:
1081 errstr = "SOCKS request rejected because "
1082 "SOCKS server cannot connect to identd on the client.";
1085 case SOCKS_REQUEST_IDENT_CONFLICT:
1086 errstr = "SOCKS request rejected because "
1087 "the client program and identd report "
1088 "different user-ids.";
1093 snprintf(buf, sizeof(buf),
1094 "SOCKS request rejected for reason code %d.", s->cd);
1098 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1099 csp->error_message = strdup(errstr);
1102 return(JB_INVALID_SOCKET);
1106 /*********************************************************************
1108 * Function : translate_socks5_error
1110 * Description : Translates a SOCKS errors to a string.
1113 * 1 : socks_error = The error code to translate.
1115 * Returns : The string translation.
1117 *********************************************************************/
1118 static const char *translate_socks5_error(int socks_error)
1120 switch (socks_error)
1122 /* XXX: these should be more descriptive */
1123 case SOCKS5_REQUEST_FAILED:
1124 return "SOCKS5 request failed";
1125 case SOCKS5_REQUEST_DENIED:
1126 return "SOCKS5 request denied";
1127 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1128 return "SOCKS5 network unreachable";
1129 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1130 return "SOCKS5 host unreachable";
1131 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1132 return "SOCKS5 connection refused";
1133 case SOCKS5_REQUEST_TTL_EXPIRED:
1134 return "SOCKS5 TTL expired";
1135 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1136 return "SOCKS5 client protocol error";
1137 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1138 return "SOCKS5 domain names unsupported";
1139 case SOCKS5_REQUEST_GRANTED:
1140 return "everything's peachy";
1142 return "SOCKS5 negotiation protocol error";
1146 /*********************************************************************
1148 * Function : socks5_connect
1150 * Description : Connect to the SOCKS server, and connect through
1151 * it to the specified server. This handles
1152 * all the SOCKS negotiation, and returns a file
1153 * descriptor for a socket which can be treated as a
1154 * normal (non-SOCKS) socket.
1157 * 1 : fwd = Specifies the SOCKS proxy to use.
1158 * 2 : target_host = The final server to connect to.
1159 * 3 : target_port = The final port to connect to.
1160 * 4 : csp = Current client state (buffers, headers, etc...)
1162 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1164 *********************************************************************/
1165 static jb_socket socks5_connect(const struct forward_spec *fwd,
1166 const char *target_host,
1168 struct client_state *csp)
1173 size_t client_pos = 0;
1174 int server_size = 0;
1177 const char *errstr = NULL;
1179 assert(fwd->gateway_host);
1180 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1182 errstr = "NULL gateway host specified";
1186 if (fwd->gateway_port <= 0)
1189 * XXX: currently this can't happen because in
1190 * case of invalid gateway ports we use the defaults.
1191 * Of course we really shouldn't do that.
1193 errstr = "invalid gateway port specified";
1197 hostlen = strlen(target_host);
1200 errstr = "target host name is longer than 255 characters";
1204 if (fwd->type != SOCKS_5)
1206 /* Should never get here */
1207 log_error(LOG_LEVEL_FATAL,
1208 "SOCKS5 impossible internal error - bad SOCKS type");
1215 assert(errstr != NULL);
1216 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1217 csp->error_message = strdup(errstr);
1218 return(JB_INVALID_SOCKET);
1221 /* pass the request to the socks server */
1222 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1224 if (sfd == JB_INVALID_SOCKET)
1226 errstr = "socks5 server unreachable";
1227 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1228 csp->error_message = strdup(errstr);
1229 return(JB_INVALID_SOCKET);
1233 cbuf[client_pos++] = '\x05'; /* Version */
1234 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1235 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1237 if (write_socket(sfd, cbuf, client_pos))
1239 errstr = "SOCKS5 negotiation write failed";
1240 csp->error_message = strdup(errstr);
1241 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1243 return(JB_INVALID_SOCKET);
1246 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1248 errstr = "SOCKS5 negotiation read failed";
1252 if (!err && (sbuf[0] != '\x05'))
1254 errstr = "SOCKS5 negotiation protocol version error";
1258 if (!err && (sbuf[1] == '\xff'))
1260 errstr = "SOCKS5 authentication required";
1264 if (!err && (sbuf[1] != '\x00'))
1266 errstr = "SOCKS5 negotiation protocol error";
1272 assert(errstr != NULL);
1273 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1274 csp->error_message = strdup(errstr);
1277 return(JB_INVALID_SOCKET);
1281 cbuf[client_pos++] = '\x05'; /* Version */
1282 cbuf[client_pos++] = '\x01'; /* TCP connect */
1283 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1284 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1285 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1286 assert(sizeof(cbuf) - client_pos > 255);
1287 /* Using strncpy because we really want the nul byte padding. */
1288 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1289 client_pos += (hostlen & 0xffu);
1290 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1291 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1293 if (write_socket(sfd, cbuf, client_pos))
1295 errstr = "SOCKS5 negotiation read failed";
1296 csp->error_message = strdup(errstr);
1297 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1300 return(JB_INVALID_SOCKET);
1303 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1304 if (server_size < 3)
1306 errstr = "SOCKS5 negotiation read failed";
1309 else if (server_size > 20)
1311 /* This is somewhat unexpected but doesn't realy matter. */
1312 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1313 "from socks server. Would have accepted up to %d.",
1314 server_size, sizeof(sbuf));
1317 if (!err && (sbuf[0] != '\x05'))
1319 errstr = "SOCKS5 negotiation protocol version error";
1323 if (!err && (sbuf[2] != '\x00'))
1325 errstr = "SOCKS5 negotiation protocol error";
1331 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1335 errstr = translate_socks5_error(sbuf[1]);
1339 assert(errstr != NULL);
1340 csp->error_message = strdup(errstr);
1341 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1345 return(JB_INVALID_SOCKET);