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