1 const char gateway_rcs[] = "$Id: gateway.c,v 1.31 2008/10/16 07:31:11 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.31 2008/10/16 07:31:11 fabiankeil
38 * - Factor socket_is_still_usable() out of get_reusable_connection().
39 * - If poll() isn't available, show a warning and assume the socket
42 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
43 * If a remembered connection is no longer usable and
44 * has been marked closed, don't bother checking if the
45 * destination matches.
47 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
48 * Add missing dots for two log messages.
50 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
51 * Flush work-in-progress changes to keep outgoing connections
52 * alive where possible. Incomplete and mostly #ifdef'd out.
54 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
55 * Return only once in forwarded_connect().
57 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
58 * Fix typo in macro name.
60 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
62 * - make the buffers quite a bit smaller.
63 * - properly report "socks5 server unreachable" failures.
64 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
65 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
66 * - log a message if the socks5 server sends more data than expected.
67 * - add some assertions and comments.
69 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
70 * - Fix a compiler warning.
71 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
73 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
74 * Remember the cause of the SOCKS5 error for the CGI message.
76 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
77 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
79 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
80 * Modified patch from Song Weijia (#1762559) to
81 * fix socks requests on big-endian platforms.
83 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
84 * - Use strlcpy() instead of strcpy().
85 * - Use the same buffer for socks requests and socks responses.
86 * - Fix bogus warning about web_server_addr being used uninitialized.
88 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
89 * - Save errors in socks4_connect() to csp->error_message.
90 * - Silence some gcc43 warnings, hopefully the right way.
92 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
93 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
94 * with what was really the latest development (the v_3_0_branch branch)
96 * Revision 1.16 2002/05/12 21:36:29 jongfoster
97 * Correcting function comments
99 * Revision 1.15 2002/03/26 22:29:54 swa
100 * we have a new homepage!
102 * Revision 1.14 2002/03/24 13:25:43 swa
103 * name change related issues
105 * Revision 1.13 2002/03/13 00:29:59 jongfoster
108 * Revision 1.12 2002/03/09 20:03:52 jongfoster
109 * - Making various functions return int rather than size_t.
110 * (Undoing a recent change). Since size_t is unsigned on
111 * Windows, functions like read_socket that return -1 on
112 * error cannot return a size_t.
114 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
115 * crashes, and also frequently caused JB to jump to 100%
116 * CPU and stay there. (Because it thought it had just
117 * read ((unsigned)-1) == 4Gb of data...)
119 * - The signature of write_socket has changed, it now simply
120 * returns success=0/failure=nonzero.
122 * - Trying to get rid of a few warnings --with-debug on
123 * Windows, I've introduced a new type "jb_socket". This is
124 * used for the socket file descriptors. On Windows, this
125 * is SOCKET (a typedef for unsigned). Everywhere else, it's
126 * an int. The error value can't be -1 any more, so it's
127 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
128 * Windows it maps to the #define INVALID_SOCKET.)
130 * - The signature of bind_port has changed.
132 * Revision 1.11 2002/03/08 17:46:04 jongfoster
133 * Fixing int/size_t warnings
135 * Revision 1.10 2002/03/07 03:50:19 oes
136 * - Improved handling of failed DNS lookups
137 * - Fixed compiler warnings
139 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
140 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
141 * threads to call select() simultaneously. So, it's time to do a real, live,
142 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
143 * (native). Both versions will work, but using __OS2__ offers multi-threading.
145 * Revision 1.8 2001/09/13 20:10:12 jongfoster
146 * Fixing missing #include under Windows
148 * Revision 1.7 2001/09/12 17:58:26 steudten
150 * add #include <string.h>
152 * Revision 1.6 2001/09/10 10:41:16 oes
153 * Added #include in.h
155 * Revision 1.5 2001/07/29 18:47:57 jongfoster
156 * Adding missing #include project.h
158 * Revision 1.4 2001/07/24 12:47:06 oes
159 * Applied BeOS support update by Eugenia
161 * Revision 1.3 2001/06/09 10:55:28 jongfoster
162 * Changing BUFSIZ ==> BUFFER_SIZE
164 * Revision 1.2 2001/06/07 23:11:38 jongfoster
165 * Removing gateways[] list - no longer used.
166 * Replacing function pointer in struct gateway with a directly
167 * called function forwarded_connect(), which can do the common
168 * task of deciding whether to connect to the web server or HTTP
170 * Replacing struct gateway with struct forward_spec
171 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
172 * It was a bug which led to the connection being made to the web
173 * server rather than the HTTP proxy, and also a buffer overrun.
175 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
176 * Initial import of version 2.9.3 source tree
179 *********************************************************************/
185 #include <sys/types.h>
188 #include <netinet/in.h>
196 #include <winsock2.h>
197 #endif /* def _WIN32 */
201 #endif /* def __BEOS__ */
205 #endif /* def __OS2__ */
210 #include "jbsockets.h"
212 #include "miscutil.h"
213 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
216 #include <sys/poll.h>
219 #endif /* def __GLIBC__ */
220 #endif /* HAVE_POLL */
221 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
223 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
225 static jb_socket socks4_connect(const struct forward_spec * fwd,
226 const char * target_host,
228 struct client_state *csp);
230 static jb_socket socks5_connect(const struct forward_spec *fwd,
231 const char *target_host,
233 struct client_state *csp);
236 #define SOCKS_REQUEST_GRANTED 90
237 #define SOCKS_REQUEST_REJECT 91
238 #define SOCKS_REQUEST_IDENT_FAILED 92
239 #define SOCKS_REQUEST_IDENT_CONFLICT 93
241 #define SOCKS5_REQUEST_GRANTED 0
242 #define SOCKS5_REQUEST_FAILED 1
243 #define SOCKS5_REQUEST_DENIED 2
244 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
245 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
246 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
247 #define SOCKS5_REQUEST_TTL_EXPIRED 6
248 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
249 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
251 /* structure of a socks client operation */
253 unsigned char vn; /* socks version number */
254 unsigned char cd; /* command code */
255 unsigned char dstport[2]; /* destination port */
256 unsigned char dstip[4]; /* destination address */
257 char userid; /* first byte of userid */
258 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
259 /* more bytes of the userid follow, terminated by a NULL */
262 /* structure of a socks server reply */
264 unsigned char vn; /* socks version number */
265 unsigned char cd; /* command code */
266 unsigned char dstport[2]; /* destination port */
267 unsigned char dstip[4]; /* destination address */
270 static const char socks_userid[] = "anonymous";
272 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
274 #define MAX_REUSABLE_CONNECTIONS 100
276 struct reusable_connection
290 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
292 static int mark_connection_unused(jb_socket sfd);
293 static void mark_connection_closed(struct reusable_connection *closed_connection);
295 /*********************************************************************
297 * Function : initialize_reusable_connections
299 * Description : Initializes the reusable_connection structures.
300 * Must be called with connection_reuse_mutex locked.
306 *********************************************************************/
307 extern void initialize_reusable_connections(void)
309 unsigned int slot = 0;
311 log_error(LOG_LEVEL_INFO,
312 "Support for 'Connection: keep-alive' is experimental, "
313 "incomplete and known not to work properly in some situations.");
315 for (slot = 0; slot < SZ(reusable_connection); slot++)
317 mark_connection_closed(&reusable_connection[slot]);
320 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
324 /*********************************************************************
326 * Function : remember_connection
328 * Description : Remembers a connection for reuse later on.
331 * 1 : sfd = Open socket to remember.
332 * 2 : http = The destination for the connection.
333 * 3 : fwd = The forwarder settings used.
337 *********************************************************************/
338 void remember_connection(jb_socket sfd, const struct http_request *http,
339 const struct forward_spec *fwd)
341 unsigned int slot = 0;
342 int free_slot_found = FALSE;
344 assert(sfd != JB_INVALID_SOCKET);
346 if (mark_connection_unused(sfd))
351 privoxy_mutex_lock(&connection_reuse_mutex);
353 /* Find free socket slot. */
354 for (slot = 0; slot < SZ(reusable_connection); slot++)
356 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
358 assert(reusable_connection[slot].in_use == 0);
359 log_error(LOG_LEVEL_CONNECT,
360 "Remembering socket %d for %s:%d in slot %d.",
361 sfd, http->host, http->port, slot);
362 free_slot_found = TRUE;
367 if (!free_slot_found)
369 log_error(LOG_LEVEL_CONNECT,
370 "No free slots found to remembering socket for %s:%d. Last slot %d.",
371 http->host, http->port, slot);
372 privoxy_mutex_unlock(&connection_reuse_mutex);
377 assert(NULL != http->host);
378 reusable_connection[slot].host = strdup(http->host);
379 if (NULL == reusable_connection[slot].host)
381 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
383 reusable_connection[slot].sfd = sfd;
384 reusable_connection[slot].port = http->port;
385 reusable_connection[slot].in_use = 0;
388 assert(reusable_connection[slot].gateway_host == NULL);
389 assert(reusable_connection[slot].gateway_port == 0);
390 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
391 assert(reusable_connection[slot].forward_host == NULL);
392 assert(reusable_connection[slot].forward_port == 0);
394 reusable_connection[slot].forwarder_type = fwd->type;
395 if (NULL != fwd->gateway_host)
397 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
398 if (NULL == reusable_connection[slot].gateway_host)
400 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
405 reusable_connection[slot].gateway_host = NULL;
407 reusable_connection[slot].gateway_port = fwd->gateway_port;
409 if (NULL != fwd->forward_host)
411 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
412 if (NULL == reusable_connection[slot].forward_host)
414 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
419 reusable_connection[slot].forward_host = NULL;
421 reusable_connection[slot].forward_port = fwd->forward_port;
423 privoxy_mutex_unlock(&connection_reuse_mutex);
427 /*********************************************************************
429 * Function : mark_connection_closed
431 * Description : Marks a reused connection closed.
432 * Must be called with connection_reuse_mutex locked.
435 * 1 : closed_connection = The connection to mark as closed.
439 *********************************************************************/
440 static void mark_connection_closed(struct reusable_connection *closed_connection)
442 closed_connection->in_use = FALSE;
443 closed_connection->sfd = JB_INVALID_SOCKET;
444 freez(closed_connection->host);
445 closed_connection->port = 0;
446 closed_connection->forwarder_type = SOCKS_NONE;
447 freez(closed_connection->gateway_host);
448 closed_connection->gateway_port = 0;
449 freez(closed_connection->forward_host);
450 closed_connection->forward_port = 0;
454 /*********************************************************************
456 * Function : forget_connection
458 * Description : Removes a previously remembered connection from
459 * the list of reusable connections.
462 * 1 : sfd = The socket belonging to the connection in question.
466 *********************************************************************/
467 void forget_connection(jb_socket sfd)
469 unsigned int slot = 0;
471 assert(sfd != JB_INVALID_SOCKET);
473 privoxy_mutex_lock(&connection_reuse_mutex);
475 for (slot = 0; slot < SZ(reusable_connection); slot++)
477 if (reusable_connection[slot].sfd == sfd)
479 assert(reusable_connection[slot].in_use);
484 if (reusable_connection[slot].sfd != sfd)
486 log_error(LOG_LEVEL_CONNECT,
487 "Socket %d already forgotten or never remembered.", sfd);
488 privoxy_mutex_unlock(&connection_reuse_mutex);
492 log_error(LOG_LEVEL_CONNECT,
493 "Forgetting socket %d for %s:%d in slot %d.",
494 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
496 mark_connection_closed(&reusable_connection[slot]);
498 privoxy_mutex_unlock(&connection_reuse_mutex);
502 /*********************************************************************
504 * Function : connection_destination_matches
506 * Description : Determines whether a remembered connection can
507 * be reused. That is whether the destination and
508 * the forwarding settings match.
511 * 1 : connection = The connection to check.
512 * 2 : http = The destination for the connection.
513 * 3 : fwd = The forwarder settings.
515 * Returns : TRUE for yes, FALSE otherwise.
517 *********************************************************************/
518 static int connection_destination_matches(const struct reusable_connection *connection,
519 const struct http_request *http,
520 const struct forward_spec *fwd)
522 /* XXX: Start of duplicated checks for debugging purposes. */
523 if (strcmpic(connection->host, http->host))
528 if (connection->forwarder_type != fwd->type)
530 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
531 connection->forwarder_type, fwd->type, http->host);
534 if (connection->gateway_port != fwd->gateway_port)
536 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
537 connection->gateway_port, fwd->gateway_port, http->host);
540 if (connection->forward_port != fwd->forward_port)
542 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
543 connection->forward_port, fwd->forward_port, http->host);
546 if (connection->forward_port != fwd->forward_port)
548 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
549 connection->forward_port, fwd->forward_port, http->host);
553 /* XXX: End of duplicated checks for debugging purposes. */
555 if ((connection->forwarder_type != fwd->type)
556 || (connection->gateway_port != fwd->gateway_port)
557 || (connection->forward_port != fwd->forward_port)
558 || (connection->port != http->port))
563 if (( (NULL != connection->gateway_host)
564 && (NULL != fwd->gateway_host)
565 && strcmpic(connection->gateway_host, fwd->gateway_host))
566 && (connection->gateway_host != fwd->gateway_host))
568 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
572 if (( (NULL != connection->forward_host)
573 && (NULL != fwd->forward_host)
574 && strcmpic(connection->forward_host, fwd->forward_host))
575 && (connection->forward_host != fwd->forward_host))
577 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
581 return (!strcmpic(connection->host, http->host));
586 /*********************************************************************
588 * Function : socket_is_still_usable
590 * Description : Decides whether or not an open socket is still usable.
593 * 1 : sfd = The socket to check.
595 * Returns : TRUE for yes, otherwise FALSE.
597 *********************************************************************/
598 static int socket_is_still_usable(jb_socket sfd)
602 struct pollfd poll_fd[1];
603 memset(poll_fd, 0, sizeof(poll_fd));
605 poll_fd[0].events = POLLIN;
607 poll_result = poll(poll_fd, 1, 0);
609 if (-1 != poll_result)
611 return !(poll_fd[0].revents & POLLIN);
615 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
619 log_error(LOG_LEVEL_INFO,
620 "Detecting already dead sockets isn't implemented for your "
621 "platform yet. Assuming sockets stay alive forever, expect "
622 "an increase in connection problems.");
624 #endif /* def HAVE_POLL */
628 /*********************************************************************
630 * Function : get_reusable_connection
632 * Description : Returns an open socket to a previously remembered
633 * open connection (if there is one).
636 * 1 : http = The destination for the connection.
637 * 2 : fwd = The forwarder settings.
639 * Returns : JB_INVALID_SOCKET => No reusable connection found,
640 * otherwise a usable socket.
642 *********************************************************************/
643 static jb_socket get_reusable_connection(const struct http_request *http,
644 const struct forward_spec *fwd)
646 jb_socket sfd = JB_INVALID_SOCKET;
647 unsigned int slot = 0;
649 privoxy_mutex_lock(&connection_reuse_mutex);
651 for (slot = 0; slot < SZ(reusable_connection); slot++)
653 if (!reusable_connection[slot].in_use
654 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
656 if (!socket_is_still_usable(reusable_connection[slot].sfd))
658 log_error(LOG_LEVEL_CONNECT,
659 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
660 reusable_connection[slot].sfd, reusable_connection[slot].host,
661 reusable_connection[slot].port, slot);
662 mark_connection_closed(&reusable_connection[slot]);
666 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
668 reusable_connection[slot].in_use = TRUE;
669 sfd = reusable_connection[slot].sfd;
670 log_error(LOG_LEVEL_CONNECT,
671 "Found reusable socket %d for %s:%d in slot %d.",
672 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
678 privoxy_mutex_unlock(&connection_reuse_mutex);
685 /*********************************************************************
687 * Function : mark_connection_unused
689 * Description : Gives a remembered connection free for reuse.
692 * 1 : sfd = The socket belonging to the connection in question.
694 * Returns : TRUE => Socket found and marked as unused.
695 * FALSE => Socket not found.
697 *********************************************************************/
698 static int mark_connection_unused(jb_socket sfd)
700 unsigned int slot = 0;
701 int socket_found = FALSE;
703 assert(sfd != JB_INVALID_SOCKET);
705 privoxy_mutex_lock(&connection_reuse_mutex);
707 for (slot = 0; slot < SZ(reusable_connection); slot++)
709 if (reusable_connection[slot].sfd == sfd)
711 assert(reusable_connection[slot].in_use);
716 if (reusable_connection[slot].sfd == sfd)
719 log_error(LOG_LEVEL_CONNECT,
720 "Marking open socket %d for %s:%d in slot %d as unused.",
721 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
722 reusable_connection[slot].in_use = 0;
725 privoxy_mutex_unlock(&connection_reuse_mutex);
730 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
733 /*********************************************************************
735 * Function : forwarded_connect
737 * Description : Connect to a specified web server, possibly via
738 * a HTTP proxy and/or a SOCKS proxy.
741 * 1 : fwd = the proxies to use when connecting.
742 * 2 : http = the http request and apropos headers
743 * 3 : csp = Current client state (buffers, headers, etc...)
745 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
747 *********************************************************************/
748 jb_socket forwarded_connect(const struct forward_spec * fwd,
749 struct http_request *http,
750 struct client_state *csp)
752 const char * dest_host;
754 jb_socket sfd = JB_INVALID_SOCKET;
756 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
757 sfd = get_reusable_connection(http, fwd);
758 if (JB_INVALID_SOCKET == sfd)
760 log_error(LOG_LEVEL_CONNECT,
761 "No reusable socket for %s:%d found. Opening a new one.",
762 http->host, http->port);
768 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
770 /* Figure out if we need to connect to the web server or a HTTP proxy. */
771 if (fwd->forward_host)
774 dest_host = fwd->forward_host;
775 dest_port = fwd->forward_port;
780 dest_host = http->host;
781 dest_port = http->port;
784 /* Connect, maybe using a SOCKS proxy */
788 sfd = connect_to(dest_host, dest_port, csp);
792 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
795 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
798 /* Should never get here */
799 log_error(LOG_LEVEL_FATAL,
800 "SOCKS4 impossible internal error - bad SOCKS type.");
808 /*********************************************************************
810 * Function : socks4_connect
812 * Description : Connect to the SOCKS server, and connect through
813 * it to the specified server. This handles
814 * all the SOCKS negotiation, and returns a file
815 * descriptor for a socket which can be treated as a
816 * normal (non-SOCKS) socket.
818 * Logged error messages are saved to csp->error_message
819 * and later reused by error_response() for the CGI
820 * message. strdup allocation failures are handled there.
823 * 1 : fwd = Specifies the SOCKS proxy to use.
824 * 2 : target_host = The final server to connect to.
825 * 3 : target_port = The final port to connect to.
826 * 4 : csp = Current client state (buffers, headers, etc...)
828 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
830 *********************************************************************/
831 static jb_socket socks4_connect(const struct forward_spec * fwd,
832 const char * target_host,
834 struct client_state *csp)
836 unsigned int web_server_addr;
837 char buf[BUFFER_SIZE];
838 struct socks_op *c = (struct socks_op *)buf;
839 struct socks_reply *s = (struct socks_reply *)buf;
846 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
848 /* XXX: Shouldn't the config file parser prevent this? */
849 errstr = "NULL gateway host specified.";
853 if (fwd->gateway_port <= 0)
855 errstr = "invalid gateway port specified.";
861 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
862 csp->error_message = strdup(errstr);
864 return(JB_INVALID_SOCKET);
867 /* build a socks request for connection to the web server */
869 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
871 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
876 web_server_addr = resolve_hostname_to_ip(target_host);
877 if (web_server_addr == INADDR_NONE)
879 errstr = "could not resolve target host";
880 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
885 web_server_addr = htonl(web_server_addr);
889 web_server_addr = 0x00000001;
890 n = csiz + strlen(target_host) + 1;
894 errstr = "buffer cbuf too small.";
895 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
900 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
902 * What we forward to the socks4a server should have the
903 * size of socks_op, plus the length of the userid plus
904 * its \0 byte (which we don't have to add because the
905 * first byte of the userid is counted twice as it's also
906 * part of sock_op) minus the padding bytes (which are part
907 * of the userid as well), plus the length of the target_host
908 * (which is stored csiz bytes after the beginning of the buffer),
909 * plus another \0 byte.
911 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
916 /* Should never get here */
917 log_error(LOG_LEVEL_FATAL,
918 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
920 return(JB_INVALID_SOCKET);
925 csp->error_message = strdup(errstr);
926 return(JB_INVALID_SOCKET);
931 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
932 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
933 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
934 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
935 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
936 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
938 /* pass the request to the socks server */
939 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
941 if (sfd == JB_INVALID_SOCKET)
944 * XXX: connect_to should fill in the exact reason.
945 * Most likely resolving the IP of the forwarder failed.
947 errstr = "connect_to failed: see logfile for details";
950 else if (write_socket(sfd, (char *)c, csiz))
952 errstr = "SOCKS4 negotiation write failed.";
953 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
957 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
959 errstr = "SOCKS4 negotiation read failed.";
960 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
967 csp->error_message = strdup(errstr);
968 return(JB_INVALID_SOCKET);
973 case SOCKS_REQUEST_GRANTED:
976 case SOCKS_REQUEST_REJECT:
977 errstr = "SOCKS request rejected or failed.";
980 case SOCKS_REQUEST_IDENT_FAILED:
981 errstr = "SOCKS request rejected because "
982 "SOCKS server cannot connect to identd on the client.";
985 case SOCKS_REQUEST_IDENT_CONFLICT:
986 errstr = "SOCKS request rejected because "
987 "the client program and identd report "
988 "different user-ids.";
993 snprintf(buf, sizeof(buf),
994 "SOCKS request rejected for reason code %d.", s->cd);
998 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
999 csp->error_message = strdup(errstr);
1002 return(JB_INVALID_SOCKET);
1006 /*********************************************************************
1008 * Function : translate_socks5_error
1010 * Description : Translates a SOCKS errors to a string.
1013 * 1 : socks_error = The error code to translate.
1015 * Returns : The string translation.
1017 *********************************************************************/
1018 static const char *translate_socks5_error(int socks_error)
1020 switch (socks_error)
1022 /* XXX: these should be more descriptive */
1023 case SOCKS5_REQUEST_FAILED:
1024 return "SOCKS5 request failed";
1025 case SOCKS5_REQUEST_DENIED:
1026 return "SOCKS5 request denied";
1027 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1028 return "SOCKS5 network unreachable";
1029 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1030 return "SOCKS5 host unreachable";
1031 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1032 return "SOCKS5 connection refused";
1033 case SOCKS5_REQUEST_TTL_EXPIRED:
1034 return "SOCKS5 TTL expired";
1035 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1036 return "SOCKS5 client protocol error";
1037 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1038 return "SOCKS5 domain names unsupported";
1039 case SOCKS5_REQUEST_GRANTED:
1040 return "everything's peachy";
1042 return "SOCKS5 negotiation protocol error";
1046 /*********************************************************************
1048 * Function : socks5_connect
1050 * Description : Connect to the SOCKS server, and connect through
1051 * it to the specified server. This handles
1052 * all the SOCKS negotiation, and returns a file
1053 * descriptor for a socket which can be treated as a
1054 * normal (non-SOCKS) socket.
1057 * 1 : fwd = Specifies the SOCKS proxy to use.
1058 * 2 : target_host = The final server to connect to.
1059 * 3 : target_port = The final port to connect to.
1060 * 4 : csp = Current client state (buffers, headers, etc...)
1062 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1064 *********************************************************************/
1065 static jb_socket socks5_connect(const struct forward_spec *fwd,
1066 const char *target_host,
1068 struct client_state *csp)
1073 size_t client_pos = 0;
1074 int server_size = 0;
1077 const char *errstr = NULL;
1079 assert(fwd->gateway_host);
1080 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1082 errstr = "NULL gateway host specified";
1086 if (fwd->gateway_port <= 0)
1089 * XXX: currently this can't happen because in
1090 * case of invalid gateway ports we use the defaults.
1091 * Of course we really shouldn't do that.
1093 errstr = "invalid gateway port specified";
1097 hostlen = strlen(target_host);
1100 errstr = "target host name is longer than 255 characters";
1104 if (fwd->type != SOCKS_5)
1106 /* Should never get here */
1107 log_error(LOG_LEVEL_FATAL,
1108 "SOCKS5 impossible internal error - bad SOCKS type");
1115 assert(errstr != NULL);
1116 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1117 csp->error_message = strdup(errstr);
1118 return(JB_INVALID_SOCKET);
1121 /* pass the request to the socks server */
1122 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1124 if (sfd == JB_INVALID_SOCKET)
1126 errstr = "socks5 server unreachable";
1127 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1128 csp->error_message = strdup(errstr);
1129 return(JB_INVALID_SOCKET);
1133 cbuf[client_pos++] = '\x05'; /* Version */
1134 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1135 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1137 if (write_socket(sfd, cbuf, client_pos))
1139 errstr = "SOCKS5 negotiation write failed";
1140 csp->error_message = strdup(errstr);
1141 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1143 return(JB_INVALID_SOCKET);
1146 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1148 errstr = "SOCKS5 negotiation read failed";
1152 if (!err && (sbuf[0] != '\x05'))
1154 errstr = "SOCKS5 negotiation protocol version error";
1158 if (!err && (sbuf[1] == '\xff'))
1160 errstr = "SOCKS5 authentication required";
1164 if (!err && (sbuf[1] != '\x00'))
1166 errstr = "SOCKS5 negotiation protocol error";
1172 assert(errstr != NULL);
1173 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1174 csp->error_message = strdup(errstr);
1177 return(JB_INVALID_SOCKET);
1181 cbuf[client_pos++] = '\x05'; /* Version */
1182 cbuf[client_pos++] = '\x01'; /* TCP connect */
1183 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1184 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1185 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1186 assert(sizeof(cbuf) - client_pos > 255);
1187 /* Using strncpy because we really want the nul byte padding. */
1188 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1189 client_pos += (hostlen & 0xffu);
1190 cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
1191 cbuf[client_pos++] = (char)((target_port ) & 0xffu);
1193 if (write_socket(sfd, cbuf, client_pos))
1195 errstr = "SOCKS5 negotiation read failed";
1196 csp->error_message = strdup(errstr);
1197 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1200 return(JB_INVALID_SOCKET);
1203 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1204 if (server_size < 3)
1206 errstr = "SOCKS5 negotiation read failed";
1209 else if (server_size > 20)
1211 /* This is somewhat unexpected but doesn't realy matter. */
1212 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1213 "from socks server. Would have accepted up to %d.",
1214 server_size, sizeof(sbuf));
1217 if (!err && (sbuf[0] != '\x05'))
1219 errstr = "SOCKS5 negotiation protocol version error";
1223 if (!err && (sbuf[2] != '\x00'))
1225 errstr = "SOCKS5 negotiation protocol error";
1231 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1235 errstr = translate_socks5_error(sbuf[1]);
1239 assert(errstr != NULL);
1240 csp->error_message = strdup(errstr);
1241 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1245 return(JB_INVALID_SOCKET);