1 const char gateway_rcs[] = "$Id: gateway.c,v 1.29 2008/10/11 16:59: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.29 2008/10/11 16:59:41 fabiankeil
38 * Add missing dots for two log messages.
40 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
41 * Flush work-in-progress changes to keep outgoing connections
42 * alive where possible. Incomplete and mostly #ifdef'd out.
44 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
45 * Return only once in forwarded_connect().
47 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
48 * Fix typo in macro name.
50 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
52 * - make the buffers quite a bit smaller.
53 * - properly report "socks5 server unreachable" failures.
54 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
55 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
56 * - log a message if the socks5 server sends more data than expected.
57 * - add some assertions and comments.
59 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
60 * - Fix a compiler warning.
61 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
63 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
64 * Remember the cause of the SOCKS5 error for the CGI message.
66 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
67 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
69 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
70 * Modified patch from Song Weijia (#1762559) to
71 * fix socks requests on big-endian platforms.
73 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
74 * - Use strlcpy() instead of strcpy().
75 * - Use the same buffer for socks requests and socks responses.
76 * - Fix bogus warning about web_server_addr being used uninitialized.
78 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
79 * - Save errors in socks4_connect() to csp->error_message.
80 * - Silence some gcc43 warnings, hopefully the right way.
82 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
83 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
84 * with what was really the latest development (the v_3_0_branch branch)
86 * Revision 1.16 2002/05/12 21:36:29 jongfoster
87 * Correcting function comments
89 * Revision 1.15 2002/03/26 22:29:54 swa
90 * we have a new homepage!
92 * Revision 1.14 2002/03/24 13:25:43 swa
93 * name change related issues
95 * Revision 1.13 2002/03/13 00:29:59 jongfoster
98 * Revision 1.12 2002/03/09 20:03:52 jongfoster
99 * - Making various functions return int rather than size_t.
100 * (Undoing a recent change). Since size_t is unsigned on
101 * Windows, functions like read_socket that return -1 on
102 * error cannot return a size_t.
104 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
105 * crashes, and also frequently caused JB to jump to 100%
106 * CPU and stay there. (Because it thought it had just
107 * read ((unsigned)-1) == 4Gb of data...)
109 * - The signature of write_socket has changed, it now simply
110 * returns success=0/failure=nonzero.
112 * - Trying to get rid of a few warnings --with-debug on
113 * Windows, I've introduced a new type "jb_socket". This is
114 * used for the socket file descriptors. On Windows, this
115 * is SOCKET (a typedef for unsigned). Everywhere else, it's
116 * an int. The error value can't be -1 any more, so it's
117 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
118 * Windows it maps to the #define INVALID_SOCKET.)
120 * - The signature of bind_port has changed.
122 * Revision 1.11 2002/03/08 17:46:04 jongfoster
123 * Fixing int/size_t warnings
125 * Revision 1.10 2002/03/07 03:50:19 oes
126 * - Improved handling of failed DNS lookups
127 * - Fixed compiler warnings
129 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
130 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
131 * threads to call select() simultaneously. So, it's time to do a real, live,
132 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
133 * (native). Both versions will work, but using __OS2__ offers multi-threading.
135 * Revision 1.8 2001/09/13 20:10:12 jongfoster
136 * Fixing missing #include under Windows
138 * Revision 1.7 2001/09/12 17:58:26 steudten
140 * add #include <string.h>
142 * Revision 1.6 2001/09/10 10:41:16 oes
143 * Added #include in.h
145 * Revision 1.5 2001/07/29 18:47:57 jongfoster
146 * Adding missing #include project.h
148 * Revision 1.4 2001/07/24 12:47:06 oes
149 * Applied BeOS support update by Eugenia
151 * Revision 1.3 2001/06/09 10:55:28 jongfoster
152 * Changing BUFSIZ ==> BUFFER_SIZE
154 * Revision 1.2 2001/06/07 23:11:38 jongfoster
155 * Removing gateways[] list - no longer used.
156 * Replacing function pointer in struct gateway with a directly
157 * called function forwarded_connect(), which can do the common
158 * task of deciding whether to connect to the web server or HTTP
160 * Replacing struct gateway with struct forward_spec
161 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
162 * It was a bug which led to the connection being made to the web
163 * server rather than the HTTP proxy, and also a buffer overrun.
165 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
166 * Initial import of version 2.9.3 source tree
169 *********************************************************************/
175 #include <sys/types.h>
178 #include <netinet/in.h>
186 #include <winsock2.h>
187 #endif /* def _WIN32 */
191 #endif /* def __BEOS__ */
195 #endif /* def __OS2__ */
200 #include "jbsockets.h"
202 #include "miscutil.h"
203 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
205 #include <sys/poll.h>
206 #endif /* __GLIBC__ */
208 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
210 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
212 static jb_socket socks4_connect(const struct forward_spec * fwd,
213 const char * target_host,
215 struct client_state *csp);
217 static jb_socket socks5_connect(const struct forward_spec *fwd,
218 const char *target_host,
220 struct client_state *csp);
223 #define SOCKS_REQUEST_GRANTED 90
224 #define SOCKS_REQUEST_REJECT 91
225 #define SOCKS_REQUEST_IDENT_FAILED 92
226 #define SOCKS_REQUEST_IDENT_CONFLICT 93
228 #define SOCKS5_REQUEST_GRANTED 0
229 #define SOCKS5_REQUEST_FAILED 1
230 #define SOCKS5_REQUEST_DENIED 2
231 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
232 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
233 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
234 #define SOCKS5_REQUEST_TTL_EXPIRED 6
235 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
236 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
238 /* structure of a socks client operation */
240 unsigned char vn; /* socks version number */
241 unsigned char cd; /* command code */
242 unsigned char dstport[2]; /* destination port */
243 unsigned char dstip[4]; /* destination address */
244 char userid; /* first byte of userid */
245 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
246 /* more bytes of the userid follow, terminated by a NULL */
249 /* structure of a socks server reply */
251 unsigned char vn; /* socks version number */
252 unsigned char cd; /* command code */
253 unsigned char dstport[2]; /* destination port */
254 unsigned char dstip[4]; /* destination address */
257 static const char socks_userid[] = "anonymous";
259 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
261 #define MAX_REUSABLE_CONNECTIONS 100
263 struct reusable_connection
277 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
279 static int mark_connection_unused(jb_socket sfd);
280 static void mark_connection_closed(struct reusable_connection *closed_connection);
282 /*********************************************************************
284 * Function : initialize_reusable_connections
286 * Description : Initializes the reusable_connection structures.
287 * Must be called with connection_reuse_mutex locked.
293 *********************************************************************/
294 extern void initialize_reusable_connections(void)
296 unsigned int slot = 0;
298 log_error(LOG_LEVEL_INFO,
299 "Support for 'Connection: keep-alive' is experimental, "
300 "incomplete and known not to work properly in some situations.");
302 for (slot = 0; slot < SZ(reusable_connection); slot++)
304 mark_connection_closed(&reusable_connection[slot]);
307 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
311 /*********************************************************************
313 * Function : remember_connection
315 * Description : Remembers a connection for reuse later on.
318 * 1 : sfd = Open socket to remember.
319 * 2 : http = The destination for the connection.
320 * 3 : fwd = The forwarder settings used.
324 *********************************************************************/
325 void remember_connection(jb_socket sfd, const struct http_request *http,
326 const struct forward_spec *fwd)
328 unsigned int slot = 0;
329 int free_slot_found = FALSE;
331 assert(sfd != JB_INVALID_SOCKET);
333 if (mark_connection_unused(sfd))
338 privoxy_mutex_lock(&connection_reuse_mutex);
340 /* Find free socket slot. */
341 for (slot = 0; slot < SZ(reusable_connection); slot++)
343 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
345 assert(reusable_connection[slot].in_use == 0);
346 log_error(LOG_LEVEL_CONNECT,
347 "Remembering socket %d for %s:%d in slot %d.",
348 sfd, http->host, http->port, slot);
349 free_slot_found = TRUE;
354 if (!free_slot_found)
356 log_error(LOG_LEVEL_CONNECT,
357 "No free slots found to remembering socket for %s:%d. Last slot %d.",
358 http->host, http->port, slot);
359 privoxy_mutex_unlock(&connection_reuse_mutex);
364 assert(NULL != http->host);
365 reusable_connection[slot].host = strdup(http->host);
366 if (NULL == reusable_connection[slot].host)
368 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
370 reusable_connection[slot].sfd = sfd;
371 reusable_connection[slot].port = http->port;
372 reusable_connection[slot].in_use = 0;
375 assert(reusable_connection[slot].gateway_host == NULL);
376 assert(reusable_connection[slot].gateway_port == 0);
377 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
378 assert(reusable_connection[slot].forward_host == NULL);
379 assert(reusable_connection[slot].forward_port == 0);
381 reusable_connection[slot].forwarder_type = fwd->type;
382 if (NULL != fwd->gateway_host)
384 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
385 if (NULL == reusable_connection[slot].gateway_host)
387 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
392 reusable_connection[slot].gateway_host = NULL;
394 reusable_connection[slot].gateway_port = fwd->gateway_port;
396 if (NULL != fwd->forward_host)
398 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
399 if (NULL == reusable_connection[slot].forward_host)
401 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
406 reusable_connection[slot].forward_host = NULL;
408 reusable_connection[slot].forward_port = fwd->forward_port;
410 privoxy_mutex_unlock(&connection_reuse_mutex);
414 /*********************************************************************
416 * Function : mark_connection_closed
418 * Description : Marks a reused connection closed.
419 * Must be called with connection_reuse_mutex locked.
422 * 1 : closed_connection = The connection to mark as closed.
426 *********************************************************************/
427 static void mark_connection_closed(struct reusable_connection *closed_connection)
429 closed_connection->in_use = FALSE;
430 closed_connection->sfd = JB_INVALID_SOCKET;
431 freez(closed_connection->host);
432 closed_connection->port = 0;
433 closed_connection->forwarder_type = SOCKS_NONE;
434 freez(closed_connection->gateway_host);
435 closed_connection->gateway_port = 0;
436 freez(closed_connection->forward_host);
437 closed_connection->forward_port = 0;
441 /*********************************************************************
443 * Function : forget_connection
445 * Description : Removes a previously remembered connection from
446 * the list of reusable connections.
449 * 1 : sfd = The socket belonging to the connection in question.
453 *********************************************************************/
454 void forget_connection(jb_socket sfd)
456 unsigned int slot = 0;
458 assert(sfd != JB_INVALID_SOCKET);
460 privoxy_mutex_lock(&connection_reuse_mutex);
462 for (slot = 0; slot < SZ(reusable_connection); slot++)
464 if (reusable_connection[slot].sfd == sfd)
466 assert(reusable_connection[slot].in_use);
471 if (reusable_connection[slot].sfd != sfd)
473 log_error(LOG_LEVEL_CONNECT,
474 "Socket %d already forgotten or never remembered.", sfd);
475 privoxy_mutex_unlock(&connection_reuse_mutex);
479 log_error(LOG_LEVEL_CONNECT,
480 "Forgetting socket %d for %s:%d in slot %d.",
481 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
483 mark_connection_closed(&reusable_connection[slot]);
485 privoxy_mutex_unlock(&connection_reuse_mutex);
489 /*********************************************************************
491 * Function : connection_destination_matches
493 * Description : Determines whether a remembered connection can
494 * be reused. That is whether the destination and
495 * the forwarding settings match.
498 * 1 : connection = The connection to check.
499 * 2 : http = The destination for the connection.
500 * 3 : fwd = The forwarder settings.
502 * Returns : TRUE for yes, FALSE otherwise.
504 *********************************************************************/
505 static int connection_destination_matches(const struct reusable_connection *connection,
506 const struct http_request *http,
507 const struct forward_spec *fwd)
509 /* XXX: Start of duplicated checks for debugging purposes. */
510 if (strcmpic(connection->host, http->host))
515 if (connection->forwarder_type != fwd->type)
517 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
518 connection->forwarder_type, fwd->type, http->host);
521 if (connection->gateway_port != fwd->gateway_port)
523 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
524 connection->gateway_port, fwd->gateway_port, http->host);
527 if (connection->forward_port != fwd->forward_port)
529 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
530 connection->forward_port, fwd->forward_port, http->host);
533 if (connection->forward_port != fwd->forward_port)
535 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
536 connection->forward_port, fwd->forward_port, http->host);
540 /* XXX: End of duplicated checks for debugging purposes. */
542 if ((connection->forwarder_type != fwd->type)
543 || (connection->gateway_port != fwd->gateway_port)
544 || (connection->forward_port != fwd->forward_port)
545 || (connection->port != http->port))
550 if (( (NULL != connection->gateway_host)
551 && (NULL != fwd->gateway_host)
552 && strcmpic(connection->gateway_host, fwd->gateway_host))
553 && (connection->gateway_host != fwd->gateway_host))
555 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
559 if (( (NULL != connection->forward_host)
560 && (NULL != fwd->forward_host)
561 && strcmpic(connection->forward_host, fwd->forward_host))
562 && (connection->forward_host != fwd->forward_host))
564 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
568 return (!strcmpic(connection->host, http->host));
572 /*********************************************************************
574 * Function : get_reusable_connection
576 * Description : Returns an open socket to a previously remembered
577 * open connection (if there is one).
580 * 1 : http = The destination for the connection.
581 * 2 : fwd = The forwarder settings.
583 * Returns : JB_INVALID_SOCKET => No reusable connection found,
584 * otherwise a usable socket.
586 *********************************************************************/
587 static jb_socket get_reusable_connection(const struct http_request *http,
588 const struct forward_spec *fwd)
590 jb_socket sfd = JB_INVALID_SOCKET;
591 unsigned int slot = 0;
593 privoxy_mutex_lock(&connection_reuse_mutex);
595 for (slot = 0; slot < SZ(reusable_connection); slot++)
597 if (!reusable_connection[slot].in_use
598 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
601 struct pollfd poll_fd[1];
602 memset(poll_fd, 0, sizeof(poll_fd));
603 poll_fd[0].fd = reusable_connection[slot].sfd;
604 poll_fd[0].events = POLLIN;
606 poll_result = poll(poll_fd, 1, 0);
608 if (-1 != poll_result)
610 if ((poll_fd[0].revents & POLLIN))
612 log_error(LOG_LEVEL_CONNECT,
613 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
614 reusable_connection[slot].sfd, reusable_connection[slot].host,
615 reusable_connection[slot].port, slot);
616 mark_connection_closed(&reusable_connection[slot]);
622 log_error(LOG_LEVEL_CONNECT,
623 "Failed to poll socket %d for %s:%d in slot %d.",
624 reusable_connection[slot].sfd, reusable_connection[slot].host,
625 reusable_connection[slot].port, slot);
628 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
630 reusable_connection[slot].in_use = TRUE;
631 sfd = reusable_connection[slot].sfd;
632 log_error(LOG_LEVEL_CONNECT,
633 "Found reusable socket %d for %s:%d in slot %d.",
634 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
640 privoxy_mutex_unlock(&connection_reuse_mutex);
647 /*********************************************************************
649 * Function : mark_connection_unused
651 * Description : Gives a remembered connection free for reuse.
654 * 1 : sfd = The socket belonging to the connection in question.
656 * Returns : TRUE => Socket found and marked as unused.
657 * FALSE => Socket not found.
659 *********************************************************************/
660 static int mark_connection_unused(jb_socket sfd)
662 unsigned int slot = 0;
663 unsigned int socket_found = FALSE;
665 assert(sfd != JB_INVALID_SOCKET);
667 privoxy_mutex_lock(&connection_reuse_mutex);
669 for (slot = 0; slot < SZ(reusable_connection); slot++)
671 if (reusable_connection[slot].sfd == sfd)
673 assert(reusable_connection[slot].in_use);
678 if (reusable_connection[slot].sfd == sfd)
681 log_error(LOG_LEVEL_CONNECT,
682 "Marking open socket %d for %s:%d in slot %d as unused.",
683 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
684 reusable_connection[slot].in_use = 0;
687 privoxy_mutex_unlock(&connection_reuse_mutex);
692 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
695 /*********************************************************************
697 * Function : forwarded_connect
699 * Description : Connect to a specified web server, possibly via
700 * a HTTP proxy and/or a SOCKS proxy.
703 * 1 : fwd = the proxies to use when connecting.
704 * 2 : http = the http request and apropos headers
705 * 3 : csp = Current client state (buffers, headers, etc...)
707 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
709 *********************************************************************/
710 jb_socket forwarded_connect(const struct forward_spec * fwd,
711 struct http_request *http,
712 struct client_state *csp)
714 const char * dest_host;
716 jb_socket sfd = JB_INVALID_SOCKET;
718 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
719 sfd = get_reusable_connection(http, fwd);
720 if (JB_INVALID_SOCKET == sfd)
722 log_error(LOG_LEVEL_CONNECT,
723 "No reusable socket for %s:%d found. Opening a new one.",
724 http->host, http->port);
730 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
732 /* Figure out if we need to connect to the web server or a HTTP proxy. */
733 if (fwd->forward_host)
736 dest_host = fwd->forward_host;
737 dest_port = fwd->forward_port;
742 dest_host = http->host;
743 dest_port = http->port;
746 /* Connect, maybe using a SOCKS proxy */
750 sfd = connect_to(dest_host, dest_port, csp);
754 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
757 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
760 /* Should never get here */
761 log_error(LOG_LEVEL_FATAL,
762 "SOCKS4 impossible internal error - bad SOCKS type.");
770 /*********************************************************************
772 * Function : socks4_connect
774 * Description : Connect to the SOCKS server, and connect through
775 * it to the specified server. This handles
776 * all the SOCKS negotiation, and returns a file
777 * descriptor for a socket which can be treated as a
778 * normal (non-SOCKS) socket.
780 * Logged error messages are saved to csp->error_message
781 * and later reused by error_response() for the CGI
782 * message. strdup allocation failures are handled there.
785 * 1 : fwd = Specifies the SOCKS proxy to use.
786 * 2 : target_host = The final server to connect to.
787 * 3 : target_port = The final port to connect to.
788 * 4 : csp = Current client state (buffers, headers, etc...)
790 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
792 *********************************************************************/
793 static jb_socket socks4_connect(const struct forward_spec * fwd,
794 const char * target_host,
796 struct client_state *csp)
798 unsigned int web_server_addr;
799 char buf[BUFFER_SIZE];
800 struct socks_op *c = (struct socks_op *)buf;
801 struct socks_reply *s = (struct socks_reply *)buf;
808 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
810 /* XXX: Shouldn't the config file parser prevent this? */
811 errstr = "NULL gateway host specified.";
815 if (fwd->gateway_port <= 0)
817 errstr = "invalid gateway port specified.";
823 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
824 csp->error_message = strdup(errstr);
826 return(JB_INVALID_SOCKET);
829 /* build a socks request for connection to the web server */
831 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
833 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
838 web_server_addr = resolve_hostname_to_ip(target_host);
839 if (web_server_addr == INADDR_NONE)
841 errstr = "could not resolve target host";
842 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
847 web_server_addr = htonl(web_server_addr);
851 web_server_addr = 0x00000001;
852 n = csiz + strlen(target_host) + 1;
856 errstr = "buffer cbuf too small.";
857 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
862 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
864 * What we forward to the socks4a server should have the
865 * size of socks_op, plus the length of the userid plus
866 * its \0 byte (which we don't have to add because the
867 * first byte of the userid is counted twice as it's also
868 * part of sock_op) minus the padding bytes (which are part
869 * of the userid as well), plus the length of the target_host
870 * (which is stored csiz bytes after the beginning of the buffer),
871 * plus another \0 byte.
873 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
878 /* Should never get here */
879 log_error(LOG_LEVEL_FATAL,
880 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
882 return(JB_INVALID_SOCKET);
887 csp->error_message = strdup(errstr);
888 return(JB_INVALID_SOCKET);
893 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
894 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
895 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
896 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
897 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
898 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
900 /* pass the request to the socks server */
901 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
903 if (sfd == JB_INVALID_SOCKET)
906 * XXX: connect_to should fill in the exact reason.
907 * Most likely resolving the IP of the forwarder failed.
909 errstr = "connect_to failed: see logfile for details";
912 else if (write_socket(sfd, (char *)c, csiz))
914 errstr = "SOCKS4 negotiation write failed.";
915 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
919 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
921 errstr = "SOCKS4 negotiation read failed.";
922 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
929 csp->error_message = strdup(errstr);
930 return(JB_INVALID_SOCKET);
935 case SOCKS_REQUEST_GRANTED:
938 case SOCKS_REQUEST_REJECT:
939 errstr = "SOCKS request rejected or failed.";
942 case SOCKS_REQUEST_IDENT_FAILED:
943 errstr = "SOCKS request rejected because "
944 "SOCKS server cannot connect to identd on the client.";
947 case SOCKS_REQUEST_IDENT_CONFLICT:
948 errstr = "SOCKS request rejected because "
949 "the client program and identd report "
950 "different user-ids.";
955 snprintf(buf, sizeof(buf),
956 "SOCKS request rejected for reason code %d.", s->cd);
960 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
961 csp->error_message = strdup(errstr);
964 return(JB_INVALID_SOCKET);
968 /*********************************************************************
970 * Function : translate_socks5_error
972 * Description : Translates a SOCKS errors to a string.
975 * 1 : socks_error = The error code to translate.
977 * Returns : The string translation.
979 *********************************************************************/
980 static const char *translate_socks5_error(int socks_error)
984 /* XXX: these should be more descriptive */
985 case SOCKS5_REQUEST_FAILED:
986 return "SOCKS5 request failed";
987 case SOCKS5_REQUEST_DENIED:
988 return "SOCKS5 request denied";
989 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
990 return "SOCKS5 network unreachable";
991 case SOCKS5_REQUEST_HOST_UNREACHABLE:
992 return "SOCKS5 host unreachable";
993 case SOCKS5_REQUEST_CONNECTION_REFUSED:
994 return "SOCKS5 connection refused";
995 case SOCKS5_REQUEST_TTL_EXPIRED:
996 return "SOCKS5 TTL expired";
997 case SOCKS5_REQUEST_PROTOCOL_ERROR:
998 return "SOCKS5 client protocol error";
999 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1000 return "SOCKS5 domain names unsupported";
1001 case SOCKS5_REQUEST_GRANTED:
1002 return "everything's peachy";
1004 return "SOCKS5 negotiation protocol error";
1008 /*********************************************************************
1010 * Function : socks5_connect
1012 * Description : Connect to the SOCKS server, and connect through
1013 * it to the specified server. This handles
1014 * all the SOCKS negotiation, and returns a file
1015 * descriptor for a socket which can be treated as a
1016 * normal (non-SOCKS) socket.
1019 * 1 : fwd = Specifies the SOCKS proxy to use.
1020 * 2 : target_host = The final server to connect to.
1021 * 3 : target_port = The final port to connect to.
1022 * 4 : csp = Current client state (buffers, headers, etc...)
1024 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1026 *********************************************************************/
1027 static jb_socket socks5_connect(const struct forward_spec *fwd,
1028 const char *target_host,
1030 struct client_state *csp)
1035 size_t client_pos = 0;
1036 int server_size = 0;
1039 const char *errstr = NULL;
1041 assert(fwd->gateway_host);
1042 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1044 errstr = "NULL gateway host specified";
1048 if (fwd->gateway_port <= 0)
1051 * XXX: currently this can't happen because in
1052 * case of invalid gateway ports we use the defaults.
1053 * Of course we really shouldn't do that.
1055 errstr = "invalid gateway port specified";
1059 hostlen = strlen(target_host);
1062 errstr = "target host name is longer than 255 characters";
1066 if (fwd->type != SOCKS_5)
1068 /* Should never get here */
1069 log_error(LOG_LEVEL_FATAL,
1070 "SOCKS5 impossible internal error - bad SOCKS type");
1077 assert(errstr != NULL);
1078 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1079 csp->error_message = strdup(errstr);
1080 return(JB_INVALID_SOCKET);
1083 /* pass the request to the socks server */
1084 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1086 if (sfd == JB_INVALID_SOCKET)
1088 errstr = "socks5 server unreachable";
1089 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1090 csp->error_message = strdup(errstr);
1091 return(JB_INVALID_SOCKET);
1095 cbuf[client_pos++] = '\x05'; /* Version */
1096 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1097 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1099 if (write_socket(sfd, cbuf, client_pos))
1101 errstr = "SOCKS5 negotiation write failed";
1102 csp->error_message = strdup(errstr);
1103 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1105 return(JB_INVALID_SOCKET);
1108 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1110 errstr = "SOCKS5 negotiation read failed";
1114 if (!err && (sbuf[0] != '\x05'))
1116 errstr = "SOCKS5 negotiation protocol version error";
1120 if (!err && (sbuf[1] == '\xff'))
1122 errstr = "SOCKS5 authentication required";
1126 if (!err && (sbuf[1] != '\x00'))
1128 errstr = "SOCKS5 negotiation protocol error";
1134 assert(errstr != NULL);
1135 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1136 csp->error_message = strdup(errstr);
1139 return(JB_INVALID_SOCKET);
1143 cbuf[client_pos++] = '\x05'; /* Version */
1144 cbuf[client_pos++] = '\x01'; /* TCP connect */
1145 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1146 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1147 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1148 assert(sizeof(cbuf) - client_pos > 255);
1149 /* Using strncpy because we really want the nul byte padding. */
1150 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1151 client_pos += (hostlen & 0xffu);
1152 cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
1153 cbuf[client_pos++] = (char)((target_port ) & 0xffu);
1155 if (write_socket(sfd, cbuf, client_pos))
1157 errstr = "SOCKS5 negotiation read failed";
1158 csp->error_message = strdup(errstr);
1159 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1162 return(JB_INVALID_SOCKET);
1165 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1166 if (server_size < 3)
1168 errstr = "SOCKS5 negotiation read failed";
1171 else if (server_size > 20)
1173 /* This is somewhat unexpected but doesn't realy matter. */
1174 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1175 "from socks server. Would have accepted up to %d.",
1176 server_size, sizeof(sbuf));
1179 if (!err && (sbuf[0] != '\x05'))
1181 errstr = "SOCKS5 negotiation protocol version error";
1185 if (!err && (sbuf[2] != '\x00'))
1187 errstr = "SOCKS5 negotiation protocol error";
1193 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1197 errstr = translate_socks5_error(sbuf[1]);
1201 assert(errstr != NULL);
1202 csp->error_message = strdup(errstr);
1203 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1207 return(JB_INVALID_SOCKET);