1 const char gateway_rcs[] = "$Id: gateway.c,v 1.33 2008/10/16 16:34:21 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.33 2008/10/16 16:34:21 fabiankeil
38 * Fix two gcc44 warnings.
40 * Revision 1.32 2008/10/16 16:27:22 fabiankeil
41 * Fix compiler warning.
43 * Revision 1.31 2008/10/16 07:31:11 fabiankeil
44 * - Factor socket_is_still_usable() out of get_reusable_connection().
45 * - If poll() isn't available, show a warning and assume the socket
48 * Revision 1.30 2008/10/13 17:31:03 fabiankeil
49 * If a remembered connection is no longer usable and
50 * has been marked closed, don't bother checking if the
51 * destination matches.
53 * Revision 1.29 2008/10/11 16:59:41 fabiankeil
54 * Add missing dots for two log messages.
56 * Revision 1.28 2008/10/09 18:21:41 fabiankeil
57 * Flush work-in-progress changes to keep outgoing connections
58 * alive where possible. Incomplete and mostly #ifdef'd out.
60 * Revision 1.27 2008/09/27 15:05:51 fabiankeil
61 * Return only once in forwarded_connect().
63 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
64 * Fix typo in macro name.
66 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
68 * - make the buffers quite a bit smaller.
69 * - properly report "socks5 server unreachable" failures.
70 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
71 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
72 * - log a message if the socks5 server sends more data than expected.
73 * - add some assertions and comments.
75 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
76 * - Fix a compiler warning.
77 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
79 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
80 * Remember the cause of the SOCKS5 error for the CGI message.
82 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
83 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
85 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
86 * Modified patch from Song Weijia (#1762559) to
87 * fix socks requests on big-endian platforms.
89 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
90 * - Use strlcpy() instead of strcpy().
91 * - Use the same buffer for socks requests and socks responses.
92 * - Fix bogus warning about web_server_addr being used uninitialized.
94 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
95 * - Save errors in socks4_connect() to csp->error_message.
96 * - Silence some gcc43 warnings, hopefully the right way.
98 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
99 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
100 * with what was really the latest development (the v_3_0_branch branch)
102 * Revision 1.16 2002/05/12 21:36:29 jongfoster
103 * Correcting function comments
105 * Revision 1.15 2002/03/26 22:29:54 swa
106 * we have a new homepage!
108 * Revision 1.14 2002/03/24 13:25:43 swa
109 * name change related issues
111 * Revision 1.13 2002/03/13 00:29:59 jongfoster
114 * Revision 1.12 2002/03/09 20:03:52 jongfoster
115 * - Making various functions return int rather than size_t.
116 * (Undoing a recent change). Since size_t is unsigned on
117 * Windows, functions like read_socket that return -1 on
118 * error cannot return a size_t.
120 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
121 * crashes, and also frequently caused JB to jump to 100%
122 * CPU and stay there. (Because it thought it had just
123 * read ((unsigned)-1) == 4Gb of data...)
125 * - The signature of write_socket has changed, it now simply
126 * returns success=0/failure=nonzero.
128 * - Trying to get rid of a few warnings --with-debug on
129 * Windows, I've introduced a new type "jb_socket". This is
130 * used for the socket file descriptors. On Windows, this
131 * is SOCKET (a typedef for unsigned). Everywhere else, it's
132 * an int. The error value can't be -1 any more, so it's
133 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
134 * Windows it maps to the #define INVALID_SOCKET.)
136 * - The signature of bind_port has changed.
138 * Revision 1.11 2002/03/08 17:46:04 jongfoster
139 * Fixing int/size_t warnings
141 * Revision 1.10 2002/03/07 03:50:19 oes
142 * - Improved handling of failed DNS lookups
143 * - Fixed compiler warnings
145 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
146 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
147 * threads to call select() simultaneously. So, it's time to do a real, live,
148 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
149 * (native). Both versions will work, but using __OS2__ offers multi-threading.
151 * Revision 1.8 2001/09/13 20:10:12 jongfoster
152 * Fixing missing #include under Windows
154 * Revision 1.7 2001/09/12 17:58:26 steudten
156 * add #include <string.h>
158 * Revision 1.6 2001/09/10 10:41:16 oes
159 * Added #include in.h
161 * Revision 1.5 2001/07/29 18:47:57 jongfoster
162 * Adding missing #include project.h
164 * Revision 1.4 2001/07/24 12:47:06 oes
165 * Applied BeOS support update by Eugenia
167 * Revision 1.3 2001/06/09 10:55:28 jongfoster
168 * Changing BUFSIZ ==> BUFFER_SIZE
170 * Revision 1.2 2001/06/07 23:11:38 jongfoster
171 * Removing gateways[] list - no longer used.
172 * Replacing function pointer in struct gateway with a directly
173 * called function forwarded_connect(), which can do the common
174 * task of deciding whether to connect to the web server or HTTP
176 * Replacing struct gateway with struct forward_spec
177 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
178 * It was a bug which led to the connection being made to the web
179 * server rather than the HTTP proxy, and also a buffer overrun.
181 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
182 * Initial import of version 2.9.3 source tree
185 *********************************************************************/
191 #include <sys/types.h>
194 #include <netinet/in.h>
202 #include <winsock2.h>
203 #endif /* def _WIN32 */
207 #endif /* def __BEOS__ */
211 #endif /* def __OS2__ */
216 #include "jbsockets.h"
218 #include "miscutil.h"
219 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
222 #include <sys/poll.h>
225 #endif /* def __GLIBC__ */
226 #endif /* HAVE_POLL */
227 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
229 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
231 static jb_socket socks4_connect(const struct forward_spec * fwd,
232 const char * target_host,
234 struct client_state *csp);
236 static jb_socket socks5_connect(const struct forward_spec *fwd,
237 const char *target_host,
239 struct client_state *csp);
242 #define SOCKS_REQUEST_GRANTED 90
243 #define SOCKS_REQUEST_REJECT 91
244 #define SOCKS_REQUEST_IDENT_FAILED 92
245 #define SOCKS_REQUEST_IDENT_CONFLICT 93
247 #define SOCKS5_REQUEST_GRANTED 0
248 #define SOCKS5_REQUEST_FAILED 1
249 #define SOCKS5_REQUEST_DENIED 2
250 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
251 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
252 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
253 #define SOCKS5_REQUEST_TTL_EXPIRED 6
254 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
255 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
257 /* structure of a socks client operation */
259 unsigned char vn; /* socks version number */
260 unsigned char cd; /* command code */
261 unsigned char dstport[2]; /* destination port */
262 unsigned char dstip[4]; /* destination address */
263 char userid; /* first byte of userid */
264 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
265 /* more bytes of the userid follow, terminated by a NULL */
268 /* structure of a socks server reply */
270 unsigned char vn; /* socks version number */
271 unsigned char cd; /* command code */
272 unsigned char dstport[2]; /* destination port */
273 unsigned char dstip[4]; /* destination address */
276 static const char socks_userid[] = "anonymous";
278 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
280 #define MAX_REUSABLE_CONNECTIONS 100
281 /* XXX: should be a config option. */
282 #define CONNECTION_KEEP_ALIVE_TIMEOUT 3 * 60
284 struct reusable_connection
299 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
301 static int mark_connection_unused(jb_socket sfd);
302 static void mark_connection_closed(struct reusable_connection *closed_connection);
304 /*********************************************************************
306 * Function : initialize_reusable_connections
308 * Description : Initializes the reusable_connection structures.
309 * Must be called with connection_reuse_mutex locked.
315 *********************************************************************/
316 extern void initialize_reusable_connections(void)
318 unsigned int slot = 0;
320 log_error(LOG_LEVEL_INFO,
321 "Support for 'Connection: keep-alive' is experimental, "
322 "incomplete and known not to work properly in some situations.");
324 for (slot = 0; slot < SZ(reusable_connection); slot++)
326 mark_connection_closed(&reusable_connection[slot]);
329 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
333 /*********************************************************************
335 * Function : remember_connection
337 * Description : Remembers a connection for reuse later on.
340 * 1 : sfd = Open socket to remember.
341 * 2 : http = The destination for the connection.
342 * 3 : fwd = The forwarder settings used.
346 *********************************************************************/
347 void remember_connection(jb_socket sfd, const struct http_request *http,
348 const struct forward_spec *fwd)
350 unsigned int slot = 0;
351 int free_slot_found = FALSE;
353 assert(sfd != JB_INVALID_SOCKET);
355 if (mark_connection_unused(sfd))
360 privoxy_mutex_lock(&connection_reuse_mutex);
362 /* Find free socket slot. */
363 for (slot = 0; slot < SZ(reusable_connection); slot++)
365 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
367 assert(reusable_connection[slot].in_use == 0);
368 log_error(LOG_LEVEL_CONNECT,
369 "Remembering socket %d for %s:%d in slot %d.",
370 sfd, http->host, http->port, slot);
371 free_slot_found = TRUE;
376 if (!free_slot_found)
378 log_error(LOG_LEVEL_CONNECT,
379 "No free slots found to remembering socket for %s:%d. Last slot %d.",
380 http->host, http->port, slot);
381 privoxy_mutex_unlock(&connection_reuse_mutex);
386 assert(NULL != http->host);
387 reusable_connection[slot].host = strdup(http->host);
388 if (NULL == reusable_connection[slot].host)
390 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
392 reusable_connection[slot].sfd = sfd;
393 reusable_connection[slot].port = http->port;
394 reusable_connection[slot].in_use = 0;
395 reusable_connection[slot].timestamp = time(NULL);
398 assert(reusable_connection[slot].gateway_host == NULL);
399 assert(reusable_connection[slot].gateway_port == 0);
400 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
401 assert(reusable_connection[slot].forward_host == NULL);
402 assert(reusable_connection[slot].forward_port == 0);
404 reusable_connection[slot].forwarder_type = fwd->type;
405 if (NULL != fwd->gateway_host)
407 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
408 if (NULL == reusable_connection[slot].gateway_host)
410 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
415 reusable_connection[slot].gateway_host = NULL;
417 reusable_connection[slot].gateway_port = fwd->gateway_port;
419 if (NULL != fwd->forward_host)
421 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
422 if (NULL == reusable_connection[slot].forward_host)
424 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
429 reusable_connection[slot].forward_host = NULL;
431 reusable_connection[slot].forward_port = fwd->forward_port;
433 privoxy_mutex_unlock(&connection_reuse_mutex);
437 /*********************************************************************
439 * Function : mark_connection_closed
441 * Description : Marks a reused connection closed.
442 * Must be called with connection_reuse_mutex locked.
445 * 1 : closed_connection = The connection to mark as closed.
449 *********************************************************************/
450 static void mark_connection_closed(struct reusable_connection *closed_connection)
452 closed_connection->in_use = FALSE;
453 closed_connection->sfd = JB_INVALID_SOCKET;
454 freez(closed_connection->host);
455 closed_connection->port = 0;
456 closed_connection->timestamp = 0;
457 closed_connection->forwarder_type = SOCKS_NONE;
458 freez(closed_connection->gateway_host);
459 closed_connection->gateway_port = 0;
460 freez(closed_connection->forward_host);
461 closed_connection->forward_port = 0;
465 /*********************************************************************
467 * Function : forget_connection
469 * Description : Removes a previously remembered connection from
470 * the list of reusable connections.
473 * 1 : sfd = The socket belonging to the connection in question.
477 *********************************************************************/
478 void forget_connection(jb_socket sfd)
480 unsigned int slot = 0;
482 assert(sfd != JB_INVALID_SOCKET);
484 privoxy_mutex_lock(&connection_reuse_mutex);
486 for (slot = 0; slot < SZ(reusable_connection); slot++)
488 if (reusable_connection[slot].sfd == sfd)
490 assert(reusable_connection[slot].in_use);
495 if (reusable_connection[slot].sfd != sfd)
497 log_error(LOG_LEVEL_CONNECT,
498 "Socket %d already forgotten or never remembered.", sfd);
499 privoxy_mutex_unlock(&connection_reuse_mutex);
503 log_error(LOG_LEVEL_CONNECT,
504 "Forgetting socket %d for %s:%d in slot %d.",
505 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
507 mark_connection_closed(&reusable_connection[slot]);
509 privoxy_mutex_unlock(&connection_reuse_mutex);
513 /*********************************************************************
515 * Function : connection_destination_matches
517 * Description : Determines whether a remembered connection can
518 * be reused. That is whether the destination and
519 * the forwarding settings match.
522 * 1 : connection = The connection to check.
523 * 2 : http = The destination for the connection.
524 * 3 : fwd = The forwarder settings.
526 * Returns : TRUE for yes, FALSE otherwise.
528 *********************************************************************/
529 static int connection_destination_matches(const struct reusable_connection *connection,
530 const struct http_request *http,
531 const struct forward_spec *fwd)
533 /* XXX: Start of duplicated checks for debugging purposes. */
534 if (strcmpic(connection->host, http->host))
539 if (connection->forwarder_type != fwd->type)
541 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
542 connection->forwarder_type, fwd->type, http->host);
545 if (connection->gateway_port != fwd->gateway_port)
547 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
548 connection->gateway_port, fwd->gateway_port, http->host);
551 if (connection->forward_port != fwd->forward_port)
553 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
554 connection->forward_port, fwd->forward_port, http->host);
557 if (connection->forward_port != fwd->forward_port)
559 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
560 connection->forward_port, fwd->forward_port, http->host);
564 /* XXX: End of duplicated checks for debugging purposes. */
566 if ((connection->forwarder_type != fwd->type)
567 || (connection->gateway_port != fwd->gateway_port)
568 || (connection->forward_port != fwd->forward_port)
569 || (connection->port != http->port))
574 if (( (NULL != connection->gateway_host)
575 && (NULL != fwd->gateway_host)
576 && strcmpic(connection->gateway_host, fwd->gateway_host))
577 && (connection->gateway_host != fwd->gateway_host))
579 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
583 if (( (NULL != connection->forward_host)
584 && (NULL != fwd->forward_host)
585 && strcmpic(connection->forward_host, fwd->forward_host))
586 && (connection->forward_host != fwd->forward_host))
588 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
592 return (!strcmpic(connection->host, http->host));
597 /*********************************************************************
599 * Function : socket_is_still_usable
601 * Description : Decides whether or not an open socket is still usable.
604 * 1 : sfd = The socket to check.
606 * Returns : TRUE for yes, otherwise FALSE.
608 *********************************************************************/
609 static int socket_is_still_usable(jb_socket sfd)
613 struct pollfd poll_fd[1];
614 memset(poll_fd, 0, sizeof(poll_fd));
616 poll_fd[0].events = POLLIN;
618 poll_result = poll(poll_fd, 1, 0);
620 if (-1 != poll_result)
622 return !(poll_fd[0].revents & POLLIN);
626 log_error(LOG_LEVEL_CONNECT, "Polling socket %d failed.", sfd);
630 log_error(LOG_LEVEL_INFO,
631 "Detecting already dead sockets isn't implemented for your "
632 "platform yet. Assuming sockets stay alive forever, expect "
633 "an increase in connection problems.");
635 #endif /* def HAVE_POLL */
639 /*********************************************************************
641 * Function : get_reusable_connection
643 * Description : Returns an open socket to a previously remembered
644 * open connection (if there is one).
647 * 1 : http = The destination for the connection.
648 * 2 : fwd = The forwarder settings.
650 * Returns : JB_INVALID_SOCKET => No reusable connection found,
651 * otherwise a usable socket.
653 *********************************************************************/
654 static jb_socket get_reusable_connection(const struct http_request *http,
655 const struct forward_spec *fwd)
657 jb_socket sfd = JB_INVALID_SOCKET;
658 unsigned int slot = 0;
660 privoxy_mutex_lock(&connection_reuse_mutex);
662 for (slot = 0; slot < SZ(reusable_connection); slot++)
664 if (!reusable_connection[slot].in_use
665 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
667 time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
669 if (CONNECTION_KEEP_ALIVE_TIMEOUT < time_open)
671 log_error(LOG_LEVEL_CONNECT,
672 "The connection to %s:%d in slot %d timed out. Closing.",
673 reusable_connection[slot].host, reusable_connection[slot].port,
675 mark_connection_closed(&reusable_connection[slot]);
679 if (!socket_is_still_usable(reusable_connection[slot].sfd))
681 log_error(LOG_LEVEL_CONNECT,
682 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
683 reusable_connection[slot].sfd, reusable_connection[slot].host,
684 reusable_connection[slot].port, slot);
685 mark_connection_closed(&reusable_connection[slot]);
689 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
691 reusable_connection[slot].in_use = TRUE;
692 sfd = reusable_connection[slot].sfd;
693 log_error(LOG_LEVEL_CONNECT,
694 "Found reusable socket %d for %s:%d in slot %d.",
695 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
701 privoxy_mutex_unlock(&connection_reuse_mutex);
708 /*********************************************************************
710 * Function : mark_connection_unused
712 * Description : Gives a remembered connection free for reuse.
715 * 1 : sfd = The socket belonging to the connection in question.
717 * Returns : TRUE => Socket found and marked as unused.
718 * FALSE => Socket not found.
720 *********************************************************************/
721 static int mark_connection_unused(jb_socket sfd)
723 unsigned int slot = 0;
724 int socket_found = FALSE;
726 assert(sfd != JB_INVALID_SOCKET);
728 privoxy_mutex_lock(&connection_reuse_mutex);
730 for (slot = 0; slot < SZ(reusable_connection); slot++)
732 if (reusable_connection[slot].sfd == sfd)
734 assert(reusable_connection[slot].in_use);
739 if (reusable_connection[slot].sfd == sfd)
742 log_error(LOG_LEVEL_CONNECT,
743 "Marking open socket %d for %s:%d in slot %d as unused.",
744 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
745 reusable_connection[slot].in_use = 0;
746 reusable_connection[slot].timestamp = time(NULL);
749 privoxy_mutex_unlock(&connection_reuse_mutex);
754 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
757 /*********************************************************************
759 * Function : forwarded_connect
761 * Description : Connect to a specified web server, possibly via
762 * a HTTP proxy and/or a SOCKS proxy.
765 * 1 : fwd = the proxies to use when connecting.
766 * 2 : http = the http request and apropos headers
767 * 3 : csp = Current client state (buffers, headers, etc...)
769 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
771 *********************************************************************/
772 jb_socket forwarded_connect(const struct forward_spec * fwd,
773 struct http_request *http,
774 struct client_state *csp)
776 const char * dest_host;
778 jb_socket sfd = JB_INVALID_SOCKET;
780 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
781 sfd = get_reusable_connection(http, fwd);
782 if (JB_INVALID_SOCKET == sfd)
784 log_error(LOG_LEVEL_CONNECT,
785 "No reusable socket for %s:%d found. Opening a new one.",
786 http->host, http->port);
792 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
794 /* Figure out if we need to connect to the web server or a HTTP proxy. */
795 if (fwd->forward_host)
798 dest_host = fwd->forward_host;
799 dest_port = fwd->forward_port;
804 dest_host = http->host;
805 dest_port = http->port;
808 /* Connect, maybe using a SOCKS proxy */
812 sfd = connect_to(dest_host, dest_port, csp);
816 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
819 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
822 /* Should never get here */
823 log_error(LOG_LEVEL_FATAL,
824 "SOCKS4 impossible internal error - bad SOCKS type.");
832 /*********************************************************************
834 * Function : socks4_connect
836 * Description : Connect to the SOCKS server, and connect through
837 * it to the specified server. This handles
838 * all the SOCKS negotiation, and returns a file
839 * descriptor for a socket which can be treated as a
840 * normal (non-SOCKS) socket.
842 * Logged error messages are saved to csp->error_message
843 * and later reused by error_response() for the CGI
844 * message. strdup allocation failures are handled there.
847 * 1 : fwd = Specifies the SOCKS proxy to use.
848 * 2 : target_host = The final server to connect to.
849 * 3 : target_port = The final port to connect to.
850 * 4 : csp = Current client state (buffers, headers, etc...)
852 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
854 *********************************************************************/
855 static jb_socket socks4_connect(const struct forward_spec * fwd,
856 const char * target_host,
858 struct client_state *csp)
860 unsigned int web_server_addr;
861 char buf[BUFFER_SIZE];
862 struct socks_op *c = (struct socks_op *)buf;
863 struct socks_reply *s = (struct socks_reply *)buf;
870 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
872 /* XXX: Shouldn't the config file parser prevent this? */
873 errstr = "NULL gateway host specified.";
877 if (fwd->gateway_port <= 0)
879 errstr = "invalid gateway port specified.";
885 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
886 csp->error_message = strdup(errstr);
888 return(JB_INVALID_SOCKET);
891 /* build a socks request for connection to the web server */
893 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
895 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
900 web_server_addr = resolve_hostname_to_ip(target_host);
901 if (web_server_addr == INADDR_NONE)
903 errstr = "could not resolve target host";
904 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
909 web_server_addr = htonl(web_server_addr);
913 web_server_addr = 0x00000001;
914 n = csiz + strlen(target_host) + 1;
918 errstr = "buffer cbuf too small.";
919 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
924 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
926 * What we forward to the socks4a server should have the
927 * size of socks_op, plus the length of the userid plus
928 * its \0 byte (which we don't have to add because the
929 * first byte of the userid is counted twice as it's also
930 * part of sock_op) minus the padding bytes (which are part
931 * of the userid as well), plus the length of the target_host
932 * (which is stored csiz bytes after the beginning of the buffer),
933 * plus another \0 byte.
935 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
940 /* Should never get here */
941 log_error(LOG_LEVEL_FATAL,
942 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
944 return(JB_INVALID_SOCKET);
949 csp->error_message = strdup(errstr);
950 return(JB_INVALID_SOCKET);
955 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
956 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
957 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
958 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
959 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
960 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
962 /* pass the request to the socks server */
963 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
965 if (sfd == JB_INVALID_SOCKET)
968 * XXX: connect_to should fill in the exact reason.
969 * Most likely resolving the IP of the forwarder failed.
971 errstr = "connect_to failed: see logfile for details";
974 else if (write_socket(sfd, (char *)c, csiz))
976 errstr = "SOCKS4 negotiation write failed.";
977 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
981 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
983 errstr = "SOCKS4 negotiation read failed.";
984 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
991 csp->error_message = strdup(errstr);
992 return(JB_INVALID_SOCKET);
997 case SOCKS_REQUEST_GRANTED:
1000 case SOCKS_REQUEST_REJECT:
1001 errstr = "SOCKS request rejected or failed.";
1004 case SOCKS_REQUEST_IDENT_FAILED:
1005 errstr = "SOCKS request rejected because "
1006 "SOCKS server cannot connect to identd on the client.";
1009 case SOCKS_REQUEST_IDENT_CONFLICT:
1010 errstr = "SOCKS request rejected because "
1011 "the client program and identd report "
1012 "different user-ids.";
1017 snprintf(buf, sizeof(buf),
1018 "SOCKS request rejected for reason code %d.", s->cd);
1022 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
1023 csp->error_message = strdup(errstr);
1026 return(JB_INVALID_SOCKET);
1030 /*********************************************************************
1032 * Function : translate_socks5_error
1034 * Description : Translates a SOCKS errors to a string.
1037 * 1 : socks_error = The error code to translate.
1039 * Returns : The string translation.
1041 *********************************************************************/
1042 static const char *translate_socks5_error(int socks_error)
1044 switch (socks_error)
1046 /* XXX: these should be more descriptive */
1047 case SOCKS5_REQUEST_FAILED:
1048 return "SOCKS5 request failed";
1049 case SOCKS5_REQUEST_DENIED:
1050 return "SOCKS5 request denied";
1051 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1052 return "SOCKS5 network unreachable";
1053 case SOCKS5_REQUEST_HOST_UNREACHABLE:
1054 return "SOCKS5 host unreachable";
1055 case SOCKS5_REQUEST_CONNECTION_REFUSED:
1056 return "SOCKS5 connection refused";
1057 case SOCKS5_REQUEST_TTL_EXPIRED:
1058 return "SOCKS5 TTL expired";
1059 case SOCKS5_REQUEST_PROTOCOL_ERROR:
1060 return "SOCKS5 client protocol error";
1061 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1062 return "SOCKS5 domain names unsupported";
1063 case SOCKS5_REQUEST_GRANTED:
1064 return "everything's peachy";
1066 return "SOCKS5 negotiation protocol error";
1070 /*********************************************************************
1072 * Function : socks5_connect
1074 * Description : Connect to the SOCKS server, and connect through
1075 * it to the specified server. This handles
1076 * all the SOCKS negotiation, and returns a file
1077 * descriptor for a socket which can be treated as a
1078 * normal (non-SOCKS) socket.
1081 * 1 : fwd = Specifies the SOCKS proxy to use.
1082 * 2 : target_host = The final server to connect to.
1083 * 3 : target_port = The final port to connect to.
1084 * 4 : csp = Current client state (buffers, headers, etc...)
1086 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1088 *********************************************************************/
1089 static jb_socket socks5_connect(const struct forward_spec *fwd,
1090 const char *target_host,
1092 struct client_state *csp)
1097 size_t client_pos = 0;
1098 int server_size = 0;
1101 const char *errstr = NULL;
1103 assert(fwd->gateway_host);
1104 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1106 errstr = "NULL gateway host specified";
1110 if (fwd->gateway_port <= 0)
1113 * XXX: currently this can't happen because in
1114 * case of invalid gateway ports we use the defaults.
1115 * Of course we really shouldn't do that.
1117 errstr = "invalid gateway port specified";
1121 hostlen = strlen(target_host);
1124 errstr = "target host name is longer than 255 characters";
1128 if (fwd->type != SOCKS_5)
1130 /* Should never get here */
1131 log_error(LOG_LEVEL_FATAL,
1132 "SOCKS5 impossible internal error - bad SOCKS type");
1139 assert(errstr != NULL);
1140 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1141 csp->error_message = strdup(errstr);
1142 return(JB_INVALID_SOCKET);
1145 /* pass the request to the socks server */
1146 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1148 if (sfd == JB_INVALID_SOCKET)
1150 errstr = "socks5 server unreachable";
1151 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1152 csp->error_message = strdup(errstr);
1153 return(JB_INVALID_SOCKET);
1157 cbuf[client_pos++] = '\x05'; /* Version */
1158 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1159 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1161 if (write_socket(sfd, cbuf, client_pos))
1163 errstr = "SOCKS5 negotiation write failed";
1164 csp->error_message = strdup(errstr);
1165 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1167 return(JB_INVALID_SOCKET);
1170 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1172 errstr = "SOCKS5 negotiation read failed";
1176 if (!err && (sbuf[0] != '\x05'))
1178 errstr = "SOCKS5 negotiation protocol version error";
1182 if (!err && (sbuf[1] == '\xff'))
1184 errstr = "SOCKS5 authentication required";
1188 if (!err && (sbuf[1] != '\x00'))
1190 errstr = "SOCKS5 negotiation protocol error";
1196 assert(errstr != NULL);
1197 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1198 csp->error_message = strdup(errstr);
1201 return(JB_INVALID_SOCKET);
1205 cbuf[client_pos++] = '\x05'; /* Version */
1206 cbuf[client_pos++] = '\x01'; /* TCP connect */
1207 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1208 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1209 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1210 assert(sizeof(cbuf) - client_pos > 255);
1211 /* Using strncpy because we really want the nul byte padding. */
1212 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1213 client_pos += (hostlen & 0xffu);
1214 cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1215 cbuf[client_pos++] = (char)((target_port ) & 0xff);
1217 if (write_socket(sfd, cbuf, client_pos))
1219 errstr = "SOCKS5 negotiation read failed";
1220 csp->error_message = strdup(errstr);
1221 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1224 return(JB_INVALID_SOCKET);
1227 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1228 if (server_size < 3)
1230 errstr = "SOCKS5 negotiation read failed";
1233 else if (server_size > 20)
1235 /* This is somewhat unexpected but doesn't realy matter. */
1236 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1237 "from socks server. Would have accepted up to %d.",
1238 server_size, sizeof(sbuf));
1241 if (!err && (sbuf[0] != '\x05'))
1243 errstr = "SOCKS5 negotiation protocol version error";
1247 if (!err && (sbuf[2] != '\x00'))
1249 errstr = "SOCKS5 negotiation protocol error";
1255 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1259 errstr = translate_socks5_error(sbuf[1]);
1263 assert(errstr != NULL);
1264 csp->error_message = strdup(errstr);
1265 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1269 return(JB_INVALID_SOCKET);