1 const char gateway_rcs[] = "$Id: gateway.c,v 1.22 2008/02/03 13:46:15 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.22 2008/02/03 13:46:15 fabiankeil
38 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
40 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
41 * Modified patch from Song Weijia (#1762559) to
42 * fix socks requests on big-endian platforms.
44 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
45 * - Use strlcpy() instead of strcpy().
46 * - Use the same buffer for socks requests and socks responses.
47 * - Fix bogus warning about web_server_addr being used uninitialized.
49 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
50 * - Save errors in socks4_connect() to csp->error_message.
51 * - Silence some gcc43 warnings, hopefully the right way.
53 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
54 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
55 * with what was really the latest development (the v_3_0_branch branch)
57 * Revision 1.16 2002/05/12 21:36:29 jongfoster
58 * Correcting function comments
60 * Revision 1.15 2002/03/26 22:29:54 swa
61 * we have a new homepage!
63 * Revision 1.14 2002/03/24 13:25:43 swa
64 * name change related issues
66 * Revision 1.13 2002/03/13 00:29:59 jongfoster
69 * Revision 1.12 2002/03/09 20:03:52 jongfoster
70 * - Making various functions return int rather than size_t.
71 * (Undoing a recent change). Since size_t is unsigned on
72 * Windows, functions like read_socket that return -1 on
73 * error cannot return a size_t.
75 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
76 * crashes, and also frequently caused JB to jump to 100%
77 * CPU and stay there. (Because it thought it had just
78 * read ((unsigned)-1) == 4Gb of data...)
80 * - The signature of write_socket has changed, it now simply
81 * returns success=0/failure=nonzero.
83 * - Trying to get rid of a few warnings --with-debug on
84 * Windows, I've introduced a new type "jb_socket". This is
85 * used for the socket file descriptors. On Windows, this
86 * is SOCKET (a typedef for unsigned). Everywhere else, it's
87 * an int. The error value can't be -1 any more, so it's
88 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
89 * Windows it maps to the #define INVALID_SOCKET.)
91 * - The signature of bind_port has changed.
93 * Revision 1.11 2002/03/08 17:46:04 jongfoster
94 * Fixing int/size_t warnings
96 * Revision 1.10 2002/03/07 03:50:19 oes
97 * - Improved handling of failed DNS lookups
98 * - Fixed compiler warnings
100 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
101 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
102 * threads to call select() simultaneously. So, it's time to do a real, live,
103 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
104 * (native). Both versions will work, but using __OS2__ offers multi-threading.
106 * Revision 1.8 2001/09/13 20:10:12 jongfoster
107 * Fixing missing #include under Windows
109 * Revision 1.7 2001/09/12 17:58:26 steudten
111 * add #include <string.h>
113 * Revision 1.6 2001/09/10 10:41:16 oes
114 * Added #include in.h
116 * Revision 1.5 2001/07/29 18:47:57 jongfoster
117 * Adding missing #include project.h
119 * Revision 1.4 2001/07/24 12:47:06 oes
120 * Applied BeOS support update by Eugenia
122 * Revision 1.3 2001/06/09 10:55:28 jongfoster
123 * Changing BUFSIZ ==> BUFFER_SIZE
125 * Revision 1.2 2001/06/07 23:11:38 jongfoster
126 * Removing gateways[] list - no longer used.
127 * Replacing function pointer in struct gateway with a directly
128 * called function forwarded_connect(), which can do the common
129 * task of deciding whether to connect to the web server or HTTP
131 * Replacing struct gateway with struct forward_spec
132 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
133 * It was a bug which led to the connection being made to the web
134 * server rather than the HTTP proxy, and also a buffer overrun.
136 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
137 * Initial import of version 2.9.3 source tree
140 *********************************************************************/
146 #include <sys/types.h>
149 #include <netinet/in.h>
157 #include <winsock2.h>
158 #endif /* def _WIN32 */
162 #endif /* def __BEOS__ */
166 #endif /* def __OS2__ */
171 #include "jbsockets.h"
173 #include "miscutil.h"
175 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
177 static jb_socket socks4_connect(const struct forward_spec * fwd,
178 const char * target_host,
180 struct client_state *csp);
182 static jb_socket socks5_connect(const struct forward_spec *fwd,
183 const char *target_host,
185 struct client_state *csp);
188 #define SOCKS_REQUEST_GRANTED 90
189 #define SOCKS_REQUEST_REJECT 91
190 #define SOCKS_REQUEST_IDENT_FAILED 92
191 #define SOCKS_REQUEST_IDENT_CONFLICT 93
193 #define SOCKS5_REQUEST_GRANTED 0
194 #define SOCKS5_REQUEST_FAILED 1
195 #define SOCKS5_REQUEST_DENIED 2
196 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
197 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
198 #define SOCKS5_REQUEST_CONNECTION_REFUSEDD 5
199 #define SOCKS5_REQUEST_TTL_EXPIRED 6
200 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
201 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
203 /* structure of a socks client operation */
205 unsigned char vn; /* socks version number */
206 unsigned char cd; /* command code */
207 unsigned char dstport[2]; /* destination port */
208 unsigned char dstip[4]; /* destination address */
209 char userid; /* first byte of userid */
210 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
211 /* more bytes of the userid follow, terminated by a NULL */
214 /* structure of a socks server reply */
216 unsigned char vn; /* socks version number */
217 unsigned char cd; /* command code */
218 unsigned char dstport[2]; /* destination port */
219 unsigned char dstip[4]; /* destination address */
222 static const char socks_userid[] = "anonymous";
225 /*********************************************************************
227 * Function : forwarded_connect
229 * Description : Connect to a specified web server, possibly via
230 * a HTTP proxy and/or a SOCKS proxy.
233 * 1 : fwd = the proxies to use when connecting.
234 * 2 : http = the http request and apropos headers
235 * 3 : csp = Current client state (buffers, headers, etc...)
237 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
239 *********************************************************************/
240 jb_socket forwarded_connect(const struct forward_spec * fwd,
241 struct http_request *http,
242 struct client_state *csp)
244 const char * dest_host;
247 /* Figure out if we need to connect to the web server or a HTTP proxy. */
248 if (fwd->forward_host)
251 dest_host = fwd->forward_host;
252 dest_port = fwd->forward_port;
257 dest_host = http->host;
258 dest_port = http->port;
261 /* Connect, maybe using a SOCKS proxy */
265 return (connect_to(dest_host, dest_port, csp));
269 return (socks4_connect(fwd, dest_host, dest_port, csp));
272 return (socks5_connect(fwd, dest_host, dest_port, csp));
275 /* Should never get here */
276 log_error(LOG_LEVEL_FATAL, "SOCKS4 impossible internal error - bad SOCKS type.");
278 return(JB_INVALID_SOCKET);
283 /*********************************************************************
285 * Function : socks4_connect
287 * Description : Connect to the SOCKS server, and connect through
288 * it to the specified server. This handles
289 * all the SOCKS negotiation, and returns a file
290 * descriptor for a socket which can be treated as a
291 * normal (non-SOCKS) socket.
293 * Logged error messages are saved to csp->error_message
294 * and later reused by error_response() for the CGI
295 * message. strdup allocation failures are handled there.
298 * 1 : fwd = Specifies the SOCKS proxy to use.
299 * 2 : target_host = The final server to connect to.
300 * 3 : target_port = The final port to connect to.
301 * 4 : csp = Current client state (buffers, headers, etc...)
303 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
305 *********************************************************************/
306 static jb_socket socks4_connect(const struct forward_spec * fwd,
307 const char * target_host,
309 struct client_state *csp)
312 char buf[BUFFER_SIZE];
313 struct socks_op *c = (struct socks_op *)buf;
314 struct socks_reply *s = (struct socks_reply *)buf;
321 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
323 /* XXX: Shouldn't the config file parser prevent this? */
324 errstr = "NULL gateway host specified.";
328 if (fwd->gateway_port <= 0)
330 errstr = "invalid gateway port specified.";
336 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
337 csp->error_message = strdup(errstr);
339 return(JB_INVALID_SOCKET);
342 /* build a socks request for connection to the web server */
344 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
346 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
351 web_server_addr = htonl(resolve_hostname_to_ip(target_host));
352 if (web_server_addr == INADDR_NONE)
354 errstr = "could not resolve target host";
355 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
360 web_server_addr = 0x00000001;
361 n = csiz + strlen(target_host) + 1;
365 errstr = "buffer cbuf too small.";
366 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
371 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
373 * What we forward to the socks4a server should have the
374 * size of socks_op, plus the length of the userid plus
375 * its \0 byte (which we don't have to add because the
376 * first byte of the userid is counted twice as it's also
377 * part of sock_op) minus the padding bytes (which are part
378 * of the userid as well), plus the length of the target_host
379 * (which is stored csiz bytes after the beginning of the buffer),
380 * plus another \0 byte.
382 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
387 /* Should never get here */
388 log_error(LOG_LEVEL_FATAL,
389 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
391 return(JB_INVALID_SOCKET);
396 csp->error_message = strdup(errstr);
397 return(JB_INVALID_SOCKET);
402 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
403 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
404 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
405 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
406 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
407 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
409 /* pass the request to the socks server */
410 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
412 if (sfd == JB_INVALID_SOCKET)
415 * XXX: connect_to should fill in the exact reason.
416 * Most likely resolving the IP of the forwarder failed.
418 errstr = "connect_to failed: see logfile for details";
421 else if (write_socket(sfd, (char *)c, csiz))
423 errstr = "SOCKS4 negotiation write failed.";
424 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
428 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
430 errstr = "SOCKS4 negotiation read failed.";
431 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
438 csp->error_message = strdup(errstr);
439 return(JB_INVALID_SOCKET);
444 case SOCKS_REQUEST_GRANTED:
447 case SOCKS_REQUEST_REJECT:
448 errstr = "SOCKS request rejected or failed.";
451 case SOCKS_REQUEST_IDENT_FAILED:
452 errstr = "SOCKS request rejected because "
453 "SOCKS server cannot connect to identd on the client.";
456 case SOCKS_REQUEST_IDENT_CONFLICT:
457 errstr = "SOCKS request rejected because "
458 "the client program and identd report "
459 "different user-ids.";
464 snprintf(buf, sizeof(buf),
465 "SOCKS request rejected for reason code %d.", s->cd);
469 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
470 csp->error_message = strdup(errstr);
473 return(JB_INVALID_SOCKET);
477 /*********************************************************************
479 * Function : translate_socks5_error
481 * Description : Translates a SOCKS errors to a string.
484 * 1 : socks_error = The error code to translate.
486 * Returns : The string translation.
488 *********************************************************************/
489 static const char *translate_socks5_error(int socks_error)
493 /* XXX: these should be more descriptive */
494 case SOCKS5_REQUEST_FAILED:
495 return "SOCKS5 request failed";
496 case SOCKS5_REQUEST_DENIED:
497 return "SOCKS5 request denied";
498 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
499 return "SOCKS5 network unreachable";
500 case SOCKS5_REQUEST_HOST_UNREACHABLE:
501 return "SOCKS5 host unreachable";
502 case SOCKS5_REQUEST_CONNECTION_REFUSEDD:
503 return "SOCKS5 connection refused";
504 case SOCKS5_REQUEST_TTL_EXPIRED:
505 return "SOCKS5 TTL expired";
506 case SOCKS5_REQUEST_PROTOCOL_ERROR:
507 return "SOCKS5 client protocol error";
508 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
509 return "SOCKS5 domain names unsupported";
510 case SOCKS5_REQUEST_GRANTED:
511 return "everything's peachy";
513 return "SOCKS5 negotiation protocol error";
517 /*********************************************************************
519 * Function : socks5_connect
521 * Description : Connect to the SOCKS server, and connect through
522 * it to the specified server. This handles
523 * all the SOCKS negotiation, and returns a file
524 * descriptor for a socket which can be treated as a
525 * normal (non-SOCKS) socket.
528 * 1 : fwd = Specifies the SOCKS proxy to use.
529 * 2 : target_host = The final server to connect to.
530 * 3 : target_port = The final port to connect to.
531 * 4 : csp = Current client state (buffers, headers, etc...)
533 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
535 *********************************************************************/
536 static jb_socket socks5_connect(const struct forward_spec *fwd,
537 const char *target_host,
539 struct client_state *csp)
542 char cbuf[BUFFER_SIZE];
543 char sbuf[BUFFER_SIZE];
544 size_t client_pos = 0;
548 const char *errstr = NULL;
550 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
552 errstr = "NULL gateway host specified";
556 if (fwd->gateway_port <= 0)
558 errstr = "invalid gateway port specified";
562 hostlen = strlen(target_host);
565 errstr = "target host name is longer than 255 characters";
569 if (fwd->type != SOCKS_5)
571 /* Should never get here */
572 log_error(LOG_LEVEL_FATAL,
573 "SOCKS5 impossible internal error - bad SOCKS type");
580 assert(errstr != NULL);
581 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
582 csp->error_message = strdup(errstr);
583 return(JB_INVALID_SOCKET);
586 /* pass the request to the socks server */
587 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
589 if (sfd == JB_INVALID_SOCKET)
591 return(JB_INVALID_SOCKET);
595 cbuf[client_pos++] = '\x05'; /* Version */
596 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
597 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
599 if (write_socket(sfd, cbuf, client_pos))
601 errstr = "SOCKS5 negotiation write failed";
602 csp->error_message = strdup(errstr);
603 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
605 return(JB_INVALID_SOCKET);
608 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
610 errstr = "SOCKS5 negotiation read failed";
614 if (!err && (sbuf[0] != '\x05'))
616 errstr = "SOCKS5 negotiation protocol version error";
620 if (!err && (sbuf[1] == '\xff'))
622 errstr = "SOCKS5 authentication required";
626 if (!err && (sbuf[1] != '\x00'))
628 errstr = "SOCKS5 negotiation protocol error";
634 assert(errstr != NULL);
635 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
636 csp->error_message = strdup(errstr);
639 return(JB_INVALID_SOCKET);
643 cbuf[client_pos++] = '\x05'; /* Version */
644 cbuf[client_pos++] = '\x01'; /* TCP connect */
645 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
646 cbuf[client_pos++] = '\x03'; /* Address is domain name */
647 cbuf[client_pos++] = (char)(hostlen & 0xffu);
648 strncpy(cbuf + client_pos, target_host, 0xffu);
649 client_pos += (hostlen & 0xffu);
650 cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
651 cbuf[client_pos++] = (char)((target_port ) & 0xffu);
653 if (write_socket(sfd, cbuf, client_pos))
655 errstr = "SOCKS5 negotiation read failed";
656 csp->error_message = strdup(errstr);
657 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
660 return(JB_INVALID_SOCKET);
663 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
666 errstr = "SOCKS5 negotiation read failed";
670 if (!err && (sbuf[0] != '\x05'))
672 errstr = "SOCKS5 negotiation protocol version error";
676 if (!err && (sbuf[2] != '\x00'))
678 errstr = "SOCKS5 negotiation protocol error";
684 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
688 errstr = translate_socks5_error(sbuf[1]);
692 assert(errstr != NULL);
693 csp->error_message = strdup(errstr);
694 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
697 return(JB_INVALID_SOCKET);