Add changes from 3.0.6-2, 3.0.6-3 and several unreleased changes
[privoxy.git] / gateway.c
1 const char gateway_rcs[] = "$Id: gateway.c,v 1.19 2007/01/25 14:09:45 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/gateway.c,v $
5  *
6  * Purpose     :  Contains functions to connect to a server, possibly
7  *                using a "forwarder" (i.e. HTTP proxy and/or a SOCKS4
8  *                proxy).
9  *
10  * Copyright   :  Written by and Copyright (C) 2001-2007 the SourceForge
11  *                Privoxy team. http://www.privoxy.org/
12  *
13  *                Based on the Internet Junkbuster originally written
14  *                by and Copyright (C) 1997 Anonymous Coders and
15  *                Junkbusters Corporation.  http://www.junkbusters.com
16  *
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.
22  *
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.
28  *
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.
34  *
35  * Revisions   :
36  *    $Log: gateway.c,v $
37  *    Revision 1.19  2007/01/25 14:09:45  fabiankeil
38  *    - Save errors in socks4_connect() to csp->error_message.
39  *    - Silence some gcc43 warnings, hopefully the right way.
40  *
41  *    Revision 1.18  2006/07/18 14:48:46  david__schmidt
42  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
43  *    with what was really the latest development (the v_3_0_branch branch)
44  *
45  *    Revision 1.16  2002/05/12 21:36:29  jongfoster
46  *    Correcting function comments
47  *
48  *    Revision 1.15  2002/03/26 22:29:54  swa
49  *    we have a new homepage!
50  *
51  *    Revision 1.14  2002/03/24 13:25:43  swa
52  *    name change related issues
53  *
54  *    Revision 1.13  2002/03/13 00:29:59  jongfoster
55  *    Killing warnings
56  *
57  *    Revision 1.12  2002/03/09 20:03:52  jongfoster
58  *    - Making various functions return int rather than size_t.
59  *      (Undoing a recent change).  Since size_t is unsigned on
60  *      Windows, functions like read_socket that return -1 on
61  *      error cannot return a size_t.
62  *
63  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
64  *      crashes, and also frequently caused JB to jump to 100%
65  *      CPU and stay there.  (Because it thought it had just
66  *      read ((unsigned)-1) == 4Gb of data...)
67  *
68  *    - The signature of write_socket has changed, it now simply
69  *      returns success=0/failure=nonzero.
70  *
71  *    - Trying to get rid of a few warnings --with-debug on
72  *      Windows, I've introduced a new type "jb_socket".  This is
73  *      used for the socket file descriptors.  On Windows, this
74  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
75  *      an int.  The error value can't be -1 any more, so it's
76  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
77  *      Windows it maps to the #define INVALID_SOCKET.)
78  *
79  *    - The signature of bind_port has changed.
80  *
81  *    Revision 1.11  2002/03/08 17:46:04  jongfoster
82  *    Fixing int/size_t warnings
83  *
84  *    Revision 1.10  2002/03/07 03:50:19  oes
85  *     - Improved handling of failed DNS lookups
86  *     - Fixed compiler warnings
87  *
88  *    Revision 1.9  2001/10/25 03:40:48  david__schmidt
89  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
90  *    threads to call select() simultaneously.  So, it's time to do a real, live,
91  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
92  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
93  *
94  *    Revision 1.8  2001/09/13 20:10:12  jongfoster
95  *    Fixing missing #include under Windows
96  *
97  *    Revision 1.7  2001/09/12 17:58:26  steudten
98  *
99  *    add #include <string.h>
100  *
101  *    Revision 1.6  2001/09/10 10:41:16  oes
102  *    Added #include in.h
103  *
104  *    Revision 1.5  2001/07/29 18:47:57  jongfoster
105  *    Adding missing #include project.h
106  *
107  *    Revision 1.4  2001/07/24 12:47:06  oes
108  *    Applied BeOS support update by Eugenia
109  *
110  *    Revision 1.3  2001/06/09 10:55:28  jongfoster
111  *    Changing BUFSIZ ==> BUFFER_SIZE
112  *
113  *    Revision 1.2  2001/06/07 23:11:38  jongfoster
114  *    Removing gateways[] list - no longer used.
115  *    Replacing function pointer in struct gateway with a directly
116  *    called function forwarded_connect(), which can do the common
117  *    task of deciding whether to connect to the web server or HTTP
118  *    proxy.
119  *    Replacing struct gateway with struct forward_spec
120  *    Fixing bug with SOCKS4A and HTTP proxy server in combination.
121  *    It was a bug which led to the connection being made to the web
122  *    server rather than the HTTP proxy, and also a buffer overrun.
123  *
124  *    Revision 1.1.1.1  2001/05/15 13:58:54  oes
125  *    Initial import of version 2.9.3 source tree
126  *
127  *
128  *********************************************************************/
129 \f
130
131 #include "config.h"
132
133 #include <stdio.h>
134 #include <sys/types.h>
135
136 #ifndef _WIN32
137 #include <netinet/in.h>
138 #endif
139
140 #include <errno.h>
141 #include <string.h>
142 #include "assert.h"
143
144 #ifdef _WIN32
145 #include <winsock2.h>
146 #endif /* def _WIN32 */
147
148 #ifdef __BEOS__
149 #include <netdb.h>
150 #endif /* def __BEOS__ */
151
152 #ifdef __OS2__
153 #include <utils.h>
154 #endif /* def __OS2__ */
155
156 #include "project.h"
157 #include "jcc.h"
158 #include "errlog.h"
159 #include "jbsockets.h"
160 #include "gateway.h"
161 #include "miscutil.h"
162
163 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
164
165 static jb_socket socks4_connect(const struct forward_spec * fwd,
166                                 const char * target_host,
167                                 int target_port,
168                                 struct client_state *csp);
169
170
171 #define SOCKS_REQUEST_GRANTED          90
172 #define SOCKS_REQUEST_REJECT           91
173 #define SOCKS_REQUEST_IDENT_FAILED     92
174 #define SOCKS_REQUEST_IDENT_CONFLICT   93
175
176 /* structure of a socks client operation */
177 struct socks_op {
178    unsigned char vn;          /* socks version number */
179    unsigned char cd;          /* command code */
180    unsigned char dstport[2];  /* destination port */
181    unsigned char dstip[4];    /* destination address */
182    char userid;               /* first byte of userid */
183    /* more bytes of the userid follow, terminated by a NULL */
184 };
185
186 /* structure of a socks server reply */
187 struct socks_reply {
188    unsigned char vn;          /* socks version number */
189    unsigned char cd;          /* command code */
190    unsigned char dstport[2];  /* destination port */
191    unsigned char dstip[4];    /* destination address */
192 };
193
194 static const char socks_userid[] = "anonymous";
195
196
197 /*********************************************************************
198  *
199  * Function    :  forwarded_connect
200  *
201  * Description :  Connect to a specified web server, possibly via
202  *                a HTTP proxy and/or a SOCKS proxy.
203  *
204  * Parameters  :
205  *          1  :  fwd = the proxies to use when connecting.
206  *          2  :  http = the http request and apropos headers
207  *          3  :  csp = Current client state (buffers, headers, etc...)
208  *
209  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
210  *
211  *********************************************************************/
212 jb_socket forwarded_connect(const struct forward_spec * fwd,
213                             struct http_request *http,
214                             struct client_state *csp)
215 {
216    const char * dest_host;
217    int dest_port;
218
219    /* Figure out if we need to connect to the web server or a HTTP proxy. */
220    if (fwd->forward_host)
221    {
222       /* HTTP proxy */
223       dest_host = fwd->forward_host;
224       dest_port = fwd->forward_port;
225    }
226    else
227    {
228       /* Web server */
229       dest_host = http->host;
230       dest_port = http->port;
231    }
232
233    /* Connect, maybe using a SOCKS proxy */
234    switch (fwd->type)
235    {
236       case SOCKS_NONE:
237          return (connect_to(dest_host, dest_port, csp));
238
239       case SOCKS_4:
240       case SOCKS_4A:
241          return (socks4_connect(fwd, dest_host, dest_port, csp));
242
243       default:
244          /* Should never get here */
245          log_error(LOG_LEVEL_FATAL, "SOCKS4 impossible internal error - bad SOCKS type.");
246          errno = EINVAL;
247          return(JB_INVALID_SOCKET);
248    }
249 }
250
251
252 /*********************************************************************
253  *
254  * Function    :  socks4_connect
255  *
256  * Description :  Connect to the SOCKS server, and connect through
257  *                it to the specified server.   This handles
258  *                all the SOCKS negotiation, and returns a file
259  *                descriptor for a socket which can be treated as a
260  *                normal (non-SOCKS) socket.
261  *
262  *                Logged error messages are saved to csp->error_message
263  *                and later reused by error_response() for the CGI
264  *                message. strdup allocation failures are handled there.
265  *
266  * Parameters  :
267  *          1  :  fwd = Specifies the SOCKS proxy to use.
268  *          2  :  target_host = The final server to connect to.
269  *          3  :  target_port = The final port to connect to.
270  *          4  :  csp = Current client state (buffers, headers, etc...)
271  *
272  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
273  *
274  *********************************************************************/
275 static jb_socket socks4_connect(const struct forward_spec * fwd,
276                                 const char * target_host,
277                                 int target_port,
278                                 struct client_state *csp)
279 {
280    int web_server_addr;
281    char buf[BUFFER_SIZE];
282    struct socks_op    *c = (struct socks_op    *)buf;
283    struct socks_reply *s = (struct socks_reply *)buf;
284    size_t n;
285    size_t csiz;
286    jb_socket sfd;
287    int err = 0;
288    char *errstr = NULL;
289
290    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
291    {
292       /* XXX: Shouldn't the config file parser prevent this? */
293       errstr = "NULL gateway host specified.";
294       err = 1;
295    }
296
297    if (fwd->gateway_port <= 0)
298    {
299       errstr = "invalid gateway port specified.";
300       err = 1;
301    }
302
303    if (err)
304    {
305       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
306       csp->error_message = strdup(errstr); 
307       errno = EINVAL;
308       return(JB_INVALID_SOCKET);
309    }
310
311    /* build a socks request for connection to the web server */
312
313    strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
314
315    csiz = sizeof(*c) + sizeof(socks_userid) - 1;
316
317    switch (fwd->type)
318    {
319       case SOCKS_4:
320          web_server_addr = htonl(resolve_hostname_to_ip(target_host));
321          if (web_server_addr == INADDR_NONE)
322          {
323             errstr = "could not resolve target host";
324             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
325             err = 1;
326          }
327          break;
328       case SOCKS_4A:
329          web_server_addr = 0x00000001;
330          n = csiz + strlen(target_host) + 1;
331          if (n > sizeof(buf))
332          {
333             errno = EINVAL;
334             errstr = "buffer cbuf too small.";
335             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
336             err = 1;
337          }
338          else
339          {
340             strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
341             /*
342              * What we forward to the socks4a server should have the
343              * size of socks_op, plus the length of the userid plus
344              * its \0 byte (which we don't have to add because the
345              * first byte of the userid is counted twice as it's also
346              * part of sock_op), plus the length of the target_host
347              * (which is stored csiz bytes after the beginning of the buffer),
348              * plus another \0 byte.
349              */
350             assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) + strlen(buf + csiz) + 1);
351             csiz = n;
352          }
353          break;
354       default:
355          /* Should never get here */
356          log_error(LOG_LEVEL_FATAL,
357             "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
358          /* Not reached */
359          return(JB_INVALID_SOCKET);
360    }
361
362    if (err)
363    {
364       csp->error_message = strdup(errstr);
365       return(JB_INVALID_SOCKET);
366    }
367
368    c->vn          = 4;
369    c->cd          = 1;
370    c->dstport[0]  = (unsigned char)((target_port       >> 8  ) & 0xff);
371    c->dstport[1]  = (unsigned char)((target_port             ) & 0xff);
372    c->dstip[0]    = (unsigned char)((web_server_addr   >> 24 ) & 0xff);
373    c->dstip[1]    = (unsigned char)((web_server_addr   >> 16 ) & 0xff);
374    c->dstip[2]    = (unsigned char)((web_server_addr   >>  8 ) & 0xff);
375    c->dstip[3]    = (unsigned char)((web_server_addr         ) & 0xff);
376
377    /* pass the request to the socks server */
378    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
379
380    if (sfd == JB_INVALID_SOCKET)
381    {
382       /*
383        * XXX: connect_to should fill in the exact reason.
384        * Most likely resolving the IP of the forwarder failed.
385        */
386       errstr = "connect_to failed: see logfile for details";
387       err = 1;
388    }
389    else if (write_socket(sfd, (char *)c, csiz))
390    {
391       errstr = "SOCKS4 negotiation write failed.";
392       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
393       err = 1;
394       close_socket(sfd);
395    }
396    else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
397    {
398       errstr = "SOCKS4 negotiation read failed.";
399       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
400       err = 1;
401       close_socket(sfd);
402    }
403
404    if (err)
405    {
406       csp->error_message = strdup(errstr);      
407       return(JB_INVALID_SOCKET);
408    }
409
410    switch (s->cd)
411    {
412       case SOCKS_REQUEST_GRANTED:
413          return(sfd);
414          break;
415       case SOCKS_REQUEST_REJECT:
416          errstr = "SOCKS request rejected or failed.";
417          errno = EINVAL;
418          break;
419       case SOCKS_REQUEST_IDENT_FAILED:
420          errstr = "SOCKS request rejected because "
421             "SOCKS server cannot connect to identd on the client.";
422          errno = EACCES;
423          break;
424       case SOCKS_REQUEST_IDENT_CONFLICT:
425          errstr = "SOCKS request rejected because "
426             "the client program and identd report "
427             "different user-ids.";
428          errno = EACCES;
429          break;
430       default:
431          errno = ENOENT;
432          snprintf(buf, sizeof(buf),
433             "SOCKS request rejected for reason code %d.", s->cd);
434          errstr = buf;
435    }
436
437    log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
438    csp->error_message = strdup(errstr);
439    close_socket(sfd);
440
441    return(JB_INVALID_SOCKET);
442
443 }
444
445
446 /*
447   Local Variables:
448   tab-width: 3
449   end:
450 */