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