1 const char gateway_rcs[] = "$Id: gateway.c,v 1.40 2008/11/08 15:14:05 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.40 2008/11/08 15:14:05 fabiankeil
38 * Fix duplicated debugging check.
40 * Revision 1.39 2008/10/25 11:33:01 fabiankeil
41 * Remove already out-commented line left over from debugging.
43 * Revision 1.38 2008/10/24 17:33:00 fabiankeil
44 * - Tone the "keep-alive support is experimental" warning
45 * down a bit as hackish 0-chunk detection has been
46 * implemented recently.
47 * - Only show the "ndef HAVE_POLL" warning once on start-up.
49 * Revision 1.37 2008/10/23 17:40:53 fabiankeil
50 * Fix forget_connection() and mark_connection_unused(),
51 * which would both under certain circumstances access
52 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
54 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
55 * - Factor close_unusable_connections() out of
56 * get_reusable_connection() to make sure we really check
57 * all the remembered connections, not just the ones before
58 * the next reusable one.
59 * - Plug two file descriptor leaks. Internally marking
60 * connections as closed doesn't cut it.
62 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
63 * In socket_is_still_usable(), use select()
64 * and FD_ISSET() if poll() isn't available.
66 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
67 * Add preliminary timeout support.
69 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
70 * Fix two gcc44 warnings.
72 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
73 * Fix compiler warning.
75 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
76 * - Factor socket_is_still_usable() out of get_reusable_connection().
77 * - If poll() isn't available, show a warning and assume the socket
80 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
81 * If a remembered connection is no longer usable and
82 * has been marked closed, don't bother checking if the
83 * destination matches.
85 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
86 * Add missing dots for two log messages.
88 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
89 * Flush work-in-progress changes to keep outgoing connections
90 * alive where possible. Incomplete and mostly #ifdef'd out.
92 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
93 * Return only once in forwarded_connect().
95 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
96 * Fix typo in macro name.
98 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
100 * - make the buffers quite a bit smaller.
101 * - properly report "socks5 server unreachable" failures.
102 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
103 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
104 * - log a message if the socks5 server sends more data than expected.
105 * - add some assertions and comments.
107 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
108 * - Fix a compiler warning.
109 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
111 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
112 * Remember the cause of the SOCKS5 error for the CGI message.
114 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
115 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
117 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
118 * Modified patch from Song Weijia (#1762559) to
119 * fix socks requests on big-endian platforms.
121 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
122 * - Use strlcpy() instead of strcpy().
123 * - Use the same buffer for socks requests and socks responses.
124 * - Fix bogus warning about web_server_addr being used uninitialized.
126 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
127 * - Save errors in socks4_connect() to csp->error_message.
128 * - Silence some gcc43 warnings, hopefully the right way.
130 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
131 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
132 * with what was really the latest development (the v_3_0_branch branch)
134 * Revision 1.16 2002/05/12 21:36:29 jongfoster
135 * Correcting function comments
137 * Revision 1.15 2002/03/26 22:29:54 swa
138 * we have a new homepage!
140 * Revision 1.14 2002/03/24 13:25:43 swa
141 * name change related issues
143 * Revision 1.13 2002/03/13 00:29:59 jongfoster
146 * Revision 1.12 2002/03/09 20:03:52 jongfoster
147 * - Making various functions return int rather than size_t.
148 * (Undoing a recent change). Since size_t is unsigned on
149 * Windows, functions like read_socket that return -1 on
150 * error cannot return a size_t.
152 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
153 * crashes, and also frequently caused JB to jump to 100%
154 * CPU and stay there. (Because it thought it had just
155 * read ((unsigned)-1) == 4Gb of data...)
157 * - The signature of write_socket has changed, it now simply
158 * returns success=0/failure=nonzero.
160 * - Trying to get rid of a few warnings --with-debug on
161 * Windows, I've introduced a new type "jb_socket". This is
162 * used for the socket file descriptors. On Windows, this
163 * is SOCKET (a typedef for unsigned). Everywhere else, it's
164 * an int. The error value can't be -1 any more, so it's
165 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
166 * Windows it maps to the #define INVALID_SOCKET.)
168 * - The signature of bind_port has changed.
170 * Revision 1.11 2002/03/08 17:46:04 jongfoster
171 * Fixing int/size_t warnings
173 * Revision 1.10 2002/03/07 03:50:19 oes
174 * - Improved handling of failed DNS lookups
175 * - Fixed compiler warnings
177 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
178 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
179 * threads to call select() simultaneously. So, it's time to do a real, live,
180 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
181 * (native). Both versions will work, but using __OS2__ offers multi-threading.
183 * Revision 1.8 2001/09/13 20:10:12 jongfoster
184 * Fixing missing #include under Windows
186 * Revision 1.7 2001/09/12 17:58:26 steudten
188 * add #include <string.h>
190 * Revision 1.6 2001/09/10 10:41:16 oes
191 * Added #include in.h
193 * Revision 1.5 2001/07/29 18:47:57 jongfoster
194 * Adding missing #include project.h
196 * Revision 1.4 2001/07/24 12:47:06 oes
197 * Applied BeOS support update by Eugenia
199 * Revision 1.3 2001/06/09 10:55:28 jongfoster
200 * Changing BUFSIZ ==> BUFFER_SIZE
202 * Revision 1.2 2001/06/07 23:11:38 jongfoster
203 * Removing gateways[] list - no longer used.
204 * Replacing function pointer in struct gateway with a directly
205 * called function forwarded_connect(), which can do the common
206 * task of deciding whether to connect to the web server or HTTP
208 * Replacing struct gateway with struct forward_spec
209 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
210 * It was a bug which led to the connection being made to the web
211 * server rather than the HTTP proxy, and also a buffer overrun.
213 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
214 * Initial import of version 2.9.3 source tree
217 *********************************************************************/
223 #include <sys/types.h>
226 #include <netinet/in.h>
234 #include <winsock2.h>
235 #endif /* def _WIN32 */
239 #endif /* def __BEOS__ */
243 #endif /* def __OS2__ */
248 #include "jbsockets.h"
250 #include "miscutil.h"
251 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
254 #include <sys/poll.h>
257 #endif /* def __GLIBC__ */
258 #endif /* HAVE_POLL */
259 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
261 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
263 static jb_socket socks4_connect(const struct forward_spec * fwd,
264 const char * target_host,
266 struct client_state *csp);
268 static jb_socket socks5_connect(const struct forward_spec *fwd,
269 const char *target_host,
271 struct client_state *csp);
274 #define SOCKS_REQUEST_GRANTED 90
275 #define SOCKS_REQUEST_REJECT 91
276 #define SOCKS_REQUEST_IDENT_FAILED 92
277 #define SOCKS_REQUEST_IDENT_CONFLICT 93
279 #define SOCKS5_REQUEST_GRANTED 0
280 #define SOCKS5_REQUEST_FAILED 1
281 #define SOCKS5_REQUEST_DENIED 2
282 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
283 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
284 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
285 #define SOCKS5_REQUEST_TTL_EXPIRED 6
286 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
287 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
289 /* structure of a socks client operation */
291 unsigned char vn; /* socks version number */
292 unsigned char cd; /* command code */
293 unsigned char dstport[2]; /* destination port */
294 unsigned char dstip[4]; /* destination address */
295 char userid; /* first byte of userid */
296 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
297 /* more bytes of the userid follow, terminated by a NULL */
300 /* structure of a socks server reply */
302 unsigned char vn; /* socks version number */
303 unsigned char cd; /* command code */
304 unsigned char dstport[2]; /* destination port */
305 unsigned char dstip[4]; /* destination address */
308 static const char socks_userid[] = "anonymous";
310 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
312 #define MAX_REUSABLE_CONNECTIONS 100
313 /* XXX: should be a config option. */
314 #define CONNECTION_KEEP_ALIVE_TIMEOUT 3 * 60
316 struct reusable_connection
331 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
333 static int mark_connection_unused(jb_socket sfd);
334 static void mark_connection_closed(struct reusable_connection *closed_connection);
335 static int socket_is_still_usable(jb_socket sfd);
338 /*********************************************************************
340 * Function : initialize_reusable_connections
342 * Description : Initializes the reusable_connection structures.
343 * Must be called with connection_reuse_mutex locked.
349 *********************************************************************/
350 extern void initialize_reusable_connections(void)
352 unsigned int slot = 0;
354 log_error(LOG_LEVEL_INFO,
355 "Support for 'Connection: keep-alive' is experimental."
357 " Detecting already dead connections might not work"
358 " correctly on your platform."
359 #endif /* ndef HAVE_POLL */
362 for (slot = 0; slot < SZ(reusable_connection); slot++)
364 mark_connection_closed(&reusable_connection[slot]);
367 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
371 /*********************************************************************
373 * Function : remember_connection
375 * Description : Remembers a connection for reuse later on.
378 * 1 : sfd = Open socket to remember.
379 * 2 : http = The destination for the connection.
380 * 3 : fwd = The forwarder settings used.
384 *********************************************************************/
385 void remember_connection(jb_socket sfd, const struct http_request *http,
386 const struct forward_spec *fwd)
388 unsigned int slot = 0;
389 int free_slot_found = FALSE;
391 assert(sfd != JB_INVALID_SOCKET);
393 if (mark_connection_unused(sfd))
398 privoxy_mutex_lock(&connection_reuse_mutex);
400 /* Find free socket slot. */
401 for (slot = 0; slot < SZ(reusable_connection); slot++)
403 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
405 assert(reusable_connection[slot].in_use == 0);
406 log_error(LOG_LEVEL_CONNECT,
407 "Remembering socket %d for %s:%d in slot %d.",
408 sfd, http->host, http->port, slot);
409 free_slot_found = TRUE;
414 if (!free_slot_found)
416 log_error(LOG_LEVEL_CONNECT,
417 "No free slots found to remembering socket for %s:%d. Last slot %d.",
418 http->host, http->port, slot);
419 privoxy_mutex_unlock(&connection_reuse_mutex);
424 assert(NULL != http->host);
425 reusable_connection[slot].host = strdup(http->host);
426 if (NULL == reusable_connection[slot].host)
428 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
430 reusable_connection[slot].sfd = sfd;
431 reusable_connection[slot].port = http->port;
432 reusable_connection[slot].in_use = 0;
433 reusable_connection[slot].timestamp = time(NULL);
436 assert(reusable_connection[slot].gateway_host == NULL);
437 assert(reusable_connection[slot].gateway_port == 0);
438 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
439 assert(reusable_connection[slot].forward_host == NULL);
440 assert(reusable_connection[slot].forward_port == 0);
442 reusable_connection[slot].forwarder_type = fwd->type;
443 if (NULL != fwd->gateway_host)
445 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
446 if (NULL == reusable_connection[slot].gateway_host)
448 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
453 reusable_connection[slot].gateway_host = NULL;
455 reusable_connection[slot].gateway_port = fwd->gateway_port;
457 if (NULL != fwd->forward_host)
459 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
460 if (NULL == reusable_connection[slot].forward_host)
462 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
467 reusable_connection[slot].forward_host = NULL;
469 reusable_connection[slot].forward_port = fwd->forward_port;
471 privoxy_mutex_unlock(&connection_reuse_mutex);
475 /*********************************************************************
477 * Function : mark_connection_closed
479 * Description : Marks a reused connection closed.
480 * Must be called with connection_reuse_mutex locked.
483 * 1 : closed_connection = The connection to mark as closed.
487 *********************************************************************/
488 static void mark_connection_closed(struct reusable_connection *closed_connection)
490 closed_connection->in_use = FALSE;
491 closed_connection->sfd = JB_INVALID_SOCKET;
492 freez(closed_connection->host);
493 closed_connection->port = 0;
494 closed_connection->timestamp = 0;
495 closed_connection->forwarder_type = SOCKS_NONE;
496 freez(closed_connection->gateway_host);
497 closed_connection->gateway_port = 0;
498 freez(closed_connection->forward_host);
499 closed_connection->forward_port = 0;
503 /*********************************************************************
505 * Function : forget_connection
507 * Description : Removes a previously remembered connection from
508 * the list of reusable connections.
511 * 1 : sfd = The socket belonging to the connection in question.
515 *********************************************************************/
516 void forget_connection(jb_socket sfd)
518 unsigned int slot = 0;
520 assert(sfd != JB_INVALID_SOCKET);
522 privoxy_mutex_lock(&connection_reuse_mutex);
524 for (slot = 0; slot < SZ(reusable_connection); slot++)
526 if (reusable_connection[slot].sfd == sfd)
528 assert(reusable_connection[slot].in_use);
530 log_error(LOG_LEVEL_CONNECT,
531 "Forgetting socket %d for %s:%d in slot %d.",
532 sfd, reusable_connection[slot].host,
533 reusable_connection[slot].port, slot);
534 mark_connection_closed(&reusable_connection[slot]);
535 privoxy_mutex_unlock(&connection_reuse_mutex);
541 log_error(LOG_LEVEL_CONNECT,
542 "Socket %d already forgotten or never remembered.", sfd);
544 privoxy_mutex_unlock(&connection_reuse_mutex);
548 /*********************************************************************
550 * Function : connection_destination_matches
552 * Description : Determines whether a remembered connection can
553 * be reused. That is whether the destination and
554 * the forwarding settings match.
557 * 1 : connection = The connection to check.
558 * 2 : http = The destination for the connection.
559 * 3 : fwd = The forwarder settings.
561 * Returns : TRUE for yes, FALSE otherwise.
563 *********************************************************************/
564 static int connection_destination_matches(const struct reusable_connection *connection,
565 const struct http_request *http,
566 const struct forward_spec *fwd)
568 /* XXX: Start of duplicated checks for debugging purposes. */
569 if (strcmpic(connection->host, http->host))
574 if (connection->forwarder_type != fwd->type)
576 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
577 connection->forwarder_type, fwd->type, http->host);
580 if (connection->gateway_port != fwd->gateway_port)
582 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
583 connection->gateway_port, fwd->gateway_port, http->host);
586 if (connection->forward_port != fwd->forward_port)
588 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
589 connection->forward_port, fwd->forward_port, http->host);
592 if (connection->port != http->port)
594 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
595 connection->port, http->port, http->host);
599 /* XXX: End of duplicated checks for debugging purposes. */
601 if ((connection->forwarder_type != fwd->type)
602 || (connection->gateway_port != fwd->gateway_port)
603 || (connection->forward_port != fwd->forward_port)
604 || (connection->port != http->port))
609 if (( (NULL != connection->gateway_host)
610 && (NULL != fwd->gateway_host)
611 && strcmpic(connection->gateway_host, fwd->gateway_host))
612 && (connection->gateway_host != fwd->gateway_host))
614 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
618 if (( (NULL != connection->forward_host)
619 && (NULL != fwd->forward_host)
620 && strcmpic(connection->forward_host, fwd->forward_host))
621 && (connection->forward_host != fwd->forward_host))
623 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
627 return (!strcmpic(connection->host, http->host));
632 /*********************************************************************
634 * Function : close_unusable_connections
636 * Description : Closes remembered connections that have timed
637 * out or have been closed on the other side.
643 *********************************************************************/
644 static void close_unusable_connections(void)
646 unsigned int slot = 0;
648 for (slot = 0; slot < SZ(reusable_connection); slot++)
650 if (!reusable_connection[slot].in_use
651 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
653 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
655 if (CONNECTION_KEEP_ALIVE_TIMEOUT < time_open)
657 log_error(LOG_LEVEL_CONNECT,
658 "The connection to %s:%d in slot %d timed out. "
659 "Closing socket %d.", reusable_connection[slot].host,
660 reusable_connection[slot].port, slot,
661 reusable_connection[slot].sfd);
662 close_socket(reusable_connection[slot].sfd);
663 mark_connection_closed(&reusable_connection[slot]);
667 if (!socket_is_still_usable(reusable_connection[slot].sfd))
669 log_error(LOG_LEVEL_CONNECT,
670 "The connection to %s:%d in slot %d is no longer usable. "
671 "Closing socket %d.", reusable_connection[slot].host,
672 reusable_connection[slot].port, slot,
673 reusable_connection[slot].sfd);
674 close_socket(reusable_connection[slot].sfd);
675 mark_connection_closed(&reusable_connection[slot]);
683 /*********************************************************************
685 * Function : socket_is_still_usable
687 * Description : Decides whether or not an open socket is still usable.
690 * 1 : sfd = The socket to check.
692 * Returns : TRUE for yes, otherwise FALSE.
694 *********************************************************************/
695 static int socket_is_still_usable(jb_socket sfd)
699 struct pollfd poll_fd[1];
701 memset(poll_fd, 0, sizeof(poll_fd));
703 poll_fd[0].events = POLLIN;
705 poll_result = poll(poll_fd, 1, 0);
707 if (-1 != poll_result)
709 return !(poll_fd[0].revents & POLLIN);
713 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
718 struct timeval timeout;
720 int socket_is_alive = 0;
722 memset(&timeout, '\0', sizeof(timeout));
723 FD_ZERO(&readable_fds);
724 FD_SET(sfd, &readable_fds);
726 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
729 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
733 * XXX: I'm not sure why !FD_ISSET() works,
734 * but apparently it does.
736 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
738 return socket_is_alive;
739 #endif /* def HAVE_POLL */
743 /*********************************************************************
745 * Function : get_reusable_connection
747 * Description : Returns an open socket to a previously remembered
748 * open connection (if there is one).
751 * 1 : http = The destination for the connection.
752 * 2 : fwd = The forwarder settings.
754 * Returns : JB_INVALID_SOCKET => No reusable connection found,
755 * otherwise a usable socket.
757 *********************************************************************/
758 static jb_socket get_reusable_connection(const struct http_request *http,
759 const struct forward_spec *fwd)
761 jb_socket sfd = JB_INVALID_SOCKET;
762 unsigned int slot = 0;
764 privoxy_mutex_lock(&connection_reuse_mutex);
766 close_unusable_connections();
768 for (slot = 0; slot < SZ(reusable_connection); slot++)
770 if (!reusable_connection[slot].in_use
771 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
773 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
775 reusable_connection[slot].in_use = TRUE;
776 sfd = reusable_connection[slot].sfd;
777 log_error(LOG_LEVEL_CONNECT,
778 "Found reusable socket %d for %s:%d in slot %d.",
779 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
785 privoxy_mutex_unlock(&connection_reuse_mutex);
792 /*********************************************************************
794 * Function : mark_connection_unused
796 * Description : Gives a remembered connection free for reuse.
799 * 1 : sfd = The socket belonging to the connection in question.
801 * Returns : TRUE => Socket found and marked as unused.
802 * FALSE => Socket not found.
804 *********************************************************************/
805 static int mark_connection_unused(jb_socket sfd)
807 unsigned int slot = 0;
808 int socket_found = FALSE;
810 assert(sfd != JB_INVALID_SOCKET);
812 privoxy_mutex_lock(&connection_reuse_mutex);
814 for (slot = 0; slot < SZ(reusable_connection); slot++)
816 if (reusable_connection[slot].sfd == sfd)
818 assert(reusable_connection[slot].in_use);
820 log_error(LOG_LEVEL_CONNECT,
821 "Marking open socket %d for %s:%d in slot %d as unused.",
822 sfd, reusable_connection[slot].host,
823 reusable_connection[slot].port, slot);
824 reusable_connection[slot].in_use = 0;
825 reusable_connection[slot].timestamp = time(NULL);
830 privoxy_mutex_unlock(&connection_reuse_mutex);
835 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
838 /*********************************************************************
840 * Function : forwarded_connect
842 * Description : Connect to a specified web server, possibly via
843 * a HTTP proxy and/or a SOCKS proxy.
846 * 1 : fwd = the proxies to use when connecting.
847 * 2 : http = the http request and apropos headers
848 * 3 : csp = Current client state (buffers, headers, etc...)
850 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
852 *********************************************************************/
853 jb_socket forwarded_connect(const struct forward_spec * fwd,
854 struct http_request *http,
855 struct client_state *csp)
857 const char * dest_host;
859 jb_socket sfd = JB_INVALID_SOCKET;
861 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
862 sfd = get_reusable_connection(http, fwd);
863 if (JB_INVALID_SOCKET == sfd)
865 log_error(LOG_LEVEL_CONNECT,
866 "No reusable socket for %s:%d found. Opening a new one.",
867 http->host, http->port);
873 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
875 /* Figure out if we need to connect to the web server or a HTTP proxy. */
876 if (fwd->forward_host)
879 dest_host = fwd->forward_host;
880 dest_port = fwd->forward_port;
885 dest_host = http->host;
886 dest_port = http->port;
889 /* Connect, maybe using a SOCKS proxy */
893 sfd = connect_to(dest_host, dest_port, csp);
897 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
900 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
903 /* Should never get here */
904 log_error(LOG_LEVEL_FATAL,
905 "SOCKS4 impossible internal error - bad SOCKS type.");
913 /*********************************************************************
915 * Function : socks4_connect
917 * Description : Connect to the SOCKS server, and connect through
918 * it to the specified server. This handles
919 * all the SOCKS negotiation, and returns a file
920 * descriptor for a socket which can be treated as a
921 * normal (non-SOCKS) socket.
923 * Logged error messages are saved to csp->error_message
924 * and later reused by error_response() for the CGI
925 * message. strdup allocation failures are handled there.
928 * 1 : fwd = Specifies the SOCKS proxy to use.
929 * 2 : target_host = The final server to connect to.
930 * 3 : target_port = The final port to connect to.
931 * 4 : csp = Current client state (buffers, headers, etc...)
933 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
935 *********************************************************************/
936 static jb_socket socks4_connect(const struct forward_spec * fwd,
937 const char * target_host,
939 struct client_state *csp)
941 unsigned int web_server_addr;
942 char buf[BUFFER_SIZE];
943 struct socks_op *c = (struct socks_op *)buf;
944 struct socks_reply *s = (struct socks_reply *)buf;
951 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
953 /* XXX: Shouldn't the config file parser prevent this? */
954 errstr = "NULL gateway host specified.";
958 if (fwd->gateway_port <= 0)
960 errstr = "invalid gateway port specified.";
966 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
967 csp->error_message = strdup(errstr);
969 return(JB_INVALID_SOCKET);
972 /* build a socks request for connection to the web server */
974 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
976 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
981 web_server_addr = resolve_hostname_to_ip(target_host);
982 if (web_server_addr == INADDR_NONE)
984 errstr = "could not resolve target host";
985 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
990 web_server_addr = htonl(web_server_addr);
994 web_server_addr = 0x00000001;
995 n = csiz + strlen(target_host) + 1;
999 errstr = "buffer cbuf too small.";
1000 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1005 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
1007 * What we forward to the socks4a server should have the
1008 * size of socks_op, plus the length of the userid plus
1009 * its \0 byte (which we don't have to add because the
1010 * first byte of the userid is counted twice as it's also
1011 * part of sock_op) minus the padding bytes (which are part
1012 * of the userid as well), plus the length of the target_host
1013 * (which is stored csiz bytes after the beginning of the buffer),
1014 * plus another \0 byte.
1016 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
1021 /* Should never get here */
1022 log_error(LOG_LEVEL_FATAL,
1023 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
1025 return(JB_INVALID_SOCKET);
1030 csp->error_message = strdup(errstr);
1031 return(JB_INVALID_SOCKET);
1036 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1037 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1038 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1039 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1040 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1041 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1043 /* pass the request to the socks server */
1044 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1046 if (sfd == JB_INVALID_SOCKET)
1049 * XXX: connect_to should fill in the exact reason.
1050 * Most likely resolving the IP of the forwarder failed.
1052 errstr = "connect_to failed: see logfile for details";
1055 else if (write_socket(sfd, (char *)c, csiz))
1057 errstr = "SOCKS4 negotiation write failed.";
1058 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1062 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1064 errstr = "SOCKS4 negotiation read failed.";
1065 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1072 csp->error_message = strdup(errstr);
1073 return(JB_INVALID_SOCKET);
1078 case SOCKS_REQUEST_GRANTED:
1081 case SOCKS_REQUEST_REJECT:
1082 errstr = "SOCKS request rejected or failed.";
1085 case SOCKS_REQUEST_IDENT_FAILED:
1086 errstr = "SOCKS request rejected because "
1087 "SOCKS server cannot connect to identd on the client.";
1090 case SOCKS_REQUEST_IDENT_CONFLICT:
1091 errstr = "SOCKS request rejected because "
1092 "the client program and identd report "
1093 "different user-ids.";
1098 snprintf(buf, sizeof(buf),
1099 "SOCKS request rejected for reason code %d.", s->cd);
1103 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1104 csp->error_message = strdup(errstr);
1107 return(JB_INVALID_SOCKET);
1111 /*********************************************************************
1113 * Function : translate_socks5_error
1115 * Description : Translates a SOCKS errors to a string.
1118 * 1 : socks_error = The error code to translate.
1120 * Returns : The string translation.
1122 *********************************************************************/
1123 static const char *translate_socks5_error(int socks_error)
1125 switch (socks_error)
1127 /* XXX: these should be more descriptive */
1128 case SOCKS5_REQUEST_FAILED:
1129 return "SOCKS5 request failed";
1130 case SOCKS5_REQUEST_DENIED:
1131 return "SOCKS5 request denied";
1132 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1133 return "SOCKS5 network unreachable";
1134 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1135 return "SOCKS5 host unreachable";
1136 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1137 return "SOCKS5 connection refused";
1138 case SOCKS5_REQUEST_TTL_EXPIRED:
1139 return "SOCKS5 TTL expired";
1140 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1141 return "SOCKS5 client protocol error";
1142 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1143 return "SOCKS5 domain names unsupported";
1144 case SOCKS5_REQUEST_GRANTED:
1145 return "everything's peachy";
1147 return "SOCKS5 negotiation protocol error";
1151 /*********************************************************************
1153 * Function : socks5_connect
1155 * Description : Connect to the SOCKS server, and connect through
1156 * it to the specified server. This handles
1157 * all the SOCKS negotiation, and returns a file
1158 * descriptor for a socket which can be treated as a
1159 * normal (non-SOCKS) socket.
1162 * 1 : fwd = Specifies the SOCKS proxy to use.
1163 * 2 : target_host = The final server to connect to.
1164 * 3 : target_port = The final port to connect to.
1165 * 4 : csp = Current client state (buffers, headers, etc...)
1167 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1169 *********************************************************************/
1170 static jb_socket socks5_connect(const struct forward_spec *fwd,
1171 const char *target_host,
1173 struct client_state *csp)
1178 size_t client_pos = 0;
1179 int server_size = 0;
1182 const char *errstr = NULL;
1184 assert(fwd->gateway_host);
1185 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1187 errstr = "NULL gateway host specified";
1191 if (fwd->gateway_port <= 0)
1194 * XXX: currently this can't happen because in
1195 * case of invalid gateway ports we use the defaults.
1196 * Of course we really shouldn't do that.
1198 errstr = "invalid gateway port specified";
1202 hostlen = strlen(target_host);
1205 errstr = "target host name is longer than 255 characters";
1209 if (fwd->type != SOCKS_5)
1211 /* Should never get here */
1212 log_error(LOG_LEVEL_FATAL,
1213 "SOCKS5 impossible internal error - bad SOCKS type");
1220 assert(errstr != NULL);
1221 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1222 csp->error_message = strdup(errstr);
1223 return(JB_INVALID_SOCKET);
1226 /* pass the request to the socks server */
1227 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1229 if (sfd == JB_INVALID_SOCKET)
1231 errstr = "socks5 server unreachable";
1232 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1233 csp->error_message = strdup(errstr);
1234 return(JB_INVALID_SOCKET);
1238 cbuf[client_pos++] = '\x05'; /* Version */
1239 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1240 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1242 if (write_socket(sfd, cbuf, client_pos))
1244 errstr = "SOCKS5 negotiation write failed";
1245 csp->error_message = strdup(errstr);
1246 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1248 return(JB_INVALID_SOCKET);
1251 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1253 errstr = "SOCKS5 negotiation read failed";
1257 if (!err && (sbuf[0] != '\x05'))
1259 errstr = "SOCKS5 negotiation protocol version error";
1263 if (!err && (sbuf[1] == '\xff'))
1265 errstr = "SOCKS5 authentication required";
1269 if (!err && (sbuf[1] != '\x00'))
1271 errstr = "SOCKS5 negotiation protocol error";
1277 assert(errstr != NULL);
1278 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1279 csp->error_message = strdup(errstr);
1282 return(JB_INVALID_SOCKET);
1286 cbuf[client_pos++] = '\x05'; /* Version */
1287 cbuf[client_pos++] = '\x01'; /* TCP connect */
1288 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1289 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1290 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1291 assert(sizeof(cbuf) - client_pos > 255);
1292 /* Using strncpy because we really want the nul byte padding. */
1293 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1294 client_pos += (hostlen & 0xffu);
1295 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1296 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1298 if (write_socket(sfd, cbuf, client_pos))
1300 errstr = "SOCKS5 negotiation read failed";
1301 csp->error_message = strdup(errstr);
1302 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1305 return(JB_INVALID_SOCKET);
1308 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1309 if (server_size < 3)
1311 errstr = "SOCKS5 negotiation read failed";
1314 else if (server_size > 20)
1316 /* This is somewhat unexpected but doesn't realy matter. */
1317 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1318 "from socks server. Would have accepted up to %d.",
1319 server_size, sizeof(sbuf));
1322 if (!err && (sbuf[0] != '\x05'))
1324 errstr = "SOCKS5 negotiation protocol version error";
1328 if (!err && (sbuf[2] != '\x00'))
1330 errstr = "SOCKS5 negotiation protocol error";
1336 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1340 errstr = translate_socks5_error(sbuf[1]);
1344 assert(errstr != NULL);
1345 csp->error_message = strdup(errstr);
1346 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1350 return(JB_INVALID_SOCKET);