1 const char gateway_rcs[] = "$Id: gateway.c,v 1.27 2008/09/27 15:05:51 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.27 2008/09/27 15:05:51 fabiankeil
38 * Return only once in forwarded_connect().
40 * Revision 1.26 2008/08/18 17:42:06 fabiankeil
41 * Fix typo in macro name.
43 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
45 * - make the buffers quite a bit smaller.
46 * - properly report "socks5 server unreachable" failures.
47 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
48 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
49 * - log a message if the socks5 server sends more data than expected.
50 * - add some assertions and comments.
52 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
53 * - Fix a compiler warning.
54 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
56 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
57 * Remember the cause of the SOCKS5 error for the CGI message.
59 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
60 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
62 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
63 * Modified patch from Song Weijia (#1762559) to
64 * fix socks requests on big-endian platforms.
66 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
67 * - Use strlcpy() instead of strcpy().
68 * - Use the same buffer for socks requests and socks responses.
69 * - Fix bogus warning about web_server_addr being used uninitialized.
71 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
72 * - Save errors in socks4_connect() to csp->error_message.
73 * - Silence some gcc43 warnings, hopefully the right way.
75 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
76 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
77 * with what was really the latest development (the v_3_0_branch branch)
79 * Revision 1.16 2002/05/12 21:36:29 jongfoster
80 * Correcting function comments
82 * Revision 1.15 2002/03/26 22:29:54 swa
83 * we have a new homepage!
85 * Revision 1.14 2002/03/24 13:25:43 swa
86 * name change related issues
88 * Revision 1.13 2002/03/13 00:29:59 jongfoster
91 * Revision 1.12 2002/03/09 20:03:52 jongfoster
92 * - Making various functions return int rather than size_t.
93 * (Undoing a recent change). Since size_t is unsigned on
94 * Windows, functions like read_socket that return -1 on
95 * error cannot return a size_t.
97 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
98 * crashes, and also frequently caused JB to jump to 100%
99 * CPU and stay there. (Because it thought it had just
100 * read ((unsigned)-1) == 4Gb of data...)
102 * - The signature of write_socket has changed, it now simply
103 * returns success=0/failure=nonzero.
105 * - Trying to get rid of a few warnings --with-debug on
106 * Windows, I've introduced a new type "jb_socket". This is
107 * used for the socket file descriptors. On Windows, this
108 * is SOCKET (a typedef for unsigned). Everywhere else, it's
109 * an int. The error value can't be -1 any more, so it's
110 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
111 * Windows it maps to the #define INVALID_SOCKET.)
113 * - The signature of bind_port has changed.
115 * Revision 1.11 2002/03/08 17:46:04 jongfoster
116 * Fixing int/size_t warnings
118 * Revision 1.10 2002/03/07 03:50:19 oes
119 * - Improved handling of failed DNS lookups
120 * - Fixed compiler warnings
122 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
123 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
124 * threads to call select() simultaneously. So, it's time to do a real, live,
125 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
126 * (native). Both versions will work, but using __OS2__ offers multi-threading.
128 * Revision 1.8 2001/09/13 20:10:12 jongfoster
129 * Fixing missing #include under Windows
131 * Revision 1.7 2001/09/12 17:58:26 steudten
133 * add #include <string.h>
135 * Revision 1.6 2001/09/10 10:41:16 oes
136 * Added #include in.h
138 * Revision 1.5 2001/07/29 18:47:57 jongfoster
139 * Adding missing #include project.h
141 * Revision 1.4 2001/07/24 12:47:06 oes
142 * Applied BeOS support update by Eugenia
144 * Revision 1.3 2001/06/09 10:55:28 jongfoster
145 * Changing BUFSIZ ==> BUFFER_SIZE
147 * Revision 1.2 2001/06/07 23:11:38 jongfoster
148 * Removing gateways[] list - no longer used.
149 * Replacing function pointer in struct gateway with a directly
150 * called function forwarded_connect(), which can do the common
151 * task of deciding whether to connect to the web server or HTTP
153 * Replacing struct gateway with struct forward_spec
154 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
155 * It was a bug which led to the connection being made to the web
156 * server rather than the HTTP proxy, and also a buffer overrun.
158 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
159 * Initial import of version 2.9.3 source tree
162 *********************************************************************/
168 #include <sys/types.h>
171 #include <netinet/in.h>
179 #include <winsock2.h>
180 #endif /* def _WIN32 */
184 #endif /* def __BEOS__ */
188 #endif /* def __OS2__ */
193 #include "jbsockets.h"
195 #include "miscutil.h"
196 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
198 #include <sys/poll.h>
199 #endif /* __GLIBC__ */
201 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
203 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
205 static jb_socket socks4_connect(const struct forward_spec * fwd,
206 const char * target_host,
208 struct client_state *csp);
210 static jb_socket socks5_connect(const struct forward_spec *fwd,
211 const char *target_host,
213 struct client_state *csp);
216 #define SOCKS_REQUEST_GRANTED 90
217 #define SOCKS_REQUEST_REJECT 91
218 #define SOCKS_REQUEST_IDENT_FAILED 92
219 #define SOCKS_REQUEST_IDENT_CONFLICT 93
221 #define SOCKS5_REQUEST_GRANTED 0
222 #define SOCKS5_REQUEST_FAILED 1
223 #define SOCKS5_REQUEST_DENIED 2
224 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
225 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
226 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
227 #define SOCKS5_REQUEST_TTL_EXPIRED 6
228 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
229 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
231 /* structure of a socks client operation */
233 unsigned char vn; /* socks version number */
234 unsigned char cd; /* command code */
235 unsigned char dstport[2]; /* destination port */
236 unsigned char dstip[4]; /* destination address */
237 char userid; /* first byte of userid */
238 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
239 /* more bytes of the userid follow, terminated by a NULL */
242 /* structure of a socks server reply */
244 unsigned char vn; /* socks version number */
245 unsigned char cd; /* command code */
246 unsigned char dstport[2]; /* destination port */
247 unsigned char dstip[4]; /* destination address */
250 static const char socks_userid[] = "anonymous";
252 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
254 #define MAX_REUSABLE_CONNECTIONS 100
256 struct reusable_connection
270 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
272 static int mark_connection_unused(jb_socket sfd);
273 static void mark_connection_closed(struct reusable_connection *closed_connection);
275 /*********************************************************************
277 * Function : initialize_reusable_connections
279 * Description : Initializes the reusable_connection structures.
280 * Must be called with connection_reuse_mutex locked.
286 *********************************************************************/
287 extern void initialize_reusable_connections(void)
289 unsigned int slot = 0;
291 log_error(LOG_LEVEL_INFO,
292 "Support for 'Connection: keep-alive' is experimental, "
293 "incomplete and known not to work properly in some situations.");
295 for (slot = 0; slot < SZ(reusable_connection); slot++)
297 mark_connection_closed(&reusable_connection[slot]);
300 log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
304 /*********************************************************************
306 * Function : remember_connection
308 * Description : Remembers a connection for reuse later on.
311 * 1 : sfd = Open socket to remember.
312 * 2 : http = The destination for the connection.
313 * 3 : fwd = The forwarder settings used.
317 *********************************************************************/
318 void remember_connection(jb_socket sfd, const struct http_request *http,
319 const struct forward_spec *fwd)
321 unsigned int slot = 0;
322 int free_slot_found = FALSE;
324 assert(sfd != JB_INVALID_SOCKET);
326 if (mark_connection_unused(sfd))
331 privoxy_mutex_lock(&connection_reuse_mutex);
333 /* Find free socket slot. */
334 for (slot = 0; slot < SZ(reusable_connection); slot++)
336 if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
338 assert(reusable_connection[slot].in_use == 0);
339 log_error(LOG_LEVEL_CONNECT,
340 "Remembering socket %d for %s:%d in slot %d.",
341 sfd, http->host, http->port, slot);
342 free_slot_found = TRUE;
347 if (!free_slot_found)
349 log_error(LOG_LEVEL_CONNECT,
350 "No free slots found to remembering socket for %s:%d. Last slot %d.",
351 http->host, http->port, slot);
352 privoxy_mutex_unlock(&connection_reuse_mutex);
357 assert(NULL != http->host);
358 reusable_connection[slot].host = strdup(http->host);
359 if (NULL == reusable_connection[slot].host)
361 log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
363 reusable_connection[slot].sfd = sfd;
364 reusable_connection[slot].port = http->port;
365 reusable_connection[slot].in_use = 0;
368 assert(reusable_connection[slot].gateway_host == NULL);
369 assert(reusable_connection[slot].gateway_port == 0);
370 assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
371 assert(reusable_connection[slot].forward_host == NULL);
372 assert(reusable_connection[slot].forward_port == 0);
374 reusable_connection[slot].forwarder_type = fwd->type;
375 if (NULL != fwd->gateway_host)
377 reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
378 if (NULL == reusable_connection[slot].gateway_host)
380 log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
385 reusable_connection[slot].gateway_host = NULL;
387 reusable_connection[slot].gateway_port = fwd->gateway_port;
389 if (NULL != fwd->forward_host)
391 reusable_connection[slot].forward_host = strdup(fwd->forward_host);
392 if (NULL == reusable_connection[slot].forward_host)
394 log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
399 reusable_connection[slot].forward_host = NULL;
401 reusable_connection[slot].forward_port = fwd->forward_port;
403 privoxy_mutex_unlock(&connection_reuse_mutex);
407 /*********************************************************************
409 * Function : mark_connection_closed
411 * Description : Marks a reused connection closed.
412 * Must be called with connection_reuse_mutex locked.
415 * 1 : closed_connection = The connection to mark as closed.
419 *********************************************************************/
420 static void mark_connection_closed(struct reusable_connection *closed_connection)
422 closed_connection->in_use = FALSE;
423 closed_connection->sfd = JB_INVALID_SOCKET;
424 freez(closed_connection->host);
425 closed_connection->port = 0;
426 closed_connection->forwarder_type = SOCKS_NONE;
427 freez(closed_connection->gateway_host);
428 closed_connection->gateway_port = 0;
429 freez(closed_connection->forward_host);
430 closed_connection->forward_port = 0;
434 /*********************************************************************
436 * Function : forget_connection
438 * Description : Removes a previously remembered connection from
439 * the list of reusable connections.
442 * 1 : sfd = The socket belonging to the connection in question.
446 *********************************************************************/
447 void forget_connection(jb_socket sfd)
449 unsigned int slot = 0;
451 assert(sfd != JB_INVALID_SOCKET);
453 privoxy_mutex_lock(&connection_reuse_mutex);
455 for (slot = 0; slot < SZ(reusable_connection); slot++)
457 if (reusable_connection[slot].sfd == sfd)
459 assert(reusable_connection[slot].in_use);
464 if (reusable_connection[slot].sfd != sfd)
466 log_error(LOG_LEVEL_CONNECT,
467 "Socket %d already forgotten or never remembered.", sfd);
468 privoxy_mutex_unlock(&connection_reuse_mutex);
472 log_error(LOG_LEVEL_CONNECT,
473 "Forgetting socket %d for %s:%d in slot %d.",
474 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
476 mark_connection_closed(&reusable_connection[slot]);
478 privoxy_mutex_unlock(&connection_reuse_mutex);
482 /*********************************************************************
484 * Function : connection_destination_matches
486 * Description : Determines whether a remembered connection can
487 * be reused. That is whether the destination and
488 * the forwarding settings match.
491 * 1 : connection = The connection to check.
492 * 2 : http = The destination for the connection.
493 * 3 : fwd = The forwarder settings.
495 * Returns : TRUE for yes, FALSE otherwise.
497 *********************************************************************/
498 static int connection_destination_matches(const struct reusable_connection *connection,
499 const struct http_request *http,
500 const struct forward_spec *fwd)
502 /* XXX: Start of duplicated checks for debugging purposes. */
503 if (strcmpic(connection->host, http->host))
508 if (connection->forwarder_type != fwd->type)
510 log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
511 connection->forwarder_type, fwd->type, http->host);
514 if (connection->gateway_port != fwd->gateway_port)
516 log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
517 connection->gateway_port, fwd->gateway_port, http->host);
520 if (connection->forward_port != fwd->forward_port)
522 log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
523 connection->forward_port, fwd->forward_port, http->host);
526 if (connection->forward_port != fwd->forward_port)
528 log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
529 connection->forward_port, fwd->forward_port, http->host);
533 /* XXX: End of duplicated checks for debugging purposes. */
535 if ((connection->forwarder_type != fwd->type)
536 || (connection->gateway_port != fwd->gateway_port)
537 || (connection->forward_port != fwd->forward_port)
538 || (connection->port != http->port))
543 if (( (NULL != connection->gateway_host)
544 && (NULL != fwd->gateway_host)
545 && strcmpic(connection->gateway_host, fwd->gateway_host))
546 && (connection->gateway_host != fwd->gateway_host))
548 log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
552 if (( (NULL != connection->forward_host)
553 && (NULL != fwd->forward_host)
554 && strcmpic(connection->forward_host, fwd->forward_host))
555 && (connection->forward_host != fwd->forward_host))
557 log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
561 return (!strcmpic(connection->host, http->host));
565 /*********************************************************************
567 * Function : get_reusable_connection
569 * Description : Returns an open socket to a previously remembered
570 * open connection (if there is one).
573 * 1 : http = The destination for the connection.
574 * 2 : fwd = The forwarder settings.
576 * Returns : JB_INVALID_SOCKET => No reusable connection found,
577 * otherwise a usable socket.
579 *********************************************************************/
580 static jb_socket get_reusable_connection(const struct http_request *http,
581 const struct forward_spec *fwd)
583 jb_socket sfd = JB_INVALID_SOCKET;
584 unsigned int slot = 0;
586 privoxy_mutex_lock(&connection_reuse_mutex);
588 for (slot = 0; slot < SZ(reusable_connection); slot++)
590 if (!reusable_connection[slot].in_use
591 && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
594 struct pollfd poll_fd[1];
595 memset(poll_fd, 0, sizeof(poll_fd));
596 poll_fd[0].fd = reusable_connection[slot].sfd;
597 poll_fd[0].events = POLLIN;
599 poll_result = poll(poll_fd, 1, 0);
601 if (-1 != poll_result)
603 if ((poll_fd[0].revents & POLLIN))
605 log_error(LOG_LEVEL_CONNECT,
606 "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
607 reusable_connection[slot].sfd, reusable_connection[slot].host,
608 reusable_connection[slot].port, slot);
609 mark_connection_closed(&reusable_connection[slot]);
614 log_error(LOG_LEVEL_CONNECT,
615 "Failed to poll socket %d for %s:%d in slot %d",
616 reusable_connection[slot].sfd, reusable_connection[slot].host,
617 reusable_connection[slot].port, slot);
621 if (connection_destination_matches(&reusable_connection[slot], http, fwd))
623 reusable_connection[slot].in_use = TRUE;
624 sfd = reusable_connection[slot].sfd;
625 log_error(LOG_LEVEL_CONNECT,
626 "Found reusable socket %d for %s:%d in slot %d",
627 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
633 privoxy_mutex_unlock(&connection_reuse_mutex);
640 /*********************************************************************
642 * Function : mark_connection_unused
644 * Description : Gives a remembered connection free for reuse.
647 * 1 : sfd = The socket belonging to the connection in question.
649 * Returns : TRUE => Socket found and marked as unused.
650 * FALSE => Socket not found.
652 *********************************************************************/
653 static int mark_connection_unused(jb_socket sfd)
655 unsigned int slot = 0;
656 unsigned int socket_found = FALSE;
658 assert(sfd != JB_INVALID_SOCKET);
660 privoxy_mutex_lock(&connection_reuse_mutex);
662 for (slot = 0; slot < SZ(reusable_connection); slot++)
664 if (reusable_connection[slot].sfd == sfd)
666 assert(reusable_connection[slot].in_use);
671 if (reusable_connection[slot].sfd == sfd)
674 log_error(LOG_LEVEL_CONNECT,
675 "Marking open socket %d for %s:%d in slot %d as unused.",
676 sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
677 reusable_connection[slot].in_use = 0;
680 privoxy_mutex_unlock(&connection_reuse_mutex);
685 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
688 /*********************************************************************
690 * Function : forwarded_connect
692 * Description : Connect to a specified web server, possibly via
693 * a HTTP proxy and/or a SOCKS proxy.
696 * 1 : fwd = the proxies to use when connecting.
697 * 2 : http = the http request and apropos headers
698 * 3 : csp = Current client state (buffers, headers, etc...)
700 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
702 *********************************************************************/
703 jb_socket forwarded_connect(const struct forward_spec * fwd,
704 struct http_request *http,
705 struct client_state *csp)
707 const char * dest_host;
709 jb_socket sfd = JB_INVALID_SOCKET;
711 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
712 sfd = get_reusable_connection(http, fwd);
713 if (JB_INVALID_SOCKET == sfd)
715 log_error(LOG_LEVEL_CONNECT,
716 "No reusable socket for %s:%d found. Opening a new one.",
717 http->host, http->port);
723 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
725 /* Figure out if we need to connect to the web server or a HTTP proxy. */
726 if (fwd->forward_host)
729 dest_host = fwd->forward_host;
730 dest_port = fwd->forward_port;
735 dest_host = http->host;
736 dest_port = http->port;
739 /* Connect, maybe using a SOCKS proxy */
743 sfd = connect_to(dest_host, dest_port, csp);
747 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
750 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
753 /* Should never get here */
754 log_error(LOG_LEVEL_FATAL,
755 "SOCKS4 impossible internal error - bad SOCKS type.");
763 /*********************************************************************
765 * Function : socks4_connect
767 * Description : Connect to the SOCKS server, and connect through
768 * it to the specified server. This handles
769 * all the SOCKS negotiation, and returns a file
770 * descriptor for a socket which can be treated as a
771 * normal (non-SOCKS) socket.
773 * Logged error messages are saved to csp->error_message
774 * and later reused by error_response() for the CGI
775 * message. strdup allocation failures are handled there.
778 * 1 : fwd = Specifies the SOCKS proxy to use.
779 * 2 : target_host = The final server to connect to.
780 * 3 : target_port = The final port to connect to.
781 * 4 : csp = Current client state (buffers, headers, etc...)
783 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
785 *********************************************************************/
786 static jb_socket socks4_connect(const struct forward_spec * fwd,
787 const char * target_host,
789 struct client_state *csp)
791 unsigned int web_server_addr;
792 char buf[BUFFER_SIZE];
793 struct socks_op *c = (struct socks_op *)buf;
794 struct socks_reply *s = (struct socks_reply *)buf;
801 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
803 /* XXX: Shouldn't the config file parser prevent this? */
804 errstr = "NULL gateway host specified.";
808 if (fwd->gateway_port <= 0)
810 errstr = "invalid gateway port specified.";
816 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
817 csp->error_message = strdup(errstr);
819 return(JB_INVALID_SOCKET);
822 /* build a socks request for connection to the web server */
824 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
826 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
831 web_server_addr = resolve_hostname_to_ip(target_host);
832 if (web_server_addr == INADDR_NONE)
834 errstr = "could not resolve target host";
835 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
840 web_server_addr = htonl(web_server_addr);
844 web_server_addr = 0x00000001;
845 n = csiz + strlen(target_host) + 1;
849 errstr = "buffer cbuf too small.";
850 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
855 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
857 * What we forward to the socks4a server should have the
858 * size of socks_op, plus the length of the userid plus
859 * its \0 byte (which we don't have to add because the
860 * first byte of the userid is counted twice as it's also
861 * part of sock_op) minus the padding bytes (which are part
862 * of the userid as well), plus the length of the target_host
863 * (which is stored csiz bytes after the beginning of the buffer),
864 * plus another \0 byte.
866 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
871 /* Should never get here */
872 log_error(LOG_LEVEL_FATAL,
873 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
875 return(JB_INVALID_SOCKET);
880 csp->error_message = strdup(errstr);
881 return(JB_INVALID_SOCKET);
886 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
887 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
888 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
889 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
890 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
891 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
893 /* pass the request to the socks server */
894 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
896 if (sfd == JB_INVALID_SOCKET)
899 * XXX: connect_to should fill in the exact reason.
900 * Most likely resolving the IP of the forwarder failed.
902 errstr = "connect_to failed: see logfile for details";
905 else if (write_socket(sfd, (char *)c, csiz))
907 errstr = "SOCKS4 negotiation write failed.";
908 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
912 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
914 errstr = "SOCKS4 negotiation read failed.";
915 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
922 csp->error_message = strdup(errstr);
923 return(JB_INVALID_SOCKET);
928 case SOCKS_REQUEST_GRANTED:
931 case SOCKS_REQUEST_REJECT:
932 errstr = "SOCKS request rejected or failed.";
935 case SOCKS_REQUEST_IDENT_FAILED:
936 errstr = "SOCKS request rejected because "
937 "SOCKS server cannot connect to identd on the client.";
940 case SOCKS_REQUEST_IDENT_CONFLICT:
941 errstr = "SOCKS request rejected because "
942 "the client program and identd report "
943 "different user-ids.";
948 snprintf(buf, sizeof(buf),
949 "SOCKS request rejected for reason code %d.", s->cd);
953 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
954 csp->error_message = strdup(errstr);
957 return(JB_INVALID_SOCKET);
961 /*********************************************************************
963 * Function : translate_socks5_error
965 * Description : Translates a SOCKS errors to a string.
968 * 1 : socks_error = The error code to translate.
970 * Returns : The string translation.
972 *********************************************************************/
973 static const char *translate_socks5_error(int socks_error)
977 /* XXX: these should be more descriptive */
978 case SOCKS5_REQUEST_FAILED:
979 return "SOCKS5 request failed";
980 case SOCKS5_REQUEST_DENIED:
981 return "SOCKS5 request denied";
982 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
983 return "SOCKS5 network unreachable";
984 case SOCKS5_REQUEST_HOST_UNREACHABLE:
985 return "SOCKS5 host unreachable";
986 case SOCKS5_REQUEST_CONNECTION_REFUSED:
987 return "SOCKS5 connection refused";
988 case SOCKS5_REQUEST_TTL_EXPIRED:
989 return "SOCKS5 TTL expired";
990 case SOCKS5_REQUEST_PROTOCOL_ERROR:
991 return "SOCKS5 client protocol error";
992 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
993 return "SOCKS5 domain names unsupported";
994 case SOCKS5_REQUEST_GRANTED:
995 return "everything's peachy";
997 return "SOCKS5 negotiation protocol error";
1001 /*********************************************************************
1003 * Function : socks5_connect
1005 * Description : Connect to the SOCKS server, and connect through
1006 * it to the specified server. This handles
1007 * all the SOCKS negotiation, and returns a file
1008 * descriptor for a socket which can be treated as a
1009 * normal (non-SOCKS) socket.
1012 * 1 : fwd = Specifies the SOCKS proxy to use.
1013 * 2 : target_host = The final server to connect to.
1014 * 3 : target_port = The final port to connect to.
1015 * 4 : csp = Current client state (buffers, headers, etc...)
1017 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
1019 *********************************************************************/
1020 static jb_socket socks5_connect(const struct forward_spec *fwd,
1021 const char *target_host,
1023 struct client_state *csp)
1028 size_t client_pos = 0;
1029 int server_size = 0;
1032 const char *errstr = NULL;
1034 assert(fwd->gateway_host);
1035 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1037 errstr = "NULL gateway host specified";
1041 if (fwd->gateway_port <= 0)
1044 * XXX: currently this can't happen because in
1045 * case of invalid gateway ports we use the defaults.
1046 * Of course we really shouldn't do that.
1048 errstr = "invalid gateway port specified";
1052 hostlen = strlen(target_host);
1055 errstr = "target host name is longer than 255 characters";
1059 if (fwd->type != SOCKS_5)
1061 /* Should never get here */
1062 log_error(LOG_LEVEL_FATAL,
1063 "SOCKS5 impossible internal error - bad SOCKS type");
1070 assert(errstr != NULL);
1071 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1072 csp->error_message = strdup(errstr);
1073 return(JB_INVALID_SOCKET);
1076 /* pass the request to the socks server */
1077 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1079 if (sfd == JB_INVALID_SOCKET)
1081 errstr = "socks5 server unreachable";
1082 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1083 csp->error_message = strdup(errstr);
1084 return(JB_INVALID_SOCKET);
1088 cbuf[client_pos++] = '\x05'; /* Version */
1089 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1090 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1092 if (write_socket(sfd, cbuf, client_pos))
1094 errstr = "SOCKS5 negotiation write failed";
1095 csp->error_message = strdup(errstr);
1096 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1098 return(JB_INVALID_SOCKET);
1101 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1103 errstr = "SOCKS5 negotiation read failed";
1107 if (!err && (sbuf[0] != '\x05'))
1109 errstr = "SOCKS5 negotiation protocol version error";
1113 if (!err && (sbuf[1] == '\xff'))
1115 errstr = "SOCKS5 authentication required";
1119 if (!err && (sbuf[1] != '\x00'))
1121 errstr = "SOCKS5 negotiation protocol error";
1127 assert(errstr != NULL);
1128 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1129 csp->error_message = strdup(errstr);
1132 return(JB_INVALID_SOCKET);
1136 cbuf[client_pos++] = '\x05'; /* Version */
1137 cbuf[client_pos++] = '\x01'; /* TCP connect */
1138 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1139 cbuf[client_pos++] = '\x03'; /* Address is domain name */
1140 cbuf[client_pos++] = (char)(hostlen & 0xffu);
1141 assert(sizeof(cbuf) - client_pos > 255);
1142 /* Using strncpy because we really want the nul byte padding. */
1143 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1144 client_pos += (hostlen & 0xffu);
1145 cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
1146 cbuf[client_pos++] = (char)((target_port ) & 0xffu);
1148 if (write_socket(sfd, cbuf, client_pos))
1150 errstr = "SOCKS5 negotiation read failed";
1151 csp->error_message = strdup(errstr);
1152 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1155 return(JB_INVALID_SOCKET);
1158 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1159 if (server_size < 3)
1161 errstr = "SOCKS5 negotiation read failed";
1164 else if (server_size > 20)
1166 /* This is somewhat unexpected but doesn't realy matter. */
1167 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1168 "from socks server. Would have accepted up to %d.",
1169 server_size, sizeof(sbuf));
1172 if (!err && (sbuf[0] != '\x05'))
1174 errstr = "SOCKS5 negotiation protocol version error";
1178 if (!err && (sbuf[2] != '\x00'))
1180 errstr = "SOCKS5 negotiation protocol error";
1186 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1190 errstr = translate_socks5_error(sbuf[1]);
1194 assert(errstr != NULL);
1195 csp->error_message = strdup(errstr);
1196 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1200 return(JB_INVALID_SOCKET);