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