1 const char gateway_rcs[] = "$Id: gateway.c,v 1.36 2008/10/18 19:49:15 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.36 2008/10/18 19:49:15 fabiankeil
38 * - Factor close_unusable_connections() out of
39 * get_reusable_connection() to make sure we really check
40 * all the remembered connections, not just the ones before
41 * the next reusable one.
42 * - Plug two file descriptor leaks. Internally marking
43 * connections as closed doesn't cut it.
45 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
46 * In socket_is_still_usable(), use select()
47 * and FD_ISSET() if poll() isn't available.
49 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
50 * Add preliminary timeout support.
52 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
53 * Fix two gcc44 warnings.
55 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
56 * Fix compiler warning.
58 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
59 * - Factor socket_is_still_usable() out of get_reusable_connection().
60 * - If poll() isn't available, show a warning and assume the socket
63 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
64 * If a remembered connection is no longer usable and
65 * has been marked closed, don't bother checking if the
66 * destination matches.
68 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
69 * Add missing dots for two log messages.
71 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
72 * Flush work-in-progress changes to keep outgoing connections
73 * alive where possible. Incomplete and mostly #ifdef'd out.
75 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
76 * Return only once in forwarded_connect().
78 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
79 * Fix typo in macro name.
81 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
83 * - make the buffers quite a bit smaller.
84 * - properly report "socks5 server unreachable" failures.
85 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
86 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
87 * - log a message if the socks5 server sends more data than expected.
88 * - add some assertions and comments.
90 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
91 * - Fix a compiler warning.
92 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
94 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
95 * Remember the cause of the SOCKS5 error for the CGI message.
97 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
98 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
100 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
101 * Modified patch from Song Weijia (#1762559) to
102 * fix socks requests on big-endian platforms.
104 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
105 * - Use strlcpy() instead of strcpy().
106 * - Use the same buffer for socks requests and socks responses.
107 * - Fix bogus warning about web_server_addr being used uninitialized.
109 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
110 * - Save errors in socks4_connect() to csp->error_message.
111 * - Silence some gcc43 warnings, hopefully the right way.
113 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
114 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
115 * with what was really the latest development (the v_3_0_branch branch)
117 * Revision 1.16 2002/05/12 21:36:29 jongfoster
118 * Correcting function comments
120 * Revision 1.15 2002/03/26 22:29:54 swa
121 * we have a new homepage!
123 * Revision 1.14 2002/03/24 13:25:43 swa
124 * name change related issues
126 * Revision 1.13 2002/03/13 00:29:59 jongfoster
129 * Revision 1.12 2002/03/09 20:03:52 jongfoster
130 * - Making various functions return int rather than size_t.
131 * (Undoing a recent change). Since size_t is unsigned on
132 * Windows, functions like read_socket that return -1 on
133 * error cannot return a size_t.
135 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
136 * crashes, and also frequently caused JB to jump to 100%
137 * CPU and stay there. (Because it thought it had just
138 * read ((unsigned)-1) == 4Gb of data...)
140 * - The signature of write_socket has changed, it now simply
141 * returns success=0/failure=nonzero.
143 * - Trying to get rid of a few warnings --with-debug on
144 * Windows, I've introduced a new type "jb_socket". This is
145 * used for the socket file descriptors. On Windows, this
146 * is SOCKET (a typedef for unsigned). Everywhere else, it's
147 * an int. The error value can't be -1 any more, so it's
148 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
149 * Windows it maps to the #define INVALID_SOCKET.)
151 * - The signature of bind_port has changed.
153 * Revision 1.11 2002/03/08 17:46:04 jongfoster
154 * Fixing int/size_t warnings
156 * Revision 1.10 2002/03/07 03:50:19 oes
157 * - Improved handling of failed DNS lookups
158 * - Fixed compiler warnings
160 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
161 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
162 * threads to call select() simultaneously. So, it's time to do a real, live,
163 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
164 * (native). Both versions will work, but using __OS2__ offers multi-threading.
166 * Revision 1.8 2001/09/13 20:10:12 jongfoster
167 * Fixing missing #include under Windows
169 * Revision 1.7 2001/09/12 17:58:26 steudten
171 * add #include <string.h>
173 * Revision 1.6 2001/09/10 10:41:16 oes
174 * Added #include in.h
176 * Revision 1.5 2001/07/29 18:47:57 jongfoster
177 * Adding missing #include project.h
179 * Revision 1.4 2001/07/24 12:47:06 oes
180 * Applied BeOS support update by Eugenia
182 * Revision 1.3 2001/06/09 10:55:28 jongfoster
183 * Changing BUFSIZ ==> BUFFER_SIZE
185 * Revision 1.2 2001/06/07 23:11:38 jongfoster
186 * Removing gateways[] list - no longer used.
187 * Replacing function pointer in struct gateway with a directly
188 * called function forwarded_connect(), which can do the common
189 * task of deciding whether to connect to the web server or HTTP
191 * Replacing struct gateway with struct forward_spec
192 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
193 * It was a bug which led to the connection being made to the web
194 * server rather than the HTTP proxy, and also a buffer overrun.
196 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
197 * Initial import of version 2.9.3 source tree
200 *********************************************************************/
206 #include <sys/types.h>
209 #include <netinet/in.h>
217 #include <winsock2.h>
218 #endif /* def _WIN32 */
222 #endif /* def __BEOS__ */
226 #endif /* def __OS2__ */
231 #include "jbsockets.h"
233 #include "miscutil.h"
234 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
237 #include <sys/poll.h>
240 #endif /* def __GLIBC__ */
241 #endif /* HAVE_POLL */
242 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
244 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
246 static jb_socket socks4_connect(const struct forward_spec * fwd,
247 const char * target_host,
249 struct client_state *csp);
251 static jb_socket socks5_connect(const struct forward_spec *fwd,
252 const char *target_host,
254 struct client_state *csp);
257 #define SOCKS_REQUEST_GRANTED 90
258 #define SOCKS_REQUEST_REJECT 91
259 #define SOCKS_REQUEST_IDENT_FAILED 92
260 #define SOCKS_REQUEST_IDENT_CONFLICT 93
262 #define SOCKS5_REQUEST_GRANTED 0
263 #define SOCKS5_REQUEST_FAILED 1
264 #define SOCKS5_REQUEST_DENIED 2
265 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
266 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
267 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
268 #define SOCKS5_REQUEST_TTL_EXPIRED 6
269 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
270 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
272 /* structure of a socks client operation */
274 unsigned char vn; /* socks version number */
275 unsigned char cd; /* command code */
276 unsigned char dstport[2]; /* destination port */
277 unsigned char dstip[4]; /* destination address */
278 char userid; /* first byte of userid */
279 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
280 /* more bytes of the userid follow, terminated by a NULL */
283 /* structure of a socks server reply */
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 */
291 static const char socks_userid[] = "anonymous";
293 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
295 #define MAX_REUSABLE_CONNECTIONS 100
296 /* XXX: should be a config option. */
297 #define CONNECTION_KEEP_ALIVE_TIMEOUT 3 * 60
299 struct reusable_connection
314 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
316 static int mark_connection_unused(jb_socket sfd);
317 static void mark_connection_closed(struct reusable_connection *closed_connection);
318 static int socket_is_still_usable(jb_socket sfd);
321 /*********************************************************************
323 * Function : initialize_reusable_connections
325 * Description : Initializes the reusable_connection structures.
326 * Must be called with connection_reuse_mutex locked.
332 *********************************************************************/
333 extern void initialize_reusable_connections(void)
335 unsigned int slot = 0;
337 log_error(LOG_LEVEL_INFO,
338 "Support for 'Connection: keep-alive' is experimental, "
339 "incomplete and known not to work properly in some situations.");
341 for (slot = 0; slot < SZ(reusable_connection); slot++)
343 mark_connection_closed(&reusable_connection[slot]);
346 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
350 /*********************************************************************
352 * Function : remember_connection
354 * Description : Remembers a connection for reuse later on.
357 * 1 : sfd = Open socket to remember.
358 * 2 : http = The destination for the connection.
359 * 3 : fwd = The forwarder settings used.
363 *********************************************************************/
364 void remember_connection(jb_socket sfd, const struct http_request *http,
365 const struct forward_spec *fwd)
367 unsigned int slot = 0;
368 int free_slot_found = FALSE;
370 assert(sfd != JB_INVALID_SOCKET);
372 if (mark_connection_unused(sfd))
377 privoxy_mutex_lock(&connection_reuse_mutex);
379 /* Find free socket slot. */
380 for (slot = 0; slot < SZ(reusable_connection); slot++)
382 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
384 assert(reusable_connection[slot].in_use == 0);
385 log_error(LOG_LEVEL_CONNECT,
386 "Remembering socket %d for %s:%d in slot %d.",
387 sfd, http->host, http->port, slot);
388 free_slot_found = TRUE;
393 if (!free_slot_found)
395 log_error(LOG_LEVEL_CONNECT,
396 "No free slots found to remembering socket for %s:%d. Last slot %d.",
397 http->host, http->port, slot);
398 privoxy_mutex_unlock(&connection_reuse_mutex);
403 assert(NULL != http->host);
404 reusable_connection[slot].host = strdup(http->host);
405 if (NULL == reusable_connection[slot].host)
407 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
409 reusable_connection[slot].sfd = sfd;
410 reusable_connection[slot].port = http->port;
411 reusable_connection[slot].in_use = 0;
412 reusable_connection[slot].timestamp = time(NULL);
415 assert(reusable_connection[slot].gateway_host == NULL);
416 assert(reusable_connection[slot].gateway_port == 0);
417 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
418 assert(reusable_connection[slot].forward_host == NULL);
419 assert(reusable_connection[slot].forward_port == 0);
421 reusable_connection[slot].forwarder_type = fwd->type;
422 if (NULL != fwd->gateway_host)
424 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
425 if (NULL == reusable_connection[slot].gateway_host)
427 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
432 reusable_connection[slot].gateway_host = NULL;
434 reusable_connection[slot].gateway_port = fwd->gateway_port;
436 if (NULL != fwd->forward_host)
438 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
439 if (NULL == reusable_connection[slot].forward_host)
441 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
446 reusable_connection[slot].forward_host = NULL;
448 reusable_connection[slot].forward_port = fwd->forward_port;
450 privoxy_mutex_unlock(&connection_reuse_mutex);
454 /*********************************************************************
456 * Function : mark_connection_closed
458 * Description : Marks a reused connection closed.
459 * Must be called with connection_reuse_mutex locked.
462 * 1 : closed_connection = The connection to mark as closed.
466 *********************************************************************/
467 static void mark_connection_closed(struct reusable_connection *closed_connection)
469 closed_connection->in_use = FALSE;
470 closed_connection->sfd = JB_INVALID_SOCKET;
471 freez(closed_connection->host);
472 closed_connection->port = 0;
473 closed_connection->timestamp = 0;
474 closed_connection->forwarder_type = SOCKS_NONE;
475 freez(closed_connection->gateway_host);
476 closed_connection->gateway_port = 0;
477 freez(closed_connection->forward_host);
478 closed_connection->forward_port = 0;
482 /*********************************************************************
484 * Function : forget_connection
486 * Description : Removes a previously remembered connection from
487 * the list of reusable connections.
490 * 1 : sfd = The socket belonging to the connection in question.
494 *********************************************************************/
495 void forget_connection(jb_socket sfd)
497 unsigned int slot = 0;
499 assert(sfd != JB_INVALID_SOCKET);
501 privoxy_mutex_lock(&connection_reuse_mutex);
503 for (slot = 0; slot < SZ(reusable_connection); slot++)
505 if (reusable_connection[slot].sfd == sfd)
507 assert(reusable_connection[slot].in_use);
509 log_error(LOG_LEVEL_CONNECT,
510 "Forgetting socket %d for %s:%d in slot %d.",
511 sfd, reusable_connection[slot].host,
512 reusable_connection[slot].port, slot);
513 mark_connection_closed(&reusable_connection[slot]);
514 privoxy_mutex_unlock(&connection_reuse_mutex);
520 log_error(LOG_LEVEL_CONNECT,
521 "Socket %d already forgotten or never remembered.", sfd);
523 privoxy_mutex_unlock(&connection_reuse_mutex);
527 /*********************************************************************
529 * Function : connection_destination_matches
531 * Description : Determines whether a remembered connection can
532 * be reused. That is whether the destination and
533 * the forwarding settings match.
536 * 1 : connection = The connection to check.
537 * 2 : http = The destination for the connection.
538 * 3 : fwd = The forwarder settings.
540 * Returns : TRUE for yes, FALSE otherwise.
542 *********************************************************************/
543 static int connection_destination_matches(const struct reusable_connection *connection,
544 const struct http_request *http,
545 const struct forward_spec *fwd)
547 /* XXX: Start of duplicated checks for debugging purposes. */
548 if (strcmpic(connection->host, http->host))
553 if (connection->forwarder_type != fwd->type)
555 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
556 connection->forwarder_type, fwd->type, http->host);
559 if (connection->gateway_port != fwd->gateway_port)
561 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
562 connection->gateway_port, fwd->gateway_port, http->host);
565 if (connection->forward_port != fwd->forward_port)
567 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
568 connection->forward_port, fwd->forward_port, http->host);
571 if (connection->forward_port != fwd->forward_port)
573 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
574 connection->forward_port, fwd->forward_port, http->host);
578 /* XXX: End of duplicated checks for debugging purposes. */
580 if ((connection->forwarder_type != fwd->type)
581 || (connection->gateway_port != fwd->gateway_port)
582 || (connection->forward_port != fwd->forward_port)
583 || (connection->port != http->port))
588 if (( (NULL != connection->gateway_host)
589 && (NULL != fwd->gateway_host)
590 && strcmpic(connection->gateway_host, fwd->gateway_host))
591 && (connection->gateway_host != fwd->gateway_host))
593 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
597 if (( (NULL != connection->forward_host)
598 && (NULL != fwd->forward_host)
599 && strcmpic(connection->forward_host, fwd->forward_host))
600 && (connection->forward_host != fwd->forward_host))
602 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
606 return (!strcmpic(connection->host, http->host));
611 /*********************************************************************
613 * Function : close_unusable_connections
615 * Description : Closes remembered connections that have timed
616 * out or have been closed on the other side.
622 *********************************************************************/
623 static void close_unusable_connections(void)
625 unsigned int slot = 0;
627 for (slot = 0; slot < SZ(reusable_connection); slot++)
629 if (!reusable_connection[slot].in_use
630 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
632 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
634 if (CONNECTION_KEEP_ALIVE_TIMEOUT < time_open)
636 log_error(LOG_LEVEL_CONNECT,
637 "The connection to %s:%d in slot %d timed out. Closing.",
638 reusable_connection[slot].host, reusable_connection[slot].port,
640 close_socket(reusable_connection[slot].sfd);
641 mark_connection_closed(&reusable_connection[slot]);
645 if (!socket_is_still_usable(reusable_connection[slot].sfd))
647 log_error(LOG_LEVEL_CONNECT,
648 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
649 reusable_connection[slot].sfd, reusable_connection[slot].host,
650 reusable_connection[slot].port, slot);
651 close_socket(reusable_connection[slot].sfd);
652 mark_connection_closed(&reusable_connection[slot]);
660 /*********************************************************************
662 * Function : socket_is_still_usable
664 * Description : Decides whether or not an open socket is still usable.
667 * 1 : sfd = The socket to check.
669 * Returns : TRUE for yes, otherwise FALSE.
671 *********************************************************************/
672 static int socket_is_still_usable(jb_socket sfd)
676 struct pollfd poll_fd[1];
678 memset(poll_fd, 0, sizeof(poll_fd));
680 poll_fd[0].events = POLLIN;
682 poll_result = poll(poll_fd, 1, 0);
684 if (-1 != poll_result)
686 return !(poll_fd[0].revents & POLLIN);
690 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
695 struct timeval timeout;
697 int socket_is_alive = 0;
699 memset(&timeout, '\0', sizeof(timeout));
700 /* timeout.tv_usec = 150;*/
701 FD_ZERO(&readable_fds);
702 FD_SET(sfd, &readable_fds);
704 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
707 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
711 * XXX: I'm not sure why !FD_ISSET() works,
712 * but apparently it does.
714 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
716 log_error(LOG_LEVEL_INFO,
717 "Detecting already dead sockets might not work correctly "
718 "on your platform. Anyway, socket %d appears to be %s.",
719 sfd, (socket_is_alive ? "still alive" : "already dead"));
721 return socket_is_alive;
722 #endif /* def HAVE_POLL */
726 /*********************************************************************
728 * Function : get_reusable_connection
730 * Description : Returns an open socket to a previously remembered
731 * open connection (if there is one).
734 * 1 : http = The destination for the connection.
735 * 2 : fwd = The forwarder settings.
737 * Returns : JB_INVALID_SOCKET => No reusable connection found,
738 * otherwise a usable socket.
740 *********************************************************************/
741 static jb_socket get_reusable_connection(const struct http_request *http,
742 const struct forward_spec *fwd)
744 jb_socket sfd = JB_INVALID_SOCKET;
745 unsigned int slot = 0;
747 privoxy_mutex_lock(&connection_reuse_mutex);
749 close_unusable_connections();
751 for (slot = 0; slot < SZ(reusable_connection); slot++)
753 if (!reusable_connection[slot].in_use
754 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
756 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
758 reusable_connection[slot].in_use = TRUE;
759 sfd = reusable_connection[slot].sfd;
760 log_error(LOG_LEVEL_CONNECT,
761 "Found reusable socket %d for %s:%d in slot %d.",
762 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
768 privoxy_mutex_unlock(&connection_reuse_mutex);
775 /*********************************************************************
777 * Function : mark_connection_unused
779 * Description : Gives a remembered connection free for reuse.
782 * 1 : sfd = The socket belonging to the connection in question.
784 * Returns : TRUE => Socket found and marked as unused.
785 * FALSE => Socket not found.
787 *********************************************************************/
788 static int mark_connection_unused(jb_socket sfd)
790 unsigned int slot = 0;
791 int socket_found = FALSE;
793 assert(sfd != JB_INVALID_SOCKET);
795 privoxy_mutex_lock(&connection_reuse_mutex);
797 for (slot = 0; slot < SZ(reusable_connection); slot++)
799 if (reusable_connection[slot].sfd == sfd)
801 assert(reusable_connection[slot].in_use);
803 log_error(LOG_LEVEL_CONNECT,
804 "Marking open socket %d for %s:%d in slot %d as unused.",
805 sfd, reusable_connection[slot].host,
806 reusable_connection[slot].port, slot);
807 reusable_connection[slot].in_use = 0;
808 reusable_connection[slot].timestamp = time(NULL);
813 privoxy_mutex_unlock(&connection_reuse_mutex);
818 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
821 /*********************************************************************
823 * Function : forwarded_connect
825 * Description : Connect to a specified web server, possibly via
826 * a HTTP proxy and/or a SOCKS proxy.
829 * 1 : fwd = the proxies to use when connecting.
830 * 2 : http = the http request and apropos headers
831 * 3 : csp = Current client state (buffers, headers, etc...)
833 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
835 *********************************************************************/
836 jb_socket forwarded_connect(const struct forward_spec * fwd,
837 struct http_request *http,
838 struct client_state *csp)
840 const char * dest_host;
842 jb_socket sfd = JB_INVALID_SOCKET;
844 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
845 sfd = get_reusable_connection(http, fwd);
846 if (JB_INVALID_SOCKET == sfd)
848 log_error(LOG_LEVEL_CONNECT,
849 "No reusable socket for %s:%d found. Opening a new one.",
850 http->host, http->port);
856 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
858 /* Figure out if we need to connect to the web server or a HTTP proxy. */
859 if (fwd->forward_host)
862 dest_host = fwd->forward_host;
863 dest_port = fwd->forward_port;
868 dest_host = http->host;
869 dest_port = http->port;
872 /* Connect, maybe using a SOCKS proxy */
876 sfd = connect_to(dest_host, dest_port, csp);
880 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
883 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
886 /* Should never get here */
887 log_error(LOG_LEVEL_FATAL,
888 "SOCKS4 impossible internal error - bad SOCKS type.");
896 /*********************************************************************
898 * Function : socks4_connect
900 * Description : Connect to the SOCKS server, and connect through
901 * it to the specified server. This handles
902 * all the SOCKS negotiation, and returns a file
903 * descriptor for a socket which can be treated as a
904 * normal (non-SOCKS) socket.
906 * Logged error messages are saved to csp->error_message
907 * and later reused by error_response() for the CGI
908 * message. strdup allocation failures are handled there.
911 * 1 : fwd = Specifies the SOCKS proxy to use.
912 * 2 : target_host = The final server to connect to.
913 * 3 : target_port = The final port to connect to.
914 * 4 : csp = Current client state (buffers, headers, etc...)
916 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
918 *********************************************************************/
919 static jb_socket socks4_connect(const struct forward_spec * fwd,
920 const char * target_host,
922 struct client_state *csp)
924 unsigned int web_server_addr;
925 char buf[BUFFER_SIZE];
926 struct socks_op *c = (struct socks_op *)buf;
927 struct socks_reply *s = (struct socks_reply *)buf;
934 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
936 /* XXX: Shouldn't the config file parser prevent this? */
937 errstr = "NULL gateway host specified.";
941 if (fwd->gateway_port <= 0)
943 errstr = "invalid gateway port specified.";
949 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
950 csp->error_message = strdup(errstr);
952 return(JB_INVALID_SOCKET);
955 /* build a socks request for connection to the web server */
957 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
959 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
964 web_server_addr = resolve_hostname_to_ip(target_host);
965 if (web_server_addr == INADDR_NONE)
967 errstr = "could not resolve target host";
968 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
973 web_server_addr = htonl(web_server_addr);
977 web_server_addr = 0x00000001;
978 n = csiz + strlen(target_host) + 1;
982 errstr = "buffer cbuf too small.";
983 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
988 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
990 * What we forward to the socks4a server should have the
991 * size of socks_op, plus the length of the userid plus
992 * its \0 byte (which we don't have to add because the
993 * first byte of the userid is counted twice as it's also
994 * part of sock_op) minus the padding bytes (which are part
995 * of the userid as well), plus the length of the target_host
996 * (which is stored csiz bytes after the beginning of the buffer),
997 * plus another \0 byte.
999 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
1004 /* Should never get here */
1005 log_error(LOG_LEVEL_FATAL,
1006 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
1008 return(JB_INVALID_SOCKET);
1013 csp->error_message = strdup(errstr);
1014 return(JB_INVALID_SOCKET);
1019 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1020 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1021 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1022 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1023 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1024 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1026 /* pass the request to the socks server */
1027 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1029 if (sfd == JB_INVALID_SOCKET)
1032 * XXX: connect_to should fill in the exact reason.
1033 * Most likely resolving the IP of the forwarder failed.
1035 errstr = "connect_to failed: see logfile for details";
1038 else if (write_socket(sfd, (char *)c, csiz))
1040 errstr = "SOCKS4 negotiation write failed.";
1041 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1045 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1047 errstr = "SOCKS4 negotiation read failed.";
1048 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1055 csp->error_message = strdup(errstr);
1056 return(JB_INVALID_SOCKET);
1061 case SOCKS_REQUEST_GRANTED:
1064 case SOCKS_REQUEST_REJECT:
1065 errstr = "SOCKS request rejected or failed.";
1068 case SOCKS_REQUEST_IDENT_FAILED:
1069 errstr = "SOCKS request rejected because "
1070 "SOCKS server cannot connect to identd on the client.";
1073 case SOCKS_REQUEST_IDENT_CONFLICT:
1074 errstr = "SOCKS request rejected because "
1075 "the client program and identd report "
1076 "different user-ids.";
1081 snprintf(buf, sizeof(buf),
1082 "SOCKS request rejected for reason code %d.", s->cd);
1086 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1087 csp->error_message = strdup(errstr);
1090 return(JB_INVALID_SOCKET);
1094 /*********************************************************************
1096 * Function : translate_socks5_error
1098 * Description : Translates a SOCKS errors to a string.
1101 * 1 : socks_error = The error code to translate.
1103 * Returns : The string translation.
1105 *********************************************************************/
1106 static const char *translate_socks5_error(int socks_error)
1108 switch (socks_error)
1110 /* XXX: these should be more descriptive */
1111 case SOCKS5_REQUEST_FAILED:
1112 return "SOCKS5 request failed";
1113 case SOCKS5_REQUEST_DENIED:
1114 return "SOCKS5 request denied";
1115 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1116 return "SOCKS5 network unreachable";
1117 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1118 return "SOCKS5 host unreachable";
1119 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1120 return "SOCKS5 connection refused";
1121 case SOCKS5_REQUEST_TTL_EXPIRED:
1122 return "SOCKS5 TTL expired";
1123 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1124 return "SOCKS5 client protocol error";
1125 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1126 return "SOCKS5 domain names unsupported";
1127 case SOCKS5_REQUEST_GRANTED:
1128 return "everything's peachy";
1130 return "SOCKS5 negotiation protocol error";
1134 /*********************************************************************
1136 * Function : socks5_connect
1138 * Description : Connect to the SOCKS server, and connect through
1139 * it to the specified server. This handles
1140 * all the SOCKS negotiation, and returns a file
1141 * descriptor for a socket which can be treated as a
1142 * normal (non-SOCKS) socket.
1145 * 1 : fwd = Specifies the SOCKS proxy to use.
1146 * 2 : target_host = The final server to connect to.
1147 * 3 : target_port = The final port to connect to.
1148 * 4 : csp = Current client state (buffers, headers, etc...)
1150 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1152 *********************************************************************/
1153 static jb_socket socks5_connect(const struct forward_spec *fwd,
1154 const char *target_host,
1156 struct client_state *csp)
1161 size_t client_pos = 0;
1162 int server_size = 0;
1165 const char *errstr = NULL;
1167 assert(fwd->gateway_host);
1168 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1170 errstr = "NULL gateway host specified";
1174 if (fwd->gateway_port <= 0)
1177 * XXX: currently this can't happen because in
1178 * case of invalid gateway ports we use the defaults.
1179 * Of course we really shouldn't do that.
1181 errstr = "invalid gateway port specified";
1185 hostlen = strlen(target_host);
1188 errstr = "target host name is longer than 255 characters";
1192 if (fwd->type != SOCKS_5)
1194 /* Should never get here */
1195 log_error(LOG_LEVEL_FATAL,
1196 "SOCKS5 impossible internal error - bad SOCKS type");
1203 assert(errstr != NULL);
1204 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1205 csp->error_message = strdup(errstr);
1206 return(JB_INVALID_SOCKET);
1209 /* pass the request to the socks server */
1210 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1212 if (sfd == JB_INVALID_SOCKET)
1214 errstr = "socks5 server unreachable";
1215 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1216 csp->error_message = strdup(errstr);
1217 return(JB_INVALID_SOCKET);
1221 cbuf[client_pos++] = '\x05'; /* Version */
1222 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1223 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1225 if (write_socket(sfd, cbuf, client_pos))
1227 errstr = "SOCKS5 negotiation write failed";
1228 csp->error_message = strdup(errstr);
1229 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1231 return(JB_INVALID_SOCKET);
1234 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1236 errstr = "SOCKS5 negotiation read failed";
1240 if (!err && (sbuf[0] != '\x05'))
1242 errstr = "SOCKS5 negotiation protocol version error";
1246 if (!err && (sbuf[1] == '\xff'))
1248 errstr = "SOCKS5 authentication required";
1252 if (!err && (sbuf[1] != '\x00'))
1254 errstr = "SOCKS5 negotiation protocol error";
1260 assert(errstr != NULL);
1261 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1262 csp->error_message = strdup(errstr);
1265 return(JB_INVALID_SOCKET);
1269 cbuf[client_pos++] = '\x05'; /* Version */
1270 cbuf[client_pos++] = '\x01'; /* TCP connect */
1271 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1272 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1273 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1274 assert(sizeof(cbuf) - client_pos > 255);
1275 /* Using strncpy because we really want the nul byte padding. */
1276 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1277 client_pos += (hostlen & 0xffu);
1278 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1279 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1281 if (write_socket(sfd, cbuf, client_pos))
1283 errstr = "SOCKS5 negotiation read failed";
1284 csp->error_message = strdup(errstr);
1285 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1288 return(JB_INVALID_SOCKET);
1291 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1292 if (server_size < 3)
1294 errstr = "SOCKS5 negotiation read failed";
1297 else if (server_size > 20)
1299 /* This is somewhat unexpected but doesn't realy matter. */
1300 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1301 "from socks server. Would have accepted up to %d.",
1302 server_size, sizeof(sbuf));
1305 if (!err && (sbuf[0] != '\x05'))
1307 errstr = "SOCKS5 negotiation protocol version error";
1311 if (!err && (sbuf[2] != '\x00'))
1313 errstr = "SOCKS5 negotiation protocol error";
1319 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1323 errstr = translate_socks5_error(sbuf[1]);
1327 assert(errstr != NULL);
1328 csp->error_message = strdup(errstr);
1329 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1333 return(JB_INVALID_SOCKET);