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