1 const char gateway_rcs[] = "$Id: gateway.c,v 1.28 2008/10/09 18:21:41 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.28 2008/10/09 18:21:41 fabiankeil
38 * Flush work-in-progress changes to keep outgoing connections
39 * alive where possible. Incomplete and mostly #ifdef'd out.
41 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
42 * Return only once in forwarded_connect().
44 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
45 * Fix typo in macro name.
47 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
49 * - make the buffers quite a bit smaller.
50 * - properly report "socks5 server unreachable" failures.
51 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
52 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
53 * - log a message if the socks5 server sends more data than expected.
54 * - add some assertions and comments.
56 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
57 * - Fix a compiler warning.
58 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
60 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
61 * Remember the cause of the SOCKS5 error for the CGI message.
63 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
64 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
66 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
67 * Modified patch from Song Weijia (#1762559) to
68 * fix socks requests on big-endian platforms.
70 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
71 * - Use strlcpy() instead of strcpy().
72 * - Use the same buffer for socks requests and socks responses.
73 * - Fix bogus warning about web_server_addr being used uninitialized.
75 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
76 * - Save errors in socks4_connect() to csp->error_message.
77 * - Silence some gcc43 warnings, hopefully the right way.
79 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
80 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
81 * with what was really the latest development (the v_3_0_branch branch)
83 * Revision 1.16 2002/05/12 21:36:29 jongfoster
84 * Correcting function comments
86 * Revision 1.15 2002/03/26 22:29:54 swa
87 * we have a new homepage!
89 * Revision 1.14 2002/03/24 13:25:43 swa
90 * name change related issues
92 * Revision 1.13 2002/03/13 00:29:59 jongfoster
95 * Revision 1.12 2002/03/09 20:03:52 jongfoster
96 * - Making various functions return int rather than size_t.
97 * (Undoing a recent change). Since size_t is unsigned on
98 * Windows, functions like read_socket that return -1 on
99 * error cannot return a size_t.
101 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
102 * crashes, and also frequently caused JB to jump to 100%
103 * CPU and stay there. (Because it thought it had just
104 * read ((unsigned)-1) == 4Gb of data...)
106 * - The signature of write_socket has changed, it now simply
107 * returns success=0/failure=nonzero.
109 * - Trying to get rid of a few warnings --with-debug on
110 * Windows, I've introduced a new type "jb_socket". This is
111 * used for the socket file descriptors. On Windows, this
112 * is SOCKET (a typedef for unsigned). Everywhere else, it's
113 * an int. The error value can't be -1 any more, so it's
114 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
115 * Windows it maps to the #define INVALID_SOCKET.)
117 * - The signature of bind_port has changed.
119 * Revision 1.11 2002/03/08 17:46:04 jongfoster
120 * Fixing int/size_t warnings
122 * Revision 1.10 2002/03/07 03:50:19 oes
123 * - Improved handling of failed DNS lookups
124 * - Fixed compiler warnings
126 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
127 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
128 * threads to call select() simultaneously. So, it's time to do a real, live,
129 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
130 * (native). Both versions will work, but using __OS2__ offers multi-threading.
132 * Revision 1.8 2001/09/13 20:10:12 jongfoster
133 * Fixing missing #include under Windows
135 * Revision 1.7 2001/09/12 17:58:26 steudten
137 * add #include <string.h>
139 * Revision 1.6 2001/09/10 10:41:16 oes
140 * Added #include in.h
142 * Revision 1.5 2001/07/29 18:47:57 jongfoster
143 * Adding missing #include project.h
145 * Revision 1.4 2001/07/24 12:47:06 oes
146 * Applied BeOS support update by Eugenia
148 * Revision 1.3 2001/06/09 10:55:28 jongfoster
149 * Changing BUFSIZ ==> BUFFER_SIZE
151 * Revision 1.2 2001/06/07 23:11:38 jongfoster
152 * Removing gateways[] list - no longer used.
153 * Replacing function pointer in struct gateway with a directly
154 * called function forwarded_connect(), which can do the common
155 * task of deciding whether to connect to the web server or HTTP
157 * Replacing struct gateway with struct forward_spec
158 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
159 * It was a bug which led to the connection being made to the web
160 * server rather than the HTTP proxy, and also a buffer overrun.
162 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
163 * Initial import of version 2.9.3 source tree
166 *********************************************************************/
172 #include <sys/types.h>
175 #include <netinet/in.h>
183 #include <winsock2.h>
184 #endif /* def _WIN32 */
188 #endif /* def __BEOS__ */
192 #endif /* def __OS2__ */
197 #include "jbsockets.h"
199 #include "miscutil.h"
200 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
202 #include <sys/poll.h>
203 #endif /* __GLIBC__ */
205 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
207 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
209 static jb_socket socks4_connect(const struct forward_spec * fwd,
210 const char * target_host,
212 struct client_state *csp);
214 static jb_socket socks5_connect(const struct forward_spec *fwd,
215 const char *target_host,
217 struct client_state *csp);
220 #define SOCKS_REQUEST_GRANTED 90
221 #define SOCKS_REQUEST_REJECT 91
222 #define SOCKS_REQUEST_IDENT_FAILED 92
223 #define SOCKS_REQUEST_IDENT_CONFLICT 93
225 #define SOCKS5_REQUEST_GRANTED 0
226 #define SOCKS5_REQUEST_FAILED 1
227 #define SOCKS5_REQUEST_DENIED 2
228 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
229 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
230 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
231 #define SOCKS5_REQUEST_TTL_EXPIRED 6
232 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
233 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
235 /* structure of a socks client operation */
237 unsigned char vn; /* socks version number */
238 unsigned char cd; /* command code */
239 unsigned char dstport[2]; /* destination port */
240 unsigned char dstip[4]; /* destination address */
241 char userid; /* first byte of userid */
242 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
243 /* more bytes of the userid follow, terminated by a NULL */
246 /* structure of a socks server reply */
248 unsigned char vn; /* socks version number */
249 unsigned char cd; /* command code */
250 unsigned char dstport[2]; /* destination port */
251 unsigned char dstip[4]; /* destination address */
254 static const char socks_userid[] = "anonymous";
256 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
258 #define MAX_REUSABLE_CONNECTIONS 100
260 struct reusable_connection
274 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
276 static int mark_connection_unused(jb_socket sfd);
277 static void mark_connection_closed(struct reusable_connection *closed_connection);
279 /*********************************************************************
281 * Function : initialize_reusable_connections
283 * Description : Initializes the reusable_connection structures.
284 * Must be called with connection_reuse_mutex locked.
290 *********************************************************************/
291 extern void initialize_reusable_connections(void)
293 unsigned int slot = 0;
295 log_error(LOG_LEVEL_INFO,
296 "Support for 'Connection: keep-alive' is experimental, "
297 "incomplete and known not to work properly in some situations.");
299 for (slot = 0; slot < SZ(reusable_connection); slot++)
301 mark_connection_closed(&reusable_connection[slot]);
304 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
308 /*********************************************************************
310 * Function : remember_connection
312 * Description : Remembers a connection for reuse later on.
315 * 1 : sfd = Open socket to remember.
316 * 2 : http = The destination for the connection.
317 * 3 : fwd = The forwarder settings used.
321 *********************************************************************/
322 void remember_connection(jb_socket sfd, const struct http_request *http,
323 const struct forward_spec *fwd)
325 unsigned int slot = 0;
326 int free_slot_found = FALSE;
328 assert(sfd != JB_INVALID_SOCKET);
330 if (mark_connection_unused(sfd))
335 privoxy_mutex_lock(&connection_reuse_mutex);
337 /* Find free socket slot. */
338 for (slot = 0; slot < SZ(reusable_connection); slot++)
340 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
342 assert(reusable_connection[slot].in_use == 0);
343 log_error(LOG_LEVEL_CONNECT,
344 "Remembering socket %d for %s:%d in slot %d.",
345 sfd, http->host, http->port, slot);
346 free_slot_found = TRUE;
351 if (!free_slot_found)
353 log_error(LOG_LEVEL_CONNECT,
354 "No free slots found to remembering socket for %s:%d. Last slot %d.",
355 http->host, http->port, slot);
356 privoxy_mutex_unlock(&connection_reuse_mutex);
361 assert(NULL != http->host);
362 reusable_connection[slot].host = strdup(http->host);
363 if (NULL == reusable_connection[slot].host)
365 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
367 reusable_connection[slot].sfd = sfd;
368 reusable_connection[slot].port = http->port;
369 reusable_connection[slot].in_use = 0;
372 assert(reusable_connection[slot].gateway_host == NULL);
373 assert(reusable_connection[slot].gateway_port == 0);
374 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
375 assert(reusable_connection[slot].forward_host == NULL);
376 assert(reusable_connection[slot].forward_port == 0);
378 reusable_connection[slot].forwarder_type = fwd->type;
379 if (NULL != fwd->gateway_host)
381 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
382 if (NULL == reusable_connection[slot].gateway_host)
384 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
389 reusable_connection[slot].gateway_host = NULL;
391 reusable_connection[slot].gateway_port = fwd->gateway_port;
393 if (NULL != fwd->forward_host)
395 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
396 if (NULL == reusable_connection[slot].forward_host)
398 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
403 reusable_connection[slot].forward_host = NULL;
405 reusable_connection[slot].forward_port = fwd->forward_port;
407 privoxy_mutex_unlock(&connection_reuse_mutex);
411 /*********************************************************************
413 * Function : mark_connection_closed
415 * Description : Marks a reused connection closed.
416 * Must be called with connection_reuse_mutex locked.
419 * 1 : closed_connection = The connection to mark as closed.
423 *********************************************************************/
424 static void mark_connection_closed(struct reusable_connection *closed_connection)
426 closed_connection->in_use = FALSE;
427 closed_connection->sfd = JB_INVALID_SOCKET;
428 freez(closed_connection->host);
429 closed_connection->port = 0;
430 closed_connection->forwarder_type = SOCKS_NONE;
431 freez(closed_connection->gateway_host);
432 closed_connection->gateway_port = 0;
433 freez(closed_connection->forward_host);
434 closed_connection->forward_port = 0;
438 /*********************************************************************
440 * Function : forget_connection
442 * Description : Removes a previously remembered connection from
443 * the list of reusable connections.
446 * 1 : sfd = The socket belonging to the connection in question.
450 *********************************************************************/
451 void forget_connection(jb_socket sfd)
453 unsigned int slot = 0;
455 assert(sfd != JB_INVALID_SOCKET);
457 privoxy_mutex_lock(&connection_reuse_mutex);
459 for (slot = 0; slot < SZ(reusable_connection); slot++)
461 if (reusable_connection[slot].sfd == sfd)
463 assert(reusable_connection[slot].in_use);
468 if (reusable_connection[slot].sfd != sfd)
470 log_error(LOG_LEVEL_CONNECT,
471 "Socket %d already forgotten or never remembered.", sfd);
472 privoxy_mutex_unlock(&connection_reuse_mutex);
476 log_error(LOG_LEVEL_CONNECT,
477 "Forgetting socket %d for %s:%d in slot %d.",
478 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
480 mark_connection_closed(&reusable_connection[slot]);
482 privoxy_mutex_unlock(&connection_reuse_mutex);
486 /*********************************************************************
488 * Function : connection_destination_matches
490 * Description : Determines whether a remembered connection can
491 * be reused. That is whether the destination and
492 * the forwarding settings match.
495 * 1 : connection = The connection to check.
496 * 2 : http = The destination for the connection.
497 * 3 : fwd = The forwarder settings.
499 * Returns : TRUE for yes, FALSE otherwise.
501 *********************************************************************/
502 static int connection_destination_matches(const struct reusable_connection *connection,
503 const struct http_request *http,
504 const struct forward_spec *fwd)
506 /* XXX: Start of duplicated checks for debugging purposes. */
507 if (strcmpic(connection->host, http->host))
512 if (connection->forwarder_type != fwd->type)
514 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
515 connection->forwarder_type, fwd->type, http->host);
518 if (connection->gateway_port != fwd->gateway_port)
520 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
521 connection->gateway_port, fwd->gateway_port, http->host);
524 if (connection->forward_port != fwd->forward_port)
526 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
527 connection->forward_port, fwd->forward_port, http->host);
530 if (connection->forward_port != fwd->forward_port)
532 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
533 connection->forward_port, fwd->forward_port, http->host);
537 /* XXX: End of duplicated checks for debugging purposes. */
539 if ((connection->forwarder_type != fwd->type)
540 || (connection->gateway_port != fwd->gateway_port)
541 || (connection->forward_port != fwd->forward_port)
542 || (connection->port != http->port))
547 if (( (NULL != connection->gateway_host)
548 && (NULL != fwd->gateway_host)
549 && strcmpic(connection->gateway_host, fwd->gateway_host))
550 && (connection->gateway_host != fwd->gateway_host))
552 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
556 if (( (NULL != connection->forward_host)
557 && (NULL != fwd->forward_host)
558 && strcmpic(connection->forward_host, fwd->forward_host))
559 && (connection->forward_host != fwd->forward_host))
561 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
565 return (!strcmpic(connection->host, http->host));
569 /*********************************************************************
571 * Function : get_reusable_connection
573 * Description : Returns an open socket to a previously remembered
574 * open connection (if there is one).
577 * 1 : http = The destination for the connection.
578 * 2 : fwd = The forwarder settings.
580 * Returns : JB_INVALID_SOCKET => No reusable connection found,
581 * otherwise a usable socket.
583 *********************************************************************/
584 static jb_socket get_reusable_connection(const struct http_request *http,
585 const struct forward_spec *fwd)
587 jb_socket sfd = JB_INVALID_SOCKET;
588 unsigned int slot = 0;
590 privoxy_mutex_lock(&connection_reuse_mutex);
592 for (slot = 0; slot < SZ(reusable_connection); slot++)
594 if (!reusable_connection[slot].in_use
595 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
598 struct pollfd poll_fd[1];
599 memset(poll_fd, 0, sizeof(poll_fd));
600 poll_fd[0].fd = reusable_connection[slot].sfd;
601 poll_fd[0].events = POLLIN;
603 poll_result = poll(poll_fd, 1, 0);
605 if (-1 != poll_result)
607 if ((poll_fd[0].revents & POLLIN))
609 log_error(LOG_LEVEL_CONNECT,
610 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
611 reusable_connection[slot].sfd, reusable_connection[slot].host,
612 reusable_connection[slot].port, slot);
613 mark_connection_closed(&reusable_connection[slot]);
618 log_error(LOG_LEVEL_CONNECT,
619 "Failed to poll socket %d for %s:%d in slot %d.",
620 reusable_connection[slot].sfd, reusable_connection[slot].host,
621 reusable_connection[slot].port, slot);
625 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
627 reusable_connection[slot].in_use = TRUE;
628 sfd = reusable_connection[slot].sfd;
629 log_error(LOG_LEVEL_CONNECT,
630 "Found reusable socket %d for %s:%d in slot %d.",
631 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
637 privoxy_mutex_unlock(&connection_reuse_mutex);
644 /*********************************************************************
646 * Function : mark_connection_unused
648 * Description : Gives a remembered connection free for reuse.
651 * 1 : sfd = The socket belonging to the connection in question.
653 * Returns : TRUE => Socket found and marked as unused.
654 * FALSE => Socket not found.
656 *********************************************************************/
657 static int mark_connection_unused(jb_socket sfd)
659 unsigned int slot = 0;
660 unsigned int socket_found = FALSE;
662 assert(sfd != JB_INVALID_SOCKET);
664 privoxy_mutex_lock(&connection_reuse_mutex);
666 for (slot = 0; slot < SZ(reusable_connection); slot++)
668 if (reusable_connection[slot].sfd == sfd)
670 assert(reusable_connection[slot].in_use);
675 if (reusable_connection[slot].sfd == sfd)
678 log_error(LOG_LEVEL_CONNECT,
679 "Marking open socket %d for %s:%d in slot %d as unused.",
680 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
681 reusable_connection[slot].in_use = 0;
684 privoxy_mutex_unlock(&connection_reuse_mutex);
689 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
692 /*********************************************************************
694 * Function : forwarded_connect
696 * Description : Connect to a specified web server, possibly via
697 * a HTTP proxy and/or a SOCKS proxy.
700 * 1 : fwd = the proxies to use when connecting.
701 * 2 : http = the http request and apropos headers
702 * 3 : csp = Current client state (buffers, headers, etc...)
704 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
706 *********************************************************************/
707 jb_socket forwarded_connect(const struct forward_spec * fwd,
708 struct http_request *http,
709 struct client_state *csp)
711 const char * dest_host;
713 jb_socket sfd = JB_INVALID_SOCKET;
715 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
716 sfd = get_reusable_connection(http, fwd);
717 if (JB_INVALID_SOCKET == sfd)
719 log_error(LOG_LEVEL_CONNECT,
720 "No reusable socket for %s:%d found. Opening a new one.",
721 http->host, http->port);
727 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
729 /* Figure out if we need to connect to the web server or a HTTP proxy. */
730 if (fwd->forward_host)
733 dest_host = fwd->forward_host;
734 dest_port = fwd->forward_port;
739 dest_host = http->host;
740 dest_port = http->port;
743 /* Connect, maybe using a SOCKS proxy */
747 sfd = connect_to(dest_host, dest_port, csp);
751 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
754 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
757 /* Should never get here */
758 log_error(LOG_LEVEL_FATAL,
759 "SOCKS4 impossible internal error - bad SOCKS type.");
767 /*********************************************************************
769 * Function : socks4_connect
771 * Description : Connect to the SOCKS server, and connect through
772 * it to the specified server. This handles
773 * all the SOCKS negotiation, and returns a file
774 * descriptor for a socket which can be treated as a
775 * normal (non-SOCKS) socket.
777 * Logged error messages are saved to csp->error_message
778 * and later reused by error_response() for the CGI
779 * message. strdup allocation failures are handled there.
782 * 1 : fwd = Specifies the SOCKS proxy to use.
783 * 2 : target_host = The final server to connect to.
784 * 3 : target_port = The final port to connect to.
785 * 4 : csp = Current client state (buffers, headers, etc...)
787 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
789 *********************************************************************/
790 static jb_socket socks4_connect(const struct forward_spec * fwd,
791 const char * target_host,
793 struct client_state *csp)
795 unsigned int web_server_addr;
796 char buf[BUFFER_SIZE];
797 struct socks_op *c = (struct socks_op *)buf;
798 struct socks_reply *s = (struct socks_reply *)buf;
805 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
807 /* XXX: Shouldn't the config file parser prevent this? */
808 errstr = "NULL gateway host specified.";
812 if (fwd->gateway_port <= 0)
814 errstr = "invalid gateway port specified.";
820 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
821 csp->error_message = strdup(errstr);
823 return(JB_INVALID_SOCKET);
826 /* build a socks request for connection to the web server */
828 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
830 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
835 web_server_addr = resolve_hostname_to_ip(target_host);
836 if (web_server_addr == INADDR_NONE)
838 errstr = "could not resolve target host";
839 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
844 web_server_addr = htonl(web_server_addr);
848 web_server_addr = 0x00000001;
849 n = csiz + strlen(target_host) + 1;
853 errstr = "buffer cbuf too small.";
854 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
859 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
861 * What we forward to the socks4a server should have the
862 * size of socks_op, plus the length of the userid plus
863 * its \0 byte (which we don't have to add because the
864 * first byte of the userid is counted twice as it's also
865 * part of sock_op) minus the padding bytes (which are part
866 * of the userid as well), plus the length of the target_host
867 * (which is stored csiz bytes after the beginning of the buffer),
868 * plus another \0 byte.
870 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
875 /* Should never get here */
876 log_error(LOG_LEVEL_FATAL,
877 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
879 return(JB_INVALID_SOCKET);
884 csp->error_message = strdup(errstr);
885 return(JB_INVALID_SOCKET);
890 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
891 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
892 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
893 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
894 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
895 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
897 /* pass the request to the socks server */
898 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
900 if (sfd == JB_INVALID_SOCKET)
903 * XXX: connect_to should fill in the exact reason.
904 * Most likely resolving the IP of the forwarder failed.
906 errstr = "connect_to failed: see logfile for details";
909 else if (write_socket(sfd, (char *)c, csiz))
911 errstr = "SOCKS4 negotiation write failed.";
912 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
916 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
918 errstr = "SOCKS4 negotiation read failed.";
919 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
926 csp->error_message = strdup(errstr);
927 return(JB_INVALID_SOCKET);
932 case SOCKS_REQUEST_GRANTED:
935 case SOCKS_REQUEST_REJECT:
936 errstr = "SOCKS request rejected or failed.";
939 case SOCKS_REQUEST_IDENT_FAILED:
940 errstr = "SOCKS request rejected because "
941 "SOCKS server cannot connect to identd on the client.";
944 case SOCKS_REQUEST_IDENT_CONFLICT:
945 errstr = "SOCKS request rejected because "
946 "the client program and identd report "
947 "different user-ids.";
952 snprintf(buf, sizeof(buf),
953 "SOCKS request rejected for reason code %d.", s->cd);
957 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
958 csp->error_message = strdup(errstr);
961 return(JB_INVALID_SOCKET);
965 /*********************************************************************
967 * Function : translate_socks5_error
969 * Description : Translates a SOCKS errors to a string.
972 * 1 : socks_error = The error code to translate.
974 * Returns : The string translation.
976 *********************************************************************/
977 static const char *translate_socks5_error(int socks_error)
981 /* XXX: these should be more descriptive */
982 case SOCKS5_REQUEST_FAILED:
983 return "SOCKS5 request failed";
984 case SOCKS5_REQUEST_DENIED:
985 return "SOCKS5 request denied";
986 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
987 return "SOCKS5 network unreachable";
988 case SOCKS5_REQUEST_HOST_UNREACHABLE:
989 return "SOCKS5 host unreachable";
990 case SOCKS5_REQUEST_CONNECTION_REFUSED:
991 return "SOCKS5 connection refused";
992 case SOCKS5_REQUEST_TTL_EXPIRED:
993 return "SOCKS5 TTL expired";
994 case SOCKS5_REQUEST_PROTOCOL_ERROR:
995 return "SOCKS5 client protocol error";
996 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
997 return "SOCKS5 domain names unsupported";
998 case SOCKS5_REQUEST_GRANTED:
999 return "everything's peachy";
1001 return "SOCKS5 negotiation protocol error";
1005 /*********************************************************************
1007 * Function : socks5_connect
1009 * Description : Connect to the SOCKS server, and connect through
1010 * it to the specified server. This handles
1011 * all the SOCKS negotiation, and returns a file
1012 * descriptor for a socket which can be treated as a
1013 * normal (non-SOCKS) socket.
1016 * 1 : fwd = Specifies the SOCKS proxy to use.
1017 * 2 : target_host = The final server to connect to.
1018 * 3 : target_port = The final port to connect to.
1019 * 4 : csp = Current client state (buffers, headers, etc...)
1021 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1023 *********************************************************************/
1024 static jb_socket socks5_connect(const struct forward_spec *fwd,
1025 const char *target_host,
1027 struct client_state *csp)
1032 size_t client_pos = 0;
1033 int server_size = 0;
1036 const char *errstr = NULL;
1038 assert(fwd->gateway_host);
1039 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1041 errstr = "NULL gateway host specified";
1045 if (fwd->gateway_port <= 0)
1048 * XXX: currently this can't happen because in
1049 * case of invalid gateway ports we use the defaults.
1050 * Of course we really shouldn't do that.
1052 errstr = "invalid gateway port specified";
1056 hostlen = strlen(target_host);
1059 errstr = "target host name is longer than 255 characters";
1063 if (fwd->type != SOCKS_5)
1065 /* Should never get here */
1066 log_error(LOG_LEVEL_FATAL,
1067 "SOCKS5 impossible internal error - bad SOCKS type");
1074 assert(errstr != NULL);
1075 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1076 csp->error_message = strdup(errstr);
1077 return(JB_INVALID_SOCKET);
1080 /* pass the request to the socks server */
1081 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1083 if (sfd == JB_INVALID_SOCKET)
1085 errstr = "socks5 server unreachable";
1086 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1087 csp->error_message = strdup(errstr);
1088 return(JB_INVALID_SOCKET);
1092 cbuf[client_pos++] = '\x05'; /* Version */
1093 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1094 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1096 if (write_socket(sfd, cbuf, client_pos))
1098 errstr = "SOCKS5 negotiation write failed";
1099 csp->error_message = strdup(errstr);
1100 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1102 return(JB_INVALID_SOCKET);
1105 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1107 errstr = "SOCKS5 negotiation read failed";
1111 if (!err && (sbuf[0] != '\x05'))
1113 errstr = "SOCKS5 negotiation protocol version error";
1117 if (!err && (sbuf[1] == '\xff'))
1119 errstr = "SOCKS5 authentication required";
1123 if (!err && (sbuf[1] != '\x00'))
1125 errstr = "SOCKS5 negotiation protocol error";
1131 assert(errstr != NULL);
1132 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1133 csp->error_message = strdup(errstr);
1136 return(JB_INVALID_SOCKET);
1140 cbuf[client_pos++] = '\x05'; /* Version */
1141 cbuf[client_pos++] = '\x01'; /* TCP connect */
1142 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1143 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1144 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1145 assert(sizeof(cbuf) - client_pos > 255);
1146 /* Using strncpy because we really want the nul byte padding. */
1147 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1148 client_pos += (hostlen & 0xffu);
1149 cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
1150 cbuf[client_pos++] = (char)((target_port ) & 0xffu);
1152 if (write_socket(sfd, cbuf, client_pos))
1154 errstr = "SOCKS5 negotiation read failed";
1155 csp->error_message = strdup(errstr);
1156 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1159 return(JB_INVALID_SOCKET);
1162 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1163 if (server_size < 3)
1165 errstr = "SOCKS5 negotiation read failed";
1168 else if (server_size > 20)
1170 /* This is somewhat unexpected but doesn't realy matter. */
1171 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1172 "from socks server. Would have accepted up to %d.",
1173 server_size, sizeof(sbuf));
1176 if (!err && (sbuf[0] != '\x05'))
1178 errstr = "SOCKS5 negotiation protocol version error";
1182 if (!err && (sbuf[2] != '\x00'))
1184 errstr = "SOCKS5 negotiation protocol error";
1190 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1194 errstr = translate_socks5_error(sbuf[1]);
1198 assert(errstr != NULL);
1199 csp->error_message = strdup(errstr);
1200 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1204 return(JB_INVALID_SOCKET);