1 const char gateway_rcs[] = "$Id: gateway.c,v 1.32 2008/10/16 16:27:22 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.32 2008/10/16 16:27:22 fabiankeil
38 * Fix compiler warning.
40 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
41 * - Factor socket_is_still_usable() out of get_reusable_connection().
42 * - If poll() isn't available, show a warning and assume the socket
45 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
46 * If a remembered connection is no longer usable and
47 * has been marked closed, don't bother checking if the
48 * destination matches.
50 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
51 * Add missing dots for two log messages.
53 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
54 * Flush work-in-progress changes to keep outgoing connections
55 * alive where possible. Incomplete and mostly #ifdef'd out.
57 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
58 * Return only once in forwarded_connect().
60 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
61 * Fix typo in macro name.
63 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
65 * - make the buffers quite a bit smaller.
66 * - properly report "socks5 server unreachable" failures.
67 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
68 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
69 * - log a message if the socks5 server sends more data than expected.
70 * - add some assertions and comments.
72 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
73 * - Fix a compiler warning.
74 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
76 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
77 * Remember the cause of the SOCKS5 error for the CGI message.
79 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
80 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
82 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
83 * Modified patch from Song Weijia (#1762559) to
84 * fix socks requests on big-endian platforms.
86 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
87 * - Use strlcpy() instead of strcpy().
88 * - Use the same buffer for socks requests and socks responses.
89 * - Fix bogus warning about web_server_addr being used uninitialized.
91 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
92 * - Save errors in socks4_connect() to csp->error_message.
93 * - Silence some gcc43 warnings, hopefully the right way.
95 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
96 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
97 * with what was really the latest development (the v_3_0_branch branch)
99 * Revision 1.16 2002/05/12 21:36:29 jongfoster
100 * Correcting function comments
102 * Revision 1.15 2002/03/26 22:29:54 swa
103 * we have a new homepage!
105 * Revision 1.14 2002/03/24 13:25:43 swa
106 * name change related issues
108 * Revision 1.13 2002/03/13 00:29:59 jongfoster
111 * Revision 1.12 2002/03/09 20:03:52 jongfoster
112 * - Making various functions return int rather than size_t.
113 * (Undoing a recent change). Since size_t is unsigned on
114 * Windows, functions like read_socket that return -1 on
115 * error cannot return a size_t.
117 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
118 * crashes, and also frequently caused JB to jump to 100%
119 * CPU and stay there. (Because it thought it had just
120 * read ((unsigned)-1) == 4Gb of data...)
122 * - The signature of write_socket has changed, it now simply
123 * returns success=0/failure=nonzero.
125 * - Trying to get rid of a few warnings --with-debug on
126 * Windows, I've introduced a new type "jb_socket". This is
127 * used for the socket file descriptors. On Windows, this
128 * is SOCKET (a typedef for unsigned). Everywhere else, it's
129 * an int. The error value can't be -1 any more, so it's
130 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
131 * Windows it maps to the #define INVALID_SOCKET.)
133 * - The signature of bind_port has changed.
135 * Revision 1.11 2002/03/08 17:46:04 jongfoster
136 * Fixing int/size_t warnings
138 * Revision 1.10 2002/03/07 03:50:19 oes
139 * - Improved handling of failed DNS lookups
140 * - Fixed compiler warnings
142 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
143 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
144 * threads to call select() simultaneously. So, it's time to do a real, live,
145 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
146 * (native). Both versions will work, but using __OS2__ offers multi-threading.
148 * Revision 1.8 2001/09/13 20:10:12 jongfoster
149 * Fixing missing #include under Windows
151 * Revision 1.7 2001/09/12 17:58:26 steudten
153 * add #include <string.h>
155 * Revision 1.6 2001/09/10 10:41:16 oes
156 * Added #include in.h
158 * Revision 1.5 2001/07/29 18:47:57 jongfoster
159 * Adding missing #include project.h
161 * Revision 1.4 2001/07/24 12:47:06 oes
162 * Applied BeOS support update by Eugenia
164 * Revision 1.3 2001/06/09 10:55:28 jongfoster
165 * Changing BUFSIZ ==> BUFFER_SIZE
167 * Revision 1.2 2001/06/07 23:11:38 jongfoster
168 * Removing gateways[] list - no longer used.
169 * Replacing function pointer in struct gateway with a directly
170 * called function forwarded_connect(), which can do the common
171 * task of deciding whether to connect to the web server or HTTP
173 * Replacing struct gateway with struct forward_spec
174 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
175 * It was a bug which led to the connection being made to the web
176 * server rather than the HTTP proxy, and also a buffer overrun.
178 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
179 * Initial import of version 2.9.3 source tree
182 *********************************************************************/
188 #include <sys/types.h>
191 #include <netinet/in.h>
199 #include <winsock2.h>
200 #endif /* def _WIN32 */
204 #endif /* def __BEOS__ */
208 #endif /* def __OS2__ */
213 #include "jbsockets.h"
215 #include "miscutil.h"
216 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
219 #include <sys/poll.h>
222 #endif /* def __GLIBC__ */
223 #endif /* HAVE_POLL */
224 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
226 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
228 static jb_socket socks4_connect(const struct forward_spec * fwd,
229 const char * target_host,
231 struct client_state *csp);
233 static jb_socket socks5_connect(const struct forward_spec *fwd,
234 const char *target_host,
236 struct client_state *csp);
239 #define SOCKS_REQUEST_GRANTED 90
240 #define SOCKS_REQUEST_REJECT 91
241 #define SOCKS_REQUEST_IDENT_FAILED 92
242 #define SOCKS_REQUEST_IDENT_CONFLICT 93
244 #define SOCKS5_REQUEST_GRANTED 0
245 #define SOCKS5_REQUEST_FAILED 1
246 #define SOCKS5_REQUEST_DENIED 2
247 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
248 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
249 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
250 #define SOCKS5_REQUEST_TTL_EXPIRED 6
251 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
252 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
254 /* structure of a socks client operation */
256 unsigned char vn; /* socks version number */
257 unsigned char cd; /* command code */
258 unsigned char dstport[2]; /* destination port */
259 unsigned char dstip[4]; /* destination address */
260 char userid; /* first byte of userid */
261 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
262 /* more bytes of the userid follow, terminated by a NULL */
265 /* structure of a socks server reply */
267 unsigned char vn; /* socks version number */
268 unsigned char cd; /* command code */
269 unsigned char dstport[2]; /* destination port */
270 unsigned char dstip[4]; /* destination address */
273 static const char socks_userid[] = "anonymous";
275 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
277 #define MAX_REUSABLE_CONNECTIONS 100
279 struct reusable_connection
293 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
295 static int mark_connection_unused(jb_socket sfd);
296 static void mark_connection_closed(struct reusable_connection *closed_connection);
298 /*********************************************************************
300 * Function : initialize_reusable_connections
302 * Description : Initializes the reusable_connection structures.
303 * Must be called with connection_reuse_mutex locked.
309 *********************************************************************/
310 extern void initialize_reusable_connections(void)
312 unsigned int slot = 0;
314 log_error(LOG_LEVEL_INFO,
315 "Support for 'Connection: keep-alive' is experimental, "
316 "incomplete and known not to work properly in some situations.");
318 for (slot = 0; slot < SZ(reusable_connection); slot++)
320 mark_connection_closed(&reusable_connection[slot]);
323 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
327 /*********************************************************************
329 * Function : remember_connection
331 * Description : Remembers a connection for reuse later on.
334 * 1 : sfd = Open socket to remember.
335 * 2 : http = The destination for the connection.
336 * 3 : fwd = The forwarder settings used.
340 *********************************************************************/
341 void remember_connection(jb_socket sfd, const struct http_request *http,
342 const struct forward_spec *fwd)
344 unsigned int slot = 0;
345 int free_slot_found = FALSE;
347 assert(sfd != JB_INVALID_SOCKET);
349 if (mark_connection_unused(sfd))
354 privoxy_mutex_lock(&connection_reuse_mutex);
356 /* Find free socket slot. */
357 for (slot = 0; slot < SZ(reusable_connection); slot++)
359 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
361 assert(reusable_connection[slot].in_use == 0);
362 log_error(LOG_LEVEL_CONNECT,
363 "Remembering socket %d for %s:%d in slot %d.",
364 sfd, http->host, http->port, slot);
365 free_slot_found = TRUE;
370 if (!free_slot_found)
372 log_error(LOG_LEVEL_CONNECT,
373 "No free slots found to remembering socket for %s:%d. Last slot %d.",
374 http->host, http->port, slot);
375 privoxy_mutex_unlock(&connection_reuse_mutex);
380 assert(NULL != http->host);
381 reusable_connection[slot].host = strdup(http->host);
382 if (NULL == reusable_connection[slot].host)
384 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
386 reusable_connection[slot].sfd = sfd;
387 reusable_connection[slot].port = http->port;
388 reusable_connection[slot].in_use = 0;
391 assert(reusable_connection[slot].gateway_host == NULL);
392 assert(reusable_connection[slot].gateway_port == 0);
393 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
394 assert(reusable_connection[slot].forward_host == NULL);
395 assert(reusable_connection[slot].forward_port == 0);
397 reusable_connection[slot].forwarder_type = fwd->type;
398 if (NULL != fwd->gateway_host)
400 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
401 if (NULL == reusable_connection[slot].gateway_host)
403 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
408 reusable_connection[slot].gateway_host = NULL;
410 reusable_connection[slot].gateway_port = fwd->gateway_port;
412 if (NULL != fwd->forward_host)
414 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
415 if (NULL == reusable_connection[slot].forward_host)
417 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
422 reusable_connection[slot].forward_host = NULL;
424 reusable_connection[slot].forward_port = fwd->forward_port;
426 privoxy_mutex_unlock(&connection_reuse_mutex);
430 /*********************************************************************
432 * Function : mark_connection_closed
434 * Description : Marks a reused connection closed.
435 * Must be called with connection_reuse_mutex locked.
438 * 1 : closed_connection = The connection to mark as closed.
442 *********************************************************************/
443 static void mark_connection_closed(struct reusable_connection *closed_connection)
445 closed_connection->in_use = FALSE;
446 closed_connection->sfd = JB_INVALID_SOCKET;
447 freez(closed_connection->host);
448 closed_connection->port = 0;
449 closed_connection->forwarder_type = SOCKS_NONE;
450 freez(closed_connection->gateway_host);
451 closed_connection->gateway_port = 0;
452 freez(closed_connection->forward_host);
453 closed_connection->forward_port = 0;
457 /*********************************************************************
459 * Function : forget_connection
461 * Description : Removes a previously remembered connection from
462 * the list of reusable connections.
465 * 1 : sfd = The socket belonging to the connection in question.
469 *********************************************************************/
470 void forget_connection(jb_socket sfd)
472 unsigned int slot = 0;
474 assert(sfd != JB_INVALID_SOCKET);
476 privoxy_mutex_lock(&connection_reuse_mutex);
478 for (slot = 0; slot < SZ(reusable_connection); slot++)
480 if (reusable_connection[slot].sfd == sfd)
482 assert(reusable_connection[slot].in_use);
487 if (reusable_connection[slot].sfd != sfd)
489 log_error(LOG_LEVEL_CONNECT,
490 "Socket %d already forgotten or never remembered.", sfd);
491 privoxy_mutex_unlock(&connection_reuse_mutex);
495 log_error(LOG_LEVEL_CONNECT,
496 "Forgetting socket %d for %s:%d in slot %d.",
497 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
499 mark_connection_closed(&reusable_connection[slot]);
501 privoxy_mutex_unlock(&connection_reuse_mutex);
505 /*********************************************************************
507 * Function : connection_destination_matches
509 * Description : Determines whether a remembered connection can
510 * be reused. That is whether the destination and
511 * the forwarding settings match.
514 * 1 : connection = The connection to check.
515 * 2 : http = The destination for the connection.
516 * 3 : fwd = The forwarder settings.
518 * Returns : TRUE for yes, FALSE otherwise.
520 *********************************************************************/
521 static int connection_destination_matches(const struct reusable_connection *connection,
522 const struct http_request *http,
523 const struct forward_spec *fwd)
525 /* XXX: Start of duplicated checks for debugging purposes. */
526 if (strcmpic(connection->host, http->host))
531 if (connection->forwarder_type != fwd->type)
533 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
534 connection->forwarder_type, fwd->type, http->host);
537 if (connection->gateway_port != fwd->gateway_port)
539 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
540 connection->gateway_port, fwd->gateway_port, http->host);
543 if (connection->forward_port != fwd->forward_port)
545 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
546 connection->forward_port, fwd->forward_port, http->host);
549 if (connection->forward_port != fwd->forward_port)
551 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
552 connection->forward_port, fwd->forward_port, http->host);
556 /* XXX: End of duplicated checks for debugging purposes. */
558 if ((connection->forwarder_type != fwd->type)
559 || (connection->gateway_port != fwd->gateway_port)
560 || (connection->forward_port != fwd->forward_port)
561 || (connection->port != http->port))
566 if (( (NULL != connection->gateway_host)
567 && (NULL != fwd->gateway_host)
568 && strcmpic(connection->gateway_host, fwd->gateway_host))
569 && (connection->gateway_host != fwd->gateway_host))
571 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
575 if (( (NULL != connection->forward_host)
576 && (NULL != fwd->forward_host)
577 && strcmpic(connection->forward_host, fwd->forward_host))
578 && (connection->forward_host != fwd->forward_host))
580 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
584 return (!strcmpic(connection->host, http->host));
589 /*********************************************************************
591 * Function : socket_is_still_usable
593 * Description : Decides whether or not an open socket is still usable.
596 * 1 : sfd = The socket to check.
598 * Returns : TRUE for yes, otherwise FALSE.
600 *********************************************************************/
601 static int socket_is_still_usable(jb_socket sfd)
605 struct pollfd poll_fd[1];
606 memset(poll_fd, 0, sizeof(poll_fd));
608 poll_fd[0].events = POLLIN;
610 poll_result = poll(poll_fd, 1, 0);
612 if (-1 != poll_result)
614 return !(poll_fd[0].revents & POLLIN);
618 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
622 log_error(LOG_LEVEL_INFO,
623 "Detecting already dead sockets isn't implemented for your "
624 "platform yet. Assuming sockets stay alive forever, expect "
625 "an increase in connection problems.");
627 #endif /* def HAVE_POLL */
631 /*********************************************************************
633 * Function : get_reusable_connection
635 * Description : Returns an open socket to a previously remembered
636 * open connection (if there is one).
639 * 1 : http = The destination for the connection.
640 * 2 : fwd = The forwarder settings.
642 * Returns : JB_INVALID_SOCKET => No reusable connection found,
643 * otherwise a usable socket.
645 *********************************************************************/
646 static jb_socket get_reusable_connection(const struct http_request *http,
647 const struct forward_spec *fwd)
649 jb_socket sfd = JB_INVALID_SOCKET;
650 unsigned int slot = 0;
652 privoxy_mutex_lock(&connection_reuse_mutex);
654 for (slot = 0; slot < SZ(reusable_connection); slot++)
656 if (!reusable_connection[slot].in_use
657 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
659 if (!socket_is_still_usable(reusable_connection[slot].sfd))
661 log_error(LOG_LEVEL_CONNECT,
662 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
663 reusable_connection[slot].sfd, reusable_connection[slot].host,
664 reusable_connection[slot].port, slot);
665 mark_connection_closed(&reusable_connection[slot]);
669 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
671 reusable_connection[slot].in_use = TRUE;
672 sfd = reusable_connection[slot].sfd;
673 log_error(LOG_LEVEL_CONNECT,
674 "Found reusable socket %d for %s:%d in slot %d.",
675 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
681 privoxy_mutex_unlock(&connection_reuse_mutex);
688 /*********************************************************************
690 * Function : mark_connection_unused
692 * Description : Gives a remembered connection free for reuse.
695 * 1 : sfd = The socket belonging to the connection in question.
697 * Returns : TRUE => Socket found and marked as unused.
698 * FALSE => Socket not found.
700 *********************************************************************/
701 static int mark_connection_unused(jb_socket sfd)
703 unsigned int slot = 0;
704 int socket_found = FALSE;
706 assert(sfd != JB_INVALID_SOCKET);
708 privoxy_mutex_lock(&connection_reuse_mutex);
710 for (slot = 0; slot < SZ(reusable_connection); slot++)
712 if (reusable_connection[slot].sfd == sfd)
714 assert(reusable_connection[slot].in_use);
719 if (reusable_connection[slot].sfd == sfd)
722 log_error(LOG_LEVEL_CONNECT,
723 "Marking open socket %d for %s:%d in slot %d as unused.",
724 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
725 reusable_connection[slot].in_use = 0;
728 privoxy_mutex_unlock(&connection_reuse_mutex);
733 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
736 /*********************************************************************
738 * Function : forwarded_connect
740 * Description : Connect to a specified web server, possibly via
741 * a HTTP proxy and/or a SOCKS proxy.
744 * 1 : fwd = the proxies to use when connecting.
745 * 2 : http = the http request and apropos headers
746 * 3 : csp = Current client state (buffers, headers, etc...)
748 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
750 *********************************************************************/
751 jb_socket forwarded_connect(const struct forward_spec * fwd,
752 struct http_request *http,
753 struct client_state *csp)
755 const char * dest_host;
757 jb_socket sfd = JB_INVALID_SOCKET;
759 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
760 sfd = get_reusable_connection(http, fwd);
761 if (JB_INVALID_SOCKET == sfd)
763 log_error(LOG_LEVEL_CONNECT,
764 "No reusable socket for %s:%d found. Opening a new one.",
765 http->host, http->port);
771 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
773 /* Figure out if we need to connect to the web server or a HTTP proxy. */
774 if (fwd->forward_host)
777 dest_host = fwd->forward_host;
778 dest_port = fwd->forward_port;
783 dest_host = http->host;
784 dest_port = http->port;
787 /* Connect, maybe using a SOCKS proxy */
791 sfd = connect_to(dest_host, dest_port, csp);
795 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
798 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
801 /* Should never get here */
802 log_error(LOG_LEVEL_FATAL,
803 "SOCKS4 impossible internal error - bad SOCKS type.");
811 /*********************************************************************
813 * Function : socks4_connect
815 * Description : Connect to the SOCKS server, and connect through
816 * it to the specified server. This handles
817 * all the SOCKS negotiation, and returns a file
818 * descriptor for a socket which can be treated as a
819 * normal (non-SOCKS) socket.
821 * Logged error messages are saved to csp->error_message
822 * and later reused by error_response() for the CGI
823 * message. strdup allocation failures are handled there.
826 * 1 : fwd = Specifies the SOCKS proxy to use.
827 * 2 : target_host = The final server to connect to.
828 * 3 : target_port = The final port to connect to.
829 * 4 : csp = Current client state (buffers, headers, etc...)
831 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
833 *********************************************************************/
834 static jb_socket socks4_connect(const struct forward_spec * fwd,
835 const char * target_host,
837 struct client_state *csp)
839 unsigned int web_server_addr;
840 char buf[BUFFER_SIZE];
841 struct socks_op *c = (struct socks_op *)buf;
842 struct socks_reply *s = (struct socks_reply *)buf;
849 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
851 /* XXX: Shouldn't the config file parser prevent this? */
852 errstr = "NULL gateway host specified.";
856 if (fwd->gateway_port <= 0)
858 errstr = "invalid gateway port specified.";
864 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
865 csp->error_message = strdup(errstr);
867 return(JB_INVALID_SOCKET);
870 /* build a socks request for connection to the web server */
872 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
874 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
879 web_server_addr = resolve_hostname_to_ip(target_host);
880 if (web_server_addr == INADDR_NONE)
882 errstr = "could not resolve target host";
883 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
888 web_server_addr = htonl(web_server_addr);
892 web_server_addr = 0x00000001;
893 n = csiz + strlen(target_host) + 1;
897 errstr = "buffer cbuf too small.";
898 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
903 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
905 * What we forward to the socks4a server should have the
906 * size of socks_op, plus the length of the userid plus
907 * its \0 byte (which we don't have to add because the
908 * first byte of the userid is counted twice as it's also
909 * part of sock_op) minus the padding bytes (which are part
910 * of the userid as well), plus the length of the target_host
911 * (which is stored csiz bytes after the beginning of the buffer),
912 * plus another \0 byte.
914 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
919 /* Should never get here */
920 log_error(LOG_LEVEL_FATAL,
921 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
923 return(JB_INVALID_SOCKET);
928 csp->error_message = strdup(errstr);
929 return(JB_INVALID_SOCKET);
934 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
935 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
936 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
937 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
938 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
939 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
941 /* pass the request to the socks server */
942 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
944 if (sfd == JB_INVALID_SOCKET)
947 * XXX: connect_to should fill in the exact reason.
948 * Most likely resolving the IP of the forwarder failed.
950 errstr = "connect_to failed: see logfile for details";
953 else if (write_socket(sfd, (char *)c, csiz))
955 errstr = "SOCKS4 negotiation write failed.";
956 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
960 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
962 errstr = "SOCKS4 negotiation read failed.";
963 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
970 csp->error_message = strdup(errstr);
971 return(JB_INVALID_SOCKET);
976 case SOCKS_REQUEST_GRANTED:
979 case SOCKS_REQUEST_REJECT:
980 errstr = "SOCKS request rejected or failed.";
983 case SOCKS_REQUEST_IDENT_FAILED:
984 errstr = "SOCKS request rejected because "
985 "SOCKS server cannot connect to identd on the client.";
988 case SOCKS_REQUEST_IDENT_CONFLICT:
989 errstr = "SOCKS request rejected because "
990 "the client program and identd report "
991 "different user-ids.";
996 snprintf(buf, sizeof(buf),
997 "SOCKS request rejected for reason code %d.", s->cd);
1001 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1002 csp->error_message = strdup(errstr);
1005 return(JB_INVALID_SOCKET);
1009 /*********************************************************************
1011 * Function : translate_socks5_error
1013 * Description : Translates a SOCKS errors to a string.
1016 * 1 : socks_error = The error code to translate.
1018 * Returns : The string translation.
1020 *********************************************************************/
1021 static const char *translate_socks5_error(int socks_error)
1023 switch (socks_error)
1025 /* XXX: these should be more descriptive */
1026 case SOCKS5_REQUEST_FAILED:
1027 return "SOCKS5 request failed";
1028 case SOCKS5_REQUEST_DENIED:
1029 return "SOCKS5 request denied";
1030 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1031 return "SOCKS5 network unreachable";
1032 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1033 return "SOCKS5 host unreachable";
1034 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1035 return "SOCKS5 connection refused";
1036 case SOCKS5_REQUEST_TTL_EXPIRED:
1037 return "SOCKS5 TTL expired";
1038 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1039 return "SOCKS5 client protocol error";
1040 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1041 return "SOCKS5 domain names unsupported";
1042 case SOCKS5_REQUEST_GRANTED:
1043 return "everything's peachy";
1045 return "SOCKS5 negotiation protocol error";
1049 /*********************************************************************
1051 * Function : socks5_connect
1053 * Description : Connect to the SOCKS server, and connect through
1054 * it to the specified server. This handles
1055 * all the SOCKS negotiation, and returns a file
1056 * descriptor for a socket which can be treated as a
1057 * normal (non-SOCKS) socket.
1060 * 1 : fwd = Specifies the SOCKS proxy to use.
1061 * 2 : target_host = The final server to connect to.
1062 * 3 : target_port = The final port to connect to.
1063 * 4 : csp = Current client state (buffers, headers, etc...)
1065 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1067 *********************************************************************/
1068 static jb_socket socks5_connect(const struct forward_spec *fwd,
1069 const char *target_host,
1071 struct client_state *csp)
1076 size_t client_pos = 0;
1077 int server_size = 0;
1080 const char *errstr = NULL;
1082 assert(fwd->gateway_host);
1083 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1085 errstr = "NULL gateway host specified";
1089 if (fwd->gateway_port <= 0)
1092 * XXX: currently this can't happen because in
1093 * case of invalid gateway ports we use the defaults.
1094 * Of course we really shouldn't do that.
1096 errstr = "invalid gateway port specified";
1100 hostlen = strlen(target_host);
1103 errstr = "target host name is longer than 255 characters";
1107 if (fwd->type != SOCKS_5)
1109 /* Should never get here */
1110 log_error(LOG_LEVEL_FATAL,
1111 "SOCKS5 impossible internal error - bad SOCKS type");
1118 assert(errstr != NULL);
1119 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1120 csp->error_message = strdup(errstr);
1121 return(JB_INVALID_SOCKET);
1124 /* pass the request to the socks server */
1125 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1127 if (sfd == JB_INVALID_SOCKET)
1129 errstr = "socks5 server unreachable";
1130 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1131 csp->error_message = strdup(errstr);
1132 return(JB_INVALID_SOCKET);
1136 cbuf[client_pos++] = '\x05'; /* Version */
1137 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1138 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1140 if (write_socket(sfd, cbuf, client_pos))
1142 errstr = "SOCKS5 negotiation write failed";
1143 csp->error_message = strdup(errstr);
1144 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1146 return(JB_INVALID_SOCKET);
1149 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1151 errstr = "SOCKS5 negotiation read failed";
1155 if (!err && (sbuf[0] != '\x05'))
1157 errstr = "SOCKS5 negotiation protocol version error";
1161 if (!err && (sbuf[1] == '\xff'))
1163 errstr = "SOCKS5 authentication required";
1167 if (!err && (sbuf[1] != '\x00'))
1169 errstr = "SOCKS5 negotiation protocol error";
1175 assert(errstr != NULL);
1176 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1177 csp->error_message = strdup(errstr);
1180 return(JB_INVALID_SOCKET);
1184 cbuf[client_pos++] = '\x05'; /* Version */
1185 cbuf[client_pos++] = '\x01'; /* TCP connect */
1186 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1187 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1188 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1189 assert(sizeof(cbuf) - client_pos > 255);
1190 /* Using strncpy because we really want the nul byte padding. */
1191 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1192 client_pos += (hostlen & 0xffu);
1193 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1194 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1196 if (write_socket(sfd, cbuf, client_pos))
1198 errstr = "SOCKS5 negotiation read failed";
1199 csp->error_message = strdup(errstr);
1200 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1203 return(JB_INVALID_SOCKET);
1206 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1207 if (server_size < 3)
1209 errstr = "SOCKS5 negotiation read failed";
1212 else if (server_size > 20)
1214 /* This is somewhat unexpected but doesn't realy matter. */
1215 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1216 "from socks server. Would have accepted up to %d.",
1217 server_size, sizeof(sbuf));
1220 if (!err && (sbuf[0] != '\x05'))
1222 errstr = "SOCKS5 negotiation protocol version error";
1226 if (!err && (sbuf[2] != '\x00'))
1228 errstr = "SOCKS5 negotiation protocol error";
1234 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1238 errstr = translate_socks5_error(sbuf[1]);
1242 assert(errstr != NULL);
1243 csp->error_message = strdup(errstr);
1244 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1248 return(JB_INVALID_SOCKET);