1 const char gateway_rcs[] = "$Id: gateway.c,v 1.25 2008/02/07 18:09:46 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-2007 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.25 2008/02/07 18:09:46 fabiankeil
39 * - make the buffers quite a bit smaller.
40 * - properly report "socks5 server unreachable" failures.
41 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
42 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
43 * - log a message if the socks5 server sends more data than expected.
44 * - add some assertions and comments.
46 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
47 * - Fix a compiler warning.
48 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
50 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
51 * Remember the cause of the SOCKS5 error for the CGI message.
53 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
54 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
56 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
57 * Modified patch from Song Weijia (#1762559) to
58 * fix socks requests on big-endian platforms.
60 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
61 * - Use strlcpy() instead of strcpy().
62 * - Use the same buffer for socks requests and socks responses.
63 * - Fix bogus warning about web_server_addr being used uninitialized.
65 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
66 * - Save errors in socks4_connect() to csp->error_message.
67 * - Silence some gcc43 warnings, hopefully the right way.
69 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
70 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
71 * with what was really the latest development (the v_3_0_branch branch)
73 * Revision 1.16 2002/05/12 21:36:29 jongfoster
74 * Correcting function comments
76 * Revision 1.15 2002/03/26 22:29:54 swa
77 * we have a new homepage!
79 * Revision 1.14 2002/03/24 13:25:43 swa
80 * name change related issues
82 * Revision 1.13 2002/03/13 00:29:59 jongfoster
85 * Revision 1.12 2002/03/09 20:03:52 jongfoster
86 * - Making various functions return int rather than size_t.
87 * (Undoing a recent change). Since size_t is unsigned on
88 * Windows, functions like read_socket that return -1 on
89 * error cannot return a size_t.
91 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
92 * crashes, and also frequently caused JB to jump to 100%
93 * CPU and stay there. (Because it thought it had just
94 * read ((unsigned)-1) == 4Gb of data...)
96 * - The signature of write_socket has changed, it now simply
97 * returns success=0/failure=nonzero.
99 * - Trying to get rid of a few warnings --with-debug on
100 * Windows, I've introduced a new type "jb_socket". This is
101 * used for the socket file descriptors. On Windows, this
102 * is SOCKET (a typedef for unsigned). Everywhere else, it's
103 * an int. The error value can't be -1 any more, so it's
104 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
105 * Windows it maps to the #define INVALID_SOCKET.)
107 * - The signature of bind_port has changed.
109 * Revision 1.11 2002/03/08 17:46:04 jongfoster
110 * Fixing int/size_t warnings
112 * Revision 1.10 2002/03/07 03:50:19 oes
113 * - Improved handling of failed DNS lookups
114 * - Fixed compiler warnings
116 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
117 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
118 * threads to call select() simultaneously. So, it's time to do a real, live,
119 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
120 * (native). Both versions will work, but using __OS2__ offers multi-threading.
122 * Revision 1.8 2001/09/13 20:10:12 jongfoster
123 * Fixing missing #include under Windows
125 * Revision 1.7 2001/09/12 17:58:26 steudten
127 * add #include <string.h>
129 * Revision 1.6 2001/09/10 10:41:16 oes
130 * Added #include in.h
132 * Revision 1.5 2001/07/29 18:47:57 jongfoster
133 * Adding missing #include project.h
135 * Revision 1.4 2001/07/24 12:47:06 oes
136 * Applied BeOS support update by Eugenia
138 * Revision 1.3 2001/06/09 10:55:28 jongfoster
139 * Changing BUFSIZ ==> BUFFER_SIZE
141 * Revision 1.2 2001/06/07 23:11:38 jongfoster
142 * Removing gateways[] list - no longer used.
143 * Replacing function pointer in struct gateway with a directly
144 * called function forwarded_connect(), which can do the common
145 * task of deciding whether to connect to the web server or HTTP
147 * Replacing struct gateway with struct forward_spec
148 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
149 * It was a bug which led to the connection being made to the web
150 * server rather than the HTTP proxy, and also a buffer overrun.
152 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
153 * Initial import of version 2.9.3 source tree
156 *********************************************************************/
162 #include <sys/types.h>
165 #include <netinet/in.h>
173 #include <winsock2.h>
174 #endif /* def _WIN32 */
178 #endif /* def __BEOS__ */
182 #endif /* def __OS2__ */
187 #include "jbsockets.h"
189 #include "miscutil.h"
191 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
193 static jb_socket socks4_connect(const struct forward_spec * fwd,
194 const char * target_host,
196 struct client_state *csp);
198 static jb_socket socks5_connect(const struct forward_spec *fwd,
199 const char *target_host,
201 struct client_state *csp);
204 #define SOCKS_REQUEST_GRANTED 90
205 #define SOCKS_REQUEST_REJECT 91
206 #define SOCKS_REQUEST_IDENT_FAILED 92
207 #define SOCKS_REQUEST_IDENT_CONFLICT 93
209 #define SOCKS5_REQUEST_GRANTED 0
210 #define SOCKS5_REQUEST_FAILED 1
211 #define SOCKS5_REQUEST_DENIED 2
212 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
213 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
214 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
215 #define SOCKS5_REQUEST_TTL_EXPIRED 6
216 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
217 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
219 /* structure of a socks client operation */
221 unsigned char vn; /* socks version number */
222 unsigned char cd; /* command code */
223 unsigned char dstport[2]; /* destination port */
224 unsigned char dstip[4]; /* destination address */
225 char userid; /* first byte of userid */
226 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
227 /* more bytes of the userid follow, terminated by a NULL */
230 /* structure of a socks server reply */
232 unsigned char vn; /* socks version number */
233 unsigned char cd; /* command code */
234 unsigned char dstport[2]; /* destination port */
235 unsigned char dstip[4]; /* destination address */
238 static const char socks_userid[] = "anonymous";
241 /*********************************************************************
243 * Function : forwarded_connect
245 * Description : Connect to a specified web server, possibly via
246 * a HTTP proxy and/or a SOCKS proxy.
249 * 1 : fwd = the proxies to use when connecting.
250 * 2 : http = the http request and apropos headers
251 * 3 : csp = Current client state (buffers, headers, etc...)
253 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
255 *********************************************************************/
256 jb_socket forwarded_connect(const struct forward_spec * fwd,
257 struct http_request *http,
258 struct client_state *csp)
260 const char * dest_host;
263 /* Figure out if we need to connect to the web server or a HTTP proxy. */
264 if (fwd->forward_host)
267 dest_host = fwd->forward_host;
268 dest_port = fwd->forward_port;
273 dest_host = http->host;
274 dest_port = http->port;
277 /* Connect, maybe using a SOCKS proxy */
281 return (connect_to(dest_host, dest_port, csp));
285 return (socks4_connect(fwd, dest_host, dest_port, csp));
288 return (socks5_connect(fwd, dest_host, dest_port, csp));
291 /* Should never get here */
292 log_error(LOG_LEVEL_FATAL, "SOCKS4 impossible internal error - bad SOCKS type.");
294 return(JB_INVALID_SOCKET);
299 /*********************************************************************
301 * Function : socks4_connect
303 * Description : Connect to the SOCKS server, and connect through
304 * it to the specified server. This handles
305 * all the SOCKS negotiation, and returns a file
306 * descriptor for a socket which can be treated as a
307 * normal (non-SOCKS) socket.
309 * Logged error messages are saved to csp->error_message
310 * and later reused by error_response() for the CGI
311 * message. strdup allocation failures are handled there.
314 * 1 : fwd = Specifies the SOCKS proxy to use.
315 * 2 : target_host = The final server to connect to.
316 * 3 : target_port = The final port to connect to.
317 * 4 : csp = Current client state (buffers, headers, etc...)
319 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
321 *********************************************************************/
322 static jb_socket socks4_connect(const struct forward_spec * fwd,
323 const char * target_host,
325 struct client_state *csp)
327 unsigned int web_server_addr;
328 char buf[BUFFER_SIZE];
329 struct socks_op *c = (struct socks_op *)buf;
330 struct socks_reply *s = (struct socks_reply *)buf;
337 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
339 /* XXX: Shouldn't the config file parser prevent this? */
340 errstr = "NULL gateway host specified.";
344 if (fwd->gateway_port <= 0)
346 errstr = "invalid gateway port specified.";
352 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
353 csp->error_message = strdup(errstr);
355 return(JB_INVALID_SOCKET);
358 /* build a socks request for connection to the web server */
360 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
362 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
367 web_server_addr = resolve_hostname_to_ip(target_host);
368 if (web_server_addr == INADDR_NONE)
370 errstr = "could not resolve target host";
371 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
376 web_server_addr = htonl(web_server_addr);
380 web_server_addr = 0x00000001;
381 n = csiz + strlen(target_host) + 1;
385 errstr = "buffer cbuf too small.";
386 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
391 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
393 * What we forward to the socks4a server should have the
394 * size of socks_op, plus the length of the userid plus
395 * its \0 byte (which we don't have to add because the
396 * first byte of the userid is counted twice as it's also
397 * part of sock_op) minus the padding bytes (which are part
398 * of the userid as well), plus the length of the target_host
399 * (which is stored csiz bytes after the beginning of the buffer),
400 * plus another \0 byte.
402 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
407 /* Should never get here */
408 log_error(LOG_LEVEL_FATAL,
409 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
411 return(JB_INVALID_SOCKET);
416 csp->error_message = strdup(errstr);
417 return(JB_INVALID_SOCKET);
422 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
423 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
424 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
425 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
426 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
427 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
429 /* pass the request to the socks server */
430 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
432 if (sfd == JB_INVALID_SOCKET)
435 * XXX: connect_to should fill in the exact reason.
436 * Most likely resolving the IP of the forwarder failed.
438 errstr = "connect_to failed: see logfile for details";
441 else if (write_socket(sfd, (char *)c, csiz))
443 errstr = "SOCKS4 negotiation write failed.";
444 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
448 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
450 errstr = "SOCKS4 negotiation read failed.";
451 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
458 csp->error_message = strdup(errstr);
459 return(JB_INVALID_SOCKET);
464 case SOCKS_REQUEST_GRANTED:
467 case SOCKS_REQUEST_REJECT:
468 errstr = "SOCKS request rejected or failed.";
471 case SOCKS_REQUEST_IDENT_FAILED:
472 errstr = "SOCKS request rejected because "
473 "SOCKS server cannot connect to identd on the client.";
476 case SOCKS_REQUEST_IDENT_CONFLICT:
477 errstr = "SOCKS request rejected because "
478 "the client program and identd report "
479 "different user-ids.";
484 snprintf(buf, sizeof(buf),
485 "SOCKS request rejected for reason code %d.", s->cd);
489 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
490 csp->error_message = strdup(errstr);
493 return(JB_INVALID_SOCKET);
497 /*********************************************************************
499 * Function : translate_socks5_error
501 * Description : Translates a SOCKS errors to a string.
504 * 1 : socks_error = The error code to translate.
506 * Returns : The string translation.
508 *********************************************************************/
509 static const char *translate_socks5_error(int socks_error)
513 /* XXX: these should be more descriptive */
514 case SOCKS5_REQUEST_FAILED:
515 return "SOCKS5 request failed";
516 case SOCKS5_REQUEST_DENIED:
517 return "SOCKS5 request denied";
518 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
519 return "SOCKS5 network unreachable";
520 case SOCKS5_REQUEST_HOST_UNREACHABLE:
521 return "SOCKS5 host unreachable";
522 case SOCKS5_REQUEST_CONNECTION_REFUSED:
523 return "SOCKS5 connection refused";
524 case SOCKS5_REQUEST_TTL_EXPIRED:
525 return "SOCKS5 TTL expired";
526 case SOCKS5_REQUEST_PROTOCOL_ERROR:
527 return "SOCKS5 client protocol error";
528 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
529 return "SOCKS5 domain names unsupported";
530 case SOCKS5_REQUEST_GRANTED:
531 return "everything's peachy";
533 return "SOCKS5 negotiation protocol error";
537 /*********************************************************************
539 * Function : socks5_connect
541 * Description : Connect to the SOCKS server, and connect through
542 * it to the specified server. This handles
543 * all the SOCKS negotiation, and returns a file
544 * descriptor for a socket which can be treated as a
545 * normal (non-SOCKS) socket.
548 * 1 : fwd = Specifies the SOCKS proxy to use.
549 * 2 : target_host = The final server to connect to.
550 * 3 : target_port = The final port to connect to.
551 * 4 : csp = Current client state (buffers, headers, etc...)
553 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
555 *********************************************************************/
556 static jb_socket socks5_connect(const struct forward_spec *fwd,
557 const char *target_host,
559 struct client_state *csp)
564 size_t client_pos = 0;
568 const char *errstr = NULL;
570 assert(fwd->gateway_host);
571 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
573 errstr = "NULL gateway host specified";
577 if (fwd->gateway_port <= 0)
580 * XXX: currently this can't happen because in
581 * case of invalid gateway ports we use the defaults.
582 * Of course we really shouldn't do that.
584 errstr = "invalid gateway port specified";
588 hostlen = strlen(target_host);
591 errstr = "target host name is longer than 255 characters";
595 if (fwd->type != SOCKS_5)
597 /* Should never get here */
598 log_error(LOG_LEVEL_FATAL,
599 "SOCKS5 impossible internal error - bad SOCKS type");
606 assert(errstr != NULL);
607 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
608 csp->error_message = strdup(errstr);
609 return(JB_INVALID_SOCKET);
612 /* pass the request to the socks server */
613 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
615 if (sfd == JB_INVALID_SOCKET)
617 errstr = "socks5 server unreachable";
618 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
619 csp->error_message = strdup(errstr);
620 return(JB_INVALID_SOCKET);
624 cbuf[client_pos++] = '\x05'; /* Version */
625 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
626 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
628 if (write_socket(sfd, cbuf, client_pos))
630 errstr = "SOCKS5 negotiation write failed";
631 csp->error_message = strdup(errstr);
632 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
634 return(JB_INVALID_SOCKET);
637 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
639 errstr = "SOCKS5 negotiation read failed";
643 if (!err && (sbuf[0] != '\x05'))
645 errstr = "SOCKS5 negotiation protocol version error";
649 if (!err && (sbuf[1] == '\xff'))
651 errstr = "SOCKS5 authentication required";
655 if (!err && (sbuf[1] != '\x00'))
657 errstr = "SOCKS5 negotiation protocol error";
663 assert(errstr != NULL);
664 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
665 csp->error_message = strdup(errstr);
668 return(JB_INVALID_SOCKET);
672 cbuf[client_pos++] = '\x05'; /* Version */
673 cbuf[client_pos++] = '\x01'; /* TCP connect */
674 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
675 cbuf[client_pos++] = '\x03'; /* Address is domain name */
676 cbuf[client_pos++] = (char)(hostlen & 0xffu);
677 assert(sizeof(cbuf) - client_pos > 255);
678 /* Using strncpy because we really want the nul byte padding. */
679 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
680 client_pos += (hostlen & 0xffu);
681 cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
682 cbuf[client_pos++] = (char)((target_port ) & 0xffu);
684 if (write_socket(sfd, cbuf, client_pos))
686 errstr = "SOCKS5 negotiation read failed";
687 csp->error_message = strdup(errstr);
688 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
691 return(JB_INVALID_SOCKET);
694 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
697 errstr = "SOCKS5 negotiation read failed";
700 else if (server_size > 20)
702 /* This is somewhat unexpected but doesn't realy matter. */
703 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
704 "from socks server. Would have accepted up to %d.",
705 server_size, sizeof(sbuf));
708 if (!err && (sbuf[0] != '\x05'))
710 errstr = "SOCKS5 negotiation protocol version error";
714 if (!err && (sbuf[2] != '\x00'))
716 errstr = "SOCKS5 negotiation protocol error";
722 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
726 errstr = translate_socks5_error(sbuf[1]);
730 assert(errstr != NULL);
731 csp->error_message = strdup(errstr);
732 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
736 return(JB_INVALID_SOCKET);