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