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