1 const char gateway_rcs[] = "$Id: gateway.c,v 1.23 2008/02/04 13:11:35 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.23 2008/02/04 13:11:35 fabiankeil
38 * Remember the cause of the SOCKS5 error for the CGI message.
40 * Revision 1.22 2008/02/03 13:46:15 fabiankeil
41 * Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
43 * Revision 1.21 2007/07/28 12:30:03 fabiankeil
44 * Modified patch from Song Weijia (#1762559) to
45 * fix socks requests on big-endian platforms.
47 * Revision 1.20 2007/05/14 10:23:48 fabiankeil
48 * - Use strlcpy() instead of strcpy().
49 * - Use the same buffer for socks requests and socks responses.
50 * - Fix bogus warning about web_server_addr being used uninitialized.
52 * Revision 1.19 2007/01/25 14:09:45 fabiankeil
53 * - Save errors in socks4_connect() to csp->error_message.
54 * - Silence some gcc43 warnings, hopefully the right way.
56 * Revision 1.18 2006/07/18 14:48:46 david__schmidt
57 * Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
58 * with what was really the latest development (the v_3_0_branch branch)
60 * Revision 1.16 2002/05/12 21:36:29 jongfoster
61 * Correcting function comments
63 * Revision 1.15 2002/03/26 22:29:54 swa
64 * we have a new homepage!
66 * Revision 1.14 2002/03/24 13:25:43 swa
67 * name change related issues
69 * Revision 1.13 2002/03/13 00:29:59 jongfoster
72 * Revision 1.12 2002/03/09 20:03:52 jongfoster
73 * - Making various functions return int rather than size_t.
74 * (Undoing a recent change). Since size_t is unsigned on
75 * Windows, functions like read_socket that return -1 on
76 * error cannot return a size_t.
78 * THIS WAS A MAJOR BUG - it caused frequent, unpredictable
79 * crashes, and also frequently caused JB to jump to 100%
80 * CPU and stay there. (Because it thought it had just
81 * read ((unsigned)-1) == 4Gb of data...)
83 * - The signature of write_socket has changed, it now simply
84 * returns success=0/failure=nonzero.
86 * - Trying to get rid of a few warnings --with-debug on
87 * Windows, I've introduced a new type "jb_socket". This is
88 * used for the socket file descriptors. On Windows, this
89 * is SOCKET (a typedef for unsigned). Everywhere else, it's
90 * an int. The error value can't be -1 any more, so it's
91 * now JB_INVALID_SOCKET (which is -1 on UNIX, and in
92 * Windows it maps to the #define INVALID_SOCKET.)
94 * - The signature of bind_port has changed.
96 * Revision 1.11 2002/03/08 17:46:04 jongfoster
97 * Fixing int/size_t warnings
99 * Revision 1.10 2002/03/07 03:50:19 oes
100 * - Improved handling of failed DNS lookups
101 * - Fixed compiler warnings
103 * Revision 1.9 2001/10/25 03:40:48 david__schmidt
104 * Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
105 * threads to call select() simultaneously. So, it's time to do a real, live,
106 * native OS/2 port. See defines for __EMX__ (the porting layer) vs. __OS2__
107 * (native). Both versions will work, but using __OS2__ offers multi-threading.
109 * Revision 1.8 2001/09/13 20:10:12 jongfoster
110 * Fixing missing #include under Windows
112 * Revision 1.7 2001/09/12 17:58:26 steudten
114 * add #include <string.h>
116 * Revision 1.6 2001/09/10 10:41:16 oes
117 * Added #include in.h
119 * Revision 1.5 2001/07/29 18:47:57 jongfoster
120 * Adding missing #include project.h
122 * Revision 1.4 2001/07/24 12:47:06 oes
123 * Applied BeOS support update by Eugenia
125 * Revision 1.3 2001/06/09 10:55:28 jongfoster
126 * Changing BUFSIZ ==> BUFFER_SIZE
128 * Revision 1.2 2001/06/07 23:11:38 jongfoster
129 * Removing gateways[] list - no longer used.
130 * Replacing function pointer in struct gateway with a directly
131 * called function forwarded_connect(), which can do the common
132 * task of deciding whether to connect to the web server or HTTP
134 * Replacing struct gateway with struct forward_spec
135 * Fixing bug with SOCKS4A and HTTP proxy server in combination.
136 * It was a bug which led to the connection being made to the web
137 * server rather than the HTTP proxy, and also a buffer overrun.
139 * Revision 1.1.1.1 2001/05/15 13:58:54 oes
140 * Initial import of version 2.9.3 source tree
143 *********************************************************************/
149 #include <sys/types.h>
152 #include <netinet/in.h>
160 #include <winsock2.h>
161 #endif /* def _WIN32 */
165 #endif /* def __BEOS__ */
169 #endif /* def __OS2__ */
174 #include "jbsockets.h"
176 #include "miscutil.h"
178 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
180 static jb_socket socks4_connect(const struct forward_spec * fwd,
181 const char * target_host,
183 struct client_state *csp);
185 static jb_socket socks5_connect(const struct forward_spec *fwd,
186 const char *target_host,
188 struct client_state *csp);
191 #define SOCKS_REQUEST_GRANTED 90
192 #define SOCKS_REQUEST_REJECT 91
193 #define SOCKS_REQUEST_IDENT_FAILED 92
194 #define SOCKS_REQUEST_IDENT_CONFLICT 93
196 #define SOCKS5_REQUEST_GRANTED 0
197 #define SOCKS5_REQUEST_FAILED 1
198 #define SOCKS5_REQUEST_DENIED 2
199 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
200 #define SOCKS5_REQUEST_HOST_UNREACHABLE 4
201 #define SOCKS5_REQUEST_CONNECTION_REFUSEDD 5
202 #define SOCKS5_REQUEST_TTL_EXPIRED 6
203 #define SOCKS5_REQUEST_PROTOCOL_ERROR 7
204 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE 8
206 /* structure of a socks client operation */
208 unsigned char vn; /* socks version number */
209 unsigned char cd; /* command code */
210 unsigned char dstport[2]; /* destination port */
211 unsigned char dstip[4]; /* destination address */
212 char userid; /* first byte of userid */
213 char padding[3]; /* make sure sizeof(struct socks_op) is endian-independent. */
214 /* more bytes of the userid follow, terminated by a NULL */
217 /* structure of a socks server reply */
219 unsigned char vn; /* socks version number */
220 unsigned char cd; /* command code */
221 unsigned char dstport[2]; /* destination port */
222 unsigned char dstip[4]; /* destination address */
225 static const char socks_userid[] = "anonymous";
228 /*********************************************************************
230 * Function : forwarded_connect
232 * Description : Connect to a specified web server, possibly via
233 * a HTTP proxy and/or a SOCKS proxy.
236 * 1 : fwd = the proxies to use when connecting.
237 * 2 : http = the http request and apropos headers
238 * 3 : csp = Current client state (buffers, headers, etc...)
240 * Returns : JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
242 *********************************************************************/
243 jb_socket forwarded_connect(const struct forward_spec * fwd,
244 struct http_request *http,
245 struct client_state *csp)
247 const char * dest_host;
250 /* Figure out if we need to connect to the web server or a HTTP proxy. */
251 if (fwd->forward_host)
254 dest_host = fwd->forward_host;
255 dest_port = fwd->forward_port;
260 dest_host = http->host;
261 dest_port = http->port;
264 /* Connect, maybe using a SOCKS proxy */
268 return (connect_to(dest_host, dest_port, csp));
272 return (socks4_connect(fwd, dest_host, dest_port, csp));
275 return (socks5_connect(fwd, dest_host, dest_port, csp));
278 /* Should never get here */
279 log_error(LOG_LEVEL_FATAL, "SOCKS4 impossible internal error - bad SOCKS type.");
281 return(JB_INVALID_SOCKET);
286 /*********************************************************************
288 * Function : socks4_connect
290 * Description : Connect to the SOCKS server, and connect through
291 * it to the specified server. This handles
292 * all the SOCKS negotiation, and returns a file
293 * descriptor for a socket which can be treated as a
294 * normal (non-SOCKS) socket.
296 * Logged error messages are saved to csp->error_message
297 * and later reused by error_response() for the CGI
298 * message. strdup allocation failures are handled there.
301 * 1 : fwd = Specifies the SOCKS proxy to use.
302 * 2 : target_host = The final server to connect to.
303 * 3 : target_port = The final port to connect to.
304 * 4 : csp = Current client state (buffers, headers, etc...)
306 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
308 *********************************************************************/
309 static jb_socket socks4_connect(const struct forward_spec * fwd,
310 const char * target_host,
312 struct client_state *csp)
314 unsigned int web_server_addr;
315 char buf[BUFFER_SIZE];
316 struct socks_op *c = (struct socks_op *)buf;
317 struct socks_reply *s = (struct socks_reply *)buf;
324 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
326 /* XXX: Shouldn't the config file parser prevent this? */
327 errstr = "NULL gateway host specified.";
331 if (fwd->gateway_port <= 0)
333 errstr = "invalid gateway port specified.";
339 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
340 csp->error_message = strdup(errstr);
342 return(JB_INVALID_SOCKET);
345 /* build a socks request for connection to the web server */
347 strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
349 csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
354 web_server_addr = resolve_hostname_to_ip(target_host);
355 if (web_server_addr == INADDR_NONE)
357 errstr = "could not resolve target host";
358 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
363 web_server_addr = htonl(web_server_addr);
367 web_server_addr = 0x00000001;
368 n = csiz + strlen(target_host) + 1;
372 errstr = "buffer cbuf too small.";
373 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
378 strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
380 * What we forward to the socks4a server should have the
381 * size of socks_op, plus the length of the userid plus
382 * its \0 byte (which we don't have to add because the
383 * first byte of the userid is counted twice as it's also
384 * part of sock_op) minus the padding bytes (which are part
385 * of the userid as well), plus the length of the target_host
386 * (which is stored csiz bytes after the beginning of the buffer),
387 * plus another \0 byte.
389 assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
394 /* Should never get here */
395 log_error(LOG_LEVEL_FATAL,
396 "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
398 return(JB_INVALID_SOCKET);
403 csp->error_message = strdup(errstr);
404 return(JB_INVALID_SOCKET);
409 c->dstport[0] = (unsigned char)((target_port >> 8 ) & 0xff);
410 c->dstport[1] = (unsigned char)((target_port ) & 0xff);
411 c->dstip[0] = (unsigned char)((web_server_addr >> 24 ) & 0xff);
412 c->dstip[1] = (unsigned char)((web_server_addr >> 16 ) & 0xff);
413 c->dstip[2] = (unsigned char)((web_server_addr >> 8 ) & 0xff);
414 c->dstip[3] = (unsigned char)((web_server_addr ) & 0xff);
416 /* pass the request to the socks server */
417 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
419 if (sfd == JB_INVALID_SOCKET)
422 * XXX: connect_to should fill in the exact reason.
423 * Most likely resolving the IP of the forwarder failed.
425 errstr = "connect_to failed: see logfile for details";
428 else if (write_socket(sfd, (char *)c, csiz))
430 errstr = "SOCKS4 negotiation write failed.";
431 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
435 else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
437 errstr = "SOCKS4 negotiation read failed.";
438 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
445 csp->error_message = strdup(errstr);
446 return(JB_INVALID_SOCKET);
451 case SOCKS_REQUEST_GRANTED:
454 case SOCKS_REQUEST_REJECT:
455 errstr = "SOCKS request rejected or failed.";
458 case SOCKS_REQUEST_IDENT_FAILED:
459 errstr = "SOCKS request rejected because "
460 "SOCKS server cannot connect to identd on the client.";
463 case SOCKS_REQUEST_IDENT_CONFLICT:
464 errstr = "SOCKS request rejected because "
465 "the client program and identd report "
466 "different user-ids.";
471 snprintf(buf, sizeof(buf),
472 "SOCKS request rejected for reason code %d.", s->cd);
476 log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
477 csp->error_message = strdup(errstr);
480 return(JB_INVALID_SOCKET);
484 /*********************************************************************
486 * Function : translate_socks5_error
488 * Description : Translates a SOCKS errors to a string.
491 * 1 : socks_error = The error code to translate.
493 * Returns : The string translation.
495 *********************************************************************/
496 static const char *translate_socks5_error(int socks_error)
500 /* XXX: these should be more descriptive */
501 case SOCKS5_REQUEST_FAILED:
502 return "SOCKS5 request failed";
503 case SOCKS5_REQUEST_DENIED:
504 return "SOCKS5 request denied";
505 case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
506 return "SOCKS5 network unreachable";
507 case SOCKS5_REQUEST_HOST_UNREACHABLE:
508 return "SOCKS5 host unreachable";
509 case SOCKS5_REQUEST_CONNECTION_REFUSEDD:
510 return "SOCKS5 connection refused";
511 case SOCKS5_REQUEST_TTL_EXPIRED:
512 return "SOCKS5 TTL expired";
513 case SOCKS5_REQUEST_PROTOCOL_ERROR:
514 return "SOCKS5 client protocol error";
515 case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
516 return "SOCKS5 domain names unsupported";
517 case SOCKS5_REQUEST_GRANTED:
518 return "everything's peachy";
520 return "SOCKS5 negotiation protocol error";
524 /*********************************************************************
526 * Function : socks5_connect
528 * Description : Connect to the SOCKS server, and connect through
529 * it to the specified server. This handles
530 * all the SOCKS negotiation, and returns a file
531 * descriptor for a socket which can be treated as a
532 * normal (non-SOCKS) socket.
535 * 1 : fwd = Specifies the SOCKS proxy to use.
536 * 2 : target_host = The final server to connect to.
537 * 3 : target_port = The final port to connect to.
538 * 4 : csp = Current client state (buffers, headers, etc...)
540 * Returns : JB_INVALID_SOCKET => failure, else a socket file descriptor.
542 *********************************************************************/
543 static jb_socket socks5_connect(const struct forward_spec *fwd,
544 const char *target_host,
546 struct client_state *csp)
549 char cbuf[BUFFER_SIZE];
550 char sbuf[BUFFER_SIZE];
551 size_t client_pos = 0;
555 const char *errstr = NULL;
557 if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
559 errstr = "NULL gateway host specified";
563 if (fwd->gateway_port <= 0)
565 errstr = "invalid gateway port specified";
569 hostlen = strlen(target_host);
572 errstr = "target host name is longer than 255 characters";
576 if (fwd->type != SOCKS_5)
578 /* Should never get here */
579 log_error(LOG_LEVEL_FATAL,
580 "SOCKS5 impossible internal error - bad SOCKS type");
587 assert(errstr != NULL);
588 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
589 csp->error_message = strdup(errstr);
590 return(JB_INVALID_SOCKET);
593 /* pass the request to the socks server */
594 sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
596 if (sfd == JB_INVALID_SOCKET)
598 return(JB_INVALID_SOCKET);
602 cbuf[client_pos++] = '\x05'; /* Version */
603 cbuf[client_pos++] = '\x01'; /* One authentication method supported */
604 cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
606 if (write_socket(sfd, cbuf, client_pos))
608 errstr = "SOCKS5 negotiation write failed";
609 csp->error_message = strdup(errstr);
610 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
612 return(JB_INVALID_SOCKET);
615 if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
617 errstr = "SOCKS5 negotiation read failed";
621 if (!err && (sbuf[0] != '\x05'))
623 errstr = "SOCKS5 negotiation protocol version error";
627 if (!err && (sbuf[1] == '\xff'))
629 errstr = "SOCKS5 authentication required";
633 if (!err && (sbuf[1] != '\x00'))
635 errstr = "SOCKS5 negotiation protocol error";
641 assert(errstr != NULL);
642 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
643 csp->error_message = strdup(errstr);
646 return(JB_INVALID_SOCKET);
650 cbuf[client_pos++] = '\x05'; /* Version */
651 cbuf[client_pos++] = '\x01'; /* TCP connect */
652 cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
653 cbuf[client_pos++] = '\x03'; /* Address is domain name */
654 cbuf[client_pos++] = (char)(hostlen & 0xffu);
655 strncpy(cbuf + client_pos, target_host, 0xffu);
656 client_pos += (hostlen & 0xffu);
657 cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
658 cbuf[client_pos++] = (char)((target_port ) & 0xffu);
660 if (write_socket(sfd, cbuf, client_pos))
662 errstr = "SOCKS5 negotiation read failed";
663 csp->error_message = strdup(errstr);
664 log_error(LOG_LEVEL_CONNECT, "%s", errstr);
667 return(JB_INVALID_SOCKET);
670 server_size = read_socket(sfd, sbuf, sizeof(sbuf));
673 errstr = "SOCKS5 negotiation read failed";
677 if (!err && (sbuf[0] != '\x05'))
679 errstr = "SOCKS5 negotiation protocol version error";
683 if (!err && (sbuf[2] != '\x00'))
685 errstr = "SOCKS5 negotiation protocol error";
691 if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
695 errstr = translate_socks5_error(sbuf[1]);
699 assert(errstr != NULL);
700 csp->error_message = strdup(errstr);
701 log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
704 return(JB_INVALID_SOCKET);