1 const char gateway_rcs[] = "$Id: gateway.c,v 1.37 2008/10/23 17:40:53 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.37 2008/10/23 17:40:53 fabiankeil
38 * Fix forget_connection() and mark_connection_unused(),
39 * which would both under certain circumstances access
40 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
42 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
43 * - Factor close_unusable_connections() out of
44 * get_reusable_connection() to make sure we really check
45 * all the remembered connections, not just the ones before
46 * the next reusable one.
47 * - Plug two file descriptor leaks. Internally marking
48 * connections as closed doesn't cut it.
50 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
51 * In socket_is_still_usable(), use select()
52 * and FD_ISSET() if poll() isn't available.
54 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
55 * Add preliminary timeout support.
57 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
58 * Fix two gcc44 warnings.
60 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
61 * Fix compiler warning.
63 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
64 * - Factor socket_is_still_usable() out of get_reusable_connection().
65 * - If poll() isn't available, show a warning and assume the socket
68 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
69 * If a remembered connection is no longer usable and
70 * has been marked closed, don't bother checking if the
71 * destination matches.
73 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
74 * Add missing dots for two log messages.
76 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
77 * Flush work-in-progress changes to keep outgoing connections
78 * alive where possible. Incomplete and mostly #ifdef'd out.
80 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
81 * Return only once in forwarded_connect().
83 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
84 * Fix typo in macro name.
86 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
88 * - make the buffers quite a bit smaller.
89 * - properly report "socks5 server unreachable" failures.
90 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
91 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
92 * - log a message if the socks5 server sends more data than expected.
93 * - add some assertions and comments.
95 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
96 * - Fix a compiler warning.
97 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
99 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
100 * Remember the cause of the SOCKS5 error for the CGI message.
102 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
103 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
105 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
106 * Modified patch from Song Weijia (#1762559) to
107 * fix socks requests on big-endian platforms.
109 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
110 * - Use strlcpy() instead of strcpy().
111 * - Use the same buffer for socks requests and socks responses.
112 * - Fix bogus warning about web_server_addr being used uninitialized.
114 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
115 * - Save errors in socks4_connect() to csp->error_message.
116 * - Silence some gcc43 warnings, hopefully the right way.
118 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
119 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
120 * with what was really the latest development (the v_3_0_branch branch)
122 * Revision 1.16 2002/05/12 21:36:29 jongfoster
123 * Correcting function comments
125 * Revision 1.15 2002/03/26 22:29:54 swa
126 * we have a new homepage!
128 * Revision 1.14 2002/03/24 13:25:43 swa
129 * name change related issues
131 * Revision 1.13 2002/03/13 00:29:59 jongfoster
134 * Revision 1.12 2002/03/09 20:03:52 jongfoster
135 * - Making various functions return int rather than size_t.
136 * (Undoing a recent change). Since size_t is unsigned on
137 * Windows, functions like read_socket that return -1 on
138 * error cannot return a size_t.
140 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
141 * crashes, and also frequently caused JB to jump to 100%
142 * CPU and stay there. (Because it thought it had just
143 * read ((unsigned)-1) == 4Gb of data...)
145 * - The signature of write_socket has changed, it now simply
146 * returns success=0/failure=nonzero.
148 * - Trying to get rid of a few warnings --with-debug on
149 * Windows, I've introduced a new type "jb_socket". This is
150 * used for the socket file descriptors. On Windows, this
151 * is SOCKET (a typedef for unsigned). Everywhere else, it's
152 * an int. The error value can't be -1 any more, so it's
153 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
154 * Windows it maps to the #define INVALID_SOCKET.)
156 * - The signature of bind_port has changed.
158 * Revision 1.11 2002/03/08 17:46:04 jongfoster
159 * Fixing int/size_t warnings
161 * Revision 1.10 2002/03/07 03:50:19 oes
162 * - Improved handling of failed DNS lookups
163 * - Fixed compiler warnings
165 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
166 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
167 * threads to call select() simultaneously. So, it's time to do a real, live,
168 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
169 * (native). Both versions will work, but using __OS2__ offers multi-threading.
171 * Revision 1.8 2001/09/13 20:10:12 jongfoster
172 * Fixing missing #include under Windows
174 * Revision 1.7 2001/09/12 17:58:26 steudten
176 * add #include <string.h>
178 * Revision 1.6 2001/09/10 10:41:16 oes
179 * Added #include in.h
181 * Revision 1.5 2001/07/29 18:47:57 jongfoster
182 * Adding missing #include project.h
184 * Revision 1.4 2001/07/24 12:47:06 oes
185 * Applied BeOS support update by Eugenia
187 * Revision 1.3 2001/06/09 10:55:28 jongfoster
188 * Changing BUFSIZ ==> BUFFER_SIZE
190 * Revision 1.2 2001/06/07 23:11:38 jongfoster
191 * Removing gateways[] list - no longer used.
192 * Replacing function pointer in struct gateway with a directly
193 * called function forwarded_connect(), which can do the common
194 * task of deciding whether to connect to the web server or HTTP
196 * Replacing struct gateway with struct forward_spec
197 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
198 * It was a bug which led to the connection being made to the web
199 * server rather than the HTTP proxy, and also a buffer overrun.
201 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
202 * Initial import of version 2.9.3 source tree
205 *********************************************************************/
211 #include <sys/types.h>
214 #include <netinet/in.h>
222 #include <winsock2.h>
223 #endif /* def _WIN32 */
227 #endif /* def __BEOS__ */
231 #endif /* def __OS2__ */
236 #include "jbsockets.h"
238 #include "miscutil.h"
239 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
242 #include <sys/poll.h>
245 #endif /* def __GLIBC__ */
246 #endif /* HAVE_POLL */
247 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
249 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
251 static jb_socket socks4_connect(const struct forward_spec * fwd,
252 const char * target_host,
254 struct client_state *csp);
256 static jb_socket socks5_connect(const struct forward_spec *fwd,
257 const char *target_host,
259 struct client_state *csp);
262 #define SOCKS_REQUEST_GRANTED 90
263 #define SOCKS_REQUEST_REJECT 91
264 #define SOCKS_REQUEST_IDENT_FAILED 92
265 #define SOCKS_REQUEST_IDENT_CONFLICT 93
267 #define SOCKS5_REQUEST_GRANTED 0
268 #define SOCKS5_REQUEST_FAILED 1
269 #define SOCKS5_REQUEST_DENIED 2
270 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
271 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
272 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
273 #define SOCKS5_REQUEST_TTL_EXPIRED 6
274 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
275 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
277 /* structure of a socks client operation */
279 unsigned char vn; /* socks version number */
280 unsigned char cd; /* command code */
281 unsigned char dstport[2]; /* destination port */
282 unsigned char dstip[4]; /* destination address */
283 char userid; /* first byte of userid */
284 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
285 /* more bytes of the userid follow, terminated by a NULL */
288 /* structure of a socks server reply */
290 unsigned char vn; /* socks version number */
291 unsigned char cd; /* command code */
292 unsigned char dstport[2]; /* destination port */
293 unsigned char dstip[4]; /* destination address */
296 static const char socks_userid[] = "anonymous";
298 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
300 #define MAX_REUSABLE_CONNECTIONS 100
301 /* XXX: should be a config option. */
302 #define CONNECTION_KEEP_ALIVE_TIMEOUT 3 * 60
304 struct reusable_connection
319 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
321 static int mark_connection_unused(jb_socket sfd);
322 static void mark_connection_closed(struct reusable_connection *closed_connection);
323 static int socket_is_still_usable(jb_socket sfd);
326 /*********************************************************************
328 * Function : initialize_reusable_connections
330 * Description : Initializes the reusable_connection structures.
331 * Must be called with connection_reuse_mutex locked.
337 *********************************************************************/
338 extern void initialize_reusable_connections(void)
340 unsigned int slot = 0;
342 log_error(LOG_LEVEL_INFO,
343 "Support for 'Connection: keep-alive' is experimental."
345 " Detecting already dead connections might not work"
346 " correctly on your platform."
347 #endif /* ndef HAVE_POLL */
350 for (slot = 0; slot < SZ(reusable_connection); slot++)
352 mark_connection_closed(&reusable_connection[slot]);
355 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
359 /*********************************************************************
361 * Function : remember_connection
363 * Description : Remembers a connection for reuse later on.
366 * 1 : sfd = Open socket to remember.
367 * 2 : http = The destination for the connection.
368 * 3 : fwd = The forwarder settings used.
372 *********************************************************************/
373 void remember_connection(jb_socket sfd, const struct http_request *http,
374 const struct forward_spec *fwd)
376 unsigned int slot = 0;
377 int free_slot_found = FALSE;
379 assert(sfd != JB_INVALID_SOCKET);
381 if (mark_connection_unused(sfd))
386 privoxy_mutex_lock(&connection_reuse_mutex);
388 /* Find free socket slot. */
389 for (slot = 0; slot < SZ(reusable_connection); slot++)
391 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
393 assert(reusable_connection[slot].in_use == 0);
394 log_error(LOG_LEVEL_CONNECT,
395 "Remembering socket %d for %s:%d in slot %d.",
396 sfd, http->host, http->port, slot);
397 free_slot_found = TRUE;
402 if (!free_slot_found)
404 log_error(LOG_LEVEL_CONNECT,
405 "No free slots found to remembering socket for %s:%d. Last slot %d.",
406 http->host, http->port, slot);
407 privoxy_mutex_unlock(&connection_reuse_mutex);
412 assert(NULL != http->host);
413 reusable_connection[slot].host = strdup(http->host);
414 if (NULL == reusable_connection[slot].host)
416 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
418 reusable_connection[slot].sfd = sfd;
419 reusable_connection[slot].port = http->port;
420 reusable_connection[slot].in_use = 0;
421 reusable_connection[slot].timestamp = time(NULL);
424 assert(reusable_connection[slot].gateway_host == NULL);
425 assert(reusable_connection[slot].gateway_port == 0);
426 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
427 assert(reusable_connection[slot].forward_host == NULL);
428 assert(reusable_connection[slot].forward_port == 0);
430 reusable_connection[slot].forwarder_type = fwd->type;
431 if (NULL != fwd->gateway_host)
433 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
434 if (NULL == reusable_connection[slot].gateway_host)
436 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
441 reusable_connection[slot].gateway_host = NULL;
443 reusable_connection[slot].gateway_port = fwd->gateway_port;
445 if (NULL != fwd->forward_host)
447 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
448 if (NULL == reusable_connection[slot].forward_host)
450 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
455 reusable_connection[slot].forward_host = NULL;
457 reusable_connection[slot].forward_port = fwd->forward_port;
459 privoxy_mutex_unlock(&connection_reuse_mutex);
463 /*********************************************************************
465 * Function : mark_connection_closed
467 * Description : Marks a reused connection closed.
468 * Must be called with connection_reuse_mutex locked.
471 * 1 : closed_connection = The connection to mark as closed.
475 *********************************************************************/
476 static void mark_connection_closed(struct reusable_connection *closed_connection)
478 closed_connection->in_use = FALSE;
479 closed_connection->sfd = JB_INVALID_SOCKET;
480 freez(closed_connection->host);
481 closed_connection->port = 0;
482 closed_connection->timestamp = 0;
483 closed_connection->forwarder_type = SOCKS_NONE;
484 freez(closed_connection->gateway_host);
485 closed_connection->gateway_port = 0;
486 freez(closed_connection->forward_host);
487 closed_connection->forward_port = 0;
491 /*********************************************************************
493 * Function : forget_connection
495 * Description : Removes a previously remembered connection from
496 * the list of reusable connections.
499 * 1 : sfd = The socket belonging to the connection in question.
503 *********************************************************************/
504 void forget_connection(jb_socket sfd)
506 unsigned int slot = 0;
508 assert(sfd != JB_INVALID_SOCKET);
510 privoxy_mutex_lock(&connection_reuse_mutex);
512 for (slot = 0; slot < SZ(reusable_connection); slot++)
514 if (reusable_connection[slot].sfd == sfd)
516 assert(reusable_connection[slot].in_use);
518 log_error(LOG_LEVEL_CONNECT,
519 "Forgetting socket %d for %s:%d in slot %d.",
520 sfd, reusable_connection[slot].host,
521 reusable_connection[slot].port, slot);
522 mark_connection_closed(&reusable_connection[slot]);
523 privoxy_mutex_unlock(&connection_reuse_mutex);
529 log_error(LOG_LEVEL_CONNECT,
530 "Socket %d already forgotten or never remembered.", sfd);
532 privoxy_mutex_unlock(&connection_reuse_mutex);
536 /*********************************************************************
538 * Function : connection_destination_matches
540 * Description : Determines whether a remembered connection can
541 * be reused. That is whether the destination and
542 * the forwarding settings match.
545 * 1 : connection = The connection to check.
546 * 2 : http = The destination for the connection.
547 * 3 : fwd = The forwarder settings.
549 * Returns : TRUE for yes, FALSE otherwise.
551 *********************************************************************/
552 static int connection_destination_matches(const struct reusable_connection *connection,
553 const struct http_request *http,
554 const struct forward_spec *fwd)
556 /* XXX: Start of duplicated checks for debugging purposes. */
557 if (strcmpic(connection->host, http->host))
562 if (connection->forwarder_type != fwd->type)
564 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
565 connection->forwarder_type, fwd->type, http->host);
568 if (connection->gateway_port != fwd->gateway_port)
570 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
571 connection->gateway_port, fwd->gateway_port, http->host);
574 if (connection->forward_port != fwd->forward_port)
576 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
577 connection->forward_port, fwd->forward_port, http->host);
580 if (connection->forward_port != fwd->forward_port)
582 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
583 connection->forward_port, fwd->forward_port, http->host);
587 /* XXX: End of duplicated checks for debugging purposes. */
589 if ((connection->forwarder_type != fwd->type)
590 || (connection->gateway_port != fwd->gateway_port)
591 || (connection->forward_port != fwd->forward_port)
592 || (connection->port != http->port))
597 if (( (NULL != connection->gateway_host)
598 && (NULL != fwd->gateway_host)
599 && strcmpic(connection->gateway_host, fwd->gateway_host))
600 && (connection->gateway_host != fwd->gateway_host))
602 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
606 if (( (NULL != connection->forward_host)
607 && (NULL != fwd->forward_host)
608 && strcmpic(connection->forward_host, fwd->forward_host))
609 && (connection->forward_host != fwd->forward_host))
611 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
615 return (!strcmpic(connection->host, http->host));
620 /*********************************************************************
622 * Function : close_unusable_connections
624 * Description : Closes remembered connections that have timed
625 * out or have been closed on the other side.
631 *********************************************************************/
632 static void close_unusable_connections(void)
634 unsigned int slot = 0;
636 for (slot = 0; slot < SZ(reusable_connection); slot++)
638 if (!reusable_connection[slot].in_use
639 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
641 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
643 if (CONNECTION_KEEP_ALIVE_TIMEOUT < time_open)
645 log_error(LOG_LEVEL_CONNECT,
646 "The connection to %s:%d in slot %d timed out. Closing.",
647 reusable_connection[slot].host, reusable_connection[slot].port,
649 close_socket(reusable_connection[slot].sfd);
650 mark_connection_closed(&reusable_connection[slot]);
654 if (!socket_is_still_usable(reusable_connection[slot].sfd))
656 log_error(LOG_LEVEL_CONNECT,
657 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
658 reusable_connection[slot].sfd, reusable_connection[slot].host,
659 reusable_connection[slot].port, slot);
660 close_socket(reusable_connection[slot].sfd);
661 mark_connection_closed(&reusable_connection[slot]);
669 /*********************************************************************
671 * Function : socket_is_still_usable
673 * Description : Decides whether or not an open socket is still usable.
676 * 1 : sfd = The socket to check.
678 * Returns : TRUE for yes, otherwise FALSE.
680 *********************************************************************/
681 static int socket_is_still_usable(jb_socket sfd)
685 struct pollfd poll_fd[1];
687 memset(poll_fd, 0, sizeof(poll_fd));
689 poll_fd[0].events = POLLIN;
691 poll_result = poll(poll_fd, 1, 0);
693 if (-1 != poll_result)
695 return !(poll_fd[0].revents & POLLIN);
699 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
704 struct timeval timeout;
706 int socket_is_alive = 0;
708 memset(&timeout, '\0', sizeof(timeout));
709 /* timeout.tv_usec = 150;*/
710 FD_ZERO(&readable_fds);
711 FD_SET(sfd, &readable_fds);
713 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
716 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
720 * XXX: I'm not sure why !FD_ISSET() works,
721 * but apparently it does.
723 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
725 return socket_is_alive;
726 #endif /* def HAVE_POLL */
730 /*********************************************************************
732 * Function : get_reusable_connection
734 * Description : Returns an open socket to a previously remembered
735 * open connection (if there is one).
738 * 1 : http = The destination for the connection.
739 * 2 : fwd = The forwarder settings.
741 * Returns : JB_INVALID_SOCKET => No reusable connection found,
742 * otherwise a usable socket.
744 *********************************************************************/
745 static jb_socket get_reusable_connection(const struct http_request *http,
746 const struct forward_spec *fwd)
748 jb_socket sfd = JB_INVALID_SOCKET;
749 unsigned int slot = 0;
751 privoxy_mutex_lock(&connection_reuse_mutex);
753 close_unusable_connections();
755 for (slot = 0; slot < SZ(reusable_connection); slot++)
757 if (!reusable_connection[slot].in_use
758 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
760 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
762 reusable_connection[slot].in_use = TRUE;
763 sfd = reusable_connection[slot].sfd;
764 log_error(LOG_LEVEL_CONNECT,
765 "Found reusable socket %d for %s:%d in slot %d.",
766 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
772 privoxy_mutex_unlock(&connection_reuse_mutex);
779 /*********************************************************************
781 * Function : mark_connection_unused
783 * Description : Gives a remembered connection free for reuse.
786 * 1 : sfd = The socket belonging to the connection in question.
788 * Returns : TRUE => Socket found and marked as unused.
789 * FALSE => Socket not found.
791 *********************************************************************/
792 static int mark_connection_unused(jb_socket sfd)
794 unsigned int slot = 0;
795 int socket_found = FALSE;
797 assert(sfd != JB_INVALID_SOCKET);
799 privoxy_mutex_lock(&connection_reuse_mutex);
801 for (slot = 0; slot < SZ(reusable_connection); slot++)
803 if (reusable_connection[slot].sfd == sfd)
805 assert(reusable_connection[slot].in_use);
807 log_error(LOG_LEVEL_CONNECT,
808 "Marking open socket %d for %s:%d in slot %d as unused.",
809 sfd, reusable_connection[slot].host,
810 reusable_connection[slot].port, slot);
811 reusable_connection[slot].in_use = 0;
812 reusable_connection[slot].timestamp = time(NULL);
817 privoxy_mutex_unlock(&connection_reuse_mutex);
822 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
825 /*********************************************************************
827 * Function : forwarded_connect
829 * Description : Connect to a specified web server, possibly via
830 * a HTTP proxy and/or a SOCKS proxy.
833 * 1 : fwd = the proxies to use when connecting.
834 * 2 : http = the http request and apropos headers
835 * 3 : csp = Current client state (buffers, headers, etc...)
837 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
839 *********************************************************************/
840 jb_socket forwarded_connect(const struct forward_spec * fwd,
841 struct http_request *http,
842 struct client_state *csp)
844 const char * dest_host;
846 jb_socket sfd = JB_INVALID_SOCKET;
848 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
849 sfd = get_reusable_connection(http, fwd);
850 if (JB_INVALID_SOCKET == sfd)
852 log_error(LOG_LEVEL_CONNECT,
853 "No reusable socket for %s:%d found. Opening a new one.",
854 http->host, http->port);
860 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
862 /* Figure out if we need to connect to the web server or a HTTP proxy. */
863 if (fwd->forward_host)
866 dest_host = fwd->forward_host;
867 dest_port = fwd->forward_port;
872 dest_host = http->host;
873 dest_port = http->port;
876 /* Connect, maybe using a SOCKS proxy */
880 sfd = connect_to(dest_host, dest_port, csp);
884 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
887 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
890 /* Should never get here */
891 log_error(LOG_LEVEL_FATAL,
892 "SOCKS4 impossible internal error - bad SOCKS type.");
900 /*********************************************************************
902 * Function : socks4_connect
904 * Description : Connect to the SOCKS server, and connect through
905 * it to the specified server. This handles
906 * all the SOCKS negotiation, and returns a file
907 * descriptor for a socket which can be treated as a
908 * normal (non-SOCKS) socket.
910 * Logged error messages are saved to csp->error_message
911 * and later reused by error_response() for the CGI
912 * message. strdup allocation failures are handled there.
915 * 1 : fwd = Specifies the SOCKS proxy to use.
916 * 2 : target_host = The final server to connect to.
917 * 3 : target_port = The final port to connect to.
918 * 4 : csp = Current client state (buffers, headers, etc...)
920 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
922 *********************************************************************/
923 static jb_socket socks4_connect(const struct forward_spec * fwd,
924 const char * target_host,
926 struct client_state *csp)
928 unsigned int web_server_addr;
929 char buf[BUFFER_SIZE];
930 struct socks_op *c = (struct socks_op *)buf;
931 struct socks_reply *s = (struct socks_reply *)buf;
938 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
940 /* XXX: Shouldn't the config file parser prevent this? */
941 errstr = "NULL gateway host specified.";
945 if (fwd->gateway_port <= 0)
947 errstr = "invalid gateway port specified.";
953 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
954 csp->error_message = strdup(errstr);
956 return(JB_INVALID_SOCKET);
959 /* build a socks request for connection to the web server */
961 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
963 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
968 web_server_addr = resolve_hostname_to_ip(target_host);
969 if (web_server_addr == INADDR_NONE)
971 errstr = "could not resolve target host";
972 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
977 web_server_addr = htonl(web_server_addr);
981 web_server_addr = 0x00000001;
982 n = csiz + strlen(target_host) + 1;
986 errstr = "buffer cbuf too small.";
987 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
992 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
994 * What we forward to the socks4a server should have the
995 * size of socks_op, plus the length of the userid plus
996 * its \0 byte (which we don't have to add because the
997 * first byte of the userid is counted twice as it's also
998 * part of sock_op) minus the padding bytes (which are part
999 * of the userid as well), plus the length of the target_host
1000 * (which is stored csiz bytes after the beginning of the buffer),
1001 * plus another \0 byte.
1003 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
1008 /* Should never get here */
1009 log_error(LOG_LEVEL_FATAL,
1010 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
1012 return(JB_INVALID_SOCKET);
1017 csp->error_message = strdup(errstr);
1018 return(JB_INVALID_SOCKET);
1023 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1024 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1025 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1026 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1027 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1028 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1030 /* pass the request to the socks server */
1031 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1033 if (sfd == JB_INVALID_SOCKET)
1036 * XXX: connect_to should fill in the exact reason.
1037 * Most likely resolving the IP of the forwarder failed.
1039 errstr = "connect_to failed: see logfile for details";
1042 else if (write_socket(sfd, (char *)c, csiz))
1044 errstr = "SOCKS4 negotiation write failed.";
1045 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1049 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1051 errstr = "SOCKS4 negotiation read failed.";
1052 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1059 csp->error_message = strdup(errstr);
1060 return(JB_INVALID_SOCKET);
1065 case SOCKS_REQUEST_GRANTED:
1068 case SOCKS_REQUEST_REJECT:
1069 errstr = "SOCKS request rejected or failed.";
1072 case SOCKS_REQUEST_IDENT_FAILED:
1073 errstr = "SOCKS request rejected because "
1074 "SOCKS server cannot connect to identd on the client.";
1077 case SOCKS_REQUEST_IDENT_CONFLICT:
1078 errstr = "SOCKS request rejected because "
1079 "the client program and identd report "
1080 "different user-ids.";
1085 snprintf(buf, sizeof(buf),
1086 "SOCKS request rejected for reason code %d.", s->cd);
1090 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1091 csp->error_message = strdup(errstr);
1094 return(JB_INVALID_SOCKET);
1098 /*********************************************************************
1100 * Function : translate_socks5_error
1102 * Description : Translates a SOCKS errors to a string.
1105 * 1 : socks_error = The error code to translate.
1107 * Returns : The string translation.
1109 *********************************************************************/
1110 static const char *translate_socks5_error(int socks_error)
1112 switch (socks_error)
1114 /* XXX: these should be more descriptive */
1115 case SOCKS5_REQUEST_FAILED:
1116 return "SOCKS5 request failed";
1117 case SOCKS5_REQUEST_DENIED:
1118 return "SOCKS5 request denied";
1119 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1120 return "SOCKS5 network unreachable";
1121 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1122 return "SOCKS5 host unreachable";
1123 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1124 return "SOCKS5 connection refused";
1125 case SOCKS5_REQUEST_TTL_EXPIRED:
1126 return "SOCKS5 TTL expired";
1127 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1128 return "SOCKS5 client protocol error";
1129 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1130 return "SOCKS5 domain names unsupported";
1131 case SOCKS5_REQUEST_GRANTED:
1132 return "everything's peachy";
1134 return "SOCKS5 negotiation protocol error";
1138 /*********************************************************************
1140 * Function : socks5_connect
1142 * Description : Connect to the SOCKS server, and connect through
1143 * it to the specified server. This handles
1144 * all the SOCKS negotiation, and returns a file
1145 * descriptor for a socket which can be treated as a
1146 * normal (non-SOCKS) socket.
1149 * 1 : fwd = Specifies the SOCKS proxy to use.
1150 * 2 : target_host = The final server to connect to.
1151 * 3 : target_port = The final port to connect to.
1152 * 4 : csp = Current client state (buffers, headers, etc...)
1154 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1156 *********************************************************************/
1157 static jb_socket socks5_connect(const struct forward_spec *fwd,
1158 const char *target_host,
1160 struct client_state *csp)
1165 size_t client_pos = 0;
1166 int server_size = 0;
1169 const char *errstr = NULL;
1171 assert(fwd->gateway_host);
1172 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1174 errstr = "NULL gateway host specified";
1178 if (fwd->gateway_port <= 0)
1181 * XXX: currently this can't happen because in
1182 * case of invalid gateway ports we use the defaults.
1183 * Of course we really shouldn't do that.
1185 errstr = "invalid gateway port specified";
1189 hostlen = strlen(target_host);
1192 errstr = "target host name is longer than 255 characters";
1196 if (fwd->type != SOCKS_5)
1198 /* Should never get here */
1199 log_error(LOG_LEVEL_FATAL,
1200 "SOCKS5 impossible internal error - bad SOCKS type");
1207 assert(errstr != NULL);
1208 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1209 csp->error_message = strdup(errstr);
1210 return(JB_INVALID_SOCKET);
1213 /* pass the request to the socks server */
1214 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1216 if (sfd == JB_INVALID_SOCKET)
1218 errstr = "socks5 server unreachable";
1219 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1220 csp->error_message = strdup(errstr);
1221 return(JB_INVALID_SOCKET);
1225 cbuf[client_pos++] = '\x05'; /* Version */
1226 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1227 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1229 if (write_socket(sfd, cbuf, client_pos))
1231 errstr = "SOCKS5 negotiation write failed";
1232 csp->error_message = strdup(errstr);
1233 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1235 return(JB_INVALID_SOCKET);
1238 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1240 errstr = "SOCKS5 negotiation read failed";
1244 if (!err && (sbuf[0] != '\x05'))
1246 errstr = "SOCKS5 negotiation protocol version error";
1250 if (!err && (sbuf[1] == '\xff'))
1252 errstr = "SOCKS5 authentication required";
1256 if (!err && (sbuf[1] != '\x00'))
1258 errstr = "SOCKS5 negotiation protocol error";
1264 assert(errstr != NULL);
1265 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1266 csp->error_message = strdup(errstr);
1269 return(JB_INVALID_SOCKET);
1273 cbuf[client_pos++] = '\x05'; /* Version */
1274 cbuf[client_pos++] = '\x01'; /* TCP connect */
1275 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1276 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1277 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1278 assert(sizeof(cbuf) - client_pos > 255);
1279 /* Using strncpy because we really want the nul byte padding. */
1280 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1281 client_pos += (hostlen & 0xffu);
1282 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1283 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1285 if (write_socket(sfd, cbuf, client_pos))
1287 errstr = "SOCKS5 negotiation read failed";
1288 csp->error_message = strdup(errstr);
1289 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1292 return(JB_INVALID_SOCKET);
1295 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1296 if (server_size < 3)
1298 errstr = "SOCKS5 negotiation read failed";
1301 else if (server_size > 20)
1303 /* This is somewhat unexpected but doesn't realy matter. */
1304 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1305 "from socks server. Would have accepted up to %d.",
1306 server_size, sizeof(sbuf));
1309 if (!err && (sbuf[0] != '\x05'))
1311 errstr = "SOCKS5 negotiation protocol version error";
1315 if (!err && (sbuf[2] != '\x00'))
1317 errstr = "SOCKS5 negotiation protocol error";
1323 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1327 errstr = translate_socks5_error(sbuf[1]);
1331 assert(errstr != NULL);
1332 csp->error_message = strdup(errstr);
1333 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1337 return(JB_INVALID_SOCKET);