1 const char gateway_rcs[] = "$Id: gateway.c,v 1.24 2008/02/04 14:56:29 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.24 2008/02/04 14:56:29 fabiankeil
38 * - Fix a compiler warning.
39 * - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
41 * Revision 1.23 2008/02/04 13:11:35 fabiankeil
42 * Remember the cause of the SOCKS5 error for the CGI message.
44 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
45 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
47 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
48 * Modified patch from Song Weijia (#1762559) to
49 * fix socks requests on big-endian platforms.
51 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
52 * - Use strlcpy() instead of strcpy().
53 * - Use the same buffer for socks requests and socks responses.
54 * - Fix bogus warning about web_server_addr being used uninitialized.
56 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
57 * - Save errors in socks4_connect() to csp->error_message.
58 * - Silence some gcc43 warnings, hopefully the right way.
60 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
61 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
62 * with what was really the latest development (the v_3_0_branch branch)
64 * Revision 1.16 2002/05/12 21:36:29 jongfoster
65 * Correcting function comments
67 * Revision 1.15 2002/03/26 22:29:54 swa
68 * we have a new homepage!
70 * Revision 1.14 2002/03/24 13:25:43 swa
71 * name change related issues
73 * Revision 1.13 2002/03/13 00:29:59 jongfoster
76 * Revision 1.12 2002/03/09 20:03:52 jongfoster
77 * - Making various functions return int rather than size_t.
78 * (Undoing a recent change). Since size_t is unsigned on
79 * Windows, functions like read_socket that return -1 on
80 * error cannot return a size_t.
82 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
83 * crashes, and also frequently caused JB to jump to 100%
84 * CPU and stay there. (Because it thought it had just
85 * read ((unsigned)-1) == 4Gb of data...)
87 * - The signature of write_socket has changed, it now simply
88 * returns success=0/failure=nonzero.
90 * - Trying to get rid of a few warnings --with-debug on
91 * Windows, I've introduced a new type "jb_socket". This is
92 * used for the socket file descriptors. On Windows, this
93 * is SOCKET (a typedef for unsigned). Everywhere else, it's
94 * an int. The error value can't be -1 any more, so it's
95 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
96 * Windows it maps to the #define INVALID_SOCKET.)
98 * - The signature of bind_port has changed.
100 * Revision 1.11 2002/03/08 17:46:04 jongfoster
101 * Fixing int/size_t warnings
103 * Revision 1.10 2002/03/07 03:50:19 oes
104 * - Improved handling of failed DNS lookups
105 * - Fixed compiler warnings
107 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
108 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
109 * threads to call select() simultaneously. So, it's time to do a real, live,
110 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
111 * (native). Both versions will work, but using __OS2__ offers multi-threading.
113 * Revision 1.8 2001/09/13 20:10:12 jongfoster
114 * Fixing missing #include under Windows
116 * Revision 1.7 2001/09/12 17:58:26 steudten
118 * add #include <string.h>
120 * Revision 1.6 2001/09/10 10:41:16 oes
121 * Added #include in.h
123 * Revision 1.5 2001/07/29 18:47:57 jongfoster
124 * Adding missing #include project.h
126 * Revision 1.4 2001/07/24 12:47:06 oes
127 * Applied BeOS support update by Eugenia
129 * Revision 1.3 2001/06/09 10:55:28 jongfoster
130 * Changing BUFSIZ ==> BUFFER_SIZE
132 * Revision 1.2 2001/06/07 23:11:38 jongfoster
133 * Removing gateways[] list - no longer used.
134 * Replacing function pointer in struct gateway with a directly
135 * called function forwarded_connect(), which can do the common
136 * task of deciding whether to connect to the web server or HTTP
138 * Replacing struct gateway with struct forward_spec
139 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
140 * It was a bug which led to the connection being made to the web
141 * server rather than the HTTP proxy, and also a buffer overrun.
143 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
144 * Initial import of version 2.9.3 source tree
147 *********************************************************************/
153 #include <sys/types.h>
156 #include <netinet/in.h>
164 #include <winsock2.h>
165 #endif /* def _WIN32 */
169 #endif /* def __BEOS__ */
173 #endif /* def __OS2__ */
178 #include "jbsockets.h"
180 #include "miscutil.h"
182 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
184 static jb_socket socks4_connect(const struct forward_spec * fwd,
185 const char * target_host,
187 struct client_state *csp);
189 static jb_socket socks5_connect(const struct forward_spec *fwd,
190 const char *target_host,
192 struct client_state *csp);
195 #define SOCKS_REQUEST_GRANTED 90
196 #define SOCKS_REQUEST_REJECT 91
197 #define SOCKS_REQUEST_IDENT_FAILED 92
198 #define SOCKS_REQUEST_IDENT_CONFLICT 93
200 #define SOCKS5_REQUEST_GRANTED 0
201 #define SOCKS5_REQUEST_FAILED 1
202 #define SOCKS5_REQUEST_DENIED 2
203 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
204 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
205 #define SOCKS5_REQUEST_CONNECTION_REFUSEDD 5
206 #define SOCKS5_REQUEST_TTL_EXPIRED 6
207 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
208 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
210 /* structure of a socks client operation */
212 unsigned char vn; /* socks version number */
213 unsigned char cd; /* command code */
214 unsigned char dstport[2]; /* destination port */
215 unsigned char dstip[4]; /* destination address */
216 char userid; /* first byte of userid */
217 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
218 /* more bytes of the userid follow, terminated by a NULL */
221 /* structure of a socks server reply */
223 unsigned char vn; /* socks version number */
224 unsigned char cd; /* command code */
225 unsigned char dstport[2]; /* destination port */
226 unsigned char dstip[4]; /* destination address */
229 static const char socks_userid[] = "anonymous";
232 /*********************************************************************
234 * Function : forwarded_connect
236 * Description : Connect to a specified web server, possibly via
237 * a HTTP proxy and/or a SOCKS proxy.
240 * 1 : fwd = the proxies to use when connecting.
241 * 2 : http = the http request and apropos headers
242 * 3 : csp = Current client state (buffers, headers, etc...)
244 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
246 *********************************************************************/
247 jb_socket forwarded_connect(const struct forward_spec * fwd,
248 struct http_request *http,
249 struct client_state *csp)
251 const char * dest_host;
254 /* Figure out if we need to connect to the web server or a HTTP proxy. */
255 if (fwd->forward_host)
258 dest_host = fwd->forward_host;
259 dest_port = fwd->forward_port;
264 dest_host = http->host;
265 dest_port = http->port;
268 /* Connect, maybe using a SOCKS proxy */
272 return (connect_to(dest_host, dest_port, csp));
276 return (socks4_connect(fwd, dest_host, dest_port, csp));
279 return (socks5_connect(fwd, dest_host, dest_port, csp));
282 /* Should never get here */
283 log_error(LOG_LEVEL_FATAL, "SOCKS4 impossible internal error - bad SOCKS type.");
285 return(JB_INVALID_SOCKET);
290 /*********************************************************************
292 * Function : socks4_connect
294 * Description : Connect to the SOCKS server, and connect through
295 * it to the specified server. This handles
296 * all the SOCKS negotiation, and returns a file
297 * descriptor for a socket which can be treated as a
298 * normal (non-SOCKS) socket.
300 * Logged error messages are saved to csp->error_message
301 * and later reused by error_response() for the CGI
302 * message. strdup allocation failures are handled there.
305 * 1 : fwd = Specifies the SOCKS proxy to use.
306 * 2 : target_host = The final server to connect to.
307 * 3 : target_port = The final port to connect to.
308 * 4 : csp = Current client state (buffers, headers, etc...)
310 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
312 *********************************************************************/
313 static jb_socket socks4_connect(const struct forward_spec * fwd,
314 const char * target_host,
316 struct client_state *csp)
318 unsigned int web_server_addr;
319 char buf[BUFFER_SIZE];
320 struct socks_op *c = (struct socks_op *)buf;
321 struct socks_reply *s = (struct socks_reply *)buf;
328 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
330 /* XXX: Shouldn't the config file parser prevent this? */
331 errstr = "NULL gateway host specified.";
335 if (fwd->gateway_port <= 0)
337 errstr = "invalid gateway port specified.";
343 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
344 csp->error_message = strdup(errstr);
346 return(JB_INVALID_SOCKET);
349 /* build a socks request for connection to the web server */
351 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
353 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
358 web_server_addr = resolve_hostname_to_ip(target_host);
359 if (web_server_addr == INADDR_NONE)
361 errstr = "could not resolve target host";
362 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
367 web_server_addr = htonl(web_server_addr);
371 web_server_addr = 0x00000001;
372 n = csiz + strlen(target_host) + 1;
376 errstr = "buffer cbuf too small.";
377 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
382 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
384 * What we forward to the socks4a server should have the
385 * size of socks_op, plus the length of the userid plus
386 * its \0 byte (which we don't have to add because the
387 * first byte of the userid is counted twice as it's also
388 * part of sock_op) minus the padding bytes (which are part
389 * of the userid as well), plus the length of the target_host
390 * (which is stored csiz bytes after the beginning of the buffer),
391 * plus another \0 byte.
393 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
398 /* Should never get here */
399 log_error(LOG_LEVEL_FATAL,
400 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
402 return(JB_INVALID_SOCKET);
407 csp->error_message = strdup(errstr);
408 return(JB_INVALID_SOCKET);
413 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
414 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
415 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
416 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
417 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
418 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
420 /* pass the request to the socks server */
421 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
423 if (sfd == JB_INVALID_SOCKET)
426 * XXX: connect_to should fill in the exact reason.
427 * Most likely resolving the IP of the forwarder failed.
429 errstr = "connect_to failed: see logfile for details";
432 else if (write_socket(sfd, (char *)c, csiz))
434 errstr = "SOCKS4 negotiation write failed.";
435 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
439 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
441 errstr = "SOCKS4 negotiation read failed.";
442 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
449 csp->error_message = strdup(errstr);
450 return(JB_INVALID_SOCKET);
455 case SOCKS_REQUEST_GRANTED:
458 case SOCKS_REQUEST_REJECT:
459 errstr = "SOCKS request rejected or failed.";
462 case SOCKS_REQUEST_IDENT_FAILED:
463 errstr = "SOCKS request rejected because "
464 "SOCKS server cannot connect to identd on the client.";
467 case SOCKS_REQUEST_IDENT_CONFLICT:
468 errstr = "SOCKS request rejected because "
469 "the client program and identd report "
470 "different user-ids.";
475 snprintf(buf, sizeof(buf),
476 "SOCKS request rejected for reason code %d.", s->cd);
480 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
481 csp->error_message = strdup(errstr);
484 return(JB_INVALID_SOCKET);
488 /*********************************************************************
490 * Function : translate_socks5_error
492 * Description : Translates a SOCKS errors to a string.
495 * 1 : socks_error = The error code to translate.
497 * Returns : The string translation.
499 *********************************************************************/
500 static const char *translate_socks5_error(int socks_error)
504 /* XXX: these should be more descriptive */
505 case SOCKS5_REQUEST_FAILED:
506 return "SOCKS5 request failed";
507 case SOCKS5_REQUEST_DENIED:
508 return "SOCKS5 request denied";
509 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
510 return "SOCKS5 network unreachable";
511 case SOCKS5_REQUEST_HOST_UNREACHABLE:
512 return "SOCKS5 host unreachable";
513 case SOCKS5_REQUEST_CONNECTION_REFUSEDD:
514 return "SOCKS5 connection refused";
515 case SOCKS5_REQUEST_TTL_EXPIRED:
516 return "SOCKS5 TTL expired";
517 case SOCKS5_REQUEST_PROTOCOL_ERROR:
518 return "SOCKS5 client protocol error";
519 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
520 return "SOCKS5 domain names unsupported";
521 case SOCKS5_REQUEST_GRANTED:
522 return "everything's peachy";
524 return "SOCKS5 negotiation protocol error";
528 /*********************************************************************
530 * Function : socks5_connect
532 * Description : Connect to the SOCKS server, and connect through
533 * it to the specified server. This handles
534 * all the SOCKS negotiation, and returns a file
535 * descriptor for a socket which can be treated as a
536 * normal (non-SOCKS) socket.
539 * 1 : fwd = Specifies the SOCKS proxy to use.
540 * 2 : target_host = The final server to connect to.
541 * 3 : target_port = The final port to connect to.
542 * 4 : csp = Current client state (buffers, headers, etc...)
544 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
546 *********************************************************************/
547 static jb_socket socks5_connect(const struct forward_spec *fwd,
548 const char *target_host,
550 struct client_state *csp)
555 size_t client_pos = 0;
559 const char *errstr = NULL;
561 assert(fwd->gateway_host);
562 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
564 errstr = "NULL gateway host specified";
568 if (fwd->gateway_port <= 0)
571 * XXX: currently this can't happen because in
572 * case of invalid gateway ports we use the defaults.
573 * Of course we really shouldn't do that.
575 errstr = "invalid gateway port specified";
579 hostlen = strlen(target_host);
582 errstr = "target host name is longer than 255 characters";
586 if (fwd->type != SOCKS_5)
588 /* Should never get here */
589 log_error(LOG_LEVEL_FATAL,
590 "SOCKS5 impossible internal error - bad SOCKS type");
597 assert(errstr != NULL);
598 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
599 csp->error_message = strdup(errstr);
600 return(JB_INVALID_SOCKET);
603 /* pass the request to the socks server */
604 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
606 if (sfd == JB_INVALID_SOCKET)
608 errstr = "socks5 server unreachable";
609 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
610 csp->error_message = strdup(errstr);
611 return(JB_INVALID_SOCKET);
615 cbuf[client_pos++] = '\x05'; /* Version */
616 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
617 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
619 if (write_socket(sfd, cbuf, client_pos))
621 errstr = "SOCKS5 negotiation write failed";
622 csp->error_message = strdup(errstr);
623 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
625 return(JB_INVALID_SOCKET);
628 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
630 errstr = "SOCKS5 negotiation read failed";
634 if (!err && (sbuf[0] != '\x05'))
636 errstr = "SOCKS5 negotiation protocol version error";
640 if (!err && (sbuf[1] == '\xff'))
642 errstr = "SOCKS5 authentication required";
646 if (!err && (sbuf[1] != '\x00'))
648 errstr = "SOCKS5 negotiation protocol error";
654 assert(errstr != NULL);
655 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
656 csp->error_message = strdup(errstr);
659 return(JB_INVALID_SOCKET);
663 cbuf[client_pos++] = '\x05'; /* Version */
664 cbuf[client_pos++] = '\x01'; /* TCP connect */
665 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
666 cbuf[client_pos++] = '\x03'; /* Address is domain name */
667 cbuf[client_pos++] = (char)(hostlen & 0xffu);
668 assert(sizeof(cbuf) - client_pos > 255);
669 /* Using strncpy because we really want the nul byte padding. */
670 strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
671 client_pos += (hostlen & 0xffu);
672 cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
673 cbuf[client_pos++] = (char)((target_port ) & 0xffu);
675 if (write_socket(sfd, cbuf, client_pos))
677 errstr = "SOCKS5 negotiation read failed";
678 csp->error_message = strdup(errstr);
679 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
682 return(JB_INVALID_SOCKET);
685 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
688 errstr = "SOCKS5 negotiation read failed";
691 else if (server_size > 20)
693 /* This is somewhat unexpected but doesn't realy matter. */
694 log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
695 "from socks server. Would have accepted up to %d.",
696 server_size, sizeof(sbuf));
699 if (!err && (sbuf[0] != '\x05'))
701 errstr = "SOCKS5 negotiation protocol version error";
705 if (!err && (sbuf[2] != '\x00'))
707 errstr = "SOCKS5 negotiation protocol error";
713 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
717 errstr = translate_socks5_error(sbuf[1]);
721 assert(errstr != NULL);
722 csp->error_message = strdup(errstr);
723 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
727 return(JB_INVALID_SOCKET);