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