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