1 const char gateway_rcs[] = "$Id: gateway.c,v 1.38 2008/10/24 17:33:00 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.38 2008/10/24 17:33:00 fabiankeil
38 * - Tone the "keep-alive support is experimental" warning
39 * down a bit as hackish 0-chunk detection has been
40 * implemented recently.
41 * - Only show the "ndef HAVE_POLL" warning once on start-up.
43 * Revision 1.37 2008/10/23 17:40:53 fabiankeil
44 * Fix forget_connection() and mark_connection_unused(),
45 * which would both under certain circumstances access
46 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
48 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
49 * - Factor close_unusable_connections() out of
50 * get_reusable_connection() to make sure we really check
51 * all the remembered connections, not just the ones before
52 * the next reusable one.
53 * - Plug two file descriptor leaks. Internally marking
54 * connections as closed doesn't cut it.
56 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
57 * In socket_is_still_usable(), use select()
58 * and FD_ISSET() if poll() isn't available.
60 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
61 * Add preliminary timeout support.
63 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
64 * Fix two gcc44 warnings.
66 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
67 * Fix compiler warning.
69 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
70 * - Factor socket_is_still_usable() out of get_reusable_connection().
71 * - If poll() isn't available, show a warning and assume the socket
74 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
75 * If a remembered connection is no longer usable and
76 * has been marked closed, don't bother checking if the
77 * destination matches.
79 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
80 * Add missing dots for two log messages.
82 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
83 * Flush work-in-progress changes to keep outgoing connections
84 * alive where possible. Incomplete and mostly #ifdef'd out.
86 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
87 * Return only once in forwarded_connect().
89 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
90 * Fix typo in macro name.
92 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
94 * - make the buffers quite a bit smaller.
95 * - properly report "socks5 server unreachable" failures.
96 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
97 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
98 * - log a message if the socks5 server sends more data than expected.
99 * - add some assertions and comments.
101 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
102 * - Fix a compiler warning.
103 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
105 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
106 * Remember the cause of the SOCKS5 error for the CGI message.
108 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
109 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
111 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
112 * Modified patch from Song Weijia (#1762559) to
113 * fix socks requests on big-endian platforms.
115 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
116 * - Use strlcpy() instead of strcpy().
117 * - Use the same buffer for socks requests and socks responses.
118 * - Fix bogus warning about web_server_addr being used uninitialized.
120 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
121 * - Save errors in socks4_connect() to csp->error_message.
122 * - Silence some gcc43 warnings, hopefully the right way.
124 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
125 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
126 * with what was really the latest development (the v_3_0_branch branch)
128 * Revision 1.16 2002/05/12 21:36:29 jongfoster
129 * Correcting function comments
131 * Revision 1.15 2002/03/26 22:29:54 swa
132 * we have a new homepage!
134 * Revision 1.14 2002/03/24 13:25:43 swa
135 * name change related issues
137 * Revision 1.13 2002/03/13 00:29:59 jongfoster
140 * Revision 1.12 2002/03/09 20:03:52 jongfoster
141 * - Making various functions return int rather than size_t.
142 * (Undoing a recent change). Since size_t is unsigned on
143 * Windows, functions like read_socket that return -1 on
144 * error cannot return a size_t.
146 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
147 * crashes, and also frequently caused JB to jump to 100%
148 * CPU and stay there. (Because it thought it had just
149 * read ((unsigned)-1) == 4Gb of data...)
151 * - The signature of write_socket has changed, it now simply
152 * returns success=0/failure=nonzero.
154 * - Trying to get rid of a few warnings --with-debug on
155 * Windows, I've introduced a new type "jb_socket". This is
156 * used for the socket file descriptors. On Windows, this
157 * is SOCKET (a typedef for unsigned). Everywhere else, it's
158 * an int. The error value can't be -1 any more, so it's
159 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
160 * Windows it maps to the #define INVALID_SOCKET.)
162 * - The signature of bind_port has changed.
164 * Revision 1.11 2002/03/08 17:46:04 jongfoster
165 * Fixing int/size_t warnings
167 * Revision 1.10 2002/03/07 03:50:19 oes
168 * - Improved handling of failed DNS lookups
169 * - Fixed compiler warnings
171 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
172 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
173 * threads to call select() simultaneously. So, it's time to do a real, live,
174 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
175 * (native). Both versions will work, but using __OS2__ offers multi-threading.
177 * Revision 1.8 2001/09/13 20:10:12 jongfoster
178 * Fixing missing #include under Windows
180 * Revision 1.7 2001/09/12 17:58:26 steudten
182 * add #include <string.h>
184 * Revision 1.6 2001/09/10 10:41:16 oes
185 * Added #include in.h
187 * Revision 1.5 2001/07/29 18:47:57 jongfoster
188 * Adding missing #include project.h
190 * Revision 1.4 2001/07/24 12:47:06 oes
191 * Applied BeOS support update by Eugenia
193 * Revision 1.3 2001/06/09 10:55:28 jongfoster
194 * Changing BUFSIZ ==> BUFFER_SIZE
196 * Revision 1.2 2001/06/07 23:11:38 jongfoster
197 * Removing gateways[] list - no longer used.
198 * Replacing function pointer in struct gateway with a directly
199 * called function forwarded_connect(), which can do the common
200 * task of deciding whether to connect to the web server or HTTP
202 * Replacing struct gateway with struct forward_spec
203 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
204 * It was a bug which led to the connection being made to the web
205 * server rather than the HTTP proxy, and also a buffer overrun.
207 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
208 * Initial import of version 2.9.3 source tree
211 *********************************************************************/
217 #include <sys/types.h>
220 #include <netinet/in.h>
228 #include <winsock2.h>
229 #endif /* def _WIN32 */
233 #endif /* def __BEOS__ */
237 #endif /* def __OS2__ */
242 #include "jbsockets.h"
244 #include "miscutil.h"
245 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
248 #include <sys/poll.h>
251 #endif /* def __GLIBC__ */
252 #endif /* HAVE_POLL */
253 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
255 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
257 static jb_socket socks4_connect(const struct forward_spec * fwd,
258 const char * target_host,
260 struct client_state *csp);
262 static jb_socket socks5_connect(const struct forward_spec *fwd,
263 const char *target_host,
265 struct client_state *csp);
268 #define SOCKS_REQUEST_GRANTED 90
269 #define SOCKS_REQUEST_REJECT 91
270 #define SOCKS_REQUEST_IDENT_FAILED 92
271 #define SOCKS_REQUEST_IDENT_CONFLICT 93
273 #define SOCKS5_REQUEST_GRANTED 0
274 #define SOCKS5_REQUEST_FAILED 1
275 #define SOCKS5_REQUEST_DENIED 2
276 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
277 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
278 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
279 #define SOCKS5_REQUEST_TTL_EXPIRED 6
280 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
281 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
283 /* structure of a socks client operation */
285 unsigned char vn; /* socks version number */
286 unsigned char cd; /* command code */
287 unsigned char dstport[2]; /* destination port */
288 unsigned char dstip[4]; /* destination address */
289 char userid; /* first byte of userid */
290 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
291 /* more bytes of the userid follow, terminated by a NULL */
294 /* structure of a socks server reply */
296 unsigned char vn; /* socks version number */
297 unsigned char cd; /* command code */
298 unsigned char dstport[2]; /* destination port */
299 unsigned char dstip[4]; /* destination address */
302 static const char socks_userid[] = "anonymous";
304 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
306 #define MAX_REUSABLE_CONNECTIONS 100
307 /* XXX: should be a config option. */
308 #define CONNECTION_KEEP_ALIVE_TIMEOUT 3 * 60
310 struct reusable_connection
325 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
327 static int mark_connection_unused(jb_socket sfd);
328 static void mark_connection_closed(struct reusable_connection *closed_connection);
329 static int socket_is_still_usable(jb_socket sfd);
332 /*********************************************************************
334 * Function : initialize_reusable_connections
336 * Description : Initializes the reusable_connection structures.
337 * Must be called with connection_reuse_mutex locked.
343 *********************************************************************/
344 extern void initialize_reusable_connections(void)
346 unsigned int slot = 0;
348 log_error(LOG_LEVEL_INFO,
349 "Support for 'Connection: keep-alive' is experimental."
351 " Detecting already dead connections might not work"
352 " correctly on your platform."
353 #endif /* ndef HAVE_POLL */
356 for (slot = 0; slot < SZ(reusable_connection); slot++)
358 mark_connection_closed(&reusable_connection[slot]);
361 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
365 /*********************************************************************
367 * Function : remember_connection
369 * Description : Remembers a connection for reuse later on.
372 * 1 : sfd = Open socket to remember.
373 * 2 : http = The destination for the connection.
374 * 3 : fwd = The forwarder settings used.
378 *********************************************************************/
379 void remember_connection(jb_socket sfd, const struct http_request *http,
380 const struct forward_spec *fwd)
382 unsigned int slot = 0;
383 int free_slot_found = FALSE;
385 assert(sfd != JB_INVALID_SOCKET);
387 if (mark_connection_unused(sfd))
392 privoxy_mutex_lock(&connection_reuse_mutex);
394 /* Find free socket slot. */
395 for (slot = 0; slot < SZ(reusable_connection); slot++)
397 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
399 assert(reusable_connection[slot].in_use == 0);
400 log_error(LOG_LEVEL_CONNECT,
401 "Remembering socket %d for %s:%d in slot %d.",
402 sfd, http->host, http->port, slot);
403 free_slot_found = TRUE;
408 if (!free_slot_found)
410 log_error(LOG_LEVEL_CONNECT,
411 "No free slots found to remembering socket for %s:%d. Last slot %d.",
412 http->host, http->port, slot);
413 privoxy_mutex_unlock(&connection_reuse_mutex);
418 assert(NULL != http->host);
419 reusable_connection[slot].host = strdup(http->host);
420 if (NULL == reusable_connection[slot].host)
422 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
424 reusable_connection[slot].sfd = sfd;
425 reusable_connection[slot].port = http->port;
426 reusable_connection[slot].in_use = 0;
427 reusable_connection[slot].timestamp = time(NULL);
430 assert(reusable_connection[slot].gateway_host == NULL);
431 assert(reusable_connection[slot].gateway_port == 0);
432 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
433 assert(reusable_connection[slot].forward_host == NULL);
434 assert(reusable_connection[slot].forward_port == 0);
436 reusable_connection[slot].forwarder_type = fwd->type;
437 if (NULL != fwd->gateway_host)
439 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
440 if (NULL == reusable_connection[slot].gateway_host)
442 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
447 reusable_connection[slot].gateway_host = NULL;
449 reusable_connection[slot].gateway_port = fwd->gateway_port;
451 if (NULL != fwd->forward_host)
453 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
454 if (NULL == reusable_connection[slot].forward_host)
456 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
461 reusable_connection[slot].forward_host = NULL;
463 reusable_connection[slot].forward_port = fwd->forward_port;
465 privoxy_mutex_unlock(&connection_reuse_mutex);
469 /*********************************************************************
471 * Function : mark_connection_closed
473 * Description : Marks a reused connection closed.
474 * Must be called with connection_reuse_mutex locked.
477 * 1 : closed_connection = The connection to mark as closed.
481 *********************************************************************/
482 static void mark_connection_closed(struct reusable_connection *closed_connection)
484 closed_connection->in_use = FALSE;
485 closed_connection->sfd = JB_INVALID_SOCKET;
486 freez(closed_connection->host);
487 closed_connection->port = 0;
488 closed_connection->timestamp = 0;
489 closed_connection->forwarder_type = SOCKS_NONE;
490 freez(closed_connection->gateway_host);
491 closed_connection->gateway_port = 0;
492 freez(closed_connection->forward_host);
493 closed_connection->forward_port = 0;
497 /*********************************************************************
499 * Function : forget_connection
501 * Description : Removes a previously remembered connection from
502 * the list of reusable connections.
505 * 1 : sfd = The socket belonging to the connection in question.
509 *********************************************************************/
510 void forget_connection(jb_socket sfd)
512 unsigned int slot = 0;
514 assert(sfd != JB_INVALID_SOCKET);
516 privoxy_mutex_lock(&connection_reuse_mutex);
518 for (slot = 0; slot < SZ(reusable_connection); slot++)
520 if (reusable_connection[slot].sfd == sfd)
522 assert(reusable_connection[slot].in_use);
524 log_error(LOG_LEVEL_CONNECT,
525 "Forgetting socket %d for %s:%d in slot %d.",
526 sfd, reusable_connection[slot].host,
527 reusable_connection[slot].port, slot);
528 mark_connection_closed(&reusable_connection[slot]);
529 privoxy_mutex_unlock(&connection_reuse_mutex);
535 log_error(LOG_LEVEL_CONNECT,
536 "Socket %d already forgotten or never remembered.", sfd);
538 privoxy_mutex_unlock(&connection_reuse_mutex);
542 /*********************************************************************
544 * Function : connection_destination_matches
546 * Description : Determines whether a remembered connection can
547 * be reused. That is whether the destination and
548 * the forwarding settings match.
551 * 1 : connection = The connection to check.
552 * 2 : http = The destination for the connection.
553 * 3 : fwd = The forwarder settings.
555 * Returns : TRUE for yes, FALSE otherwise.
557 *********************************************************************/
558 static int connection_destination_matches(const struct reusable_connection *connection,
559 const struct http_request *http,
560 const struct forward_spec *fwd)
562 /* XXX: Start of duplicated checks for debugging purposes. */
563 if (strcmpic(connection->host, http->host))
568 if (connection->forwarder_type != fwd->type)
570 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
571 connection->forwarder_type, fwd->type, http->host);
574 if (connection->gateway_port != fwd->gateway_port)
576 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
577 connection->gateway_port, fwd->gateway_port, http->host);
580 if (connection->forward_port != fwd->forward_port)
582 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
583 connection->forward_port, fwd->forward_port, http->host);
586 if (connection->forward_port != fwd->forward_port)
588 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
589 connection->forward_port, fwd->forward_port, http->host);
593 /* XXX: End of duplicated checks for debugging purposes. */
595 if ((connection->forwarder_type != fwd->type)
596 || (connection->gateway_port != fwd->gateway_port)
597 || (connection->forward_port != fwd->forward_port)
598 || (connection->port != http->port))
603 if (( (NULL != connection->gateway_host)
604 && (NULL != fwd->gateway_host)
605 && strcmpic(connection->gateway_host, fwd->gateway_host))
606 && (connection->gateway_host != fwd->gateway_host))
608 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
612 if (( (NULL != connection->forward_host)
613 && (NULL != fwd->forward_host)
614 && strcmpic(connection->forward_host, fwd->forward_host))
615 && (connection->forward_host != fwd->forward_host))
617 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
621 return (!strcmpic(connection->host, http->host));
626 /*********************************************************************
628 * Function : close_unusable_connections
630 * Description : Closes remembered connections that have timed
631 * out or have been closed on the other side.
637 *********************************************************************/
638 static void close_unusable_connections(void)
640 unsigned int slot = 0;
642 for (slot = 0; slot < SZ(reusable_connection); slot++)
644 if (!reusable_connection[slot].in_use
645 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
647 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
649 if (CONNECTION_KEEP_ALIVE_TIMEOUT < time_open)
651 log_error(LOG_LEVEL_CONNECT,
652 "The connection to %s:%d in slot %d timed out. Closing.",
653 reusable_connection[slot].host, reusable_connection[slot].port,
655 close_socket(reusable_connection[slot].sfd);
656 mark_connection_closed(&reusable_connection[slot]);
660 if (!socket_is_still_usable(reusable_connection[slot].sfd))
662 log_error(LOG_LEVEL_CONNECT,
663 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
664 reusable_connection[slot].sfd, reusable_connection[slot].host,
665 reusable_connection[slot].port, slot);
666 close_socket(reusable_connection[slot].sfd);
667 mark_connection_closed(&reusable_connection[slot]);
675 /*********************************************************************
677 * Function : socket_is_still_usable
679 * Description : Decides whether or not an open socket is still usable.
682 * 1 : sfd = The socket to check.
684 * Returns : TRUE for yes, otherwise FALSE.
686 *********************************************************************/
687 static int socket_is_still_usable(jb_socket sfd)
691 struct pollfd poll_fd[1];
693 memset(poll_fd, 0, sizeof(poll_fd));
695 poll_fd[0].events = POLLIN;
697 poll_result = poll(poll_fd, 1, 0);
699 if (-1 != poll_result)
701 return !(poll_fd[0].revents & POLLIN);
705 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
710 struct timeval timeout;
712 int socket_is_alive = 0;
714 memset(&timeout, '\0', sizeof(timeout));
715 FD_ZERO(&readable_fds);
716 FD_SET(sfd, &readable_fds);
718 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
721 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
725 * XXX: I'm not sure why !FD_ISSET() works,
726 * but apparently it does.
728 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
730 return socket_is_alive;
731 #endif /* def HAVE_POLL */
735 /*********************************************************************
737 * Function : get_reusable_connection
739 * Description : Returns an open socket to a previously remembered
740 * open connection (if there is one).
743 * 1 : http = The destination for the connection.
744 * 2 : fwd = The forwarder settings.
746 * Returns : JB_INVALID_SOCKET => No reusable connection found,
747 * otherwise a usable socket.
749 *********************************************************************/
750 static jb_socket get_reusable_connection(const struct http_request *http,
751 const struct forward_spec *fwd)
753 jb_socket sfd = JB_INVALID_SOCKET;
754 unsigned int slot = 0;
756 privoxy_mutex_lock(&connection_reuse_mutex);
758 close_unusable_connections();
760 for (slot = 0; slot < SZ(reusable_connection); slot++)
762 if (!reusable_connection[slot].in_use
763 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
765 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
767 reusable_connection[slot].in_use = TRUE;
768 sfd = reusable_connection[slot].sfd;
769 log_error(LOG_LEVEL_CONNECT,
770 "Found reusable socket %d for %s:%d in slot %d.",
771 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
777 privoxy_mutex_unlock(&connection_reuse_mutex);
784 /*********************************************************************
786 * Function : mark_connection_unused
788 * Description : Gives a remembered connection free for reuse.
791 * 1 : sfd = The socket belonging to the connection in question.
793 * Returns : TRUE => Socket found and marked as unused.
794 * FALSE => Socket not found.
796 *********************************************************************/
797 static int mark_connection_unused(jb_socket sfd)
799 unsigned int slot = 0;
800 int socket_found = FALSE;
802 assert(sfd != JB_INVALID_SOCKET);
804 privoxy_mutex_lock(&connection_reuse_mutex);
806 for (slot = 0; slot < SZ(reusable_connection); slot++)
808 if (reusable_connection[slot].sfd == sfd)
810 assert(reusable_connection[slot].in_use);
812 log_error(LOG_LEVEL_CONNECT,
813 "Marking open socket %d for %s:%d in slot %d as unused.",
814 sfd, reusable_connection[slot].host,
815 reusable_connection[slot].port, slot);
816 reusable_connection[slot].in_use = 0;
817 reusable_connection[slot].timestamp = time(NULL);
822 privoxy_mutex_unlock(&connection_reuse_mutex);
827 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
830 /*********************************************************************
832 * Function : forwarded_connect
834 * Description : Connect to a specified web server, possibly via
835 * a HTTP proxy and/or a SOCKS proxy.
838 * 1 : fwd = the proxies to use when connecting.
839 * 2 : http = the http request and apropos headers
840 * 3 : csp = Current client state (buffers, headers, etc...)
842 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
844 *********************************************************************/
845 jb_socket forwarded_connect(const struct forward_spec * fwd,
846 struct http_request *http,
847 struct client_state *csp)
849 const char * dest_host;
851 jb_socket sfd = JB_INVALID_SOCKET;
853 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
854 sfd = get_reusable_connection(http, fwd);
855 if (JB_INVALID_SOCKET == sfd)
857 log_error(LOG_LEVEL_CONNECT,
858 "No reusable socket for %s:%d found. Opening a new one.",
859 http->host, http->port);
865 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
867 /* Figure out if we need to connect to the web server or a HTTP proxy. */
868 if (fwd->forward_host)
871 dest_host = fwd->forward_host;
872 dest_port = fwd->forward_port;
877 dest_host = http->host;
878 dest_port = http->port;
881 /* Connect, maybe using a SOCKS proxy */
885 sfd = connect_to(dest_host, dest_port, csp);
889 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
892 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
895 /* Should never get here */
896 log_error(LOG_LEVEL_FATAL,
897 "SOCKS4 impossible internal error - bad SOCKS type.");
905 /*********************************************************************
907 * Function : socks4_connect
909 * Description : Connect to the SOCKS server, and connect through
910 * it to the specified server. This handles
911 * all the SOCKS negotiation, and returns a file
912 * descriptor for a socket which can be treated as a
913 * normal (non-SOCKS) socket.
915 * Logged error messages are saved to csp->error_message
916 * and later reused by error_response() for the CGI
917 * message. strdup allocation failures are handled there.
920 * 1 : fwd = Specifies the SOCKS proxy to use.
921 * 2 : target_host = The final server to connect to.
922 * 3 : target_port = The final port to connect to.
923 * 4 : csp = Current client state (buffers, headers, etc...)
925 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
927 *********************************************************************/
928 static jb_socket socks4_connect(const struct forward_spec * fwd,
929 const char * target_host,
931 struct client_state *csp)
933 unsigned int web_server_addr;
934 char buf[BUFFER_SIZE];
935 struct socks_op *c = (struct socks_op *)buf;
936 struct socks_reply *s = (struct socks_reply *)buf;
943 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
945 /* XXX: Shouldn't the config file parser prevent this? */
946 errstr = "NULL gateway host specified.";
950 if (fwd->gateway_port <= 0)
952 errstr = "invalid gateway port specified.";
958 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
959 csp->error_message = strdup(errstr);
961 return(JB_INVALID_SOCKET);
964 /* build a socks request for connection to the web server */
966 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
968 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
973 web_server_addr = resolve_hostname_to_ip(target_host);
974 if (web_server_addr == INADDR_NONE)
976 errstr = "could not resolve target host";
977 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
982 web_server_addr = htonl(web_server_addr);
986 web_server_addr = 0x00000001;
987 n = csiz + strlen(target_host) + 1;
991 errstr = "buffer cbuf too small.";
992 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
997 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
999 * What we forward to the socks4a server should have the
1000 * size of socks_op, plus the length of the userid plus
1001 * its \0 byte (which we don't have to add because the
1002 * first byte of the userid is counted twice as it's also
1003 * part of sock_op) minus the padding bytes (which are part
1004 * of the userid as well), plus the length of the target_host
1005 * (which is stored csiz bytes after the beginning of the buffer),
1006 * plus another \0 byte.
1008 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
1013 /* Should never get here */
1014 log_error(LOG_LEVEL_FATAL,
1015 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
1017 return(JB_INVALID_SOCKET);
1022 csp->error_message = strdup(errstr);
1023 return(JB_INVALID_SOCKET);
1028 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1029 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1030 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1031 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1032 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1033 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1035 /* pass the request to the socks server */
1036 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1038 if (sfd == JB_INVALID_SOCKET)
1041 * XXX: connect_to should fill in the exact reason.
1042 * Most likely resolving the IP of the forwarder failed.
1044 errstr = "connect_to failed: see logfile for details";
1047 else if (write_socket(sfd, (char *)c, csiz))
1049 errstr = "SOCKS4 negotiation write failed.";
1050 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1054 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1056 errstr = "SOCKS4 negotiation read failed.";
1057 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1064 csp->error_message = strdup(errstr);
1065 return(JB_INVALID_SOCKET);
1070 case SOCKS_REQUEST_GRANTED:
1073 case SOCKS_REQUEST_REJECT:
1074 errstr = "SOCKS request rejected or failed.";
1077 case SOCKS_REQUEST_IDENT_FAILED:
1078 errstr = "SOCKS request rejected because "
1079 "SOCKS server cannot connect to identd on the client.";
1082 case SOCKS_REQUEST_IDENT_CONFLICT:
1083 errstr = "SOCKS request rejected because "
1084 "the client program and identd report "
1085 "different user-ids.";
1090 snprintf(buf, sizeof(buf),
1091 "SOCKS request rejected for reason code %d.", s->cd);
1095 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1096 csp->error_message = strdup(errstr);
1099 return(JB_INVALID_SOCKET);
1103 /*********************************************************************
1105 * Function : translate_socks5_error
1107 * Description : Translates a SOCKS errors to a string.
1110 * 1 : socks_error = The error code to translate.
1112 * Returns : The string translation.
1114 *********************************************************************/
1115 static const char *translate_socks5_error(int socks_error)
1117 switch (socks_error)
1119 /* XXX: these should be more descriptive */
1120 case SOCKS5_REQUEST_FAILED:
1121 return "SOCKS5 request failed";
1122 case SOCKS5_REQUEST_DENIED:
1123 return "SOCKS5 request denied";
1124 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1125 return "SOCKS5 network unreachable";
1126 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1127 return "SOCKS5 host unreachable";
1128 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1129 return "SOCKS5 connection refused";
1130 case SOCKS5_REQUEST_TTL_EXPIRED:
1131 return "SOCKS5 TTL expired";
1132 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1133 return "SOCKS5 client protocol error";
1134 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1135 return "SOCKS5 domain names unsupported";
1136 case SOCKS5_REQUEST_GRANTED:
1137 return "everything's peachy";
1139 return "SOCKS5 negotiation protocol error";
1143 /*********************************************************************
1145 * Function : socks5_connect
1147 * Description : Connect to the SOCKS server, and connect through
1148 * it to the specified server. This handles
1149 * all the SOCKS negotiation, and returns a file
1150 * descriptor for a socket which can be treated as a
1151 * normal (non-SOCKS) socket.
1154 * 1 : fwd = Specifies the SOCKS proxy to use.
1155 * 2 : target_host = The final server to connect to.
1156 * 3 : target_port = The final port to connect to.
1157 * 4 : csp = Current client state (buffers, headers, etc...)
1159 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1161 *********************************************************************/
1162 static jb_socket socks5_connect(const struct forward_spec *fwd,
1163 const char *target_host,
1165 struct client_state *csp)
1170 size_t client_pos = 0;
1171 int server_size = 0;
1174 const char *errstr = NULL;
1176 assert(fwd->gateway_host);
1177 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1179 errstr = "NULL gateway host specified";
1183 if (fwd->gateway_port <= 0)
1186 * XXX: currently this can't happen because in
1187 * case of invalid gateway ports we use the defaults.
1188 * Of course we really shouldn't do that.
1190 errstr = "invalid gateway port specified";
1194 hostlen = strlen(target_host);
1197 errstr = "target host name is longer than 255 characters";
1201 if (fwd->type != SOCKS_5)
1203 /* Should never get here */
1204 log_error(LOG_LEVEL_FATAL,
1205 "SOCKS5 impossible internal error - bad SOCKS type");
1212 assert(errstr != NULL);
1213 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1214 csp->error_message = strdup(errstr);
1215 return(JB_INVALID_SOCKET);
1218 /* pass the request to the socks server */
1219 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1221 if (sfd == JB_INVALID_SOCKET)
1223 errstr = "socks5 server unreachable";
1224 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1225 csp->error_message = strdup(errstr);
1226 return(JB_INVALID_SOCKET);
1230 cbuf[client_pos++] = '\x05'; /* Version */
1231 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1232 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1234 if (write_socket(sfd, cbuf, client_pos))
1236 errstr = "SOCKS5 negotiation write failed";
1237 csp->error_message = strdup(errstr);
1238 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1240 return(JB_INVALID_SOCKET);
1243 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1245 errstr = "SOCKS5 negotiation read failed";
1249 if (!err && (sbuf[0] != '\x05'))
1251 errstr = "SOCKS5 negotiation protocol version error";
1255 if (!err && (sbuf[1] == '\xff'))
1257 errstr = "SOCKS5 authentication required";
1261 if (!err && (sbuf[1] != '\x00'))
1263 errstr = "SOCKS5 negotiation protocol error";
1269 assert(errstr != NULL);
1270 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1271 csp->error_message = strdup(errstr);
1274 return(JB_INVALID_SOCKET);
1278 cbuf[client_pos++] = '\x05'; /* Version */
1279 cbuf[client_pos++] = '\x01'; /* TCP connect */
1280 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1281 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1282 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1283 assert(sizeof(cbuf) - client_pos > 255);
1284 /* Using strncpy because we really want the nul byte padding. */
1285 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1286 client_pos += (hostlen & 0xffu);
1287 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1288 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1290 if (write_socket(sfd, cbuf, client_pos))
1292 errstr = "SOCKS5 negotiation read failed";
1293 csp->error_message = strdup(errstr);
1294 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1297 return(JB_INVALID_SOCKET);
1300 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1301 if (server_size < 3)
1303 errstr = "SOCKS5 negotiation read failed";
1306 else if (server_size > 20)
1308 /* This is somewhat unexpected but doesn't realy matter. */
1309 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1310 "from socks server. Would have accepted up to %d.",
1311 server_size, sizeof(sbuf));
1314 if (!err && (sbuf[0] != '\x05'))
1316 errstr = "SOCKS5 negotiation protocol version error";
1320 if (!err && (sbuf[2] != '\x00'))
1322 errstr = "SOCKS5 negotiation protocol error";
1328 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1332 errstr = translate_socks5_error(sbuf[1]);
1336 assert(errstr != NULL);
1337 csp->error_message = strdup(errstr);
1338 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1342 return(JB_INVALID_SOCKET);