Add tests for enable-proxy-authentication-forwarding
[privoxy.git] / gateway.c
1 const char gateway_rcs[] = "$Id: gateway.c,v 1.92 2012/10/23 10:16:52 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 #include "list.h"
70
71 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
72 #ifdef HAVE_POLL
73 #ifdef __GLIBC__
74 #include <sys/poll.h>
75 #else
76 #include <poll.h>
77 #endif /* def __GLIBC__ */
78 #endif /* HAVE_POLL */
79 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
80
81 const char gateway_h_rcs[] = GATEWAY_H_VERSION;
82
83 static jb_socket socks4_connect(const struct forward_spec * fwd,
84                                 const char * target_host,
85                                 int target_port,
86                                 struct client_state *csp);
87
88 static jb_socket socks5_connect(const struct forward_spec *fwd,
89                                 const char *target_host,
90                                 int target_port,
91                                 struct client_state *csp);
92
93 enum {
94    SOCKS4_REQUEST_GRANTED        =  90,
95    SOCKS4_REQUEST_REJECT         =  91,
96    SOCKS4_REQUEST_IDENT_FAILED   =  92,
97    SOCKS4_REQUEST_IDENT_CONFLICT =  93
98 };
99
100 enum {
101    SOCKS5_REQUEST_GRANTED             = 0,
102    SOCKS5_REQUEST_FAILED              = 1,
103    SOCKS5_REQUEST_DENIED              = 2,
104    SOCKS5_REQUEST_NETWORK_UNREACHABLE = 3,
105    SOCKS5_REQUEST_HOST_UNREACHABLE    = 4,
106    SOCKS5_REQUEST_CONNECTION_REFUSED  = 5,
107    SOCKS5_REQUEST_TTL_EXPIRED         = 6,
108    SOCKS5_REQUEST_PROTOCOL_ERROR      = 7,
109    SOCKS5_REQUEST_BAD_ADDRESS_TYPE    = 8
110 };
111
112 /* structure of a socks client operation */
113 struct socks_op {
114    unsigned char vn;          /* socks version number */
115    unsigned char cd;          /* command code */
116    unsigned char dstport[2];  /* destination port */
117    unsigned char dstip[4];    /* destination address */
118    char userid;               /* first byte of userid */
119    char padding[3];           /* make sure sizeof(struct socks_op) is endian-independent. */
120    /* more bytes of the userid follow, terminated by a NULL */
121 };
122
123 /* structure of a socks server reply */
124 struct socks_reply {
125    unsigned char vn;          /* socks version number */
126    unsigned char cd;          /* command code */
127    unsigned char dstport[2];  /* destination port */
128    unsigned char dstip[4];    /* destination address */
129 };
130
131 static const char socks_userid[] = "anonymous";
132
133 #ifdef FEATURE_CONNECTION_SHARING
134
135 #define MAX_REUSABLE_CONNECTIONS 100
136 static unsigned int keep_alive_timeout = DEFAULT_KEEP_ALIVE_TIMEOUT;
137
138 static struct reusable_connection reusable_connection[MAX_REUSABLE_CONNECTIONS];
139 static int mark_connection_unused(const struct reusable_connection *connection);
140
141 /*********************************************************************
142  *
143  * Function    :  initialize_reusable_connections
144  *
145  * Description :  Initializes the reusable_connection structures.
146  *                Must be called with connection_reuse_mutex locked.
147  *
148  * Parameters  : N/A
149  *
150  * Returns     : void
151  *
152  *********************************************************************/
153 extern void initialize_reusable_connections(void)
154 {
155    unsigned int slot = 0;
156
157 #if !defined(HAVE_POLL) && !defined(_WIN32)
158    log_error(LOG_LEVEL_INFO,
159       "Detecting already dead connections might not work "
160       "correctly on your platform. In case of problems, "
161       "unset the keep-alive-timeout option.");
162 #endif
163
164    for (slot = 0; slot < SZ(reusable_connection); slot++)
165    {
166       mark_connection_closed(&reusable_connection[slot]);
167    }
168
169    log_error(LOG_LEVEL_CONNECT, "Initialized %d socket slots.", slot);
170 }
171
172
173 /*********************************************************************
174  *
175  * Function    :  remember_connection
176  *
177  * Description :  Remembers a server connection for reuse later on.
178  *
179  * Parameters  :
180  *          1  :  connection = The server connection to remember.
181  *
182  * Returns     : void
183  *
184  *********************************************************************/
185 void remember_connection(const struct reusable_connection *connection)
186 {
187    unsigned int slot = 0;
188    int free_slot_found = FALSE;
189
190    assert(NULL != connection);
191    assert(connection->sfd != JB_INVALID_SOCKET);
192
193    if (mark_connection_unused(connection))
194    {
195       return;
196    }
197
198    privoxy_mutex_lock(&connection_reuse_mutex);
199
200    /* Find free socket slot. */
201    for (slot = 0; slot < SZ(reusable_connection); slot++)
202    {
203       if (reusable_connection[slot].sfd == JB_INVALID_SOCKET)
204       {
205          assert(reusable_connection[slot].in_use == 0);
206          log_error(LOG_LEVEL_CONNECT,
207             "Remembering socket %d for %s:%d in slot %d.",
208             connection->sfd, connection->host, connection->port, slot);
209          free_slot_found = TRUE;
210          break;
211       }
212    }
213
214    if (!free_slot_found)
215    {
216       log_error(LOG_LEVEL_CONNECT,
217         "No free slots found to remember socket for %s:%d. Last slot %d.",
218         connection->host, connection->port, slot);
219       privoxy_mutex_unlock(&connection_reuse_mutex);
220       close_socket(connection->sfd);
221       return;
222    }
223
224    assert(NULL != connection->host);
225    reusable_connection[slot].host = strdup_or_die(connection->host);
226    reusable_connection[slot].sfd = connection->sfd;
227    reusable_connection[slot].port = connection->port;
228    reusable_connection[slot].in_use = 0;
229    reusable_connection[slot].timestamp = connection->timestamp;
230    reusable_connection[slot].request_sent = connection->request_sent;
231    reusable_connection[slot].response_received = connection->response_received;
232    reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
233    reusable_connection[slot].requests_sent_total = connection->requests_sent_total;
234
235    assert(reusable_connection[slot].gateway_host == NULL);
236    assert(reusable_connection[slot].gateway_port == 0);
237    assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
238    assert(reusable_connection[slot].forward_host == NULL);
239    assert(reusable_connection[slot].forward_port == 0);
240
241    reusable_connection[slot].forwarder_type = connection->forwarder_type;
242    if (NULL != connection->gateway_host)
243    {
244       reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
245    }
246    else
247    {
248       reusable_connection[slot].gateway_host = NULL;
249    }
250    reusable_connection[slot].gateway_port = connection->gateway_port;
251
252    if (NULL != connection->forward_host)
253    {
254       reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
255    }
256    else
257    {
258       reusable_connection[slot].forward_host = NULL;
259    }
260    reusable_connection[slot].forward_port = connection->forward_port;
261
262    privoxy_mutex_unlock(&connection_reuse_mutex);
263 }
264 #endif /* def FEATURE_CONNECTION_SHARING */
265
266
267 /*********************************************************************
268  *
269  * Function    :  mark_connection_closed
270  *
271  * Description : Marks a reused connection closed.
272  *
273  * Parameters  :
274  *          1  :  closed_connection = The connection to mark as closed.
275  *
276  * Returns     : void
277  *
278  *********************************************************************/
279 void mark_connection_closed(struct reusable_connection *closed_connection)
280 {
281    closed_connection->in_use = FALSE;
282    closed_connection->sfd = JB_INVALID_SOCKET;
283    freez(closed_connection->host);
284    closed_connection->port = 0;
285    closed_connection->timestamp = 0;
286    closed_connection->request_sent = 0;
287    closed_connection->response_received = 0;
288    closed_connection->keep_alive_timeout = 0;
289    closed_connection->requests_sent_total = 0;
290    closed_connection->forwarder_type = SOCKS_NONE;
291    freez(closed_connection->gateway_host);
292    closed_connection->gateway_port = 0;
293    freez(closed_connection->forward_host);
294    closed_connection->forward_port = 0;
295 }
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       case SOCKS_5T:
645          sfd = socks5_connect(fwd, dest_host, dest_port, csp);
646          break;
647       default:
648          /* Should never get here */
649          log_error(LOG_LEVEL_FATAL,
650             "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
651    }
652
653    if (JB_INVALID_SOCKET != sfd)
654    {
655       log_error(LOG_LEVEL_CONNECT,
656          "Created new connection to %s:%d on socket %d.",
657          http->host, http->port, sfd);
658    }
659
660    return sfd;
661
662 }
663
664
665 /*********************************************************************
666  *
667  * Function    :  socks4_connect
668  *
669  * Description :  Connect to the SOCKS server, and connect through
670  *                it to the specified server.   This handles
671  *                all the SOCKS negotiation, and returns a file
672  *                descriptor for a socket which can be treated as a
673  *                normal (non-SOCKS) socket.
674  *
675  *                Logged error messages are saved to csp->error_message
676  *                and later reused by error_response() for the CGI
677  *                message. strdup allocation failures are handled there.
678  *
679  * Parameters  :
680  *          1  :  fwd = Specifies the SOCKS proxy to use.
681  *          2  :  target_host = The final server to connect to.
682  *          3  :  target_port = The final port to connect to.
683  *          4  :  csp = Current client state (buffers, headers, etc...)
684  *
685  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
686  *
687  *********************************************************************/
688 static jb_socket socks4_connect(const struct forward_spec * fwd,
689                                 const char * target_host,
690                                 int target_port,
691                                 struct client_state *csp)
692 {
693    unsigned long web_server_addr;
694    char buf[BUFFER_SIZE];
695    struct socks_op    *c = (struct socks_op    *)buf;
696    struct socks_reply *s = (struct socks_reply *)buf;
697    size_t n;
698    size_t csiz;
699    jb_socket sfd;
700    int err = 0;
701    char *errstr = NULL;
702
703    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
704    {
705       /* XXX: Shouldn't the config file parser prevent this? */
706       errstr = "NULL gateway host specified.";
707       err = 1;
708    }
709
710    if (fwd->gateway_port <= 0)
711    {
712       errstr = "invalid gateway port specified.";
713       err = 1;
714    }
715
716    if (err)
717    {
718       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
719       csp->error_message = strdup(errstr);
720       errno = EINVAL;
721       return(JB_INVALID_SOCKET);
722    }
723
724    /* build a socks request for connection to the web server */
725
726    strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
727
728    csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
729
730    switch (fwd->type)
731    {
732       case SOCKS_4:
733          web_server_addr = resolve_hostname_to_ip(target_host);
734          if (web_server_addr == INADDR_NONE)
735          {
736             errstr = "could not resolve target host";
737             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
738             err = 1;
739          }
740          else
741          {
742             web_server_addr = htonl(web_server_addr);
743          }
744          break;
745       case SOCKS_4A:
746          web_server_addr = 0x00000001;
747          n = csiz + strlen(target_host) + 1;
748          if (n > sizeof(buf))
749          {
750             errno = EINVAL;
751             errstr = "buffer cbuf too small.";
752             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
753             err = 1;
754          }
755          else
756          {
757             strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
758             /*
759              * What we forward to the socks4a server should have the
760              * size of socks_op, plus the length of the userid plus
761              * its \0 byte (which we don't have to add because the
762              * first byte of the userid is counted twice as it's also
763              * part of sock_op) minus the padding bytes (which are part
764              * of the userid as well), plus the length of the target_host
765              * (which is stored csiz bytes after the beginning of the buffer),
766              * plus another \0 byte.
767              */
768             assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
769             csiz = n;
770          }
771          break;
772       default:
773          /* Should never get here */
774          log_error(LOG_LEVEL_FATAL,
775             "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
776          /* Not reached */
777          return(JB_INVALID_SOCKET);
778    }
779
780    if (err)
781    {
782       csp->error_message = strdup(errstr);
783       return(JB_INVALID_SOCKET);
784    }
785
786    c->vn          = 4;
787    c->cd          = 1;
788    c->dstport[0]  = (unsigned char)((target_port       >> 8 ) & 0xff);
789    c->dstport[1]  = (unsigned char)((target_port            ) & 0xff);
790    c->dstip[0]    = (unsigned char)((web_server_addr   >> 24) & 0xff);
791    c->dstip[1]    = (unsigned char)((web_server_addr   >> 16) & 0xff);
792    c->dstip[2]    = (unsigned char)((web_server_addr   >>  8) & 0xff);
793    c->dstip[3]    = (unsigned char)((web_server_addr        ) & 0xff);
794
795    /* pass the request to the socks server */
796    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
797
798    if (sfd == JB_INVALID_SOCKET)
799    {
800       /* The error an its reason have already been logged by connect_to()  */
801       return(JB_INVALID_SOCKET);
802    }
803    else if (write_socket(sfd, (char *)c, csiz))
804    {
805       errstr = "SOCKS4 negotiation write failed.";
806       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
807       err = 1;
808       close_socket(sfd);
809    }
810    else if (!data_is_available(sfd, csp->config->socket_timeout))
811    {
812       if (socket_is_still_alive(sfd))
813       {
814          errstr = "SOCKS4 negotiation timed out";
815       }
816       else
817       {
818          errstr = "SOCKS4 negotiation got aborted by the server";
819       }
820       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
821       err = 1;
822       close_socket(sfd);
823    }
824    else if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
825    {
826       errstr = "SOCKS4 negotiation read failed.";
827       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
828       err = 1;
829       close_socket(sfd);
830    }
831
832    if (err)
833    {
834       csp->error_message = strdup(errstr);
835       return(JB_INVALID_SOCKET);
836    }
837
838    switch (s->cd)
839    {
840       case SOCKS4_REQUEST_GRANTED:
841          return(sfd);
842       case SOCKS4_REQUEST_REJECT:
843          errstr = "SOCKS request rejected or failed.";
844          errno = EINVAL;
845          break;
846       case SOCKS4_REQUEST_IDENT_FAILED:
847          errstr = "SOCKS request rejected because "
848             "SOCKS server cannot connect to identd on the client.";
849          errno = EACCES;
850          break;
851       case SOCKS4_REQUEST_IDENT_CONFLICT:
852          errstr = "SOCKS request rejected because "
853             "the client program and identd report "
854             "different user-ids.";
855          errno = EACCES;
856          break;
857       default:
858          errno = ENOENT;
859          snprintf(buf, sizeof(buf),
860             "SOCKS request rejected for reason code %d.", s->cd);
861          errstr = buf;
862    }
863
864    log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
865    csp->error_message = strdup(errstr);
866    close_socket(sfd);
867
868    return(JB_INVALID_SOCKET);
869
870 }
871
872 /*********************************************************************
873  *
874  * Function    :  translate_socks5_error
875  *
876  * Description :  Translates a SOCKS errors to a string.
877  *
878  * Parameters  :
879  *          1  :  socks_error = The error code to translate.
880  *
881  * Returns     :  The string translation.
882  *
883  *********************************************************************/
884 static const char *translate_socks5_error(int socks_error)
885 {
886    switch (socks_error)
887    {
888       /* XXX: these should be more descriptive */
889       case SOCKS5_REQUEST_FAILED:
890          return "SOCKS5 request failed";
891       case SOCKS5_REQUEST_DENIED:
892          return "SOCKS5 request denied";
893       case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
894          return "SOCKS5 network unreachable";
895       case SOCKS5_REQUEST_HOST_UNREACHABLE:
896          return "SOCKS5 host unreachable";
897       case SOCKS5_REQUEST_CONNECTION_REFUSED:
898          return "SOCKS5 connection refused";
899       case SOCKS5_REQUEST_TTL_EXPIRED:
900          return "SOCKS5 TTL expired";
901       case SOCKS5_REQUEST_PROTOCOL_ERROR:
902          return "SOCKS5 client protocol error";
903       case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
904          return "SOCKS5 domain names unsupported";
905       case SOCKS5_REQUEST_GRANTED:
906          return "everything's peachy";
907       default:
908          return "SOCKS5 negotiation protocol error";
909    }
910 }
911
912 /*********************************************************************
913  *
914  * Function    :  socks5_connect
915  *
916  * Description :  Connect to the SOCKS server, and connect through
917  *                it to the specified server.   This handles
918  *                all the SOCKS negotiation, and returns a file
919  *                descriptor for a socket which can be treated as a
920  *                normal (non-SOCKS) socket.
921  *
922  * Parameters  :
923  *          1  :  fwd = Specifies the SOCKS proxy to use.
924  *          2  :  target_host = The final server to connect to.
925  *          3  :  target_port = The final port to connect to.
926  *          4  :  csp = Current client state (buffers, headers, etc...)
927  *
928  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
929  *
930  *********************************************************************/
931 static jb_socket socks5_connect(const struct forward_spec *fwd,
932                                 const char *target_host,
933                                 int target_port,
934                                 struct client_state *csp)
935 {
936    int err = 0;
937    char cbuf[300];
938    char sbuf[10];
939    size_t client_pos = 0;
940    int server_size = 0;
941    size_t hostlen = 0;
942    jb_socket sfd;
943    const char *errstr = NULL;
944
945    assert(fwd->gateway_host);
946    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
947    {
948       errstr = "NULL gateway host specified";
949       err = 1;
950    }
951
952    if (fwd->gateway_port <= 0)
953    {
954       /*
955        * XXX: currently this can't happen because in
956        * case of invalid gateway ports we use the defaults.
957        * Of course we really shouldn't do that.
958        */
959       errstr = "invalid gateway port specified";
960       err = 1;
961    }
962
963    hostlen = strlen(target_host);
964    if (hostlen > (size_t)255)
965    {
966       errstr = "target host name is longer than 255 characters";
967       err = 1;
968    }
969
970    if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
971    {
972       /* Should never get here */
973       log_error(LOG_LEVEL_FATAL,
974          "SOCKS5 impossible internal error - bad SOCKS type");
975       err = 1;
976    }
977
978    if (err)
979    {
980       errno = EINVAL;
981       assert(errstr != NULL);
982       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
983       csp->error_message = strdup(errstr);
984       return(JB_INVALID_SOCKET);
985    }
986
987    /* pass the request to the socks server */
988    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
989
990    if (sfd == JB_INVALID_SOCKET)
991    {
992       errstr = "socks5 server unreachable";
993       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
994       /* Free the generic error message provided by connect_to() */
995       freez(csp->error_message);
996       csp->error_message = strdup(errstr);
997       return(JB_INVALID_SOCKET);
998    }
999
1000    client_pos = 0;
1001    cbuf[client_pos++] = '\x05'; /* Version */
1002    cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1003    cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1004
1005    if (write_socket(sfd, cbuf, client_pos))
1006    {
1007       errstr = "SOCKS5 negotiation write failed";
1008       csp->error_message = strdup(errstr);
1009       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1010       close_socket(sfd);
1011       return(JB_INVALID_SOCKET);
1012    }
1013
1014    if (!data_is_available(sfd, csp->config->socket_timeout))
1015    {
1016       if (socket_is_still_alive(sfd))
1017       {
1018          errstr = "SOCKS5 negotiation timed out";
1019       }
1020       else
1021       {
1022          errstr = "SOCKS5 negotiation got aborted by the server";
1023       }
1024       err = 1;
1025    }
1026
1027    if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1028    {
1029       errstr = "SOCKS5 negotiation read failed";
1030       err = 1;
1031    }
1032
1033    if (!err && (sbuf[0] != '\x05'))
1034    {
1035       errstr = "SOCKS5 negotiation protocol version error";
1036       err = 1;
1037    }
1038
1039    if (!err && (sbuf[1] == '\xff'))
1040    {
1041       errstr = "SOCKS5 authentication required";
1042       err = 1;
1043    }
1044
1045    if (!err && (sbuf[1] != '\x00'))
1046    {
1047       errstr = "SOCKS5 negotiation protocol error";
1048       err = 1;
1049    }
1050
1051    if (err)
1052    {
1053       assert(errstr != NULL);
1054       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1055       csp->error_message = strdup(errstr);
1056       close_socket(sfd);
1057       errno = EINVAL;
1058       return(JB_INVALID_SOCKET);
1059    }
1060
1061    client_pos = 0;
1062    cbuf[client_pos++] = '\x05'; /* Version */
1063    cbuf[client_pos++] = '\x01'; /* TCP connect */
1064    cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1065    cbuf[client_pos++] = '\x03'; /* Address is domain name */
1066    cbuf[client_pos++] = (char)(hostlen & 0xffu);
1067    assert(sizeof(cbuf) - client_pos > (size_t)255);
1068    /* Using strncpy because we really want the nul byte padding. */
1069    strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1070    client_pos += (hostlen & 0xffu);
1071    cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1072    cbuf[client_pos++] = (char)((target_port     ) & 0xff);
1073
1074    if (write_socket(sfd, cbuf, client_pos))
1075    {
1076       errstr = "SOCKS5 negotiation write failed";
1077       csp->error_message = strdup(errstr);
1078       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1079       close_socket(sfd);
1080       errno = EINVAL;
1081       return(JB_INVALID_SOCKET);
1082    }
1083
1084    /*
1085     * Optimistically send the request headers with the initial
1086     * request if the user requested use of Tor extensions, the
1087     * CONNECT method isn't being used (in which case the client
1088     * doesn't send data until it gets our 200 response) and the
1089     * client request has been already read completely.
1090     *
1091     * Not optimistically sending the request body (if there is one)
1092     * makes it easier to implement, but isn't an actual requirement.
1093     */
1094    if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1095       && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1096    {
1097       char *client_headers = list_to_text(csp->headers);
1098       size_t header_length;
1099
1100       if (client_headers == NULL)
1101       {
1102          log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1103       }
1104       list_remove_all(csp->headers);
1105       header_length= strlen(client_headers);
1106
1107       log_error(LOG_LEVEL_CONNECT,
1108          "Optimistically sending %d bytes of client headers intended for %s",
1109          header_length, csp->http->hostport);
1110
1111       if (write_socket(sfd, client_headers, header_length))
1112       {
1113          log_error(LOG_LEVEL_CONNECT,
1114             "optimistically writing header to: %s failed: %E", csp->http->hostport);
1115          freez(client_headers);
1116          return(JB_INVALID_SOCKET);
1117       }
1118       freez(client_headers);
1119    }
1120
1121    server_size = read_socket(sfd, sbuf, sizeof(sbuf));
1122    if (server_size != sizeof(sbuf))
1123    {
1124       errstr = "SOCKS5 negotiation read failed";
1125    }
1126    else
1127    {
1128       if (sbuf[0] != '\x05')
1129       {
1130          errstr = "SOCKS5 negotiation protocol version error";
1131       }
1132       else if (sbuf[2] != '\x00')
1133       {
1134          errstr = "SOCKS5 negotiation protocol error";
1135       }
1136       else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1137       {
1138          errstr = translate_socks5_error(sbuf[1]);
1139       }
1140       else
1141       {
1142          return(sfd);
1143       }
1144    }
1145
1146    assert(errstr != NULL);
1147    csp->error_message = strdup(errstr);
1148    log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1149    close_socket(sfd);
1150    errno = EINVAL;
1151
1152    return(JB_INVALID_SOCKET);
1153
1154 }
1155
1156 /*
1157   Local Variables:
1158   tab-width: 3
1159   end:
1160 */