1 const char gateway_rcs[] = "$Id: gateway.c,v 1.26 2008/08/18 17:42:06 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.26 2008/08/18 17:42:06 fabiankeil
38 * Fix typo in macro name.
40 * Revision 1.25 2008/02/07 18:09:46 fabiankeil
42 * - make the buffers quite a bit smaller.
43 * - properly report "socks5 server unreachable" failures.
44 * - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
45 * wrong, but requires too much thinking as it doesn't depend on the buffer size.
46 * - log a message if the socks5 server sends more data than expected.
47 * - add some assertions and comments.
49 * Revision 1.24 2008/02/04 14:56:29 fabiankeil
50 * - Fix a compiler warning.
51 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
53 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
54 * Remember the cause of the SOCKS5 error for the CGI message.
56 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
57 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
59 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
60 * Modified patch from Song Weijia (#1762559) to
61 * fix socks requests on big-endian platforms.
63 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
64 * - Use strlcpy() instead of strcpy().
65 * - Use the same buffer for socks requests and socks responses.
66 * - Fix bogus warning about web_server_addr being used uninitialized.
68 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
69 * - Save errors in socks4_connect() to csp->error_message.
70 * - Silence some gcc43 warnings, hopefully the right way.
72 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
73 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
74 * with what was really the latest development (the v_3_0_branch branch)
76 * Revision 1.16 2002/05/12 21:36:29 jongfoster
77 * Correcting function comments
79 * Revision 1.15 2002/03/26 22:29:54 swa
80 * we have a new homepage!
82 * Revision 1.14 2002/03/24 13:25:43 swa
83 * name change related issues
85 * Revision 1.13 2002/03/13 00:29:59 jongfoster
88 * Revision 1.12 2002/03/09 20:03:52 jongfoster
89 * - Making various functions return int rather than size_t.
90 * (Undoing a recent change). Since size_t is unsigned on
91 * Windows, functions like read_socket that return -1 on
92 * error cannot return a size_t.
94 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
95 * crashes, and also frequently caused JB to jump to 100%
96 * CPU and stay there. (Because it thought it had just
97 * read ((unsigned)-1) == 4Gb of data...)
99 * - The signature of write_socket has changed, it now simply
100 * returns success=0/failure=nonzero.
102 * - Trying to get rid of a few warnings --with-debug on
103 * Windows, I've introduced a new type "jb_socket". This is
104 * used for the socket file descriptors. On Windows, this
105 * is SOCKET (a typedef for unsigned). Everywhere else, it's
106 * an int. The error value can't be -1 any more, so it's
107 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
108 * Windows it maps to the #define INVALID_SOCKET.)
110 * - The signature of bind_port has changed.
112 * Revision 1.11 2002/03/08 17:46:04 jongfoster
113 * Fixing int/size_t warnings
115 * Revision 1.10 2002/03/07 03:50:19 oes
116 * - Improved handling of failed DNS lookups
117 * - Fixed compiler warnings
119 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
120 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
121 * threads to call select() simultaneously. So, it's time to do a real, live,
122 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
123 * (native). Both versions will work, but using __OS2__ offers multi-threading.
125 * Revision 1.8 2001/09/13 20:10:12 jongfoster
126 * Fixing missing #include under Windows
128 * Revision 1.7 2001/09/12 17:58:26 steudten
130 * add #include <string.h>
132 * Revision 1.6 2001/09/10 10:41:16 oes
133 * Added #include in.h
135 * Revision 1.5 2001/07/29 18:47:57 jongfoster
136 * Adding missing #include project.h
138 * Revision 1.4 2001/07/24 12:47:06 oes
139 * Applied BeOS support update by Eugenia
141 * Revision 1.3 2001/06/09 10:55:28 jongfoster
142 * Changing BUFSIZ ==> BUFFER_SIZE
144 * Revision 1.2 2001/06/07 23:11:38 jongfoster
145 * Removing gateways[] list - no longer used.
146 * Replacing function pointer in struct gateway with a directly
147 * called function forwarded_connect(), which can do the common
148 * task of deciding whether to connect to the web server or HTTP
150 * Replacing struct gateway with struct forward_spec
151 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
152 * It was a bug which led to the connection being made to the web
153 * server rather than the HTTP proxy, and also a buffer overrun.
155 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
156 * Initial import of version 2.9.3 source tree
159 *********************************************************************/
165 #include <sys/types.h>
168 #include <netinet/in.h>
176 #include <winsock2.h>
177 #endif /* def _WIN32 */
181 #endif /* def __BEOS__ */
185 #endif /* def __OS2__ */
190 #include "jbsockets.h"
192 #include "miscutil.h"
194 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
196 static jb_socket socks4_connect(const struct forward_spec * fwd,
197 const char * target_host,
199 struct client_state *csp);
201 static jb_socket socks5_connect(const struct forward_spec *fwd,
202 const char *target_host,
204 struct client_state *csp);
207 #define SOCKS_REQUEST_GRANTED 90
208 #define SOCKS_REQUEST_REJECT 91
209 #define SOCKS_REQUEST_IDENT_FAILED 92
210 #define SOCKS_REQUEST_IDENT_CONFLICT 93
212 #define SOCKS5_REQUEST_GRANTED 0
213 #define SOCKS5_REQUEST_FAILED 1
214 #define SOCKS5_REQUEST_DENIED 2
215 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
216 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
217 #define SOCKS5_REQUEST_CONNECTION_REFUSED 5
218 #define SOCKS5_REQUEST_TTL_EXPIRED 6
219 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
220 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
222 /* structure of a socks client operation */
224 unsigned char vn; /* socks version number */
225 unsigned char cd; /* command code */
226 unsigned char dstport[2]; /* destination port */
227 unsigned char dstip[4]; /* destination address */
228 char userid; /* first byte of userid */
229 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
230 /* more bytes of the userid follow, terminated by a NULL */
233 /* structure of a socks server reply */
235 unsigned char vn; /* socks version number */
236 unsigned char cd; /* command code */
237 unsigned char dstport[2]; /* destination port */
238 unsigned char dstip[4]; /* destination address */
241 static const char socks_userid[] = "anonymous";
244 /*********************************************************************
246 * Function : forwarded_connect
248 * Description : Connect to a specified web server, possibly via
249 * a HTTP proxy and/or a SOCKS proxy.
252 * 1 : fwd = the proxies to use when connecting.
253 * 2 : http = the http request and apropos headers
254 * 3 : csp = Current client state (buffers, headers, etc...)
256 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
258 *********************************************************************/
259 jb_socket forwarded_connect(const struct forward_spec * fwd,
260 struct http_request *http,
261 struct client_state *csp)
263 const char * dest_host;
265 jb_socket sfd = JB_INVALID_SOCKET;
267 /* Figure out if we need to connect to the web server or a HTTP proxy. */
268 if (fwd->forward_host)
271 dest_host = fwd->forward_host;
272 dest_port = fwd->forward_port;
277 dest_host = http->host;
278 dest_port = http->port;
281 /* Connect, maybe using a SOCKS proxy */
285 sfd = connect_to(dest_host, dest_port, csp);
289 sfd = socks4_connect(fwd, dest_host, dest_port, csp);
292 sfd = socks5_connect(fwd, dest_host, dest_port, csp);
295 /* Should never get here */
296 log_error(LOG_LEVEL_FATAL,
297 "SOCKS4 impossible internal error - bad SOCKS type.");
305 /*********************************************************************
307 * Function : socks4_connect
309 * Description : Connect to the SOCKS server, and connect through
310 * it to the specified server. This handles
311 * all the SOCKS negotiation, and returns a file
312 * descriptor for a socket which can be treated as a
313 * normal (non-SOCKS) socket.
315 * Logged error messages are saved to csp->error_message
316 * and later reused by error_response() for the CGI
317 * message. strdup allocation failures are handled there.
320 * 1 : fwd = Specifies the SOCKS proxy to use.
321 * 2 : target_host = The final server to connect to.
322 * 3 : target_port = The final port to connect to.
323 * 4 : csp = Current client state (buffers, headers, etc...)
325 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
327 *********************************************************************/
328 static jb_socket socks4_connect(const struct forward_spec * fwd,
329 const char * target_host,
331 struct client_state *csp)
333 unsigned int web_server_addr;
334 char buf[BUFFER_SIZE];
335 struct socks_op *c = (struct socks_op *)buf;
336 struct socks_reply *s = (struct socks_reply *)buf;
343 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
345 /* XXX: Shouldn't the config file parser prevent this? */
346 errstr = "NULL gateway host specified.";
350 if (fwd->gateway_port <= 0)
352 errstr = "invalid gateway port specified.";
358 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
359 csp->error_message = strdup(errstr);
361 return(JB_INVALID_SOCKET);
364 /* build a socks request for connection to the web server */
366 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
368 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
373 web_server_addr = resolve_hostname_to_ip(target_host);
374 if (web_server_addr == INADDR_NONE)
376 errstr = "could not resolve target host";
377 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
382 web_server_addr = htonl(web_server_addr);
386 web_server_addr = 0x00000001;
387 n = csiz + strlen(target_host) + 1;
391 errstr = "buffer cbuf too small.";
392 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
397 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
399 * What we forward to the socks4a server should have the
400 * size of socks_op, plus the length of the userid plus
401 * its \0 byte (which we don't have to add because the
402 * first byte of the userid is counted twice as it's also
403 * part of sock_op) minus the padding bytes (which are part
404 * of the userid as well), plus the length of the target_host
405 * (which is stored csiz bytes after the beginning of the buffer),
406 * plus another \0 byte.
408 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
413 /* Should never get here */
414 log_error(LOG_LEVEL_FATAL,
415 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
417 return(JB_INVALID_SOCKET);
422 csp->error_message = strdup(errstr);
423 return(JB_INVALID_SOCKET);
428 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
429 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
430 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
431 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
432 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
433 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
435 /* pass the request to the socks server */
436 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
438 if (sfd == JB_INVALID_SOCKET)
441 * XXX: connect_to should fill in the exact reason.
442 * Most likely resolving the IP of the forwarder failed.
444 errstr = "connect_to failed: see logfile for details";
447 else if (write_socket(sfd, (char *)c, csiz))
449 errstr = "SOCKS4 negotiation write failed.";
450 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
454 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
456 errstr = "SOCKS4 negotiation read failed.";
457 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
464 csp->error_message = strdup(errstr);
465 return(JB_INVALID_SOCKET);
470 case SOCKS_REQUEST_GRANTED:
473 case SOCKS_REQUEST_REJECT:
474 errstr = "SOCKS request rejected or failed.";
477 case SOCKS_REQUEST_IDENT_FAILED:
478 errstr = "SOCKS request rejected because "
479 "SOCKS server cannot connect to identd on the client.";
482 case SOCKS_REQUEST_IDENT_CONFLICT:
483 errstr = "SOCKS request rejected because "
484 "the client program and identd report "
485 "different user-ids.";
490 snprintf(buf, sizeof(buf),
491 "SOCKS request rejected for reason code %d.", s->cd);
495 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
496 csp->error_message = strdup(errstr);
499 return(JB_INVALID_SOCKET);
503 /*********************************************************************
505 * Function : translate_socks5_error
507 * Description : Translates a SOCKS errors to a string.
510 * 1 : socks_error = The error code to translate.
512 * Returns : The string translation.
514 *********************************************************************/
515 static const char *translate_socks5_error(int socks_error)
519 /* XXX: these should be more descriptive */
520 case SOCKS5_REQUEST_FAILED:
521 return "SOCKS5 request failed";
522 case SOCKS5_REQUEST_DENIED:
523 return "SOCKS5 request denied";
524 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
525 return "SOCKS5 network unreachable";
526 case SOCKS5_REQUEST_HOST_UNREACHABLE:
527 return "SOCKS5 host unreachable";
528 case SOCKS5_REQUEST_CONNECTION_REFUSED:
529 return "SOCKS5 connection refused";
530 case SOCKS5_REQUEST_TTL_EXPIRED:
531 return "SOCKS5 TTL expired";
532 case SOCKS5_REQUEST_PROTOCOL_ERROR:
533 return "SOCKS5 client protocol error";
534 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
535 return "SOCKS5 domain names unsupported";
536 case SOCKS5_REQUEST_GRANTED:
537 return "everything's peachy";
539 return "SOCKS5 negotiation protocol error";
543 /*********************************************************************
545 * Function : socks5_connect
547 * Description : Connect to the SOCKS server, and connect through
548 * it to the specified server. This handles
549 * all the SOCKS negotiation, and returns a file
550 * descriptor for a socket which can be treated as a
551 * normal (non-SOCKS) socket.
554 * 1 : fwd = Specifies the SOCKS proxy to use.
555 * 2 : target_host = The final server to connect to.
556 * 3 : target_port = The final port to connect to.
557 * 4 : csp = Current client state (buffers, headers, etc...)
559 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
561 *********************************************************************/
562 static jb_socket socks5_connect(const struct forward_spec *fwd,
563 const char *target_host,
565 struct client_state *csp)
570 size_t client_pos = 0;
574 const char *errstr = NULL;
576 assert(fwd->gateway_host);
577 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
579 errstr = "NULL gateway host specified";
583 if (fwd->gateway_port <= 0)
586 * XXX: currently this can't happen because in
587 * case of invalid gateway ports we use the defaults.
588 * Of course we really shouldn't do that.
590 errstr = "invalid gateway port specified";
594 hostlen = strlen(target_host);
597 errstr = "target host name is longer than 255 characters";
601 if (fwd->type != SOCKS_5)
603 /* Should never get here */
604 log_error(LOG_LEVEL_FATAL,
605 "SOCKS5 impossible internal error - bad SOCKS type");
612 assert(errstr != NULL);
613 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
614 csp->error_message = strdup(errstr);
615 return(JB_INVALID_SOCKET);
618 /* pass the request to the socks server */
619 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
621 if (sfd == JB_INVALID_SOCKET)
623 errstr = "socks5 server unreachable";
624 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
625 csp->error_message = strdup(errstr);
626 return(JB_INVALID_SOCKET);
630 cbuf[client_pos++] = '\x05'; /* Version */
631 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
632 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
634 if (write_socket(sfd, cbuf, client_pos))
636 errstr = "SOCKS5 negotiation write failed";
637 csp->error_message = strdup(errstr);
638 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
640 return(JB_INVALID_SOCKET);
643 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
645 errstr = "SOCKS5 negotiation read failed";
649 if (!err && (sbuf[0] != '\x05'))
651 errstr = "SOCKS5 negotiation protocol version error";
655 if (!err && (sbuf[1] == '\xff'))
657 errstr = "SOCKS5 authentication required";
661 if (!err && (sbuf[1] != '\x00'))
663 errstr = "SOCKS5 negotiation protocol error";
669 assert(errstr != NULL);
670 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
671 csp->error_message = strdup(errstr);
674 return(JB_INVALID_SOCKET);
678 cbuf[client_pos++] = '\x05'; /* Version */
679 cbuf[client_pos++] = '\x01'; /* TCP connect */
680 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
681 cbuf[client_pos++] = '\x03'; /* Address is domain name */
682 cbuf[client_pos++] = (char)(hostlen & 0xffu);
683 assert(sizeof(cbuf) - client_pos > 255);
684 /* Using strncpy because we really want the nul byte padding. */
685 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
686 client_pos += (hostlen & 0xffu);
687 cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
688 cbuf[client_pos++] = (char)((target_port ) & 0xffu);
690 if (write_socket(sfd, cbuf, client_pos))
692 errstr = "SOCKS5 negotiation read failed";
693 csp->error_message = strdup(errstr);
694 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
697 return(JB_INVALID_SOCKET);
700 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
703 errstr = "SOCKS5 negotiation read failed";
706 else if (server_size > 20)
708 /* This is somewhat unexpected but doesn't realy matter. */
709 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
710 "from socks server. Would have accepted up to %d.",
711 server_size, sizeof(sbuf));
714 if (!err && (sbuf[0] != '\x05'))
716 errstr = "SOCKS5 negotiation protocol version error";
720 if (!err && (sbuf[2] != '\x00'))
722 errstr = "SOCKS5 negotiation protocol error";
728 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
732 errstr = translate_socks5_error(sbuf[1]);
736 assert(errstr != NULL);
737 csp->error_message = strdup(errstr);
738 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
742 return(JB_INVALID_SOCKET);