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