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