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