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