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