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