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