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