1 const char gateway_rcs[] = "$Id: gateway.c,v 1.34 2008/10/17 17:07:13 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.34 2008/10/17 17:07:13 fabiankeil
38 * Add preliminary timeout support.
40 * Revision 1.33 2008/10/16 16:34:21 fabiankeil
41 * Fix two gcc44 warnings.
43 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
44 * Fix compiler warning.
46 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
47 * - Factor socket_is_still_usable() out of get_reusable_connection().
48 * - If poll() isn't available, show a warning and assume the socket
51 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
52 * If a remembered connection is no longer usable and
53 * has been marked closed, don't bother checking if the
54 * destination matches.
56 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
57 * Add missing dots for two log messages.
59 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
60 * Flush work-in-progress changes to keep outgoing connections
61 * alive where possible. Incomplete and mostly #ifdef'd out.
63 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
64 * Return only once in forwarded_connect().
66 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
67 * Fix typo in macro name.
69 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
71 * - make the buffers quite a bit smaller.
72 * - properly report "socks5 server unreachable" failures.
73 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
74 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
75 * - log a message if the socks5 server sends more data than expected.
76 * - add some assertions and comments.
78 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
79 * - Fix a compiler warning.
80 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
82 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
83 * Remember the cause of the SOCKS5 error for the CGI message.
85 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
86 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
88 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
89 * Modified patch from Song Weijia (#1762559) to
90 * fix socks requests on big-endian platforms.
92 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
93 * - Use strlcpy() instead of strcpy().
94 * - Use the same buffer for socks requests and socks responses.
95 * - Fix bogus warning about web_server_addr being used uninitialized.
97 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
98 * - Save errors in socks4_connect() to csp->error_message.
99 * - Silence some gcc43 warnings, hopefully the right way.
101 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
102 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
103 * with what was really the latest development (the v_3_0_branch branch)
105 * Revision 1.16 2002/05/12 21:36:29 jongfoster
106 * Correcting function comments
108 * Revision 1.15 2002/03/26 22:29:54 swa
109 * we have a new homepage!
111 * Revision 1.14 2002/03/24 13:25:43 swa
112 * name change related issues
114 * Revision 1.13 2002/03/13 00:29:59 jongfoster
117 * Revision 1.12 2002/03/09 20:03:52 jongfoster
118 * - Making various functions return int rather than size_t.
119 * (Undoing a recent change). Since size_t is unsigned on
120 * Windows, functions like read_socket that return -1 on
121 * error cannot return a size_t.
123 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
124 * crashes, and also frequently caused JB to jump to 100%
125 * CPU and stay there. (Because it thought it had just
126 * read ((unsigned)-1) == 4Gb of data...)
128 * - The signature of write_socket has changed, it now simply
129 * returns success=0/failure=nonzero.
131 * - Trying to get rid of a few warnings --with-debug on
132 * Windows, I've introduced a new type "jb_socket". This is
133 * used for the socket file descriptors. On Windows, this
134 * is SOCKET (a typedef for unsigned). Everywhere else, it's
135 * an int. The error value can't be -1 any more, so it's
136 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
137 * Windows it maps to the #define INVALID_SOCKET.)
139 * - The signature of bind_port has changed.
141 * Revision 1.11 2002/03/08 17:46:04 jongfoster
142 * Fixing int/size_t warnings
144 * Revision 1.10 2002/03/07 03:50:19 oes
145 * - Improved handling of failed DNS lookups
146 * - Fixed compiler warnings
148 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
149 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
150 * threads to call select() simultaneously. So, it's time to do a real, live,
151 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
152 * (native). Both versions will work, but using __OS2__ offers multi-threading.
154 * Revision 1.8 2001/09/13 20:10:12 jongfoster
155 * Fixing missing #include under Windows
157 * Revision 1.7 2001/09/12 17:58:26 steudten
159 * add #include <string.h>
161 * Revision 1.6 2001/09/10 10:41:16 oes
162 * Added #include in.h
164 * Revision 1.5 2001/07/29 18:47:57 jongfoster
165 * Adding missing #include project.h
167 * Revision 1.4 2001/07/24 12:47:06 oes
168 * Applied BeOS support update by Eugenia
170 * Revision 1.3 2001/06/09 10:55:28 jongfoster
171 * Changing BUFSIZ ==> BUFFER_SIZE
173 * Revision 1.2 2001/06/07 23:11:38 jongfoster
174 * Removing gateways[] list - no longer used.
175 * Replacing function pointer in struct gateway with a directly
176 * called function forwarded_connect(), which can do the common
177 * task of deciding whether to connect to the web server or HTTP
179 * Replacing struct gateway with struct forward_spec
180 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
181 * It was a bug which led to the connection being made to the web
182 * server rather than the HTTP proxy, and also a buffer overrun.
184 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
185 * Initial import of version 2.9.3 source tree
188 *********************************************************************/
194 #include <sys/types.h>
197 #include <netinet/in.h>
205 #include <winsock2.h>
206 #endif /* def _WIN32 */
210 #endif /* def __BEOS__ */
214 #endif /* def __OS2__ */
219 #include "jbsockets.h"
221 #include "miscutil.h"
222 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
225 #include <sys/poll.h>
228 #endif /* def __GLIBC__ */
229 #endif /* HAVE_POLL */
230 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
232 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
234 static jb_socket socks4_connect(const struct forward_spec * fwd,
235 const char * target_host,
237 struct client_state *csp);
239 static jb_socket socks5_connect(const struct forward_spec *fwd,
240 const char *target_host,
242 struct client_state *csp);
245 #define SOCKS_REQUEST_GRANTED 90
246 #define SOCKS_REQUEST_REJECT 91
247 #define SOCKS_REQUEST_IDENT_FAILED 92
248 #define SOCKS_REQUEST_IDENT_CONFLICT 93
250 #define SOCKS5_REQUEST_GRANTED 0
251 #define SOCKS5_REQUEST_FAILED 1
252 #define SOCKS5_REQUEST_DENIED 2
253 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
254 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
255 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
256 #define SOCKS5_REQUEST_TTL_EXPIRED 6
257 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
258 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
260 /* structure of a socks client operation */
262 unsigned char vn; /* socks version number */
263 unsigned char cd; /* command code */
264 unsigned char dstport[2]; /* destination port */
265 unsigned char dstip[4]; /* destination address */
266 char userid; /* first byte of userid */
267 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
268 /* more bytes of the userid follow, terminated by a NULL */
271 /* structure of a socks server reply */
273 unsigned char vn; /* socks version number */
274 unsigned char cd; /* command code */
275 unsigned char dstport[2]; /* destination port */
276 unsigned char dstip[4]; /* destination address */
279 static const char socks_userid[] = "anonymous";
281 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
283 #define MAX_REUSABLE_CONNECTIONS 100
284 /* XXX: should be a config option. */
285 #define CONNECTION_KEEP_ALIVE_TIMEOUT 3 * 60
287 struct reusable_connection
302 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
304 static int mark_connection_unused(jb_socket sfd);
305 static void mark_connection_closed(struct reusable_connection *closed_connection);
307 /*********************************************************************
309 * Function : initialize_reusable_connections
311 * Description : Initializes the reusable_connection structures.
312 * Must be called with connection_reuse_mutex locked.
318 *********************************************************************/
319 extern void initialize_reusable_connections(void)
321 unsigned int slot = 0;
323 log_error(LOG_LEVEL_INFO,
324 "Support for 'Connection: keep-alive' is experimental, "
325 "incomplete and known not to work properly in some situations.");
327 for (slot = 0; slot < SZ(reusable_connection); slot++)
329 mark_connection_closed(&reusable_connection[slot]);
332 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
336 /*********************************************************************
338 * Function : remember_connection
340 * Description : Remembers a connection for reuse later on.
343 * 1 : sfd = Open socket to remember.
344 * 2 : http = The destination for the connection.
345 * 3 : fwd = The forwarder settings used.
349 *********************************************************************/
350 void remember_connection(jb_socket sfd, const struct http_request *http,
351 const struct forward_spec *fwd)
353 unsigned int slot = 0;
354 int free_slot_found = FALSE;
356 assert(sfd != JB_INVALID_SOCKET);
358 if (mark_connection_unused(sfd))
363 privoxy_mutex_lock(&connection_reuse_mutex);
365 /* Find free socket slot. */
366 for (slot = 0; slot < SZ(reusable_connection); slot++)
368 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
370 assert(reusable_connection[slot].in_use == 0);
371 log_error(LOG_LEVEL_CONNECT,
372 "Remembering socket %d for %s:%d in slot %d.",
373 sfd, http->host, http->port, slot);
374 free_slot_found = TRUE;
379 if (!free_slot_found)
381 log_error(LOG_LEVEL_CONNECT,
382 "No free slots found to remembering socket for %s:%d. Last slot %d.",
383 http->host, http->port, slot);
384 privoxy_mutex_unlock(&connection_reuse_mutex);
389 assert(NULL != http->host);
390 reusable_connection[slot].host = strdup(http->host);
391 if (NULL == reusable_connection[slot].host)
393 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
395 reusable_connection[slot].sfd = sfd;
396 reusable_connection[slot].port = http->port;
397 reusable_connection[slot].in_use = 0;
398 reusable_connection[slot].timestamp = time(NULL);
401 assert(reusable_connection[slot].gateway_host == NULL);
402 assert(reusable_connection[slot].gateway_port == 0);
403 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
404 assert(reusable_connection[slot].forward_host == NULL);
405 assert(reusable_connection[slot].forward_port == 0);
407 reusable_connection[slot].forwarder_type = fwd->type;
408 if (NULL != fwd->gateway_host)
410 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
411 if (NULL == reusable_connection[slot].gateway_host)
413 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
418 reusable_connection[slot].gateway_host = NULL;
420 reusable_connection[slot].gateway_port = fwd->gateway_port;
422 if (NULL != fwd->forward_host)
424 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
425 if (NULL == reusable_connection[slot].forward_host)
427 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
432 reusable_connection[slot].forward_host = NULL;
434 reusable_connection[slot].forward_port = fwd->forward_port;
436 privoxy_mutex_unlock(&connection_reuse_mutex);
440 /*********************************************************************
442 * Function : mark_connection_closed
444 * Description : Marks a reused connection closed.
445 * Must be called with connection_reuse_mutex locked.
448 * 1 : closed_connection = The connection to mark as closed.
452 *********************************************************************/
453 static void mark_connection_closed(struct reusable_connection *closed_connection)
455 closed_connection->in_use = FALSE;
456 closed_connection->sfd = JB_INVALID_SOCKET;
457 freez(closed_connection->host);
458 closed_connection->port = 0;
459 closed_connection->timestamp = 0;
460 closed_connection->forwarder_type = SOCKS_NONE;
461 freez(closed_connection->gateway_host);
462 closed_connection->gateway_port = 0;
463 freez(closed_connection->forward_host);
464 closed_connection->forward_port = 0;
468 /*********************************************************************
470 * Function : forget_connection
472 * Description : Removes a previously remembered connection from
473 * the list of reusable connections.
476 * 1 : sfd = The socket belonging to the connection in question.
480 *********************************************************************/
481 void forget_connection(jb_socket sfd)
483 unsigned int slot = 0;
485 assert(sfd != JB_INVALID_SOCKET);
487 privoxy_mutex_lock(&connection_reuse_mutex);
489 for (slot = 0; slot < SZ(reusable_connection); slot++)
491 if (reusable_connection[slot].sfd == sfd)
493 assert(reusable_connection[slot].in_use);
498 if (reusable_connection[slot].sfd != sfd)
500 log_error(LOG_LEVEL_CONNECT,
501 "Socket %d already forgotten or never remembered.", sfd);
502 privoxy_mutex_unlock(&connection_reuse_mutex);
506 log_error(LOG_LEVEL_CONNECT,
507 "Forgetting socket %d for %s:%d in slot %d.",
508 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
510 mark_connection_closed(&reusable_connection[slot]);
512 privoxy_mutex_unlock(&connection_reuse_mutex);
516 /*********************************************************************
518 * Function : connection_destination_matches
520 * Description : Determines whether a remembered connection can
521 * be reused. That is whether the destination and
522 * the forwarding settings match.
525 * 1 : connection = The connection to check.
526 * 2 : http = The destination for the connection.
527 * 3 : fwd = The forwarder settings.
529 * Returns : TRUE for yes, FALSE otherwise.
531 *********************************************************************/
532 static int connection_destination_matches(const struct reusable_connection *connection,
533 const struct http_request *http,
534 const struct forward_spec *fwd)
536 /* XXX: Start of duplicated checks for debugging purposes. */
537 if (strcmpic(connection->host, http->host))
542 if (connection->forwarder_type != fwd->type)
544 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
545 connection->forwarder_type, fwd->type, http->host);
548 if (connection->gateway_port != fwd->gateway_port)
550 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
551 connection->gateway_port, fwd->gateway_port, http->host);
554 if (connection->forward_port != fwd->forward_port)
556 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
557 connection->forward_port, fwd->forward_port, http->host);
560 if (connection->forward_port != fwd->forward_port)
562 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
563 connection->forward_port, fwd->forward_port, http->host);
567 /* XXX: End of duplicated checks for debugging purposes. */
569 if ((connection->forwarder_type != fwd->type)
570 || (connection->gateway_port != fwd->gateway_port)
571 || (connection->forward_port != fwd->forward_port)
572 || (connection->port != http->port))
577 if (( (NULL != connection->gateway_host)
578 && (NULL != fwd->gateway_host)
579 && strcmpic(connection->gateway_host, fwd->gateway_host))
580 && (connection->gateway_host != fwd->gateway_host))
582 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
586 if (( (NULL != connection->forward_host)
587 && (NULL != fwd->forward_host)
588 && strcmpic(connection->forward_host, fwd->forward_host))
589 && (connection->forward_host != fwd->forward_host))
591 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
595 return (!strcmpic(connection->host, http->host));
600 /*********************************************************************
602 * Function : socket_is_still_usable
604 * Description : Decides whether or not an open socket is still usable.
607 * 1 : sfd = The socket to check.
609 * Returns : TRUE for yes, otherwise FALSE.
611 *********************************************************************/
612 static int socket_is_still_usable(jb_socket sfd)
616 struct pollfd poll_fd[1];
618 memset(poll_fd, 0, sizeof(poll_fd));
620 poll_fd[0].events = POLLIN;
622 poll_result = poll(poll_fd, 1, 0);
624 if (-1 != poll_result)
626 return !(poll_fd[0].revents & POLLIN);
630 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
635 struct timeval timeout;
637 int socket_is_alive = 0;
639 memset(&timeout, '\0', sizeof(timeout));
640 /* timeout.tv_usec = 150;*/
641 FD_ZERO(&readable_fds);
642 FD_SET(sfd, &readable_fds);
644 ret = select((int)sfd+1, &readable_fds, NULL, NULL, &timeout);
647 log_error(LOG_LEVEL_ERROR, "select() failed!: %E");
651 * XXX: I'm not sure why !FD_ISSET() works,
652 * but apparently it does.
654 socket_is_alive = !FD_ISSET(sfd, &readable_fds);
656 log_error(LOG_LEVEL_INFO,
657 "Detecting already dead sockets might not work correctly "
658 "on your platform. Anyway, socket %d appears to be %s.",
659 sfd, (socket_is_alive ? "still alive" : "already dead"));
661 return socket_is_alive;
662 #endif /* def HAVE_POLL */
666 /*********************************************************************
668 * Function : get_reusable_connection
670 * Description : Returns an open socket to a previously remembered
671 * open connection (if there is one).
674 * 1 : http = The destination for the connection.
675 * 2 : fwd = The forwarder settings.
677 * Returns : JB_INVALID_SOCKET => No reusable connection found,
678 * otherwise a usable socket.
680 *********************************************************************/
681 static jb_socket get_reusable_connection(const struct http_request *http,
682 const struct forward_spec *fwd)
684 jb_socket sfd = JB_INVALID_SOCKET;
685 unsigned int slot = 0;
687 privoxy_mutex_lock(&connection_reuse_mutex);
689 for (slot = 0; slot < SZ(reusable_connection); slot++)
691 if (!reusable_connection[slot].in_use
692 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
694 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
696 if (CONNECTION_KEEP_ALIVE_TIMEOUT < time_open)
698 log_error(LOG_LEVEL_CONNECT,
699 "The connection to %s:%d in slot %d timed out. Closing.",
700 reusable_connection[slot].host, reusable_connection[slot].port,
702 mark_connection_closed(&reusable_connection[slot]);
706 if (!socket_is_still_usable(reusable_connection[slot].sfd))
708 log_error(LOG_LEVEL_CONNECT,
709 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
710 reusable_connection[slot].sfd, reusable_connection[slot].host,
711 reusable_connection[slot].port, slot);
712 mark_connection_closed(&reusable_connection[slot]);
716 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
718 reusable_connection[slot].in_use = TRUE;
719 sfd = reusable_connection[slot].sfd;
720 log_error(LOG_LEVEL_CONNECT,
721 "Found reusable socket %d for %s:%d in slot %d.",
722 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
728 privoxy_mutex_unlock(&connection_reuse_mutex);
735 /*********************************************************************
737 * Function : mark_connection_unused
739 * Description : Gives a remembered connection free for reuse.
742 * 1 : sfd = The socket belonging to the connection in question.
744 * Returns : TRUE => Socket found and marked as unused.
745 * FALSE => Socket not found.
747 *********************************************************************/
748 static int mark_connection_unused(jb_socket sfd)
750 unsigned int slot = 0;
751 int socket_found = FALSE;
753 assert(sfd != JB_INVALID_SOCKET);
755 privoxy_mutex_lock(&connection_reuse_mutex);
757 for (slot = 0; slot < SZ(reusable_connection); slot++)
759 if (reusable_connection[slot].sfd == sfd)
761 assert(reusable_connection[slot].in_use);
766 if (reusable_connection[slot].sfd == sfd)
769 log_error(LOG_LEVEL_CONNECT,
770 "Marking open socket %d for %s:%d in slot %d as unused.",
771 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
772 reusable_connection[slot].in_use = 0;
773 reusable_connection[slot].timestamp = time(NULL);
776 privoxy_mutex_unlock(&connection_reuse_mutex);
781 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
784 /*********************************************************************
786 * Function : forwarded_connect
788 * Description : Connect to a specified web server, possibly via
789 * a HTTP proxy and/or a SOCKS proxy.
792 * 1 : fwd = the proxies to use when connecting.
793 * 2 : http = the http request and apropos headers
794 * 3 : csp = Current client state (buffers, headers, etc...)
796 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
798 *********************************************************************/
799 jb_socket forwarded_connect(const struct forward_spec * fwd,
800 struct http_request *http,
801 struct client_state *csp)
803 const char * dest_host;
805 jb_socket sfd = JB_INVALID_SOCKET;
807 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
808 sfd = get_reusable_connection(http, fwd);
809 if (JB_INVALID_SOCKET == sfd)
811 log_error(LOG_LEVEL_CONNECT,
812 "No reusable socket for %s:%d found. Opening a new one.",
813 http->host, http->port);
819 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
821 /* Figure out if we need to connect to the web server or a HTTP proxy. */
822 if (fwd->forward_host)
825 dest_host = fwd->forward_host;
826 dest_port = fwd->forward_port;
831 dest_host = http->host;
832 dest_port = http->port;
835 /* Connect, maybe using a SOCKS proxy */
839 sfd = connect_to(dest_host, dest_port, csp);
843 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
846 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
849 /* Should never get here */
850 log_error(LOG_LEVEL_FATAL,
851 "SOCKS4 impossible internal error - bad SOCKS type.");
859 /*********************************************************************
861 * Function : socks4_connect
863 * Description : Connect to the SOCKS server, and connect through
864 * it to the specified server. This handles
865 * all the SOCKS negotiation, and returns a file
866 * descriptor for a socket which can be treated as a
867 * normal (non-SOCKS) socket.
869 * Logged error messages are saved to csp->error_message
870 * and later reused by error_response() for the CGI
871 * message. strdup allocation failures are handled there.
874 * 1 : fwd = Specifies the SOCKS proxy to use.
875 * 2 : target_host = The final server to connect to.
876 * 3 : target_port = The final port to connect to.
877 * 4 : csp = Current client state (buffers, headers, etc...)
879 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
881 *********************************************************************/
882 static jb_socket socks4_connect(const struct forward_spec * fwd,
883 const char * target_host,
885 struct client_state *csp)
887 unsigned int web_server_addr;
888 char buf[BUFFER_SIZE];
889 struct socks_op *c = (struct socks_op *)buf;
890 struct socks_reply *s = (struct socks_reply *)buf;
897 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
899 /* XXX: Shouldn't the config file parser prevent this? */
900 errstr = "NULL gateway host specified.";
904 if (fwd->gateway_port <= 0)
906 errstr = "invalid gateway port specified.";
912 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
913 csp->error_message = strdup(errstr);
915 return(JB_INVALID_SOCKET);
918 /* build a socks request for connection to the web server */
920 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
922 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
927 web_server_addr = resolve_hostname_to_ip(target_host);
928 if (web_server_addr == INADDR_NONE)
930 errstr = "could not resolve target host";
931 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
936 web_server_addr = htonl(web_server_addr);
940 web_server_addr = 0x00000001;
941 n = csiz + strlen(target_host) + 1;
945 errstr = "buffer cbuf too small.";
946 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
951 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
953 * What we forward to the socks4a server should have the
954 * size of socks_op, plus the length of the userid plus
955 * its \0 byte (which we don't have to add because the
956 * first byte of the userid is counted twice as it's also
957 * part of sock_op) minus the padding bytes (which are part
958 * of the userid as well), plus the length of the target_host
959 * (which is stored csiz bytes after the beginning of the buffer),
960 * plus another \0 byte.
962 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
967 /* Should never get here */
968 log_error(LOG_LEVEL_FATAL,
969 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
971 return(JB_INVALID_SOCKET);
976 csp->error_message = strdup(errstr);
977 return(JB_INVALID_SOCKET);
982 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
983 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
984 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
985 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
986 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
987 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
989 /* pass the request to the socks server */
990 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
992 if (sfd == JB_INVALID_SOCKET)
995 * XXX: connect_to should fill in the exact reason.
996 * Most likely resolving the IP of the forwarder failed.
998 errstr = "connect_to failed: see logfile for details";
1001 else if (write_socket(sfd, (char *)c, csiz))
1003 errstr = "SOCKS4 negotiation write failed.";
1004 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1008 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
1010 errstr = "SOCKS4 negotiation read failed.";
1011 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1018 csp->error_message = strdup(errstr);
1019 return(JB_INVALID_SOCKET);
1024 case SOCKS_REQUEST_GRANTED:
1027 case SOCKS_REQUEST_REJECT:
1028 errstr = "SOCKS request rejected or failed.";
1031 case SOCKS_REQUEST_IDENT_FAILED:
1032 errstr = "SOCKS request rejected because "
1033 "SOCKS server cannot connect to identd on the client.";
1036 case SOCKS_REQUEST_IDENT_CONFLICT:
1037 errstr = "SOCKS request rejected because "
1038 "the client program and identd report "
1039 "different user-ids.";
1044 snprintf(buf, sizeof(buf),
1045 "SOCKS request rejected for reason code %d.", s->cd);
1049 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1050 csp->error_message = strdup(errstr);
1053 return(JB_INVALID_SOCKET);
1057 /*********************************************************************
1059 * Function : translate_socks5_error
1061 * Description : Translates a SOCKS errors to a string.
1064 * 1 : socks_error = The error code to translate.
1066 * Returns : The string translation.
1068 *********************************************************************/
1069 static const char *translate_socks5_error(int socks_error)
1071 switch (socks_error)
1073 /* XXX: these should be more descriptive */
1074 case SOCKS5_REQUEST_FAILED:
1075 return "SOCKS5 request failed";
1076 case SOCKS5_REQUEST_DENIED:
1077 return "SOCKS5 request denied";
1078 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1079 return "SOCKS5 network unreachable";
1080 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1081 return "SOCKS5 host unreachable";
1082 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1083 return "SOCKS5 connection refused";
1084 case SOCKS5_REQUEST_TTL_EXPIRED:
1085 return "SOCKS5 TTL expired";
1086 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1087 return "SOCKS5 client protocol error";
1088 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1089 return "SOCKS5 domain names unsupported";
1090 case SOCKS5_REQUEST_GRANTED:
1091 return "everything's peachy";
1093 return "SOCKS5 negotiation protocol error";
1097 /*********************************************************************
1099 * Function : socks5_connect
1101 * Description : Connect to the SOCKS server, and connect through
1102 * it to the specified server. This handles
1103 * all the SOCKS negotiation, and returns a file
1104 * descriptor for a socket which can be treated as a
1105 * normal (non-SOCKS) socket.
1108 * 1 : fwd = Specifies the SOCKS proxy to use.
1109 * 2 : target_host = The final server to connect to.
1110 * 3 : target_port = The final port to connect to.
1111 * 4 : csp = Current client state (buffers, headers, etc...)
1113 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1115 *********************************************************************/
1116 static jb_socket socks5_connect(const struct forward_spec *fwd,
1117 const char *target_host,
1119 struct client_state *csp)
1124 size_t client_pos = 0;
1125 int server_size = 0;
1128 const char *errstr = NULL;
1130 assert(fwd->gateway_host);
1131 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1133 errstr = "NULL gateway host specified";
1137 if (fwd->gateway_port <= 0)
1140 * XXX: currently this can't happen because in
1141 * case of invalid gateway ports we use the defaults.
1142 * Of course we really shouldn't do that.
1144 errstr = "invalid gateway port specified";
1148 hostlen = strlen(target_host);
1151 errstr = "target host name is longer than 255 characters";
1155 if (fwd->type != SOCKS_5)
1157 /* Should never get here */
1158 log_error(LOG_LEVEL_FATAL,
1159 "SOCKS5 impossible internal error - bad SOCKS type");
1166 assert(errstr != NULL);
1167 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1168 csp->error_message = strdup(errstr);
1169 return(JB_INVALID_SOCKET);
1172 /* pass the request to the socks server */
1173 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1175 if (sfd == JB_INVALID_SOCKET)
1177 errstr = "socks5 server unreachable";
1178 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1179 csp->error_message = strdup(errstr);
1180 return(JB_INVALID_SOCKET);
1184 cbuf[client_pos++] = '\x05'; /* Version */
1185 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1186 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1188 if (write_socket(sfd, cbuf, client_pos))
1190 errstr = "SOCKS5 negotiation write failed";
1191 csp->error_message = strdup(errstr);
1192 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1194 return(JB_INVALID_SOCKET);
1197 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1199 errstr = "SOCKS5 negotiation read failed";
1203 if (!err && (sbuf[0] != '\x05'))
1205 errstr = "SOCKS5 negotiation protocol version error";
1209 if (!err && (sbuf[1] == '\xff'))
1211 errstr = "SOCKS5 authentication required";
1215 if (!err && (sbuf[1] != '\x00'))
1217 errstr = "SOCKS5 negotiation protocol error";
1223 assert(errstr != NULL);
1224 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1225 csp->error_message = strdup(errstr);
1228 return(JB_INVALID_SOCKET);
1232 cbuf[client_pos++] = '\x05'; /* Version */
1233 cbuf[client_pos++] = '\x01'; /* TCP connect */
1234 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1235 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1236 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1237 assert(sizeof(cbuf) - client_pos > 255);
1238 /* Using strncpy because we really want the nul byte padding. */
1239 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1240 client_pos += (hostlen & 0xffu);
1241 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1242 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1244 if (write_socket(sfd, cbuf, client_pos))
1246 errstr = "SOCKS5 negotiation read failed";
1247 csp->error_message = strdup(errstr);
1248 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1251 return(JB_INVALID_SOCKET);
1254 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1255 if (server_size < 3)
1257 errstr = "SOCKS5 negotiation read failed";
1260 else if (server_size > 20)
1262 /* This is somewhat unexpected but doesn't realy matter. */
1263 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1264 "from socks server. Would have accepted up to %d.",
1265 server_size, sizeof(sbuf));
1268 if (!err && (sbuf[0] != '\x05'))
1270 errstr = "SOCKS5 negotiation protocol version error";
1274 if (!err && (sbuf[2] != '\x00'))
1276 errstr = "SOCKS5 negotiation protocol error";
1282 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1286 errstr = translate_socks5_error(sbuf[1]);
1290 assert(errstr != NULL);
1291 csp->error_message = strdup(errstr);
1292 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1296 return(JB_INVALID_SOCKET);