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