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