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