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