1 const char gateway_rcs[] = "$Id: gateway.c,v 1.21 2007/07/28 12:30:03 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.21 2007/07/28 12:30:03 fabiankeil
38 * Modified patch from Song Weijia (#1762559) to
39 * fix socks requests on big-endian platforms.
41 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
42 * - Use strlcpy() instead of strcpy().
43 * - Use the same buffer for socks requests and socks responses.
44 * - Fix bogus warning about web_server_addr being used uninitialized.
46 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
47 * - Save errors in socks4_connect() to csp->error_message.
48 * - Silence some gcc43 warnings, hopefully the right way.
50 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
51 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
52 * with what was really the latest development (the v_3_0_branch branch)
54 * Revision 1.16 2002/05/12 21:36:29 jongfoster
55 * Correcting function comments
57 * Revision 1.15 2002/03/26 22:29:54 swa
58 * we have a new homepage!
60 * Revision 1.14 2002/03/24 13:25:43 swa
61 * name change related issues
63 * Revision 1.13 2002/03/13 00:29:59 jongfoster
66 * Revision 1.12 2002/03/09 20:03:52 jongfoster
67 * - Making various functions return int rather than size_t.
68 * (Undoing a recent change). Since size_t is unsigned on
69 * Windows, functions like read_socket that return -1 on
70 * error cannot return a size_t.
72 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
73 * crashes, and also frequently caused JB to jump to 100%
74 * CPU and stay there. (Because it thought it had just
75 * read ((unsigned)-1) == 4Gb of data...)
77 * - The signature of write_socket has changed, it now simply
78 * returns success=0/failure=nonzero.
80 * - Trying to get rid of a few warnings --with-debug on
81 * Windows, I've introduced a new type "jb_socket". This is
82 * used for the socket file descriptors. On Windows, this
83 * is SOCKET (a typedef for unsigned). Everywhere else, it's
84 * an int. The error value can't be -1 any more, so it's
85 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
86 * Windows it maps to the #define INVALID_SOCKET.)
88 * - The signature of bind_port has changed.
90 * Revision 1.11 2002/03/08 17:46:04 jongfoster
91 * Fixing int/size_t warnings
93 * Revision 1.10 2002/03/07 03:50:19 oes
94 * - Improved handling of failed DNS lookups
95 * - Fixed compiler warnings
97 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
98 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
99 * threads to call select() simultaneously. So, it's time to do a real, live,
100 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
101 * (native). Both versions will work, but using __OS2__ offers multi-threading.
103 * Revision 1.8 2001/09/13 20:10:12 jongfoster
104 * Fixing missing #include under Windows
106 * Revision 1.7 2001/09/12 17:58:26 steudten
108 * add #include <string.h>
110 * Revision 1.6 2001/09/10 10:41:16 oes
111 * Added #include in.h
113 * Revision 1.5 2001/07/29 18:47:57 jongfoster
114 * Adding missing #include project.h
116 * Revision 1.4 2001/07/24 12:47:06 oes
117 * Applied BeOS support update by Eugenia
119 * Revision 1.3 2001/06/09 10:55:28 jongfoster
120 * Changing BUFSIZ ==> BUFFER_SIZE
122 * Revision 1.2 2001/06/07 23:11:38 jongfoster
123 * Removing gateways[] list - no longer used.
124 * Replacing function pointer in struct gateway with a directly
125 * called function forwarded_connect(), which can do the common
126 * task of deciding whether to connect to the web server or HTTP
128 * Replacing struct gateway with struct forward_spec
129 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
130 * It was a bug which led to the connection being made to the web
131 * server rather than the HTTP proxy, and also a buffer overrun.
133 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
134 * Initial import of version 2.9.3 source tree
137 *********************************************************************/
143 #include <sys/types.h>
146 #include <netinet/in.h>
154 #include <winsock2.h>
155 #endif /* def _WIN32 */
159 #endif /* def __BEOS__ */
163 #endif /* def __OS2__ */
168 #include "jbsockets.h"
170 #include "miscutil.h"
172 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
174 static jb_socket socks4_connect(const struct forward_spec * fwd,
175 const char * target_host,
177 struct client_state *csp);
179 static jb_socket socks5_connect(const struct forward_spec *fwd,
180 const char *target_host,
182 struct client_state *csp);
185 #define SOCKS_REQUEST_GRANTED 90
186 #define SOCKS_REQUEST_REJECT 91
187 #define SOCKS_REQUEST_IDENT_FAILED 92
188 #define SOCKS_REQUEST_IDENT_CONFLICT 93
190 #define SOCKS5_REQUEST_GRANTED 0
191 #define SOCKS5_REQUEST_FAILED 1
192 #define SOCKS5_REQUEST_DENIED 2
193 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
194 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
195 #define SOCKS5_REQUEST_CONNECTION_REFUSEDD 5
196 #define SOCKS5_REQUEST_TTL_EXPIRED 6
197 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
198 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
200 /* structure of a socks client operation */
202 unsigned char vn; /* socks version number */
203 unsigned char cd; /* command code */
204 unsigned char dstport[2]; /* destination port */
205 unsigned char dstip[4]; /* destination address */
206 char userid; /* first byte of userid */
207 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
208 /* more bytes of the userid follow, terminated by a NULL */
211 /* structure of a socks server reply */
213 unsigned char vn; /* socks version number */
214 unsigned char cd; /* command code */
215 unsigned char dstport[2]; /* destination port */
216 unsigned char dstip[4]; /* destination address */
219 static const char socks_userid[] = "anonymous";
222 /*********************************************************************
224 * Function : forwarded_connect
226 * Description : Connect to a specified web server, possibly via
227 * a HTTP proxy and/or a SOCKS proxy.
230 * 1 : fwd = the proxies to use when connecting.
231 * 2 : http = the http request and apropos headers
232 * 3 : csp = Current client state (buffers, headers, etc...)
234 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
236 *********************************************************************/
237 jb_socket forwarded_connect(const struct forward_spec * fwd,
238 struct http_request *http,
239 struct client_state *csp)
241 const char * dest_host;
244 /* Figure out if we need to connect to the web server or a HTTP proxy. */
245 if (fwd->forward_host)
248 dest_host = fwd->forward_host;
249 dest_port = fwd->forward_port;
254 dest_host = http->host;
255 dest_port = http->port;
258 /* Connect, maybe using a SOCKS proxy */
262 return (connect_to(dest_host, dest_port, csp));
266 return (socks4_connect(fwd, dest_host, dest_port, csp));
269 return (socks5_connect(fwd, dest_host, dest_port, csp));
272 /* Should never get here */
273 log_error(LOG_LEVEL_FATAL, "SOCKS4 impossible internal error - bad SOCKS type.");
275 return(JB_INVALID_SOCKET);
280 /*********************************************************************
282 * Function : socks4_connect
284 * Description : Connect to the SOCKS server, and connect through
285 * it to the specified server. This handles
286 * all the SOCKS negotiation, and returns a file
287 * descriptor for a socket which can be treated as a
288 * normal (non-SOCKS) socket.
290 * Logged error messages are saved to csp->error_message
291 * and later reused by error_response() for the CGI
292 * message. strdup allocation failures are handled there.
295 * 1 : fwd = Specifies the SOCKS proxy to use.
296 * 2 : target_host = The final server to connect to.
297 * 3 : target_port = The final port to connect to.
298 * 4 : csp = Current client state (buffers, headers, etc...)
300 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
302 *********************************************************************/
303 static jb_socket socks4_connect(const struct forward_spec * fwd,
304 const char * target_host,
306 struct client_state *csp)
309 char buf[BUFFER_SIZE];
310 struct socks_op *c = (struct socks_op *)buf;
311 struct socks_reply *s = (struct socks_reply *)buf;
318 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
320 /* XXX: Shouldn't the config file parser prevent this? */
321 errstr = "NULL gateway host specified.";
325 if (fwd->gateway_port <= 0)
327 errstr = "invalid gateway port specified.";
333 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
334 csp->error_message = strdup(errstr);
336 return(JB_INVALID_SOCKET);
339 /* build a socks request for connection to the web server */
341 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
343 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
348 web_server_addr = htonl(resolve_hostname_to_ip(target_host));
349 if (web_server_addr == INADDR_NONE)
351 errstr = "could not resolve target host";
352 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
357 web_server_addr = 0x00000001;
358 n = csiz + strlen(target_host) + 1;
362 errstr = "buffer cbuf too small.";
363 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
368 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
370 * What we forward to the socks4a server should have the
371 * size of socks_op, plus the length of the userid plus
372 * its \0 byte (which we don't have to add because the
373 * first byte of the userid is counted twice as it's also
374 * part of sock_op) minus the padding bytes (which are part
375 * of the userid as well), plus the length of the target_host
376 * (which is stored csiz bytes after the beginning of the buffer),
377 * plus another \0 byte.
379 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
384 /* Should never get here */
385 log_error(LOG_LEVEL_FATAL,
386 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
388 return(JB_INVALID_SOCKET);
393 csp->error_message = strdup(errstr);
394 return(JB_INVALID_SOCKET);
399 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
400 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
401 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
402 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
403 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
404 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
406 /* pass the request to the socks server */
407 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
409 if (sfd == JB_INVALID_SOCKET)
412 * XXX: connect_to should fill in the exact reason.
413 * Most likely resolving the IP of the forwarder failed.
415 errstr = "connect_to failed: see logfile for details";
418 else if (write_socket(sfd, (char *)c, csiz))
420 errstr = "SOCKS4 negotiation write failed.";
421 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
425 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
427 errstr = "SOCKS4 negotiation read failed.";
428 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
435 csp->error_message = strdup(errstr);
436 return(JB_INVALID_SOCKET);
441 case SOCKS_REQUEST_GRANTED:
444 case SOCKS_REQUEST_REJECT:
445 errstr = "SOCKS request rejected or failed.";
448 case SOCKS_REQUEST_IDENT_FAILED:
449 errstr = "SOCKS request rejected because "
450 "SOCKS server cannot connect to identd on the client.";
453 case SOCKS_REQUEST_IDENT_CONFLICT:
454 errstr = "SOCKS request rejected because "
455 "the client program and identd report "
456 "different user-ids.";
461 snprintf(buf, sizeof(buf),
462 "SOCKS request rejected for reason code %d.", s->cd);
466 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
467 csp->error_message = strdup(errstr);
470 return(JB_INVALID_SOCKET);
475 /*********************************************************************
477 * Function : socks5_connect
479 * Description : Connect to the SOCKS server, and connect through
480 * it to the specified server. This handles
481 * all the SOCKS negotiation, and returns a file
482 * descriptor for a socket which can be treated as a
483 * normal (non-SOCKS) socket.
486 * 1 : fwd = Specifies the SOCKS proxy to use.
487 * 2 : target_host = The final server to connect to.
488 * 3 : target_port = The final port to connect to.
489 * 4 : csp = Current client state (buffers, headers, etc...)
491 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
493 *********************************************************************/
494 static jb_socket socks5_connect(const struct forward_spec *fwd,
495 const char *target_host,
497 struct client_state *csp)
500 char cbuf[BUFFER_SIZE];
501 char sbuf[BUFFER_SIZE];
502 size_t client_pos = 0;
507 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
509 log_error(LOG_LEVEL_CONNECT, "socks5_connect: NULL gateway host specified");
513 if (fwd->gateway_port <= 0)
515 log_error(LOG_LEVEL_CONNECT, "socks5_connect: invalid gateway port specified");
519 hostlen = strlen(target_host);
522 log_error(LOG_LEVEL_CONNECT, "socks5_connect: target host name is longer than 255 characters.");
526 if (fwd->type != SOCKS_5)
528 /* Should never get here */
529 log_error(LOG_LEVEL_FATAL, "SOCKS5 impossible internal error - bad SOCKS type.");
536 return(JB_INVALID_SOCKET);
539 /* pass the request to the socks server */
540 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
542 if (sfd == JB_INVALID_SOCKET)
544 return(JB_INVALID_SOCKET);
548 cbuf[client_pos++] = '\x05'; /* Version */
549 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
550 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
552 if (write_socket(sfd, cbuf, client_pos))
554 log_error(LOG_LEVEL_CONNECT, "SOCKS5 negotiation write failed...");
556 return(JB_INVALID_SOCKET);
559 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
561 log_error(LOG_LEVEL_CONNECT, "SOCKS5 negotiation read failed...");
565 if (!err && (sbuf[0] != '\x05'))
567 log_error(LOG_LEVEL_CONNECT, "SOCKS5 negotiation protocol version error");
571 if (!err && (sbuf[1] == '\xff'))
573 log_error(LOG_LEVEL_CONNECT, "SOCKS5 authentication required");
577 if (!err && (sbuf[1] != '\x00'))
579 log_error(LOG_LEVEL_CONNECT, "SOCKS5 negotiation protocol error");
587 return(JB_INVALID_SOCKET);
591 cbuf[client_pos++] = '\x05'; /* Version */
592 cbuf[client_pos++] = '\x01'; /* TCP connect */
593 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
594 cbuf[client_pos++] = '\x03'; /* Address is domain name */
595 cbuf[client_pos++] = (char)(hostlen & 0xffu);
596 strncpy(cbuf + client_pos, target_host, 0xffu);
597 client_pos += (hostlen & 0xffu);
598 cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
599 cbuf[client_pos++] = (char)((target_port ) & 0xffu);
601 if (write_socket(sfd, cbuf, client_pos))
603 log_error(LOG_LEVEL_CONNECT, "SOCKS5 negotiation write failed...");
606 return(JB_INVALID_SOCKET);
609 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
612 log_error(LOG_LEVEL_CONNECT, "SOCKS5 negotiation read failed...");
616 if (!err && (sbuf[0] != '\x05'))
618 log_error(LOG_LEVEL_CONNECT, "SOCKS5 negotiation protocol version error");
622 if (!err && (sbuf[2] != '\x00'))
624 log_error(LOG_LEVEL_CONNECT, "SOCKS5 negotiation protocol error");
632 case SOCKS5_REQUEST_GRANTED:
635 case SOCKS5_REQUEST_FAILED:
636 log_error(LOG_LEVEL_CONNECT, "SOCKS5 request failed");
638 case SOCKS5_REQUEST_DENIED:
639 log_error(LOG_LEVEL_CONNECT, "SOCKS5 request denied");
641 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
642 log_error(LOG_LEVEL_CONNECT, "SOCKS5 request - network unreachable");
644 case SOCKS5_REQUEST_HOST_UNREACHABLE:
645 log_error(LOG_LEVEL_CONNECT, "SOCKS5 request - host unreachable");
647 case SOCKS5_REQUEST_CONNECTION_REFUSEDD:
648 log_error(LOG_LEVEL_CONNECT, "SOCKS5 request - connection refused");
650 case SOCKS5_REQUEST_TTL_EXPIRED:
651 log_error(LOG_LEVEL_CONNECT, "SOCKS5 request - TTL expired");
653 case SOCKS5_REQUEST_PROTOCOL_ERROR:
654 log_error(LOG_LEVEL_CONNECT, "SOCKS5 request - client protocol error");
656 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
657 log_error(LOG_LEVEL_CONNECT, "SOCKS5 request - domain names unsupported");
660 log_error(LOG_LEVEL_CONNECT, "SOCKS5 negotiation protocol error");
668 return(JB_INVALID_SOCKET);