Fix gcc45 warning.
[privoxy.git] / gateway.c
1 const char gateway_rcs[] = "$Id: gateway.c,v 1.57 2009/07/13 17:12:28 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  *                or SOCKS5 proxy).
9  *
10  * Copyright   :  Written by and Copyright (C) 2001-2009 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  *********************************************************************/
36
37
38 #include "config.h"
39
40 #include <stdio.h>
41 #include <sys/types.h>
42
43 #ifndef _WIN32
44 #include <netinet/in.h>
45 #endif
46
47 #include <errno.h>
48 #include <string.h>
49 #include "assert.h"
50
51 #ifdef _WIN32
52 #include <winsock2.h>
53 #endif /* def _WIN32 */
54
55 #ifdef __BEOS__
56 #include <netdb.h>
57 #endif /* def __BEOS__ */
58
59 #ifdef __OS2__
60 #include <utils.h>
61 #endif /* def __OS2__ */
62
63 #include "project.h"
64 #include "jcc.h"
65 #include "errlog.h"
66 #include "jbsockets.h"
67 #include "gateway.h"
68 #include "miscutil.h"
69 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
70 #ifdef HAVE_POLL
71 #ifdef __GLIBC__ 
72 #include <sys/poll.h>
73 #else
74 #include <poll.h>
75 #endif /* def __GLIBC__ */
76 #endif /* HAVE_POLL */
77 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
78
79 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
80
81 static jb_socket socks4_connect(const struct forward_spec * fwd,
82                                 const char * target_host,
83                                 int target_port,
84                                 struct client_state *csp);
85
86 static jb_socket socks5_connect(const struct forward_spec *fwd,
87                                 const char *target_host,
88                                 int target_port,
89                                 struct client_state *csp);
90
91
92 #define SOCKS_REQUEST_GRANTED          90
93 #define SOCKS_REQUEST_REJECT           91
94 #define SOCKS_REQUEST_IDENT_FAILED     92
95 #define SOCKS_REQUEST_IDENT_CONFLICT   93
96
97 #define SOCKS5_REQUEST_GRANTED             0
98 #define SOCKS5_REQUEST_FAILED              1
99 #define SOCKS5_REQUEST_DENIED              2
100 #define SOCKS5_REQUEST_NETWORK_UNREACHABLE 3
101 #define SOCKS5_REQUEST_HOST_UNREACHABLE    4
102 #define SOCKS5_REQUEST_CONNECTION_REFUSED  5
103 #define SOCKS5_REQUEST_TTL_EXPIRED         6
104 #define SOCKS5_REQUEST_PROTOCOL_ERROR      7
105 #define SOCKS5_REQUEST_BAD_ADDRESS_TYPE    8
106
107 /* structure of a socks client operation */
108 struct socks_op {
109    unsigned char vn;          /* socks version number */
110    unsigned char cd;          /* command code */
111    unsigned char dstport[2];  /* destination port */
112    unsigned char dstip[4];    /* destination address */
113    char userid;               /* first byte of userid */
114    char padding[3];           /* make sure sizeof(struct socks_op) is endian-independent. */
115    /* more bytes of the userid follow, terminated by a NULL */
116 };
117
118 /* structure of a socks server reply */
119 struct socks_reply {
120    unsigned char vn;          /* socks version number */
121    unsigned char cd;          /* command code */
122    unsigned char dstport[2];  /* destination port */
123    unsigned char dstip[4];    /* destination address */
124 };
125
126 static const char socks_userid[] = "anonymous";
127
128 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
129
130 #define MAX_REUSABLE_CONNECTIONS 100
131 static unsigned int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
132
133 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
134 static int mark_connection_unused(const struct reusable_connection *connection);
135
136 /*********************************************************************
137  *
138  * Function    :  initialize_reusable_connections
139  *
140  * Description :  Initializes the reusable_connection structures.
141  *                Must be called with connection_reuse_mutex locked.
142  *
143  * Parameters  : N/A
144  *
145  * Returns     : void
146  *
147  *********************************************************************/
148 extern void initialize_reusable_connections(void)
149 {
150    unsigned int slot = 0;
151
152 #if !defined(HAVE_POLL) && !defined(_WIN32)
153    log_error(LOG_LEVEL_INFO,
154       "Detecting already dead connections might not work "
155       "correctly on your platform. In case of problems, "
156       "unset the keep-alive-timeout option.");
157 #endif
158
159    for (slot = 0; slot < SZ(reusable_connection); slot++)
160    {
161       mark_connection_closed(&reusable_connection[slot]);
162    }
163
164    log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
165 }
166
167
168 /*********************************************************************
169  *
170  * Function    :  remember_connection
171  *
172  * Description :  Remembers a connection for reuse later on.
173  *
174  * Parameters  :
175  *          1  :  csp = Current client state (buffers, headers, etc...)
176  *          2  :  fwd = The forwarder settings used.
177  *
178  * Returns     : void
179  *
180  *********************************************************************/
181 void remember_connection(const struct client_state *csp, const struct forward_spec *fwd)
182 {
183    unsigned int slot = 0;
184    int free_slot_found = FALSE;
185    const struct reusable_connection *connection = &csp->server_connection;
186    const struct http_request *http = csp->http;
187
188    assert(connection->sfd != JB_INVALID_SOCKET);
189
190    if (mark_connection_unused(connection))
191    {
192       return;
193    }
194
195    privoxy_mutex_lock(&connection_reuse_mutex);
196
197    /* Find free socket slot. */
198    for (slot = 0; slot < SZ(reusable_connection); slot++)
199    {
200       if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
201       {
202          assert(reusable_connection[slot].in_use == 0);
203          log_error(LOG_LEVEL_CONNECT,
204             "Remembering socket %d for %s:%d in slot %d.",
205             connection->sfd, http->host, http->port, slot);
206          free_slot_found = TRUE;
207          break;
208       }
209    }
210
211    if (!free_slot_found)
212    {
213       log_error(LOG_LEVEL_CONNECT,
214         "No free slots found to remembering socket for %s:%d. Last slot %d.",
215         http->host, http->port, slot);
216       privoxy_mutex_unlock(&connection_reuse_mutex);
217       close_socket(connection->sfd);
218       return;
219    }
220
221    assert(NULL != http->host);
222    reusable_connection[slot].host = strdup(http->host);
223    if (NULL == reusable_connection[slot].host)
224    {
225       log_error(LOG_LEVEL_FATAL, "Out of memory saving socket.");
226    }
227    reusable_connection[slot].sfd = connection->sfd;
228    reusable_connection[slot].port = http->port;
229    reusable_connection[slot].in_use = 0;
230    reusable_connection[slot].timestamp = connection->timestamp;
231    reusable_connection->request_sent = connection->request_sent;
232    reusable_connection->response_received = connection->response_received;
233    reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
234
235    assert(NULL != fwd);
236    assert(reusable_connection[slot].gateway_host == NULL);
237    assert(reusable_connection[slot].gateway_port == 0);
238    assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
239    assert(reusable_connection[slot].forward_host == NULL);
240    assert(reusable_connection[slot].forward_port == 0);
241
242    reusable_connection[slot].forwarder_type = fwd->type;
243    if (NULL != fwd->gateway_host)
244    {
245       reusable_connection[slot].gateway_host = strdup(fwd->gateway_host);
246       if (NULL == reusable_connection[slot].gateway_host)
247       {
248          log_error(LOG_LEVEL_FATAL, "Out of memory saving gateway_host.");
249       }
250    }
251    else
252    {
253       reusable_connection[slot].gateway_host = NULL;
254    }
255    reusable_connection[slot].gateway_port = fwd->gateway_port;
256
257    if (NULL != fwd->forward_host)
258    {
259       reusable_connection[slot].forward_host = strdup(fwd->forward_host);
260       if (NULL == reusable_connection[slot].forward_host)
261       {
262          log_error(LOG_LEVEL_FATAL, "Out of memory saving forward_host.");
263       }
264    }
265    else
266    {
267       reusable_connection[slot].forward_host = NULL;
268    }
269    reusable_connection[slot].forward_port = fwd->forward_port;
270
271    privoxy_mutex_unlock(&connection_reuse_mutex);
272 }
273
274
275 /*********************************************************************
276  *
277  * Function    :  mark_connection_closed
278  *
279  * Description : Marks a reused connection closed.
280  *
281  * Parameters  :
282  *          1  :  closed_connection = The connection to mark as closed.
283  *
284  * Returns     : void
285  *
286  *********************************************************************/
287 void mark_connection_closed(struct reusable_connection *closed_connection)
288 {
289    closed_connection->in_use = FALSE;
290    closed_connection->sfd = JB_INVALID_SOCKET;
291    freez(closed_connection->host);
292    closed_connection->port = 0;
293    closed_connection->timestamp = 0;
294    closed_connection->request_sent = 0;
295    closed_connection->response_received = 0;
296    closed_connection->keep_alive_timeout = 0;
297    closed_connection->forwarder_type = SOCKS_NONE;
298    freez(closed_connection->gateway_host);
299    closed_connection->gateway_port = 0;
300    freez(closed_connection->forward_host);
301    closed_connection->forward_port = 0;
302 }
303
304
305 /*********************************************************************
306  *
307  * Function    :  forget_connection
308  *
309  * Description :  Removes a previously remembered connection from
310  *                the list of reusable connections.
311  *
312  * Parameters  :
313  *          1  :  sfd = The socket belonging to the connection in question.
314  *
315  * Returns     : void
316  *
317  *********************************************************************/
318 void forget_connection(jb_socket sfd)
319 {
320    unsigned int slot = 0;
321
322    assert(sfd != JB_INVALID_SOCKET);
323
324    privoxy_mutex_lock(&connection_reuse_mutex);
325
326    for (slot = 0; slot < SZ(reusable_connection); slot++)
327    {
328       if (reusable_connection[slot].sfd == sfd)
329       {
330          assert(reusable_connection[slot].in_use);
331
332          log_error(LOG_LEVEL_CONNECT,
333             "Forgetting socket %d for %s:%d in slot %d.",
334             sfd, reusable_connection[slot].host,
335             reusable_connection[slot].port, slot);
336          mark_connection_closed(&reusable_connection[slot]);
337          privoxy_mutex_unlock(&connection_reuse_mutex);
338
339          return;
340       }
341    }
342
343    log_error(LOG_LEVEL_CONNECT,
344       "Socket %d already forgotten or never remembered.", sfd);
345
346    privoxy_mutex_unlock(&connection_reuse_mutex);
347 }
348
349
350 /*********************************************************************
351  *
352  * Function    :  connection_destination_matches
353  *
354  * Description :  Determines whether a remembered connection can
355  *                be reused. That is, whether the destination and
356  *                the forwarding settings match.
357  *
358  * Parameters  :
359  *          1  :  connection = The connection to check.
360  *          2  :  http = The destination for the connection.
361  *          3  :  fwd  = The forwarder settings.
362  *
363  * Returns     :  TRUE for yes, FALSE otherwise.
364  *
365  *********************************************************************/
366 int connection_destination_matches(const struct reusable_connection *connection,
367                                    const struct http_request *http,
368                                    const struct forward_spec *fwd)
369 {
370    if ((connection->forwarder_type != fwd->type)
371     || (connection->gateway_port   != fwd->gateway_port)
372     || (connection->forward_port   != fwd->forward_port)
373     || (connection->port           != http->port))
374    {
375       return FALSE;
376    }
377
378    if ((    (NULL != connection->gateway_host)
379          && (NULL != fwd->gateway_host)
380          && strcmpic(connection->gateway_host, fwd->gateway_host))
381        && (connection->gateway_host != fwd->gateway_host))
382    {
383       log_error(LOG_LEVEL_CONNECT, "Gateway mismatch.");
384       return FALSE;
385    }
386
387    if ((    (NULL != connection->forward_host)
388          && (NULL != fwd->forward_host)
389          && strcmpic(connection->forward_host, fwd->forward_host))
390       && (connection->forward_host != fwd->forward_host))
391    {
392       log_error(LOG_LEVEL_CONNECT, "Forwarding proxy mismatch.");
393       return FALSE;
394    }
395
396    return (!strcmpic(connection->host, http->host));
397
398 }
399
400
401 /*********************************************************************
402  *
403  * Function    :  close_unusable_connections
404  *
405  * Description :  Closes remembered connections that have timed
406  *                out or have been closed on the other side.
407  *
408  * Parameters  :  none
409  *
410  * Returns     :  Number of connections that are still alive.
411  *
412  *********************************************************************/
413 int close_unusable_connections(void)
414 {
415    unsigned int slot = 0;
416    int connections_alive = 0;
417
418    privoxy_mutex_lock(&connection_reuse_mutex);
419
420    for (slot = 0; slot < SZ(reusable_connection); slot++)
421    {
422       if (!reusable_connection[slot].in_use
423          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
424       {
425          time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
426          time_t latency = reusable_connection[slot].response_received -
427             reusable_connection[slot].request_sent;
428
429          if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
430          {
431             log_error(LOG_LEVEL_CONNECT,
432                "The connection to %s:%d in slot %d timed out. "
433                "Closing socket %d. Timeout is: %d. Assumed latency: %d",
434                reusable_connection[slot].host,
435                reusable_connection[slot].port, slot,
436                reusable_connection[slot].sfd,
437                reusable_connection[slot].keep_alive_timeout,
438                latency);
439             close_socket(reusable_connection[slot].sfd);
440             mark_connection_closed(&reusable_connection[slot]);
441          }
442          else if (!socket_is_still_usable(reusable_connection[slot].sfd))
443          {
444             log_error(LOG_LEVEL_CONNECT,
445                "The connection to %s:%d in slot %d is no longer usable. "
446                "Closing socket %d.", reusable_connection[slot].host,
447                reusable_connection[slot].port, slot,
448                reusable_connection[slot].sfd);
449             close_socket(reusable_connection[slot].sfd);
450             mark_connection_closed(&reusable_connection[slot]);
451          }
452          else
453          {
454             connections_alive++;
455          }
456       }
457    }
458
459    privoxy_mutex_unlock(&connection_reuse_mutex);
460
461    return connections_alive;
462
463 }
464
465
466 /*********************************************************************
467  *
468  * Function    :  get_reusable_connection
469  *
470  * Description :  Returns an open socket to a previously remembered
471  *                open connection (if there is one).
472  *
473  * Parameters  :
474  *          1  :  http = The destination for the connection.
475  *          2  :  fwd  = The forwarder settings.
476  *
477  * Returns     :  JB_INVALID_SOCKET => No reusable connection found,
478  *                otherwise a usable socket.
479  *
480  *********************************************************************/
481 static jb_socket get_reusable_connection(const struct http_request *http,
482                                          const struct forward_spec *fwd)
483 {
484    jb_socket sfd = JB_INVALID_SOCKET;
485    unsigned int slot = 0;
486
487    close_unusable_connections();
488
489    privoxy_mutex_lock(&connection_reuse_mutex);
490
491    for (slot = 0; slot < SZ(reusable_connection); slot++)
492    {
493       if (!reusable_connection[slot].in_use
494          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
495       {
496          if (connection_destination_matches(&reusable_connection[slot], http, fwd))
497          {
498             reusable_connection[slot].in_use = TRUE;
499             sfd = reusable_connection[slot].sfd;
500             log_error(LOG_LEVEL_CONNECT,
501                "Found reusable socket %d for %s:%d in slot %d.",
502                sfd, reusable_connection[slot].host, reusable_connection[slot].port, slot);
503             break;
504          }
505       }
506    }
507
508    privoxy_mutex_unlock(&connection_reuse_mutex);
509
510    return sfd;
511
512 }
513
514
515 /*********************************************************************
516  *
517  * Function    :  mark_connection_unused
518  *
519  * Description :  Gives a remembered connection free for reuse.
520  *
521  * Parameters  :
522  *          1  :  connection = The connection in question.
523  *
524  * Returns     :  TRUE => Socket found and marked as unused.
525  *                FALSE => Socket not found.
526  *
527  *********************************************************************/
528 static int mark_connection_unused(const struct reusable_connection *connection)
529 {
530    unsigned int slot = 0;
531    int socket_found = FALSE;
532
533    assert(connection->sfd != JB_INVALID_SOCKET);
534
535    privoxy_mutex_lock(&connection_reuse_mutex);
536
537    for (slot = 0; slot < SZ(reusable_connection); slot++)
538    {
539       if (reusable_connection[slot].sfd == connection->sfd)
540       {
541          assert(reusable_connection[slot].in_use);
542          socket_found = TRUE;
543          log_error(LOG_LEVEL_CONNECT,
544             "Marking open socket %d for %s:%d in slot %d as unused.",
545             connection->sfd, reusable_connection[slot].host,
546             reusable_connection[slot].port, slot);
547          reusable_connection[slot].in_use = 0;
548          reusable_connection[slot].timestamp = connection->timestamp;
549          break;
550       }
551    }
552
553    privoxy_mutex_unlock(&connection_reuse_mutex);
554
555    return socket_found;
556
557 }
558
559
560 /*********************************************************************
561  *
562  * Function    :  set_keep_alive_timeout
563  *
564  * Description :  Sets the timeout after which open
565  *                connections will no longer be reused.
566  *
567  * Parameters  :
568  *          1  :  timeout = The timeout in seconds.
569  *
570  * Returns     :  void
571  *
572  *********************************************************************/
573 void set_keep_alive_timeout(unsigned int timeout)
574 {
575    keep_alive_timeout = timeout;
576 }
577 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
578
579
580 /*********************************************************************
581  *
582  * Function    :  forwarded_connect
583  *
584  * Description :  Connect to a specified web server, possibly via
585  *                a HTTP proxy and/or a SOCKS proxy.
586  *
587  * Parameters  :
588  *          1  :  fwd = the proxies to use when connecting.
589  *          2  :  http = the http request and apropos headers
590  *          3  :  csp = Current client state (buffers, headers, etc...)
591  *
592  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
593  *
594  *********************************************************************/
595 jb_socket forwarded_connect(const struct forward_spec * fwd,
596                             struct http_request *http,
597                             struct client_state *csp)
598 {
599    const char * dest_host;
600    int dest_port;
601    jb_socket sfd = JB_INVALID_SOCKET;
602
603 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
604    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
605       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
606    {
607       sfd = get_reusable_connection(http, fwd);
608       if (JB_INVALID_SOCKET != sfd)
609       {
610          return sfd;
611       }
612    }
613 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
614
615    /* Figure out if we need to connect to the web server or a HTTP proxy. */
616    if (fwd->forward_host)
617    {
618       /* HTTP proxy */
619       dest_host = fwd->forward_host;
620       dest_port = fwd->forward_port;
621    }
622    else
623    {
624       /* Web server */
625       dest_host = http->host;
626       dest_port = http->port;
627    }
628
629    /* Connect, maybe using a SOCKS proxy */
630    switch (fwd->type)
631    {
632       case SOCKS_NONE:
633          sfd = connect_to(dest_host, dest_port, csp);
634          break;
635       case SOCKS_4:
636       case SOCKS_4A:
637          sfd = socks4_connect(fwd, dest_host, dest_port, csp);
638          break;
639       case SOCKS_5:
640          sfd = socks5_connect(fwd, dest_host, dest_port, csp);
641          break;
642       default:
643          /* Should never get here */
644          log_error(LOG_LEVEL_FATAL,
645             "SOCKS4 impossible internal error - bad SOCKS type.");
646    }
647
648    if (JB_INVALID_SOCKET != sfd)
649    {
650       log_error(LOG_LEVEL_CONNECT,
651          "Created new connection to %s:%d on socket %d.",
652          http->host, http->port, sfd);
653    }
654
655    return sfd;
656
657 }
658
659
660 /*********************************************************************
661  *
662  * Function    :  socks4_connect
663  *
664  * Description :  Connect to the SOCKS server, and connect through
665  *                it to the specified server.   This handles
666  *                all the SOCKS negotiation, and returns a file
667  *                descriptor for a socket which can be treated as a
668  *                normal (non-SOCKS) socket.
669  *
670  *                Logged error messages are saved to csp->error_message
671  *                and later reused by error_response() for the CGI
672  *                message. strdup allocation failures are handled there.
673  *
674  * Parameters  :
675  *          1  :  fwd = Specifies the SOCKS proxy to use.
676  *          2  :  target_host = The final server to connect to.
677  *          3  :  target_port = The final port to connect to.
678  *          4  :  csp = Current client state (buffers, headers, etc...)
679  *
680  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
681  *
682  *********************************************************************/
683 static jb_socket socks4_connect(const struct forward_spec * fwd,
684                                 const char * target_host,
685                                 int target_port,
686                                 struct client_state *csp)
687 {
688    unsigned long web_server_addr;
689    char buf[BUFFER_SIZE];
690    struct socks_op    *c = (struct socks_op    *)buf;
691    struct socks_reply *s = (struct socks_reply *)buf;
692    size_t n;
693    size_t csiz;
694    jb_socket sfd;
695    int err = 0;
696    char *errstr = NULL;
697
698    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
699    {
700       /* XXX: Shouldn't the config file parser prevent this? */
701       errstr = "NULL gateway host specified.";
702       err = 1;
703    }
704
705    if (fwd->gateway_port <= 0)
706    {
707       errstr = "invalid gateway port specified.";
708       err = 1;
709    }
710
711    if (err)
712    {
713       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
714       csp->error_message = strdup(errstr); 
715       errno = EINVAL;
716       return(JB_INVALID_SOCKET);
717    }
718
719    /* build a socks request for connection to the web server */
720
721    strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
722
723    csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
724
725    switch (fwd->type)
726    {
727       case SOCKS_4:
728          web_server_addr = resolve_hostname_to_ip(target_host);
729          if (web_server_addr == INADDR_NONE)
730          {
731             errstr = "could not resolve target host";
732             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
733             err = 1;
734          }
735          else
736          {
737             web_server_addr = htonl(web_server_addr);
738          }
739          break;
740       case SOCKS_4A:
741          web_server_addr = 0x00000001;
742          n = csiz + strlen(target_host) + 1;
743          if (n > sizeof(buf))
744          {
745             errno = EINVAL;
746             errstr = "buffer cbuf too small.";
747             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
748             err = 1;
749          }
750          else
751          {
752             strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
753             /*
754              * What we forward to the socks4a server should have the
755              * size of socks_op, plus the length of the userid plus
756              * its \0 byte (which we don't have to add because the
757              * first byte of the userid is counted twice as it's also
758              * part of sock_op) minus the padding bytes (which are part
759              * of the userid as well), plus the length of the target_host
760              * (which is stored csiz bytes after the beginning of the buffer),
761              * plus another \0 byte.
762              */
763             assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
764             csiz = n;
765          }
766          break;
767       default:
768          /* Should never get here */
769          log_error(LOG_LEVEL_FATAL,
770             "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
771          /* Not reached */
772          return(JB_INVALID_SOCKET);
773    }
774
775    if (err)
776    {
777       csp->error_message = strdup(errstr);
778       return(JB_INVALID_SOCKET);
779    }
780
781    c->vn          = 4;
782    c->cd          = 1;
783    c->dstport[0]  = (unsigned char)((target_port       >> 8  ) & 0xff);
784    c->dstport[1]  = (unsigned char)((target_port             ) & 0xff);
785    c->dstip[0]    = (unsigned char)((web_server_addr   >> 24 ) & 0xff);
786    c->dstip[1]    = (unsigned char)((web_server_addr   >> 16 ) & 0xff);
787    c->dstip[2]    = (unsigned char)((web_server_addr   >>  8 ) & 0xff);
788    c->dstip[3]    = (unsigned char)((web_server_addr         ) & 0xff);
789
790    /* pass the request to the socks server */
791    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
792
793    if (sfd == JB_INVALID_SOCKET)
794    {
795       /*
796        * XXX: connect_to should fill in the exact reason.
797        * Most likely resolving the IP of the forwarder failed.
798        */
799       errstr = "connect_to failed: see logfile for details";
800       err = 1;
801    }
802    else if (write_socket(sfd, (char *)c, csiz))
803    {
804       errstr = "SOCKS4 negotiation write failed.";
805       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
806       err = 1;
807       close_socket(sfd);
808    }
809    else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
810    {
811       errstr = "SOCKS4 negotiation read failed.";
812       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
813       err = 1;
814       close_socket(sfd);
815    }
816
817    if (err)
818    {
819       csp->error_message = strdup(errstr);      
820       return(JB_INVALID_SOCKET);
821    }
822
823    switch (s->cd)
824    {
825       case SOCKS_REQUEST_GRANTED:
826          return(sfd);
827       case SOCKS_REQUEST_REJECT:
828          errstr = "SOCKS request rejected or failed.";
829          errno = EINVAL;
830          break;
831       case SOCKS_REQUEST_IDENT_FAILED:
832          errstr = "SOCKS request rejected because "
833             "SOCKS server cannot connect to identd on the client.";
834          errno = EACCES;
835          break;
836       case SOCKS_REQUEST_IDENT_CONFLICT:
837          errstr = "SOCKS request rejected because "
838             "the client program and identd report "
839             "different user-ids.";
840          errno = EACCES;
841          break;
842       default:
843          errno = ENOENT;
844          snprintf(buf, sizeof(buf),
845             "SOCKS request rejected for reason code %d.", s->cd);
846          errstr = buf;
847    }
848
849    log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
850    csp->error_message = strdup(errstr);
851    close_socket(sfd);
852
853    return(JB_INVALID_SOCKET);
854
855 }
856
857 /*********************************************************************
858  *
859  * Function    :  translate_socks5_error
860  *
861  * Description :  Translates a SOCKS errors to a string.
862  *
863  * Parameters  :
864  *          1  :  socks_error = The error code to translate.
865  *
866  * Returns     :  The string translation.
867  *
868  *********************************************************************/
869 static const char *translate_socks5_error(int socks_error)
870 {
871    switch (socks_error)
872    {
873       /* XXX: these should be more descriptive */
874       case SOCKS5_REQUEST_FAILED:
875          return "SOCKS5 request failed";
876       case SOCKS5_REQUEST_DENIED:
877          return "SOCKS5 request denied";
878       case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
879          return "SOCKS5 network unreachable";
880       case SOCKS5_REQUEST_HOST_UNREACHABLE:
881          return "SOCKS5 host unreachable";
882       case SOCKS5_REQUEST_CONNECTION_REFUSED:
883          return "SOCKS5 connection refused";
884       case SOCKS5_REQUEST_TTL_EXPIRED:
885          return "SOCKS5 TTL expired";
886       case SOCKS5_REQUEST_PROTOCOL_ERROR:
887          return "SOCKS5 client protocol error";
888       case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
889          return "SOCKS5 domain names unsupported";
890       case SOCKS5_REQUEST_GRANTED:
891          return "everything's peachy";
892       default:
893          return "SOCKS5 negotiation protocol error";
894    }
895 }
896
897 /*********************************************************************
898  *
899  * Function    :  socks5_connect
900  *
901  * Description :  Connect to the SOCKS server, and connect through
902  *                it to the specified server.   This handles
903  *                all the SOCKS negotiation, and returns a file
904  *                descriptor for a socket which can be treated as a
905  *                normal (non-SOCKS) socket.
906  *
907  * Parameters  :
908  *          1  :  fwd = Specifies the SOCKS proxy to use.
909  *          2  :  target_host = The final server to connect to.
910  *          3  :  target_port = The final port to connect to.
911  *          4  :  csp = Current client state (buffers, headers, etc...)
912  *
913  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
914  *
915  *********************************************************************/
916 static jb_socket socks5_connect(const struct forward_spec *fwd,
917                                 const char *target_host,
918                                 int target_port,
919                                 struct client_state *csp)
920 {
921    int err = 0;
922    char cbuf[300];
923    char sbuf[30];
924    size_t client_pos = 0;
925    int server_size = 0;
926    size_t hostlen = 0;
927    jb_socket sfd;
928    const char *errstr = NULL;
929
930    assert(fwd->gateway_host);
931    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
932    {
933       errstr = "NULL gateway host specified";
934       err = 1;
935    }
936
937    if (fwd->gateway_port <= 0)
938    {
939       /*
940        * XXX: currently this can't happen because in
941        * case of invalid gateway ports we use the defaults.
942        * Of course we really shouldn't do that.
943        */
944       errstr = "invalid gateway port specified";
945       err = 1;
946    }
947
948    hostlen = strlen(target_host);
949    if (hostlen > (size_t)255)
950    {
951       errstr = "target host name is longer than 255 characters";
952       err = 1;
953    }
954
955    if (fwd->type != SOCKS_5)
956    {
957       /* Should never get here */
958       log_error(LOG_LEVEL_FATAL,
959          "SOCKS5 impossible internal error - bad SOCKS type");
960       err = 1;
961    }
962
963    if (err)
964    {
965       errno = EINVAL;
966       assert(errstr != NULL);
967       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
968       csp->error_message = strdup(errstr);
969       return(JB_INVALID_SOCKET);
970    }
971
972    /* pass the request to the socks server */
973    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
974
975    if (sfd == JB_INVALID_SOCKET)
976    {
977       errstr = "socks5 server unreachable";
978       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
979       csp->error_message = strdup(errstr);
980       return(JB_INVALID_SOCKET);
981    }
982
983    client_pos = 0;
984    cbuf[client_pos++] = '\x05'; /* Version */
985    cbuf[client_pos++] = '\x01'; /* One authentication method supported */
986    cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
987
988    if (write_socket(sfd, cbuf, client_pos))
989    {
990       errstr = "SOCKS5 negotiation write failed";
991       csp->error_message = strdup(errstr);
992       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
993       close_socket(sfd);
994       return(JB_INVALID_SOCKET);
995    }
996
997    if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
998    {
999       errstr = "SOCKS5 negotiation read failed";
1000       err = 1;
1001    }
1002
1003    if (!err && (sbuf[0] != '\x05'))
1004    {
1005       errstr = "SOCKS5 negotiation protocol version error";
1006       err = 1;
1007    }
1008
1009    if (!err && (sbuf[1] == '\xff'))
1010    {
1011       errstr = "SOCKS5 authentication required";
1012       err = 1;
1013    }
1014
1015    if (!err && (sbuf[1] != '\x00'))
1016    {
1017       errstr = "SOCKS5 negotiation protocol error";
1018       err = 1;
1019    }
1020
1021    if (err)
1022    {
1023       assert(errstr != NULL);
1024       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1025       csp->error_message = strdup(errstr);
1026       close_socket(sfd);
1027       errno = EINVAL;
1028       return(JB_INVALID_SOCKET);
1029    }
1030
1031    client_pos = 0;
1032    cbuf[client_pos++] = '\x05'; /* Version */
1033    cbuf[client_pos++] = '\x01'; /* TCP connect */
1034    cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1035    cbuf[client_pos++] = '\x03'; /* Address is domain name */
1036    cbuf[client_pos++] = (char)(hostlen & 0xffu);
1037    assert(sizeof(cbuf) - client_pos > (size_t)255);
1038    /* Using strncpy because we really want the nul byte padding. */
1039    strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1040    client_pos += (hostlen & 0xffu);
1041    cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1042    cbuf[client_pos++] = (char)((target_port     ) & 0xff);
1043
1044    if (write_socket(sfd, cbuf, client_pos))
1045    {
1046       errstr = "SOCKS5 negotiation read failed";
1047       csp->error_message = strdup(errstr);
1048       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1049       close_socket(sfd);
1050       errno = EINVAL;
1051       return(JB_INVALID_SOCKET);
1052    }
1053
1054    server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1055    if (server_size < 3)
1056    {
1057       errstr = "SOCKS5 negotiation read failed";
1058       err = 1;
1059    }
1060    else if (server_size > 20)
1061    {
1062       /* This is somewhat unexpected but doesn't realy matter. */
1063       log_error(LOG_LEVEL_CONNECT, "socks5_connect: read %d bytes "
1064          "from socks server. Would have accepted up to %d.",
1065          server_size, sizeof(sbuf));
1066    }
1067
1068    if (!err && (sbuf[0] != '\x05'))
1069    {
1070       errstr = "SOCKS5 negotiation protocol version error";
1071       err = 1;
1072    }
1073
1074    if (!err && (sbuf[2] != '\x00'))
1075    {
1076       errstr = "SOCKS5 negotiation protocol error";
1077       err = 1;
1078    }
1079
1080    if (!err)
1081    {
1082       if (sbuf[1] == SOCKS5_REQUEST_GRANTED)
1083       {
1084          return(sfd);
1085       }
1086       errstr = translate_socks5_error(sbuf[1]);
1087    }
1088
1089    assert(errstr != NULL);
1090    csp->error_message = strdup(errstr);
1091    log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1092    close_socket(sfd);
1093    errno = EINVAL;
1094
1095    return(JB_INVALID_SOCKET);
1096
1097 }
1098
1099 /*
1100   Local Variables:
1101   tab-width: 3
1102   end:
1103 */