1 const char gateway_rcs[] = "$Id: gateway.c,v 1.35 2008/10/17 17:12:01 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.35 2008/10/17 17:12:01 fabiankeil
38 * In socket_is_still_usable(), use select()
39 * and FD_ISSET() if poll() isn't available.
41 * Revision 1.34 2008/10/17 17:07:13 fabiankeil
42 * Add preliminary timeout support.
44 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
45 * Fix two gcc44 warnings.
47 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
48 * Fix compiler warning.
50 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
51 * - Factor socket_is_still_usable() out of get_reusable_connection().
52 * - If poll() isn't available, show a warning and assume the socket
55 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
56 * If a remembered connection is no longer usable and
57 * has been marked closed, don't bother checking if the
58 * destination matches.
60 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
61 * Add missing dots for two log messages.
63 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
64 * Flush work-in-progress changes to keep outgoing connections
65 * alive where possible. Incomplete and mostly #ifdef'd out.
67 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
68 * Return only once in forwarded_connect().
70 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
71 * Fix typo in macro name.
73 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
75 * - make the buffers quite a bit smaller.
76 * - properly report "socks5 server unreachable" failures.
77 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
78 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
79 * - log a message if the socks5 server sends more data than expected.
80 * - add some assertions and comments.
82 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
83 * - Fix a compiler warning.
84 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
86 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
87 * Remember the cause of the SOCKS5 error for the CGI message.
89 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
90 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
92 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
93 * Modified patch from Song Weijia (#1762559) to
94 * fix socks requests on big-endian platforms.
96 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
97 * - Use strlcpy() instead of strcpy().
98 * - Use the same buffer for socks requests and socks responses.
99 * - Fix bogus warning about web_server_addr being used uninitialized.
101 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
102 * - Save errors in socks4_connect() to csp->error_message.
103 * - Silence some gcc43 warnings, hopefully the right way.
105 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
106 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
107 * with what was really the latest development (the v_3_0_branch branch)
109 * Revision 1.16 2002/05/12 21:36:29 jongfoster
110 * Correcting function comments
112 * Revision 1.15 2002/03/26 22:29:54 swa
113 * we have a new homepage!
115 * Revision 1.14 2002/03/24 13:25:43 swa
116 * name change related issues
118 * Revision 1.13 2002/03/13 00:29:59 jongfoster
121 * Revision 1.12 2002/03/09 20:03:52 jongfoster
122 * - Making various functions return int rather than size_t.
123 * (Undoing a recent change). Since size_t is unsigned on
124 * Windows, functions like read_socket that return -1 on
125 * error cannot return a size_t.
127 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
128 * crashes, and also frequently caused JB to jump to 100%
129 * CPU and stay there. (Because it thought it had just
130 * read ((unsigned)-1) == 4Gb of data...)
132 * - The signature of write_socket has changed, it now simply
133 * returns success=0/failure=nonzero.
135 * - Trying to get rid of a few warnings --with-debug on
136 * Windows, I've introduced a new type "jb_socket". This is
137 * used for the socket file descriptors. On Windows, this
138 * is SOCKET (a typedef for unsigned). Everywhere else, it's
139 * an int. The error value can't be -1 any more, so it's
140 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
141 * Windows it maps to the #define INVALID_SOCKET.)
143 * - The signature of bind_port has changed.
145 * Revision 1.11 2002/03/08 17:46:04 jongfoster
146 * Fixing int/size_t warnings
148 * Revision 1.10 2002/03/07 03:50:19 oes
149 * - Improved handling of failed DNS lookups
150 * - Fixed compiler warnings
152 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
153 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
154 * threads to call select() simultaneously. So, it's time to do a real, live,
155 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
156 * (native). Both versions will work, but using __OS2__ offers multi-threading.
158 * Revision 1.8 2001/09/13 20:10:12 jongfoster
159 * Fixing missing #include under Windows
161 * Revision 1.7 2001/09/12 17:58:26 steudten
163 * add #include <string.h>
165 * Revision 1.6 2001/09/10 10:41:16 oes
166 * Added #include in.h
168 * Revision 1.5 2001/07/29 18:47:57 jongfoster
169 * Adding missing #include project.h
171 * Revision 1.4 2001/07/24 12:47:06 oes
172 * Applied BeOS support update by Eugenia
174 * Revision 1.3 2001/06/09 10:55:28 jongfoster
175 * Changing BUFSIZ ==> BUFFER_SIZE
177 * Revision 1.2 2001/06/07 23:11:38 jongfoster
178 * Removing gateways[] list - no longer used.
179 * Replacing function pointer in struct gateway with a directly
180 * called function forwarded_connect(), which can do the common
181 * task of deciding whether to connect to the web server or HTTP
183 * Replacing struct gateway with struct forward_spec
184 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
185 * It was a bug which led to the connection being made to the web
186 * server rather than the HTTP proxy, and also a buffer overrun.
188 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
189 * Initial import of version 2.9.3 source tree
192 *********************************************************************/
198 #include <sys/types.h>
201 #include <netinet/in.h>
209 #include <winsock2.h>
210 #endif /* def _WIN32 */
214 #endif /* def __BEOS__ */
218 #endif /* def __OS2__ */
223 #include "jbsockets.h"
225 #include "miscutil.h"
226 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
229 #include <sys/poll.h>
232 #endif /* def __GLIBC__ */
233 #endif /* HAVE_POLL */
234 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
236 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
238 static jb_socket socks4_connect(const struct forward_spec * fwd,
239 const char * target_host,
241 struct client_state *csp);
243 static jb_socket socks5_connect(const struct forward_spec *fwd,
244 const char *target_host,
246 struct client_state *csp);
249 #define SOCKS_REQUEST_GRANTED 90
250 #define SOCKS_REQUEST_REJECT 91
251 #define SOCKS_REQUEST_IDENT_FAILED 92
252 #define SOCKS_REQUEST_IDENT_CONFLICT 93
254 #define SOCKS5_REQUEST_GRANTED 0
255 #define SOCKS5_REQUEST_FAILED 1
256 #define SOCKS5_REQUEST_DENIED 2
257 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
258 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
259 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
260 #define SOCKS5_REQUEST_TTL_EXPIRED 6
261 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
262 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
264 /* structure of a socks client operation */
266 unsigned char vn; /* socks version number */
267 unsigned char cd; /* command code */
268 unsigned char dstport[2]; /* destination port */
269 unsigned char dstip[4]; /* destination address */
270 char userid; /* first byte of userid */
271 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
272 /* more bytes of the userid follow, terminated by a NULL */
275 /* structure of a socks server reply */
277 unsigned char vn; /* socks version number */
278 unsigned char cd; /* command code */
279 unsigned char dstport[2]; /* destination port */
280 unsigned char dstip[4]; /* destination address */
283 static const char socks_userid[] = "anonymous";
285 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
287 #define MAX_REUSABLE_CONNECTIONS 100
288 /* XXX: should be a config option. */
289 #define CONNECTION_KEEP_ALIVE_TIMEOUT 3 * 60
291 struct reusable_connection
306 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
308 static int mark_connection_unused(jb_socket sfd);
309 static void mark_connection_closed(struct reusable_connection *closed_connection);
310 static int socket_is_still_usable(jb_socket sfd);
313 /*********************************************************************
315 * Function : initialize_reusable_connections
317 * Description : Initializes the reusable_connection structures.
318 * Must be called with connection_reuse_mutex locked.
324 *********************************************************************/
325 extern void initialize_reusable_connections(void)
327 unsigned int slot = 0;
329 log_error(LOG_LEVEL_INFO,
330 "Support for 'Connection: keep-alive' is experimental, "
331 "incomplete and known not to work properly in some situations.");
333 for (slot = 0; slot < SZ(reusable_connection); slot++)
335 mark_connection_closed(&reusable_connection[slot]);
338 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
342 /*********************************************************************
344 * Function : remember_connection
346 * Description : Remembers a connection for reuse later on.
349 * 1 : sfd = Open socket to remember.
350 * 2 : http = The destination for the connection.
351 * 3 : fwd = The forwarder settings used.
355 *********************************************************************/
356 void remember_connection(jb_socket sfd, const struct http_request *http,
357 const struct forward_spec *fwd)
359 unsigned int slot = 0;
360 int free_slot_found = FALSE;
362 assert(sfd != JB_INVALID_SOCKET);
364 if (mark_connection_unused(sfd))
369 privoxy_mutex_lock(&connection_reuse_mutex);
371 /* Find free socket slot. */
372 for (slot = 0; slot < SZ(reusable_connection); slot++)
374 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
376 assert(reusable_connection[slot].in_use == 0);
377 log_error(LOG_LEVEL_CONNECT,
378 "Remembering socket %d for %s:%d in slot %d.",
379 sfd, http->host, http->port, slot);
380 free_slot_found = TRUE;
385 if (!free_slot_found)
387 log_error(LOG_LEVEL_CONNECT,
388 "No free slots found to remembering socket for %s:%d. Last slot %d.",
389 http->host, http->port, slot);
390 privoxy_mutex_unlock(&connection_reuse_mutex);
395 assert(NULL != http->host);
396 reusable_connection[slot].host = strdup(http->host);
397 if (NULL == reusable_connection[slot].host)
399 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
401 reusable_connection[slot].sfd = sfd;
402 reusable_connection[slot].port = http->port;
403 reusable_connection[slot].in_use = 0;
404 reusable_connection[slot].timestamp = time(NULL);
407 assert(reusable_connection[slot].gateway_host == NULL);
408 assert(reusable_connection[slot].gateway_port == 0);
409 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
410 assert(reusable_connection[slot].forward_host == NULL);
411 assert(reusable_connection[slot].forward_port == 0);
413 reusable_connection[slot].forwarder_type = fwd->type;
414 if (NULL != fwd->gateway_host)
416 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
417 if (NULL == reusable_connection[slot].gateway_host)
419 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
424 reusable_connection[slot].gateway_host = NULL;
426 reusable_connection[slot].gateway_port = fwd->gateway_port;
428 if (NULL != fwd->forward_host)
430 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
431 if (NULL == reusable_connection[slot].forward_host)
433 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
438 reusable_connection[slot].forward_host = NULL;
440 reusable_connection[slot].forward_port = fwd->forward_port;
442 privoxy_mutex_unlock(&connection_reuse_mutex);
446 /*********************************************************************
448 * Function : mark_connection_closed
450 * Description : Marks a reused connection closed.
451 * Must be called with connection_reuse_mutex locked.
454 * 1 : closed_connection = The connection to mark as closed.
458 *********************************************************************/
459 static void mark_connection_closed(struct reusable_connection *closed_connection)
461 closed_connection->in_use = FALSE;
462 closed_connection->sfd = JB_INVALID_SOCKET;
463 freez(closed_connection->host);
464 closed_connection->port = 0;
465 closed_connection->timestamp = 0;
466 closed_connection->forwarder_type = SOCKS_NONE;
467 freez(closed_connection->gateway_host);
468 closed_connection->gateway_port = 0;
469 freez(closed_connection->forward_host);
470 closed_connection->forward_port = 0;
474 /*********************************************************************
476 * Function : forget_connection
478 * Description : Removes a previously remembered connection from
479 * the list of reusable connections.
482 * 1 : sfd = The socket belonging to the connection in question.
486 *********************************************************************/
487 void forget_connection(jb_socket sfd)
489 unsigned int slot = 0;
491 assert(sfd != JB_INVALID_SOCKET);
493 privoxy_mutex_lock(&connection_reuse_mutex);
495 for (slot = 0; slot < SZ(reusable_connection); slot++)
497 if (reusable_connection[slot].sfd == sfd)
499 assert(reusable_connection[slot].in_use);
504 if (reusable_connection[slot].sfd != sfd)
506 log_error(LOG_LEVEL_CONNECT,
507 "Socket %d already forgotten or never remembered.", sfd);
508 privoxy_mutex_unlock(&connection_reuse_mutex);
512 log_error(LOG_LEVEL_CONNECT,
513 "Forgetting socket %d for %s:%d in slot %d.",
514 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
516 mark_connection_closed(&reusable_connection[slot]);
518 privoxy_mutex_unlock(&connection_reuse_mutex);
522 /*********************************************************************
524 * Function : connection_destination_matches
526 * Description : Determines whether a remembered connection can
527 * be reused. That is whether the destination and
528 * the forwarding settings match.
531 * 1 : connection = The connection to check.
532 * 2 : http = The destination for the connection.
533 * 3 : fwd = The forwarder settings.
535 * Returns : TRUE for yes, FALSE otherwise.
537 *********************************************************************/
538 static int connection_destination_matches(const struct reusable_connection *connection,
539 const struct http_request *http,
540 const struct forward_spec *fwd)
542 /* XXX: Start of duplicated checks for debugging purposes. */
543 if (strcmpic(connection->host, http->host))
548 if (connection->forwarder_type != fwd->type)
550 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
551 connection->forwarder_type, fwd->type, http->host);
554 if (connection->gateway_port != fwd->gateway_port)
556 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
557 connection->gateway_port, fwd->gateway_port, http->host);
560 if (connection->forward_port != fwd->forward_port)
562 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
563 connection->forward_port, fwd->forward_port, http->host);
566 if (connection->forward_port != fwd->forward_port)
568 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
569 connection->forward_port, fwd->forward_port, http->host);
573 /* XXX: End of duplicated checks for debugging purposes. */
575 if ((connection->forwarder_type != fwd->type)
576 || (connection->gateway_port != fwd->gateway_port)
577 || (connection->forward_port != fwd->forward_port)
578 || (connection->port != http->port))
583 if (( (NULL != connection->gateway_host)
584 && (NULL != fwd->gateway_host)
585 && strcmpic(connection->gateway_host, fwd->gateway_host))
586 && (connection->gateway_host != fwd->gateway_host))
588 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
592 if (( (NULL != connection->forward_host)
593 && (NULL != fwd->forward_host)
594 && strcmpic(connection->forward_host, fwd->forward_host))
595 && (connection->forward_host != fwd->forward_host))
597 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
601 return (!strcmpic(connection->host, http->host));
606 /*********************************************************************
608 * Function : close_unusable_connections
610 * Description : Closes remembered connections that have timed
611 * out or have been closed on the other side.
617 *********************************************************************/
618 static void close_unusable_connections(void)
620 unsigned int slot = 0;
622 for (slot = 0; slot < SZ(reusable_connection); slot++)
624 if (!reusable_connection[slot].in_use
625 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
627 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
629 if (CONNECTION_KEEP_ALIVE_TIMEOUT < time_open)
631 log_error(LOG_LEVEL_CONNECT,
632 "The connection to %s:%d in slot %d timed out. Closing.",
633 reusable_connection[slot].host, reusable_connection[slot].port,
635 close_socket(reusable_connection[slot].sfd);
636 mark_connection_closed(&reusable_connection[slot]);
640 if (!socket_is_still_usable(reusable_connection[slot].sfd))
642 log_error(LOG_LEVEL_CONNECT,
643 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
644 reusable_connection[slot].sfd, reusable_connection[slot].host,
645 reusable_connection[slot].port, slot);
646 close_socket(reusable_connection[slot].sfd);
647 mark_connection_closed(&reusable_connection[slot]);
655 /*********************************************************************
657 * Function : socket_is_still_usable
659 * Description : Decides whether or not an open socket is still usable.
662 * 1 : sfd = The socket to check.
664 * Returns : TRUE for yes, otherwise FALSE.
666 *********************************************************************/
667 static int socket_is_still_usable(jb_socket sfd)
671 struct pollfd poll_fd[1];
673 memset(poll_fd, 0, sizeof(poll_fd));
675 poll_fd[0].events = POLLIN;
677 poll_result = poll(poll_fd, 1, 0);
679 if (-1 != poll_result)
681 return !(poll_fd[0].revents & POLLIN);
685 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
690 struct timeval timeout;
692 int socket_is_alive = 0;
694 memset(&timeout, '\0', sizeof(timeout));
695 /* timeout.tv_usec = 150;*/
696 FD_ZERO(&readable_fds);
697 FD_SET(sfd, &readable_fds);
699 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
702 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
706 * XXX: I'm not sure why !FD_ISSET() works,
707 * but apparently it does.
709 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
711 log_error(LOG_LEVEL_INFO,
712 "Detecting already dead sockets might not work correctly "
713 "on your platform. Anyway, socket %d appears to be %s.",
714 sfd, (socket_is_alive ? "still alive" : "already dead"));
716 return socket_is_alive;
717 #endif /* def HAVE_POLL */
721 /*********************************************************************
723 * Function : get_reusable_connection
725 * Description : Returns an open socket to a previously remembered
726 * open connection (if there is one).
729 * 1 : http = The destination for the connection.
730 * 2 : fwd = The forwarder settings.
732 * Returns : JB_INVALID_SOCKET => No reusable connection found,
733 * otherwise a usable socket.
735 *********************************************************************/
736 static jb_socket get_reusable_connection(const struct http_request *http,
737 const struct forward_spec *fwd)
739 jb_socket sfd = JB_INVALID_SOCKET;
740 unsigned int slot = 0;
742 privoxy_mutex_lock(&connection_reuse_mutex);
744 close_unusable_connections();
746 for (slot = 0; slot < SZ(reusable_connection); slot++)
748 if (!reusable_connection[slot].in_use
749 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
751 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
753 reusable_connection[slot].in_use = TRUE;
754 sfd = reusable_connection[slot].sfd;
755 log_error(LOG_LEVEL_CONNECT,
756 "Found reusable socket %d for %s:%d in slot %d.",
757 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
763 privoxy_mutex_unlock(&connection_reuse_mutex);
770 /*********************************************************************
772 * Function : mark_connection_unused
774 * Description : Gives a remembered connection free for reuse.
777 * 1 : sfd = The socket belonging to the connection in question.
779 * Returns : TRUE => Socket found and marked as unused.
780 * FALSE => Socket not found.
782 *********************************************************************/
783 static int mark_connection_unused(jb_socket sfd)
785 unsigned int slot = 0;
786 int socket_found = FALSE;
788 assert(sfd != JB_INVALID_SOCKET);
790 privoxy_mutex_lock(&connection_reuse_mutex);
792 for (slot = 0; slot < SZ(reusable_connection); slot++)
794 if (reusable_connection[slot].sfd == sfd)
796 assert(reusable_connection[slot].in_use);
801 if (reusable_connection[slot].sfd == sfd)
804 log_error(LOG_LEVEL_CONNECT,
805 "Marking open socket %d for %s:%d in slot %d as unused.",
806 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
807 reusable_connection[slot].in_use = 0;
808 reusable_connection[slot].timestamp = time(NULL);
811 privoxy_mutex_unlock(&connection_reuse_mutex);
816 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
819 /*********************************************************************
821 * Function : forwarded_connect
823 * Description : Connect to a specified web server, possibly via
824 * a HTTP proxy and/or a SOCKS proxy.
827 * 1 : fwd = the proxies to use when connecting.
828 * 2 : http = the http request and apropos headers
829 * 3 : csp = Current client state (buffers, headers, etc...)
831 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
833 *********************************************************************/
834 jb_socket forwarded_connect(const struct forward_spec * fwd,
835 struct http_request *http,
836 struct client_state *csp)
838 const char * dest_host;
840 jb_socket sfd = JB_INVALID_SOCKET;
842 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
843 sfd = get_reusable_connection(http, fwd);
844 if (JB_INVALID_SOCKET == sfd)
846 log_error(LOG_LEVEL_CONNECT,
847 "No reusable socket for %s:%d found. Opening a new one.",
848 http->host, http->port);
854 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
856 /* Figure out if we need to connect to the web server or a HTTP proxy. */
857 if (fwd->forward_host)
860 dest_host = fwd->forward_host;
861 dest_port = fwd->forward_port;
866 dest_host = http->host;
867 dest_port = http->port;
870 /* Connect, maybe using a SOCKS proxy */
874 sfd = connect_to(dest_host, dest_port, csp);
878 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
881 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
884 /* Should never get here */
885 log_error(LOG_LEVEL_FATAL,
886 "SOCKS4 impossible internal error - bad SOCKS type.");
894 /*********************************************************************
896 * Function : socks4_connect
898 * Description : Connect to the SOCKS server, and connect through
899 * it to the specified server. This handles
900 * all the SOCKS negotiation, and returns a file
901 * descriptor for a socket which can be treated as a
902 * normal (non-SOCKS) socket.
904 * Logged error messages are saved to csp->error_message
905 * and later reused by error_response() for the CGI
906 * message. strdup allocation failures are handled there.
909 * 1 : fwd = Specifies the SOCKS proxy to use.
910 * 2 : target_host = The final server to connect to.
911 * 3 : target_port = The final port to connect to.
912 * 4 : csp = Current client state (buffers, headers, etc...)
914 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
916 *********************************************************************/
917 static jb_socket socks4_connect(const struct forward_spec * fwd,
918 const char * target_host,
920 struct client_state *csp)
922 unsigned int web_server_addr;
923 char buf[BUFFER_SIZE];
924 struct socks_op *c = (struct socks_op *)buf;
925 struct socks_reply *s = (struct socks_reply *)buf;
932 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
934 /* XXX: Shouldn't the config file parser prevent this? */
935 errstr = "NULL gateway host specified.";
939 if (fwd->gateway_port <= 0)
941 errstr = "invalid gateway port specified.";
947 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
948 csp->error_message = strdup(errstr);
950 return(JB_INVALID_SOCKET);
953 /* build a socks request for connection to the web server */
955 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
957 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
962 web_server_addr = resolve_hostname_to_ip(target_host);
963 if (web_server_addr == INADDR_NONE)
965 errstr = "could not resolve target host";
966 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
971 web_server_addr = htonl(web_server_addr);
975 web_server_addr = 0x00000001;
976 n = csiz + strlen(target_host) + 1;
980 errstr = "buffer cbuf too small.";
981 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
986 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
988 * What we forward to the socks4a server should have the
989 * size of socks_op, plus the length of the userid plus
990 * its \0 byte (which we don't have to add because the
991 * first byte of the userid is counted twice as it's also
992 * part of sock_op) minus the padding bytes (which are part
993 * of the userid as well), plus the length of the target_host
994 * (which is stored csiz bytes after the beginning of the buffer),
995 * plus another \0 byte.
997 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
1002 /* Should never get here */
1003 log_error(LOG_LEVEL_FATAL,
1004 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
1006 return(JB_INVALID_SOCKET);
1011 csp->error_message = strdup(errstr);
1012 return(JB_INVALID_SOCKET);
1017 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
1018 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
1019 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
1020 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
1021 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
1022 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
1024 /* pass the request to the socks server */
1025 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1027 if (sfd == JB_INVALID_SOCKET)
1030 * XXX: connect_to should fill in the exact reason.
1031 * Most likely resolving the IP of the forwarder failed.
1033 errstr = "connect_to failed: see logfile for details";
1036 else if (write_socket(sfd, (char *)c, csiz))
1038 errstr = "SOCKS4 negotiation write failed.";
1039 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1043 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1045 errstr = "SOCKS4 negotiation read failed.";
1046 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1053 csp->error_message = strdup(errstr);
1054 return(JB_INVALID_SOCKET);
1059 case SOCKS_REQUEST_GRANTED:
1062 case SOCKS_REQUEST_REJECT:
1063 errstr = "SOCKS request rejected or failed.";
1066 case SOCKS_REQUEST_IDENT_FAILED:
1067 errstr = "SOCKS request rejected because "
1068 "SOCKS server cannot connect to identd on the client.";
1071 case SOCKS_REQUEST_IDENT_CONFLICT:
1072 errstr = "SOCKS request rejected because "
1073 "the client program and identd report "
1074 "different user-ids.";
1079 snprintf(buf, sizeof(buf),
1080 "SOCKS request rejected for reason code %d.", s->cd);
1084 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1085 csp->error_message = strdup(errstr);
1088 return(JB_INVALID_SOCKET);
1092 /*********************************************************************
1094 * Function : translate_socks5_error
1096 * Description : Translates a SOCKS errors to a string.
1099 * 1 : socks_error = The error code to translate.
1101 * Returns : The string translation.
1103 *********************************************************************/
1104 static const char *translate_socks5_error(int socks_error)
1106 switch (socks_error)
1108 /* XXX: these should be more descriptive */
1109 case SOCKS5_REQUEST_FAILED:
1110 return "SOCKS5 request failed";
1111 case SOCKS5_REQUEST_DENIED:
1112 return "SOCKS5 request denied";
1113 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1114 return "SOCKS5 network unreachable";
1115 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1116 return "SOCKS5 host unreachable";
1117 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1118 return "SOCKS5 connection refused";
1119 case SOCKS5_REQUEST_TTL_EXPIRED:
1120 return "SOCKS5 TTL expired";
1121 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1122 return "SOCKS5 client protocol error";
1123 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1124 return "SOCKS5 domain names unsupported";
1125 case SOCKS5_REQUEST_GRANTED:
1126 return "everything's peachy";
1128 return "SOCKS5 negotiation protocol error";
1132 /*********************************************************************
1134 * Function : socks5_connect
1136 * Description : Connect to the SOCKS server, and connect through
1137 * it to the specified server. This handles
1138 * all the SOCKS negotiation, and returns a file
1139 * descriptor for a socket which can be treated as a
1140 * normal (non-SOCKS) socket.
1143 * 1 : fwd = Specifies the SOCKS proxy to use.
1144 * 2 : target_host = The final server to connect to.
1145 * 3 : target_port = The final port to connect to.
1146 * 4 : csp = Current client state (buffers, headers, etc...)
1148 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1150 *********************************************************************/
1151 static jb_socket socks5_connect(const struct forward_spec *fwd,
1152 const char *target_host,
1154 struct client_state *csp)
1159 size_t client_pos = 0;
1160 int server_size = 0;
1163 const char *errstr = NULL;
1165 assert(fwd->gateway_host);
1166 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1168 errstr = "NULL gateway host specified";
1172 if (fwd->gateway_port <= 0)
1175 * XXX: currently this can't happen because in
1176 * case of invalid gateway ports we use the defaults.
1177 * Of course we really shouldn't do that.
1179 errstr = "invalid gateway port specified";
1183 hostlen = strlen(target_host);
1186 errstr = "target host name is longer than 255 characters";
1190 if (fwd->type != SOCKS_5)
1192 /* Should never get here */
1193 log_error(LOG_LEVEL_FATAL,
1194 "SOCKS5 impossible internal error - bad SOCKS type");
1201 assert(errstr != NULL);
1202 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1203 csp->error_message = strdup(errstr);
1204 return(JB_INVALID_SOCKET);
1207 /* pass the request to the socks server */
1208 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1210 if (sfd == JB_INVALID_SOCKET)
1212 errstr = "socks5 server unreachable";
1213 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1214 csp->error_message = strdup(errstr);
1215 return(JB_INVALID_SOCKET);
1219 cbuf[client_pos++] = '\x05'; /* Version */
1220 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1221 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1223 if (write_socket(sfd, cbuf, client_pos))
1225 errstr = "SOCKS5 negotiation write failed";
1226 csp->error_message = strdup(errstr);
1227 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1229 return(JB_INVALID_SOCKET);
1232 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1234 errstr = "SOCKS5 negotiation read failed";
1238 if (!err && (sbuf[0] != '\x05'))
1240 errstr = "SOCKS5 negotiation protocol version error";
1244 if (!err && (sbuf[1] == '\xff'))
1246 errstr = "SOCKS5 authentication required";
1250 if (!err && (sbuf[1] != '\x00'))
1252 errstr = "SOCKS5 negotiation protocol error";
1258 assert(errstr != NULL);
1259 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1260 csp->error_message = strdup(errstr);
1263 return(JB_INVALID_SOCKET);
1267 cbuf[client_pos++] = '\x05'; /* Version */
1268 cbuf[client_pos++] = '\x01'; /* TCP connect */
1269 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1270 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1271 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1272 assert(sizeof(cbuf) - client_pos > 255);
1273 /* Using strncpy because we really want the nul byte padding. */
1274 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1275 client_pos += (hostlen & 0xffu);
1276 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1277 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1279 if (write_socket(sfd, cbuf, client_pos))
1281 errstr = "SOCKS5 negotiation read failed";
1282 csp->error_message = strdup(errstr);
1283 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1286 return(JB_INVALID_SOCKET);
1289 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1290 if (server_size < 3)
1292 errstr = "SOCKS5 negotiation read failed";
1295 else if (server_size > 20)
1297 /* This is somewhat unexpected but doesn't realy matter. */
1298 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1299 "from socks server. Would have accepted up to %d.",
1300 server_size, sizeof(sbuf));
1303 if (!err && (sbuf[0] != '\x05'))
1305 errstr = "SOCKS5 negotiation protocol version error";
1309 if (!err && (sbuf[2] != '\x00'))
1311 errstr = "SOCKS5 negotiation protocol error";
1317 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1321 errstr = translate_socks5_error(sbuf[1]);
1325 assert(errstr != NULL);
1326 csp->error_message = strdup(errstr);
1327 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1331 return(JB_INVALID_SOCKET);