1 const char gateway_rcs[] = "$Id: gateway.c,v 1.49 2009/05/10 10:12:30 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-2009 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.49 2009/05/10 10:12:30 fabiankeil
38 * Initial keep-alive support for the client socket.
39 * Temporarily disable the server-side-only keep-alive code.
41 * Revision 1.48 2009/02/13 17:20:36 fabiankeil
42 * Reword keep-alive support warning and only show
43 * it #if !defined(HAVE_POLL) && !defined(_WIN32).
45 * Revision 1.47 2008/12/24 17:06:19 fabiankeil
46 * Keep a thread around to timeout alive connections
47 * even if no new requests are coming in.
49 * Revision 1.46 2008/12/13 11:07:23 fabiankeil
50 * Remove duplicated debugging checks
51 * in connection_destination_matches().
53 * Revision 1.45 2008/12/04 18:17:07 fabiankeil
54 * Fix some cparser warnings.
56 * Revision 1.44 2008/11/22 11:54:04 fabiankeil
57 * Move log message around to include the socket number.
59 * Revision 1.43 2008/11/13 09:15:51 fabiankeil
60 * Make keep_alive_timeout static.
62 * Revision 1.42 2008/11/13 09:08:42 fabiankeil
63 * Add new config option: keep-alive-timeout.
65 * Revision 1.41 2008/11/08 15:29:58 fabiankeil
66 * Unify two debug messages.
68 * Revision 1.40 2008/11/08 15:14:05 fabiankeil
69 * Fix duplicated debugging check.
71 * Revision 1.39 2008/10/25 11:33:01 fabiankeil
72 * Remove already out-commented line left over from debugging.
74 * Revision 1.38 2008/10/24 17:33:00 fabiankeil
75 * - Tone the "keep-alive support is experimental" warning
76 * down a bit as hackish 0-chunk detection has been
77 * implemented recently.
78 * - Only show the "ndef HAVE_POLL" warning once on start-up.
80 * Revision 1.37 2008/10/23 17:40:53 fabiankeil
81 * Fix forget_connection() and mark_connection_unused(),
82 * which would both under certain circumstances access
83 * reusable_connection[MAX_REUSABLE_CONNECTIONS]. Oops.
85 * Revision 1.36 2008/10/18 19:49:15 fabiankeil
86 * - Factor close_unusable_connections() out of
87 * get_reusable_connection() to make sure we really check
88 * all the remembered connections, not just the ones before
89 * the next reusable one.
90 * - Plug two file descriptor leaks. Internally marking
91 * connections as closed doesn't cut it.
93 * Revision 1.35 2008/10/17 17:12:01 fabiankeil
94 * In socket_is_still_usable(), use select()
95 * and FD_ISSET() if poll() isn't available.
97 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
98 * Add preliminary timeout support.
100 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
101 * Fix two gcc44 warnings.
103 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
104 * Fix compiler warning.
106 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
107 * - Factor socket_is_still_usable() out of get_reusable_connection().
108 * - If poll() isn't available, show a warning and assume the socket
111 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
112 * If a remembered connection is no longer usable and
113 * has been marked closed, don't bother checking if the
114 * destination matches.
116 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
117 * Add missing dots for two log messages.
119 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
120 * Flush work-in-progress changes to keep outgoing connections
121 * alive where possible. Incomplete and mostly #ifdef'd out.
123 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
124 * Return only once in forwarded_connect().
126 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
127 * Fix typo in macro name.
129 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
131 * - make the buffers quite a bit smaller.
132 * - properly report "socks5 server unreachable" failures.
133 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
134 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
135 * - log a message if the socks5 server sends more data than expected.
136 * - add some assertions and comments.
138 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
139 * - Fix a compiler warning.
140 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
142 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
143 * Remember the cause of the SOCKS5 error for the CGI message.
145 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
146 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
148 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
149 * Modified patch from Song Weijia (#1762559) to
150 * fix socks requests on big-endian platforms.
152 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
153 * - Use strlcpy() instead of strcpy().
154 * - Use the same buffer for socks requests and socks responses.
155 * - Fix bogus warning about web_server_addr being used uninitialized.
157 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
158 * - Save errors in socks4_connect() to csp->error_message.
159 * - Silence some gcc43 warnings, hopefully the right way.
161 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
162 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
163 * with what was really the latest development (the v_3_0_branch branch)
165 * Revision 1.16 2002/05/12 21:36:29 jongfoster
166 * Correcting function comments
168 * Revision 1.15 2002/03/26 22:29:54 swa
169 * we have a new homepage!
171 * Revision 1.14 2002/03/24 13:25:43 swa
172 * name change related issues
174 * Revision 1.13 2002/03/13 00:29:59 jongfoster
177 * Revision 1.12 2002/03/09 20:03:52 jongfoster
178 * - Making various functions return int rather than size_t.
179 * (Undoing a recent change). Since size_t is unsigned on
180 * Windows, functions like read_socket that return -1 on
181 * error cannot return a size_t.
183 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
184 * crashes, and also frequently caused JB to jump to 100%
185 * CPU and stay there. (Because it thought it had just
186 * read ((unsigned)-1) == 4Gb of data...)
188 * - The signature of write_socket has changed, it now simply
189 * returns success=0/failure=nonzero.
191 * - Trying to get rid of a few warnings --with-debug on
192 * Windows, I've introduced a new type "jb_socket". This is
193 * used for the socket file descriptors. On Windows, this
194 * is SOCKET (a typedef for unsigned). Everywhere else, it's
195 * an int. The error value can't be -1 any more, so it's
196 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
197 * Windows it maps to the #define INVALID_SOCKET.)
199 * - The signature of bind_port has changed.
201 * Revision 1.11 2002/03/08 17:46:04 jongfoster
202 * Fixing int/size_t warnings
204 * Revision 1.10 2002/03/07 03:50:19 oes
205 * - Improved handling of failed DNS lookups
206 * - Fixed compiler warnings
208 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
209 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
210 * threads to call select() simultaneously. So, it's time to do a real, live,
211 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
212 * (native). Both versions will work, but using __OS2__ offers multi-threading.
214 * Revision 1.8 2001/09/13 20:10:12 jongfoster
215 * Fixing missing #include under Windows
217 * Revision 1.7 2001/09/12 17:58:26 steudten
219 * add #include <string.h>
221 * Revision 1.6 2001/09/10 10:41:16 oes
222 * Added #include in.h
224 * Revision 1.5 2001/07/29 18:47:57 jongfoster
225 * Adding missing #include project.h
227 * Revision 1.4 2001/07/24 12:47:06 oes
228 * Applied BeOS support update by Eugenia
230 * Revision 1.3 2001/06/09 10:55:28 jongfoster
231 * Changing BUFSIZ ==> BUFFER_SIZE
233 * Revision 1.2 2001/06/07 23:11:38 jongfoster
234 * Removing gateways[] list - no longer used.
235 * Replacing function pointer in struct gateway with a directly
236 * called function forwarded_connect(), which can do the common
237 * task of deciding whether to connect to the web server or HTTP
239 * Replacing struct gateway with struct forward_spec
240 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
241 * It was a bug which led to the connection being made to the web
242 * server rather than the HTTP proxy, and also a buffer overrun.
244 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
245 * Initial import of version 2.9.3 source tree
248 *********************************************************************/
254 #include <sys/types.h>
257 #include <netinet/in.h>
265 #include <winsock2.h>
266 #endif /* def _WIN32 */
270 #endif /* def __BEOS__ */
274 #endif /* def __OS2__ */
279 #include "jbsockets.h"
281 #include "miscutil.h"
282 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
285 #include <sys/poll.h>
288 #endif /* def __GLIBC__ */
289 #endif /* HAVE_POLL */
290 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
292 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
294 static jb_socket socks4_connect(const struct forward_spec * fwd,
295 const char * target_host,
297 struct client_state *csp);
299 static jb_socket socks5_connect(const struct forward_spec *fwd,
300 const char *target_host,
302 struct client_state *csp);
305 #define SOCKS_REQUEST_GRANTED 90
306 #define SOCKS_REQUEST_REJECT 91
307 #define SOCKS_REQUEST_IDENT_FAILED 92
308 #define SOCKS_REQUEST_IDENT_CONFLICT 93
310 #define SOCKS5_REQUEST_GRANTED 0
311 #define SOCKS5_REQUEST_FAILED 1
312 #define SOCKS5_REQUEST_DENIED 2
313 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
314 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
315 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
316 #define SOCKS5_REQUEST_TTL_EXPIRED 6
317 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
318 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
320 /* structure of a socks client operation */
322 unsigned char vn; /* socks version number */
323 unsigned char cd; /* command code */
324 unsigned char dstport[2]; /* destination port */
325 unsigned char dstip[4]; /* destination address */
326 char userid; /* first byte of userid */
327 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
328 /* more bytes of the userid follow, terminated by a NULL */
331 /* structure of a socks server reply */
333 unsigned char vn; /* socks version number */
334 unsigned char cd; /* command code */
335 unsigned char dstport[2]; /* destination port */
336 unsigned char dstip[4]; /* destination address */
339 static const char socks_userid[] = "anonymous";
341 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
343 #define MAX_REUSABLE_CONNECTIONS 100
344 static int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
346 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
347 static int mark_connection_unused(jb_socket sfd);
349 /*********************************************************************
351 * Function : initialize_reusable_connections
353 * Description : Initializes the reusable_connection structures.
354 * Must be called with connection_reuse_mutex locked.
360 *********************************************************************/
361 extern void initialize_reusable_connections(void)
363 unsigned int slot = 0;
365 #if !defined(HAVE_POLL) && !defined(_WIN32)
366 log_error(LOG_LEVEL_INFO,
367 "Detecting already dead connections might not work "
368 "correctly on your platform. In case of problems, "
369 "unset the keep-alive-timeout option.");
372 for (slot = 0; slot < SZ(reusable_connection); slot++)
374 mark_connection_closed(&reusable_connection[slot]);
377 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
381 /*********************************************************************
383 * Function : remember_connection
385 * Description : Remembers a connection for reuse later on.
388 * 1 : sfd = Open socket to remember.
389 * 2 : http = The destination for the connection.
390 * 3 : fwd = The forwarder settings used.
394 *********************************************************************/
395 void remember_connection(jb_socket sfd, const struct http_request *http,
396 const struct forward_spec *fwd)
398 unsigned int slot = 0;
399 int free_slot_found = FALSE;
401 assert(sfd != JB_INVALID_SOCKET);
403 if (mark_connection_unused(sfd))
408 privoxy_mutex_lock(&connection_reuse_mutex);
410 /* Find free socket slot. */
411 for (slot = 0; slot < SZ(reusable_connection); slot++)
413 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
415 assert(reusable_connection[slot].in_use == 0);
416 log_error(LOG_LEVEL_CONNECT,
417 "Remembering socket %d for %s:%d in slot %d.",
418 sfd, http->host, http->port, slot);
419 free_slot_found = TRUE;
424 if (!free_slot_found)
426 log_error(LOG_LEVEL_CONNECT,
427 "No free slots found to remembering socket for %s:%d. Last slot %d.",
428 http->host, http->port, slot);
429 privoxy_mutex_unlock(&connection_reuse_mutex);
434 assert(NULL != http->host);
435 reusable_connection[slot].host = strdup(http->host);
436 if (NULL == reusable_connection[slot].host)
438 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
440 reusable_connection[slot].sfd = sfd;
441 reusable_connection[slot].port = http->port;
442 reusable_connection[slot].in_use = 0;
443 reusable_connection[slot].timestamp = time(NULL);
446 assert(reusable_connection[slot].gateway_host == NULL);
447 assert(reusable_connection[slot].gateway_port == 0);
448 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
449 assert(reusable_connection[slot].forward_host == NULL);
450 assert(reusable_connection[slot].forward_port == 0);
452 reusable_connection[slot].forwarder_type = fwd->type;
453 if (NULL != fwd->gateway_host)
455 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
456 if (NULL == reusable_connection[slot].gateway_host)
458 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
463 reusable_connection[slot].gateway_host = NULL;
465 reusable_connection[slot].gateway_port = fwd->gateway_port;
467 if (NULL != fwd->forward_host)
469 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
470 if (NULL == reusable_connection[slot].forward_host)
472 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
477 reusable_connection[slot].forward_host = NULL;
479 reusable_connection[slot].forward_port = fwd->forward_port;
481 privoxy_mutex_unlock(&connection_reuse_mutex);
485 /*********************************************************************
487 * Function : mark_connection_closed
489 * Description : Marks a reused connection closed.
492 * 1 : closed_connection = The connection to mark as closed.
496 *********************************************************************/
497 void mark_connection_closed(struct reusable_connection *closed_connection)
499 closed_connection->in_use = FALSE;
500 closed_connection->sfd = JB_INVALID_SOCKET;
501 freez(closed_connection->host);
502 closed_connection->port = 0;
503 closed_connection->timestamp = 0;
504 closed_connection->forwarder_type = SOCKS_NONE;
505 freez(closed_connection->gateway_host);
506 closed_connection->gateway_port = 0;
507 freez(closed_connection->forward_host);
508 closed_connection->forward_port = 0;
512 /*********************************************************************
514 * Function : forget_connection
516 * Description : Removes a previously remembered connection from
517 * the list of reusable connections.
520 * 1 : sfd = The socket belonging to the connection in question.
524 *********************************************************************/
525 void forget_connection(jb_socket sfd)
527 unsigned int slot = 0;
529 assert(sfd != JB_INVALID_SOCKET);
531 privoxy_mutex_lock(&connection_reuse_mutex);
533 for (slot = 0; slot < SZ(reusable_connection); slot++)
535 if (reusable_connection[slot].sfd == sfd)
537 assert(reusable_connection[slot].in_use);
539 log_error(LOG_LEVEL_CONNECT,
540 "Forgetting socket %d for %s:%d in slot %d.",
541 sfd, reusable_connection[slot].host,
542 reusable_connection[slot].port, slot);
543 mark_connection_closed(&reusable_connection[slot]);
544 privoxy_mutex_unlock(&connection_reuse_mutex);
550 log_error(LOG_LEVEL_CONNECT,
551 "Socket %d already forgotten or never remembered.", sfd);
553 privoxy_mutex_unlock(&connection_reuse_mutex);
557 /*********************************************************************
559 * Function : connection_destination_matches
561 * Description : Determines whether a remembered connection can
562 * be reused. That is, whether the destination and
563 * the forwarding settings match.
566 * 1 : connection = The connection to check.
567 * 2 : http = The destination for the connection.
568 * 3 : fwd = The forwarder settings.
570 * Returns : TRUE for yes, FALSE otherwise.
572 *********************************************************************/
573 int connection_destination_matches(const struct reusable_connection *connection,
574 const struct http_request *http,
575 const struct forward_spec *fwd)
577 if ((connection->forwarder_type != fwd->type)
578 || (connection->gateway_port != fwd->gateway_port)
579 || (connection->forward_port != fwd->forward_port)
580 || (connection->port != http->port))
585 if (( (NULL != connection->gateway_host)
586 && (NULL != fwd->gateway_host)
587 && strcmpic(connection->gateway_host, fwd->gateway_host))
588 && (connection->gateway_host != fwd->gateway_host))
590 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
594 if (( (NULL != connection->forward_host)
595 && (NULL != fwd->forward_host)
596 && strcmpic(connection->forward_host, fwd->forward_host))
597 && (connection->forward_host != fwd->forward_host))
599 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
603 return (!strcmpic(connection->host, http->host));
608 /*********************************************************************
610 * Function : close_unusable_connections
612 * Description : Closes remembered connections that have timed
613 * out or have been closed on the other side.
617 * Returns : Number of connections that are still alive.
619 *********************************************************************/
620 int close_unusable_connections(void)
622 unsigned int slot = 0;
623 int connections_alive = 0;
625 privoxy_mutex_lock(&connection_reuse_mutex);
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 (keep_alive_timeout < time_open)
636 log_error(LOG_LEVEL_CONNECT,
637 "The connection to %s:%d in slot %d timed out. "
638 "Closing socket %d. Timeout is: %d.",
639 reusable_connection[slot].host,
640 reusable_connection[slot].port, slot,
641 reusable_connection[slot].sfd, keep_alive_timeout);
642 close_socket(reusable_connection[slot].sfd);
643 mark_connection_closed(&reusable_connection[slot]);
645 else if (!socket_is_still_usable(reusable_connection[slot].sfd))
647 log_error(LOG_LEVEL_CONNECT,
648 "The connection to %s:%d in slot %d is no longer usable. "
649 "Closing socket %d.", reusable_connection[slot].host,
650 reusable_connection[slot].port, slot,
651 reusable_connection[slot].sfd);
652 close_socket(reusable_connection[slot].sfd);
653 mark_connection_closed(&reusable_connection[slot]);
662 privoxy_mutex_unlock(&connection_reuse_mutex);
664 return connections_alive;
669 /*********************************************************************
671 * Function : get_reusable_connection
673 * Description : Returns an open socket to a previously remembered
674 * open connection (if there is one).
677 * 1 : http = The destination for the connection.
678 * 2 : fwd = The forwarder settings.
680 * Returns : JB_INVALID_SOCKET => No reusable connection found,
681 * otherwise a usable socket.
683 *********************************************************************/
684 static jb_socket get_reusable_connection(const struct http_request *http,
685 const struct forward_spec *fwd)
687 jb_socket sfd = JB_INVALID_SOCKET;
688 unsigned int slot = 0;
690 close_unusable_connections();
692 privoxy_mutex_lock(&connection_reuse_mutex);
694 for (slot = 0; slot < SZ(reusable_connection); slot++)
696 if (!reusable_connection[slot].in_use
697 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
699 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
701 reusable_connection[slot].in_use = TRUE;
702 sfd = reusable_connection[slot].sfd;
703 log_error(LOG_LEVEL_CONNECT,
704 "Found reusable socket %d for %s:%d in slot %d.",
705 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
711 privoxy_mutex_unlock(&connection_reuse_mutex);
718 /*********************************************************************
720 * Function : mark_connection_unused
722 * Description : Gives a remembered connection free for reuse.
725 * 1 : sfd = The socket belonging to the connection in question.
727 * Returns : TRUE => Socket found and marked as unused.
728 * FALSE => Socket not found.
730 *********************************************************************/
731 static int mark_connection_unused(jb_socket sfd)
733 unsigned int slot = 0;
734 int socket_found = FALSE;
736 assert(sfd != JB_INVALID_SOCKET);
738 privoxy_mutex_lock(&connection_reuse_mutex);
740 for (slot = 0; slot < SZ(reusable_connection); slot++)
742 if (reusable_connection[slot].sfd == sfd)
744 assert(reusable_connection[slot].in_use);
746 log_error(LOG_LEVEL_CONNECT,
747 "Marking open socket %d for %s:%d in slot %d as unused.",
748 sfd, reusable_connection[slot].host,
749 reusable_connection[slot].port, slot);
750 reusable_connection[slot].in_use = 0;
751 reusable_connection[slot].timestamp = time(NULL);
756 privoxy_mutex_unlock(&connection_reuse_mutex);
763 /*********************************************************************
765 * Function : set_keep_alive_timeout
767 * Description : Sets the timeout after which open
768 * connections will no longer be reused.
771 * 1 : timeout = The timeout in seconds.
775 *********************************************************************/
776 void set_keep_alive_timeout(int timeout)
778 keep_alive_timeout = timeout;
780 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
783 /*********************************************************************
785 * Function : forwarded_connect
787 * Description : Connect to a specified web server, possibly via
788 * a HTTP proxy and/or a SOCKS proxy.
791 * 1 : fwd = the proxies to use when connecting.
792 * 2 : http = the http request and apropos headers
793 * 3 : csp = Current client state (buffers, headers, etc...)
795 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
797 *********************************************************************/
798 jb_socket forwarded_connect(const struct forward_spec * fwd,
799 struct http_request *http,
800 struct client_state *csp)
802 const char * dest_host;
804 jb_socket sfd = JB_INVALID_SOCKET;
806 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
807 if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING))
809 sfd = get_reusable_connection(http, fwd);
810 if (JB_INVALID_SOCKET != sfd)
815 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
817 /* Figure out if we need to connect to the web server or a HTTP proxy. */
818 if (fwd->forward_host)
821 dest_host = fwd->forward_host;
822 dest_port = fwd->forward_port;
827 dest_host = http->host;
828 dest_port = http->port;
831 /* Connect, maybe using a SOCKS proxy */
835 sfd = connect_to(dest_host, dest_port, csp);
839 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
842 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
845 /* Should never get here */
846 log_error(LOG_LEVEL_FATAL,
847 "SOCKS4 impossible internal error - bad SOCKS type.");
850 if (JB_INVALID_SOCKET != sfd)
852 log_error(LOG_LEVEL_CONNECT,
853 "Created new connection to %s:%d on socket %d.",
854 http->host, http->port, sfd);
862 /*********************************************************************
864 * Function : socks4_connect
866 * Description : Connect to the SOCKS server, and connect through
867 * it to the specified server. This handles
868 * all the SOCKS negotiation, and returns a file
869 * descriptor for a socket which can be treated as a
870 * normal (non-SOCKS) socket.
872 * Logged error messages are saved to csp->error_message
873 * and later reused by error_response() for the CGI
874 * message. strdup allocation failures are handled there.
877 * 1 : fwd = Specifies the SOCKS proxy to use.
878 * 2 : target_host = The final server to connect to.
879 * 3 : target_port = The final port to connect to.
880 * 4 : csp = Current client state (buffers, headers, etc...)
882 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
884 *********************************************************************/
885 static jb_socket socks4_connect(const struct forward_spec * fwd,
886 const char * target_host,
888 struct client_state *csp)
890 unsigned int web_server_addr;
891 char buf[BUFFER_SIZE];
892 struct socks_op *c = (struct socks_op *)buf;
893 struct socks_reply *s = (struct socks_reply *)buf;
900 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
902 /* XXX: Shouldn't the config file parser prevent this? */
903 errstr = "NULL gateway host specified.";
907 if (fwd->gateway_port <= 0)
909 errstr = "invalid gateway port specified.";
915 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
916 csp->error_message = strdup(errstr);
918 return(JB_INVALID_SOCKET);
921 /* build a socks request for connection to the web server */
923 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
925 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
930 web_server_addr = resolve_hostname_to_ip(target_host);
931 if (web_server_addr == INADDR_NONE)
933 errstr = "could not resolve target host";
934 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
939 web_server_addr = htonl(web_server_addr);
943 web_server_addr = 0x00000001;
944 n = csiz + strlen(target_host) + 1;
948 errstr = "buffer cbuf too small.";
949 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
954 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
956 * What we forward to the socks4a server should have the
957 * size of socks_op, plus the length of the userid plus
958 * its \0 byte (which we don't have to add because the
959 * first byte of the userid is counted twice as it's also
960 * part of sock_op) minus the padding bytes (which are part
961 * of the userid as well), plus the length of the target_host
962 * (which is stored csiz bytes after the beginning of the buffer),
963 * plus another \0 byte.
965 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
970 /* Should never get here */
971 log_error(LOG_LEVEL_FATAL,
972 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
974 return(JB_INVALID_SOCKET);
979 csp->error_message = strdup(errstr);
980 return(JB_INVALID_SOCKET);
985 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
986 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
987 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
988 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
989 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
990 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
992 /* pass the request to the socks server */
993 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
995 if (sfd == JB_INVALID_SOCKET)
998 * XXX: connect_to should fill in the exact reason.
999 * Most likely resolving the IP of the forwarder failed.
1001 errstr = "connect_to failed: see logfile for details";
1004 else if (write_socket(sfd, (char *)c, csiz))
1006 errstr = "SOCKS4 negotiation write failed.";
1007 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1011 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1013 errstr = "SOCKS4 negotiation read failed.";
1014 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1021 csp->error_message = strdup(errstr);
1022 return(JB_INVALID_SOCKET);
1027 case SOCKS_REQUEST_GRANTED:
1029 case SOCKS_REQUEST_REJECT:
1030 errstr = "SOCKS request rejected or failed.";
1033 case SOCKS_REQUEST_IDENT_FAILED:
1034 errstr = "SOCKS request rejected because "
1035 "SOCKS server cannot connect to identd on the client.";
1038 case SOCKS_REQUEST_IDENT_CONFLICT:
1039 errstr = "SOCKS request rejected because "
1040 "the client program and identd report "
1041 "different user-ids.";
1046 snprintf(buf, sizeof(buf),
1047 "SOCKS request rejected for reason code %d.", s->cd);
1051 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1052 csp->error_message = strdup(errstr);
1055 return(JB_INVALID_SOCKET);
1059 /*********************************************************************
1061 * Function : translate_socks5_error
1063 * Description : Translates a SOCKS errors to a string.
1066 * 1 : socks_error = The error code to translate.
1068 * Returns : The string translation.
1070 *********************************************************************/
1071 static const char *translate_socks5_error(int socks_error)
1073 switch (socks_error)
1075 /* XXX: these should be more descriptive */
1076 case SOCKS5_REQUEST_FAILED:
1077 return "SOCKS5 request failed";
1078 case SOCKS5_REQUEST_DENIED:
1079 return "SOCKS5 request denied";
1080 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1081 return "SOCKS5 network unreachable";
1082 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1083 return "SOCKS5 host unreachable";
1084 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1085 return "SOCKS5 connection refused";
1086 case SOCKS5_REQUEST_TTL_EXPIRED:
1087 return "SOCKS5 TTL expired";
1088 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1089 return "SOCKS5 client protocol error";
1090 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1091 return "SOCKS5 domain names unsupported";
1092 case SOCKS5_REQUEST_GRANTED:
1093 return "everything's peachy";
1095 return "SOCKS5 negotiation protocol error";
1099 /*********************************************************************
1101 * Function : socks5_connect
1103 * Description : Connect to the SOCKS server, and connect through
1104 * it to the specified server. This handles
1105 * all the SOCKS negotiation, and returns a file
1106 * descriptor for a socket which can be treated as a
1107 * normal (non-SOCKS) socket.
1110 * 1 : fwd = Specifies the SOCKS proxy to use.
1111 * 2 : target_host = The final server to connect to.
1112 * 3 : target_port = The final port to connect to.
1113 * 4 : csp = Current client state (buffers, headers, etc...)
1115 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1117 *********************************************************************/
1118 static jb_socket socks5_connect(const struct forward_spec *fwd,
1119 const char *target_host,
1121 struct client_state *csp)
1126 size_t client_pos = 0;
1127 int server_size = 0;
1130 const char *errstr = NULL;
1132 assert(fwd->gateway_host);
1133 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1135 errstr = "NULL gateway host specified";
1139 if (fwd->gateway_port <= 0)
1142 * XXX: currently this can't happen because in
1143 * case of invalid gateway ports we use the defaults.
1144 * Of course we really shouldn't do that.
1146 errstr = "invalid gateway port specified";
1150 hostlen = strlen(target_host);
1151 if (hostlen > (size_t)255)
1153 errstr = "target host name is longer than 255 characters";
1157 if (fwd->type != SOCKS_5)
1159 /* Should never get here */
1160 log_error(LOG_LEVEL_FATAL,
1161 "SOCKS5 impossible internal error - bad SOCKS type");
1168 assert(errstr != NULL);
1169 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1170 csp->error_message = strdup(errstr);
1171 return(JB_INVALID_SOCKET);
1174 /* pass the request to the socks server */
1175 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1177 if (sfd == JB_INVALID_SOCKET)
1179 errstr = "socks5 server unreachable";
1180 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1181 csp->error_message = strdup(errstr);
1182 return(JB_INVALID_SOCKET);
1186 cbuf[client_pos++] = '\x05'; /* Version */
1187 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1188 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1190 if (write_socket(sfd, cbuf, client_pos))
1192 errstr = "SOCKS5 negotiation write failed";
1193 csp->error_message = strdup(errstr);
1194 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1196 return(JB_INVALID_SOCKET);
1199 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1201 errstr = "SOCKS5 negotiation read failed";
1205 if (!err && (sbuf[0] != '\x05'))
1207 errstr = "SOCKS5 negotiation protocol version error";
1211 if (!err && (sbuf[1] == '\xff'))
1213 errstr = "SOCKS5 authentication required";
1217 if (!err && (sbuf[1] != '\x00'))
1219 errstr = "SOCKS5 negotiation protocol error";
1225 assert(errstr != NULL);
1226 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1227 csp->error_message = strdup(errstr);
1230 return(JB_INVALID_SOCKET);
1234 cbuf[client_pos++] = '\x05'; /* Version */
1235 cbuf[client_pos++] = '\x01'; /* TCP connect */
1236 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1237 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1238 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1239 assert(sizeof(cbuf) - client_pos > (size_t)255);
1240 /* Using strncpy because we really want the nul byte padding. */
1241 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1242 client_pos += (hostlen & 0xffu);
1243 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1244 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1246 if (write_socket(sfd, cbuf, client_pos))
1248 errstr = "SOCKS5 negotiation read failed";
1249 csp->error_message = strdup(errstr);
1250 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1253 return(JB_INVALID_SOCKET);
1256 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1257 if (server_size < 3)
1259 errstr = "SOCKS5 negotiation read failed";
1262 else if (server_size > 20)
1264 /* This is somewhat unexpected but doesn't realy matter. */
1265 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1266 "from socks server. Would have accepted up to %d.",
1267 server_size, sizeof(sbuf));
1270 if (!err && (sbuf[0] != '\x05'))
1272 errstr = "SOCKS5 negotiation protocol version error";
1276 if (!err && (sbuf[2] != '\x00'))
1278 errstr = "SOCKS5 negotiation protocol error";
1284 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1288 errstr = translate_socks5_error(sbuf[1]);
1292 assert(errstr != NULL);
1293 csp->error_message = strdup(errstr);
1294 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1298 return(JB_INVALID_SOCKET);