Add missing dots for two log messages.
[privoxy.git] / gateway.c
1 const char gateway_rcs[] = "$Id: gateway.c,v 1.28 2008/10/09 18:21:41 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-2008 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.28  2008/10/09 18:21:41  fabiankeil
38  *    Flush work-in-progress changes to keep outgoing connections
39  *    alive where possible. Incomplete and mostly #ifdef'd out.
40  *
41  *    Revision 1.27  2008/09/27 15:05:51  fabiankeil
42  *    Return only once in forwarded_connect().
43  *
44  *    Revision 1.26  2008/08/18 17:42:06  fabiankeil
45  *    Fix typo in macro name.
46  *
47  *    Revision 1.25  2008/02/07 18:09:46  fabiankeil
48  *    In socks5_connect:
49  *    - make the buffers quite a bit smaller.
50  *    - properly report "socks5 server unreachable" failures.
51  *    - let strncpy() use the whole buffer. Using a length of 0xffu wasn't actually
52  *      wrong, but requires too much thinking as it doesn't depend on the buffer size.
53  *    - log a message if the socks5 server sends more data than expected.
54  *    - add some assertions and comments.
55  *
56  *    Revision 1.24  2008/02/04 14:56:29  fabiankeil
57  *    - Fix a compiler warning.
58  *    - Stop assuming that htonl(INADDR_NONE) equals INADDR_NONE.
59  *
60  *    Revision 1.23  2008/02/04 13:11:35  fabiankeil
61  *    Remember the cause of the SOCKS5 error for the CGI message.
62  *
63  *    Revision 1.22  2008/02/03 13:46:15  fabiankeil
64  *    Add SOCKS5 support. Patch #1862863 by Eric M. Hopper with minor changes.
65  *
66  *    Revision 1.21  2007/07/28 12:30:03  fabiankeil
67  *    Modified patch from Song Weijia (#1762559) to
68  *    fix socks requests on big-endian platforms.
69  *
70  *    Revision 1.20  2007/05/14 10:23:48  fabiankeil
71  *    - Use strlcpy() instead of strcpy().
72  *    - Use the same buffer for socks requests and socks responses.
73  *    - Fix bogus warning about web_server_addr being used uninitialized.
74  *
75  *    Revision 1.19  2007/01/25 14:09:45  fabiankeil
76  *    - Save errors in socks4_connect() to csp->error_message.
77  *    - Silence some gcc43 warnings, hopefully the right way.
78  *
79  *    Revision 1.18  2006/07/18 14:48:46  david__schmidt
80  *    Reorganizing the repository: swapping out what was HEAD (the old 3.1 branch)
81  *    with what was really the latest development (the v_3_0_branch branch)
82  *
83  *    Revision 1.16  2002/05/12 21:36:29  jongfoster
84  *    Correcting function comments
85  *
86  *    Revision 1.15  2002/03/26 22:29:54  swa
87  *    we have a new homepage!
88  *
89  *    Revision 1.14  2002/03/24 13:25:43  swa
90  *    name change related issues
91  *
92  *    Revision 1.13  2002/03/13 00:29:59  jongfoster
93  *    Killing warnings
94  *
95  *    Revision 1.12  2002/03/09 20:03:52  jongfoster
96  *    - Making various functions return int rather than size_t.
97  *      (Undoing a recent change).  Since size_t is unsigned on
98  *      Windows, functions like read_socket that return -1 on
99  *      error cannot return a size_t.
100  *
101  *      THIS WAS A MAJOR BUG - it caused frequent, unpredictable
102  *      crashes, and also frequently caused JB to jump to 100%
103  *      CPU and stay there.  (Because it thought it had just
104  *      read ((unsigned)-1) == 4Gb of data...)
105  *
106  *    - The signature of write_socket has changed, it now simply
107  *      returns success=0/failure=nonzero.
108  *
109  *    - Trying to get rid of a few warnings --with-debug on
110  *      Windows, I've introduced a new type "jb_socket".  This is
111  *      used for the socket file descriptors.  On Windows, this
112  *      is SOCKET (a typedef for unsigned).  Everywhere else, it's
113  *      an int.  The error value can't be -1 any more, so it's
114  *      now JB_INVALID_SOCKET (which is -1 on UNIX, and in
115  *      Windows it maps to the #define INVALID_SOCKET.)
116  *
117  *    - The signature of bind_port has changed.
118  *
119  *    Revision 1.11  2002/03/08 17:46:04  jongfoster
120  *    Fixing int/size_t warnings
121  *
122  *    Revision 1.10  2002/03/07 03:50:19  oes
123  *     - Improved handling of failed DNS lookups
124  *     - Fixed compiler warnings
125  *
126  *    Revision 1.9  2001/10/25 03:40:48  david__schmidt
127  *    Change in porting tactics: OS/2's EMX porting layer doesn't allow multiple
128  *    threads to call select() simultaneously.  So, it's time to do a real, live,
129  *    native OS/2 port.  See defines for __EMX__ (the porting layer) vs. __OS2__
130  *    (native). Both versions will work, but using __OS2__ offers multi-threading.
131  *
132  *    Revision 1.8  2001/09/13 20:10:12  jongfoster
133  *    Fixing missing #include under Windows
134  *
135  *    Revision 1.7  2001/09/12 17:58:26  steudten
136  *
137  *    add #include <string.h>
138  *
139  *    Revision 1.6  2001/09/10 10:41:16  oes
140  *    Added #include in.h
141  *
142  *    Revision 1.5  2001/07/29 18:47:57  jongfoster
143  *    Adding missing #include project.h
144  *
145  *    Revision 1.4  2001/07/24 12:47:06  oes
146  *    Applied BeOS support update by Eugenia
147  *
148  *    Revision 1.3  2001/06/09 10:55:28  jongfoster
149  *    Changing BUFSIZ ==> BUFFER_SIZE
150  *
151  *    Revision 1.2  2001/06/07 23:11:38  jongfoster
152  *    Removing gateways[] list - no longer used.
153  *    Replacing function pointer in struct gateway with a directly
154  *    called function forwarded_connect(), which can do the common
155  *    task of deciding whether to connect to the web server or HTTP
156  *    proxy.
157  *    Replacing struct gateway with struct forward_spec
158  *    Fixing bug with SOCKS4A and HTTP proxy server in combination.
159  *    It was a bug which led to the connection being made to the web
160  *    server rather than the HTTP proxy, and also a buffer overrun.
161  *
162  *    Revision 1.1.1.1  2001/05/15 13:58:54  oes
163  *    Initial import of version 2.9.3 source tree
164  *
165  *
166  *********************************************************************/
167 \f
168
169 #include "config.h"
170
171 #include <stdio.h>
172 #include <sys/types.h>
173
174 #ifndef _WIN32
175 #include <netinet/in.h>
176 #endif
177
178 #include <errno.h>
179 #include <string.h>
180 #include "assert.h"
181
182 #ifdef _WIN32
183 #include <winsock2.h>
184 #endif /* def _WIN32 */
185
186 #ifdef __BEOS__
187 #include <netdb.h>
188 #endif /* def __BEOS__ */
189
190 #ifdef __OS2__
191 #include <utils.h>
192 #endif /* def __OS2__ */
193
194 #include "project.h"
195 #include "jcc.h"
196 #include "errlog.h"
197 #include "jbsockets.h"
198 #include "gateway.h"
199 #include "miscutil.h"
200 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
201 #ifdef __GLIBC__
202 #include <sys/poll.h>
203 #endif /* __GLIBC__ */
204 #include <poll.h>
205 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
206
207 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
208
209 static jb_socket socks4_connect(const struct forward_spec * fwd,
210                                 const char * target_host,
211                                 int target_port,
212                                 struct client_state *csp);
213
214 static jb_socket socks5_connect(const struct forward_spec *fwd,
215                                 const char *target_host,
216                                 int target_port,
217                                 struct client_state *csp);
218
219
220 #define SOCKS_REQUEST_GRANTED          90
221 #define SOCKS_REQUEST_REJECT           91
222 #define SOCKS_REQUEST_IDENT_FAILED     92
223 #define SOCKS_REQUEST_IDENT_CONFLICT   93
224
225 #define SOCKS5_REQUEST_GRANTED             0
226 #define SOCKS5_REQUEST_FAILED              1
227 #define SOCKS5_REQUEST_DENIED              2
228 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
229 #define SOCKS5_REQUEST_HOST_UNREACHABLE    4
230 #define SOCKS5_REQUEST_CONNECTION_REFUSED  5
231 #define SOCKS5_REQUEST_TTL_EXPIRED         6
232 #define SOCKS5_REQUEST_PROTOCOL_ERROR      7
233 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE    8
234
235 /* structure of a socks client operation */
236 struct socks_op {
237    unsigned char vn;          /* socks version number */
238    unsigned char cd;          /* command code */
239    unsigned char dstport[2];  /* destination port */
240    unsigned char dstip[4];    /* destination address */
241    char userid;               /* first byte of userid */
242    char padding[3];           /* make sure sizeof(struct socks_op) is endian-independent. */
243    /* more bytes of the userid follow, terminated by a NULL */
244 };
245
246 /* structure of a socks server reply */
247 struct socks_reply {
248    unsigned char vn;          /* socks version number */
249    unsigned char cd;          /* command code */
250    unsigned char dstport[2];  /* destination port */
251    unsigned char dstip[4];    /* destination address */
252 };
253
254 static const char socks_userid[] = "anonymous";
255
256 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
257
258 #define MAX_REUSABLE_CONNECTIONS 100
259
260 struct reusable_connection
261 {
262    jb_socket sfd;
263    int       in_use;
264    char      *host;
265    int       port;
266
267    int       forwarder_type;
268    char      *gateway_host;
269    int       gateway_port;
270    char      *forward_host;
271    int       forward_port;
272 };
273
274 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
275
276 static int mark_connection_unused(jb_socket sfd);
277 static void mark_connection_closed(struct reusable_connection *closed_connection);
278
279 /*********************************************************************
280  *
281  * Function    :  initialize_reusable_connections
282  *
283  * Description :  Initializes the reusable_connection structures.
284  *                Must be called with connection_reuse_mutex locked.
285  *
286  * Parameters  : N/A
287  *
288  * Returns     : void
289  *
290  *********************************************************************/
291 extern void initialize_reusable_connections(void)
292 {
293    unsigned int slot = 0;
294
295    log_error(LOG_LEVEL_INFO,
296       "Support for 'Connection: keep-alive' is experimental, "
297       "incomplete and known not to work properly in some situations.");
298
299    for (slot = 0; slot < SZ(reusable_connection); slot++)
300    {
301       mark_connection_closed(&reusable_connection[slot]);
302    }
303
304    log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
305 }
306
307
308 /*********************************************************************
309  *
310  * Function    :  remember_connection
311  *
312  * Description :  Remembers a connection for reuse later on.
313  *
314  * Parameters  :
315  *          1  :  sfd  = Open socket to remember.
316  *          2  :  http = The destination for the connection.
317  *          3  :  fwd  = The forwarder settings used.
318  *
319  * Returns     : void
320  *
321  *********************************************************************/
322 void remember_connection(jb_socket sfd, const struct http_request *http,
323                                         const struct forward_spec *fwd)
324 {
325    unsigned int slot = 0;
326    int free_slot_found = FALSE;
327
328    assert(sfd != JB_INVALID_SOCKET);
329
330    if (mark_connection_unused(sfd))
331    {
332       return;
333    }
334
335    privoxy_mutex_lock(&connection_reuse_mutex);
336
337    /* Find free socket slot. */
338    for (slot = 0; slot < SZ(reusable_connection); slot++)
339    {
340       if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
341       {
342          assert(reusable_connection[slot].in_use == 0);
343          log_error(LOG_LEVEL_CONNECT,
344             "Remembering socket %d for %s:%d in slot %d.",
345             sfd, http->host, http->port, slot);
346          free_slot_found = TRUE;
347          break;
348       }
349    }
350
351    if (!free_slot_found)
352    {
353       log_error(LOG_LEVEL_CONNECT,
354         "No free slots found to remembering socket for %s:%d. Last slot %d.",
355         http->host, http->port, slot);
356       privoxy_mutex_unlock(&connection_reuse_mutex);
357       close_socket(sfd);
358       return;
359    }
360
361    assert(NULL != http->host);
362    reusable_connection[slot].host = strdup(http->host);
363    if (NULL == reusable_connection[slot].host)
364    {
365       log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
366    }
367    reusable_connection[slot].sfd = sfd;
368    reusable_connection[slot].port = http->port;
369    reusable_connection[slot].in_use = 0;
370
371    assert(NULL != fwd);
372    assert(reusable_connection[slot].gateway_host == NULL);
373    assert(reusable_connection[slot].gateway_port == 0);
374    assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
375    assert(reusable_connection[slot].forward_host == NULL);
376    assert(reusable_connection[slot].forward_port == 0);
377
378    reusable_connection[slot].forwarder_type = fwd->type;
379    if (NULL != fwd->gateway_host)
380    {
381       reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
382       if (NULL == reusable_connection[slot].gateway_host)
383       {
384          log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
385       }
386    }
387    else
388    {
389       reusable_connection[slot].gateway_host = NULL;
390    }
391    reusable_connection[slot].gateway_port = fwd->gateway_port;
392
393    if (NULL != fwd->forward_host)
394    {
395       reusable_connection[slot].forward_host = strdup(fwd->forward_host);
396       if (NULL == reusable_connection[slot].forward_host)
397       {
398          log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
399       }
400    }
401    else
402    {
403       reusable_connection[slot].forward_host = NULL;
404    }
405    reusable_connection[slot].forward_port = fwd->forward_port;
406
407    privoxy_mutex_unlock(&connection_reuse_mutex);
408 }
409
410
411 /*********************************************************************
412  *
413  * Function    :  mark_connection_closed
414  *
415  * Description : Marks a reused connection closed.
416  *               Must be called with connection_reuse_mutex locked.
417  *
418  * Parameters  :
419  *          1  :  closed_connection = The connection to mark as closed.
420  *
421  * Returns     : void
422  *
423  *********************************************************************/
424 static void mark_connection_closed(struct reusable_connection *closed_connection)
425 {
426    closed_connection->in_use = FALSE;
427    closed_connection->sfd = JB_INVALID_SOCKET;
428    freez(closed_connection->host);
429    closed_connection->port = 0;
430    closed_connection->forwarder_type = SOCKS_NONE;
431    freez(closed_connection->gateway_host);
432    closed_connection->gateway_port = 0;
433    freez(closed_connection->forward_host);
434    closed_connection->forward_port = 0;
435 }
436
437
438 /*********************************************************************
439  *
440  * Function    :  forget_connection
441  *
442  * Description :  Removes a previously remembered connection from
443  *                the list of reusable connections.
444  *
445  * Parameters  :
446  *          1  :  sfd = The socket belonging to the connection in question.
447  *
448  * Returns     : void
449  *
450  *********************************************************************/
451 void forget_connection(jb_socket sfd)
452 {
453    unsigned int slot = 0;
454
455    assert(sfd != JB_INVALID_SOCKET);
456
457    privoxy_mutex_lock(&connection_reuse_mutex);
458
459    for (slot = 0; slot < SZ(reusable_connection); slot++)
460    {
461       if (reusable_connection[slot].sfd == sfd)
462       {
463          assert(reusable_connection[slot].in_use);
464          break;
465       }
466    }
467
468    if (reusable_connection[slot].sfd != sfd)
469    {
470       log_error(LOG_LEVEL_CONNECT,
471         "Socket %d already forgotten or never remembered.", sfd);
472       privoxy_mutex_unlock(&connection_reuse_mutex);
473       return;
474    }
475
476    log_error(LOG_LEVEL_CONNECT,
477       "Forgetting socket %d for %s:%d in slot %d.",
478       sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
479
480    mark_connection_closed(&reusable_connection[slot]);
481
482    privoxy_mutex_unlock(&connection_reuse_mutex);
483 }
484
485
486 /*********************************************************************
487  *
488  * Function    :  connection_destination_matches
489  *
490  * Description :  Determines whether a remembered connection can
491  *                be reused. That is whether the destination and
492  *                the forwarding settings match.
493  *
494  * Parameters  :
495  *          1  :  connection = The connection to check.
496  *          2  :  http = The destination for the connection.
497  *          3  :  fwd  = The forwarder settings.
498  *
499  * Returns     :  TRUE for yes, FALSE otherwise.
500  *
501  *********************************************************************/
502 static int connection_destination_matches(const struct reusable_connection *connection,
503                                           const struct http_request *http,
504                                           const struct forward_spec *fwd)
505 {
506    /* XXX: Start of duplicated checks for debugging purposes. */
507    if (strcmpic(connection->host, http->host))
508    {
509       return FALSE;
510    }
511
512    if (connection->forwarder_type != fwd->type)
513    {
514       log_error(LOG_LEVEL_CONNECT, "Type mismatch: %d %d (%s)",
515          connection->forwarder_type, fwd->type, http->host);
516       return FALSE;
517    }
518    if (connection->gateway_port   != fwd->gateway_port)
519    {
520       log_error(LOG_LEVEL_CONNECT, "Gateway port mismatch: %d %d (%s)",
521          connection->gateway_port, fwd->gateway_port, http->host);
522       return FALSE;
523    }
524    if (connection->forward_port   != fwd->forward_port)
525    {
526       log_error(LOG_LEVEL_CONNECT, "Forward port mismatch: %d %d (%s)",
527          connection->forward_port, fwd->forward_port, http->host);
528       return FALSE;
529    }
530    if (connection->forward_port   != fwd->forward_port)
531    {
532       log_error(LOG_LEVEL_CONNECT, "Server port mismatch: %d %d (%s)",
533          connection->forward_port, fwd->forward_port, http->host);
534       return FALSE;
535    }
536
537    /* XXX: End of duplicated checks for debugging purposes. */
538
539    if ((connection->forwarder_type != fwd->type)
540     || (connection->gateway_port   != fwd->gateway_port)
541     || (connection->forward_port   != fwd->forward_port)
542     || (connection->port           != http->port))
543    {
544       return FALSE;
545    }
546
547    if ((    (NULL != connection->gateway_host)
548          && (NULL != fwd->gateway_host)
549          && strcmpic(connection->gateway_host, fwd->gateway_host))
550        && (connection->gateway_host != fwd->gateway_host))
551    {
552       log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
553       return FALSE;
554    }
555
556    if ((    (NULL != connection->forward_host)
557          && (NULL != fwd->forward_host)
558          && strcmpic(connection->forward_host, fwd->forward_host))
559       && (connection->forward_host != fwd->forward_host))
560    {
561       log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
562       return FALSE;
563    }
564
565    return (!strcmpic(connection->host, http->host));
566
567 }
568
569 /*********************************************************************
570  *
571  * Function    :  get_reusable_connection
572  *
573  * Description :  Returns an open socket to a previously remembered
574  *                open connection (if there is one).
575  *
576  * Parameters  :
577  *          1  :  http = The destination for the connection.
578  *          2  :  fwd  = The forwarder settings.
579  *
580  * Returns     :  JB_INVALID_SOCKET => No reusable connection found,
581  *                otherwise a usable socket.
582  *
583  *********************************************************************/
584 static jb_socket get_reusable_connection(const struct http_request *http,
585                                          const struct forward_spec *fwd)
586 {
587    jb_socket sfd = JB_INVALID_SOCKET;
588    unsigned int slot = 0;
589
590    privoxy_mutex_lock(&connection_reuse_mutex);
591
592    for (slot = 0; slot < SZ(reusable_connection); slot++)
593    {
594       if (!reusable_connection[slot].in_use
595          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
596       {
597          int poll_result;
598          struct pollfd poll_fd[1];
599          memset(poll_fd, 0, sizeof(poll_fd));
600          poll_fd[0].fd = reusable_connection[slot].sfd;
601          poll_fd[0].events = POLLIN;
602
603          poll_result = poll(poll_fd, 1, 0);
604
605          if (-1 != poll_result)
606          {
607             if ((poll_fd[0].revents & POLLIN))
608             {
609                log_error(LOG_LEVEL_CONNECT,
610                   "Socket %d for %s:%d in slot %d is no longer usable. Closing.",
611                   reusable_connection[slot].sfd, reusable_connection[slot].host,
612                   reusable_connection[slot].port, slot);
613                mark_connection_closed(&reusable_connection[slot]);
614             }
615          }
616          else
617          {
618             log_error(LOG_LEVEL_CONNECT,
619                "Failed to poll socket %d for %s:%d in slot %d.",
620                reusable_connection[slot].sfd, reusable_connection[slot].host,
621                reusable_connection[slot].port, slot);
622          }
623
624
625          if (connection_destination_matches(&reusable_connection[slot], http, fwd))
626          {
627             reusable_connection[slot].in_use = TRUE;
628             sfd = reusable_connection[slot].sfd;
629             log_error(LOG_LEVEL_CONNECT,
630                "Found reusable socket %d for %s:%d in slot %d.",
631                sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
632             break;
633          }
634       }
635    }
636
637    privoxy_mutex_unlock(&connection_reuse_mutex);
638
639    return sfd;
640
641 }
642
643
644 /*********************************************************************
645  *
646  * Function    :  mark_connection_unused
647  *
648  * Description :  Gives a remembered connection free for reuse.
649  *
650  * Parameters  :
651  *          1  :  sfd = The socket belonging to the connection in question.
652  *
653  * Returns     :  TRUE => Socket found and marked as unused.
654  *                FALSE => Socket not found.
655  *
656  *********************************************************************/
657 static int mark_connection_unused(jb_socket sfd)
658 {
659    unsigned int slot = 0;
660    unsigned int socket_found = FALSE;
661
662    assert(sfd != JB_INVALID_SOCKET);
663
664    privoxy_mutex_lock(&connection_reuse_mutex);
665
666    for (slot = 0; slot < SZ(reusable_connection); slot++)
667    {
668       if (reusable_connection[slot].sfd == sfd)
669       {
670          assert(reusable_connection[slot].in_use);
671          break;
672       }
673    }
674
675    if (reusable_connection[slot].sfd == sfd)
676    {
677       socket_found = TRUE;
678       log_error(LOG_LEVEL_CONNECT,
679          "Marking open socket %d for %s:%d in slot %d as unused.",
680          sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
681       reusable_connection[slot].in_use = 0;
682    }
683
684    privoxy_mutex_unlock(&connection_reuse_mutex);
685
686    return socket_found;
687
688 }
689 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
690
691
692 /*********************************************************************
693  *
694  * Function    :  forwarded_connect
695  *
696  * Description :  Connect to a specified web server, possibly via
697  *                a HTTP proxy and/or a SOCKS proxy.
698  *
699  * Parameters  :
700  *          1  :  fwd = the proxies to use when connecting.
701  *          2  :  http = the http request and apropos headers
702  *          3  :  csp = Current client state (buffers, headers, etc...)
703  *
704  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
705  *
706  *********************************************************************/
707 jb_socket forwarded_connect(const struct forward_spec * fwd,
708                             struct http_request *http,
709                             struct client_state *csp)
710 {
711    const char * dest_host;
712    int dest_port;
713    jb_socket sfd = JB_INVALID_SOCKET;
714
715 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
716    sfd = get_reusable_connection(http, fwd);
717    if (JB_INVALID_SOCKET == sfd)
718    {
719       log_error(LOG_LEVEL_CONNECT,
720          "No reusable socket for %s:%d found. Opening a new one.",
721          http->host, http->port);
722    }
723    else
724    {
725       return sfd;
726    }
727 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
728
729    /* Figure out if we need to connect to the web server or a HTTP proxy. */
730    if (fwd->forward_host)
731    {
732       /* HTTP proxy */
733       dest_host = fwd->forward_host;
734       dest_port = fwd->forward_port;
735    }
736    else
737    {
738       /* Web server */
739       dest_host = http->host;
740       dest_port = http->port;
741    }
742
743    /* Connect, maybe using a SOCKS proxy */
744    switch (fwd->type)
745    {
746       case SOCKS_NONE:
747          sfd = connect_to(dest_host, dest_port, csp);
748          break;
749       case SOCKS_4:
750       case SOCKS_4A:
751          sfd = socks4_connect(fwd, dest_host, dest_port, csp);
752          break;
753       case SOCKS_5:
754          sfd = socks5_connect(fwd, dest_host, dest_port, csp);
755          break;
756       default:
757          /* Should never get here */
758          log_error(LOG_LEVEL_FATAL,
759             "SOCKS4 impossible internal error - bad SOCKS type.");
760    }
761
762    return sfd;
763
764 }
765
766
767 /*********************************************************************
768  *
769  * Function    :  socks4_connect
770  *
771  * Description :  Connect to the SOCKS server, and connect through
772  *                it to the specified server.   This handles
773  *                all the SOCKS negotiation, and returns a file
774  *                descriptor for a socket which can be treated as a
775  *                normal (non-SOCKS) socket.
776  *
777  *                Logged error messages are saved to csp->error_message
778  *                and later reused by error_response() for the CGI
779  *                message. strdup allocation failures are handled there.
780  *
781  * Parameters  :
782  *          1  :  fwd = Specifies the SOCKS proxy to use.
783  *          2  :  target_host = The final server to connect to.
784  *          3  :  target_port = The final port to connect to.
785  *          4  :  csp = Current client state (buffers, headers, etc...)
786  *
787  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
788  *
789  *********************************************************************/
790 static jb_socket socks4_connect(const struct forward_spec * fwd,
791                                 const char * target_host,
792                                 int target_port,
793                                 struct client_state *csp)
794 {
795    unsigned int web_server_addr;
796    char buf[BUFFER_SIZE];
797    struct socks_op    *c = (struct socks_op    *)buf;
798    struct socks_reply *s = (struct socks_reply *)buf;
799    size_t n;
800    size_t csiz;
801    jb_socket sfd;
802    int err = 0;
803    char *errstr = NULL;
804
805    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
806    {
807       /* XXX: Shouldn't the config file parser prevent this? */
808       errstr = "NULL gateway host specified.";
809       err = 1;
810    }
811
812    if (fwd->gateway_port <= 0)
813    {
814       errstr = "invalid gateway port specified.";
815       err = 1;
816    }
817
818    if (err)
819    {
820       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
821       csp->error_message = strdup(errstr); 
822       errno = EINVAL;
823       return(JB_INVALID_SOCKET);
824    }
825
826    /* build a socks request for connection to the web server */
827
828    strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
829
830    csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
831
832    switch (fwd->type)
833    {
834       case SOCKS_4:
835          web_server_addr = resolve_hostname_to_ip(target_host);
836          if (web_server_addr == INADDR_NONE)
837          {
838             errstr = "could not resolve target host";
839             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
840             err = 1;
841          }
842          else
843          {
844             web_server_addr = htonl(web_server_addr);
845          }
846          break;
847       case SOCKS_4A:
848          web_server_addr = 0x00000001;
849          n = csiz + strlen(target_host) + 1;
850          if (n > sizeof(buf))
851          {
852             errno = EINVAL;
853             errstr = "buffer cbuf too small.";
854             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
855             err = 1;
856          }
857          else
858          {
859             strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
860             /*
861              * What we forward to the socks4a server should have the
862              * size of socks_op, plus the length of the userid plus
863              * its \0 byte (which we don't have to add because the
864              * first byte of the userid is counted twice as it's also
865              * part of sock_op) minus the padding bytes (which are part
866              * of the userid as well), plus the length of the target_host
867              * (which is stored csiz bytes after the beginning of the buffer),
868              * plus another \0 byte.
869              */
870             assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
871             csiz = n;
872          }
873          break;
874       default:
875          /* Should never get here */
876          log_error(LOG_LEVEL_FATAL,
877             "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
878          /* Not reached */
879          return(JB_INVALID_SOCKET);
880    }
881
882    if (err)
883    {
884       csp->error_message = strdup(errstr);
885       return(JB_INVALID_SOCKET);
886    }
887
888    c->vn          = 4;
889    c->cd          = 1;
890    c->dstport[0]  = (unsigned char)((target_port       >> 8  ) & 0xff);
891    c->dstport[1]  = (unsigned char)((target_port             ) & 0xff);
892    c->dstip[0]    = (unsigned char)((web_server_addr   >> 24 ) & 0xff);
893    c->dstip[1]    = (unsigned char)((web_server_addr   >> 16 ) & 0xff);
894    c->dstip[2]    = (unsigned char)((web_server_addr   >>  8 ) & 0xff);
895    c->dstip[3]    = (unsigned char)((web_server_addr         ) & 0xff);
896
897    /* pass the request to the socks server */
898    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
899
900    if (sfd == JB_INVALID_SOCKET)
901    {
902       /*
903        * XXX: connect_to should fill in the exact reason.
904        * Most likely resolving the IP of the forwarder failed.
905        */
906       errstr = "connect_to failed: see logfile for details";
907       err = 1;
908    }
909    else if (write_socket(sfd, (char *)c, csiz))
910    {
911       errstr = "SOCKS4 negotiation write failed.";
912       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
913       err = 1;
914       close_socket(sfd);
915    }
916    else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
917    {
918       errstr = "SOCKS4 negotiation read failed.";
919       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
920       err = 1;
921       close_socket(sfd);
922    }
923
924    if (err)
925    {
926       csp->error_message = strdup(errstr);      
927       return(JB_INVALID_SOCKET);
928    }
929
930    switch (s->cd)
931    {
932       case SOCKS_REQUEST_GRANTED:
933          return(sfd);
934          break;
935       case SOCKS_REQUEST_REJECT:
936          errstr = "SOCKS request rejected or failed.";
937          errno = EINVAL;
938          break;
939       case SOCKS_REQUEST_IDENT_FAILED:
940          errstr = "SOCKS request rejected because "
941             "SOCKS server cannot connect to identd on the client.";
942          errno = EACCES;
943          break;
944       case SOCKS_REQUEST_IDENT_CONFLICT:
945          errstr = "SOCKS request rejected because "
946             "the client program and identd report "
947             "different user-ids.";
948          errno = EACCES;
949          break;
950       default:
951          errno = ENOENT;
952          snprintf(buf, sizeof(buf),
953             "SOCKS request rejected for reason code %d.", s->cd);
954          errstr = buf;
955    }
956
957    log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
958    csp->error_message = strdup(errstr);
959    close_socket(sfd);
960
961    return(JB_INVALID_SOCKET);
962
963 }
964
965 /*********************************************************************
966  *
967  * Function    :  translate_socks5_error
968  *
969  * Description :  Translates a SOCKS errors to a string.
970  *
971  * Parameters  :
972  *          1  :  socks_error = The error code to translate.
973  *
974  * Returns     :  The string translation.
975  *
976  *********************************************************************/
977 static const char *translate_socks5_error(int socks_error)
978 {
979    switch (socks_error)
980    {
981       /* XXX: these should be more descriptive */
982       case SOCKS5_REQUEST_FAILED:
983          return "SOCKS5 request failed";
984       case SOCKS5_REQUEST_DENIED:
985          return "SOCKS5 request denied";
986       case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
987          return "SOCKS5 network unreachable";
988       case SOCKS5_REQUEST_HOST_UNREACHABLE:
989          return "SOCKS5 host unreachable";
990       case SOCKS5_REQUEST_CONNECTION_REFUSED:
991          return "SOCKS5 connection refused";
992       case SOCKS5_REQUEST_TTL_EXPIRED:
993          return "SOCKS5 TTL expired";
994       case SOCKS5_REQUEST_PROTOCOL_ERROR:
995          return "SOCKS5 client protocol error";
996       case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
997          return "SOCKS5 domain names unsupported";
998       case SOCKS5_REQUEST_GRANTED:
999          return "everything's peachy";
1000       default:
1001          return "SOCKS5 negotiation protocol error";
1002    }
1003 }
1004
1005 /*********************************************************************
1006  *
1007  * Function    :  socks5_connect
1008  *
1009  * Description :  Connect to the SOCKS server, and connect through
1010  *                it to the specified server.   This handles
1011  *                all the SOCKS negotiation, and returns a file
1012  *                descriptor for a socket which can be treated as a
1013  *                normal (non-SOCKS) socket.
1014  *
1015  * Parameters  :
1016  *          1  :  fwd = Specifies the SOCKS proxy to use.
1017  *          2  :  target_host = The final server to connect to.
1018  *          3  :  target_port = The final port to connect to.
1019  *          4  :  csp = Current client state (buffers, headers, etc...)
1020  *
1021  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
1022  *
1023  *********************************************************************/
1024 static jb_socket socks5_connect(const struct forward_spec *fwd,
1025                                 const char *target_host,
1026                                 int target_port,
1027                                 struct client_state *csp)
1028 {
1029    int err = 0;
1030    char cbuf[300];
1031    char sbuf[30];
1032    size_t client_pos = 0;
1033    int server_size = 0;
1034    size_t hostlen = 0;
1035    jb_socket sfd;
1036    const char *errstr = NULL;
1037
1038    assert(fwd->gateway_host);
1039    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1040    {
1041       errstr = "NULL gateway host specified";
1042       err = 1;
1043    }
1044
1045    if (fwd->gateway_port <= 0)
1046    {
1047       /*
1048        * XXX: currently this can't happen because in
1049        * case of invalid gateway ports we use the defaults.
1050        * Of course we really shouldn't do that.
1051        */
1052       errstr = "invalid gateway port specified";
1053       err = 1;
1054    }
1055
1056    hostlen = strlen(target_host);
1057    if (hostlen > 255)
1058    {
1059       errstr = "target host name is longer than 255 characters";
1060       err = 1;
1061    }
1062
1063    if (fwd->type != SOCKS_5)
1064    {
1065       /* Should never get here */
1066       log_error(LOG_LEVEL_FATAL,
1067          "SOCKS5 impossible internal error - bad SOCKS type");
1068       err = 1;
1069    }
1070
1071    if (err)
1072    {
1073       errno = EINVAL;
1074       assert(errstr != NULL);
1075       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1076       csp->error_message = strdup(errstr);
1077       return(JB_INVALID_SOCKET);
1078    }
1079
1080    /* pass the request to the socks server */
1081    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1082
1083    if (sfd == JB_INVALID_SOCKET)
1084    {
1085       errstr = "socks5 server unreachable";
1086       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1087       csp->error_message = strdup(errstr);
1088       return(JB_INVALID_SOCKET);
1089    }
1090
1091    client_pos = 0;
1092    cbuf[client_pos++] = '\x05'; /* Version */
1093    cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1094    cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1095
1096    if (write_socket(sfd, cbuf, client_pos))
1097    {
1098       errstr = "SOCKS5 negotiation write failed";
1099       csp->error_message = strdup(errstr);
1100       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1101       close_socket(sfd);
1102       return(JB_INVALID_SOCKET);
1103    }
1104
1105    if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1106    {
1107       errstr = "SOCKS5 negotiation read failed";
1108       err = 1;
1109    }
1110
1111    if (!err && (sbuf[0] != '\x05'))
1112    {
1113       errstr = "SOCKS5 negotiation protocol version error";
1114       err = 1;
1115    }
1116
1117    if (!err && (sbuf[1] == '\xff'))
1118    {
1119       errstr = "SOCKS5 authentication required";
1120       err = 1;
1121    }
1122
1123    if (!err && (sbuf[1] != '\x00'))
1124    {
1125       errstr = "SOCKS5 negotiation protocol error";
1126       err = 1;
1127    }
1128
1129    if (err)
1130    {
1131       assert(errstr != NULL);
1132       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1133       csp->error_message = strdup(errstr);
1134       close_socket(sfd);
1135       errno = EINVAL;
1136       return(JB_INVALID_SOCKET);
1137    }
1138
1139    client_pos = 0;
1140    cbuf[client_pos++] = '\x05'; /* Version */
1141    cbuf[client_pos++] = '\x01'; /* TCP connect */
1142    cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1143    cbuf[client_pos++] = '\x03'; /* Address is domain name */
1144    cbuf[client_pos++] = (char)(hostlen & 0xffu);
1145    assert(sizeof(cbuf) - client_pos > 255);
1146    /* Using strncpy because we really want the nul byte padding. */
1147    strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1148    client_pos += (hostlen & 0xffu);
1149    cbuf[client_pos++] = (char)((target_port >> 8) & 0xffu);
1150    cbuf[client_pos++] = (char)((target_port     ) & 0xffu);
1151
1152    if (write_socket(sfd, cbuf, client_pos))
1153    {
1154       errstr = "SOCKS5 negotiation read failed";
1155       csp->error_message = strdup(errstr);
1156       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1157       close_socket(sfd);
1158       errno = EINVAL;
1159       return(JB_INVALID_SOCKET);
1160    }
1161
1162    server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1163    if (server_size < 3)
1164    {
1165       errstr = "SOCKS5 negotiation read failed";
1166       err = 1;
1167    }
1168    else if (server_size > 20)
1169    {
1170       /* This is somewhat unexpected but doesn't realy matter. */
1171       log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1172          "from socks server. Would have accepted up to %d.",
1173          server_size, sizeof(sbuf));
1174    }
1175
1176    if (!err && (sbuf[0] != '\x05'))
1177    {
1178       errstr = "SOCKS5 negotiation protocol version error";
1179       err = 1;
1180    }
1181
1182    if (!err && (sbuf[2] != '\x00'))
1183    {
1184       errstr = "SOCKS5 negotiation protocol error";
1185       err = 1;
1186    }
1187
1188    if (!err)
1189    {
1190       if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1191       {
1192          return(sfd);
1193       }
1194       errstr = translate_socks5_error(sbuf[1]);
1195       err = 1;
1196    }
1197
1198    assert(errstr != NULL);
1199    csp->error_message = strdup(errstr);
1200    log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1201    close_socket(sfd);
1202    errno = EINVAL;
1203
1204    return(JB_INVALID_SOCKET);
1205
1206 }
1207
1208 /*
1209   Local Variables:
1210   tab-width: 3
1211   end:
1212 */