Merge branch 'master' of ssh://git.privoxy.org:23/git/privoxy
[privoxy.git] / gateway.c
1 /*********************************************************************
2  *
3  * File        :  $Source: /cvsroot/ijbswa/current/gateway.c,v $
4  *
5  * Purpose     :  Contains functions to connect to a server, possibly
6  *                using a "forwarder" (i.e. HTTP proxy and/or a SOCKS4
7  *                or SOCKS5 proxy).
8  *
9  * Copyright   :  Written by and Copyright (C) 2001-2017 the
10  *                Privoxy team. https://www.privoxy.org/
11  *
12  *                Based on the Internet Junkbuster originally written
13  *                by and Copyright (C) 1997 Anonymous Coders and
14  *                Junkbusters Corporation.  http://www.junkbusters.com
15  *
16  *                This program is free software; you can redistribute it
17  *                and/or modify it under the terms of the GNU General
18  *                Public License as published by the Free Software
19  *                Foundation; either version 2 of the License, or (at
20  *                your option) any later version.
21  *
22  *                This program is distributed in the hope that it will
23  *                be useful, but WITHOUT ANY WARRANTY; without even the
24  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
25  *                PARTICULAR PURPOSE.  See the GNU General Public
26  *                License for more details.
27  *
28  *                The GNU General Public License should be included with
29  *                this file.  If not, you can view it at
30  *                http://www.gnu.org/copyleft/gpl.html
31  *                or write to the Free Software Foundation, Inc., 59
32  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
33  *
34  *********************************************************************/
35
36
37 #include "config.h"
38
39 #include <stdio.h>
40 #include <sys/types.h>
41
42 #ifndef _WIN32
43 #include <netinet/in.h>
44 #endif
45
46 #include <errno.h>
47 #include <string.h>
48 #include "assert.h"
49
50 #ifdef _WIN32
51 #include <winsock2.h>
52 #endif /* def _WIN32 */
53
54 #ifdef __BEOS__
55 #include <netdb.h>
56 #endif /* def __BEOS__ */
57
58 #ifdef __OS2__
59 #include <utils.h>
60 #endif /* def __OS2__ */
61
62 #include "project.h"
63 #include "jcc.h"
64 #include "errlog.h"
65 #include "jbsockets.h"
66 #include "gateway.h"
67 #include "miscutil.h"
68 #include "list.h"
69 #include "parsers.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 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 #ifndef FEATURE_CONNECTION_KEEP_ALIVE
133 #error Using FEATURE_CONNECTION_SHARING without FEATURE_CONNECTION_KEEP_ALIVE is impossible
134 #endif
135
136 #define MAX_REUSABLE_CONNECTIONS 100
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(slot < SZ(reusable_connection));
225    assert(NULL != connection->host);
226    reusable_connection[slot].host = strdup_or_die(connection->host);
227    reusable_connection[slot].sfd = connection->sfd;
228    reusable_connection[slot].port = connection->port;
229    reusable_connection[slot].in_use = 0;
230    reusable_connection[slot].timestamp = connection->timestamp;
231    reusable_connection[slot].request_sent = connection->request_sent;
232    reusable_connection[slot].response_received = connection->response_received;
233    reusable_connection[slot].keep_alive_timeout = connection->keep_alive_timeout;
234    reusable_connection[slot].requests_sent_total = connection->requests_sent_total;
235
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 = connection->forwarder_type;
243    if (NULL != connection->gateway_host)
244    {
245       reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
246    }
247    else
248    {
249       reusable_connection[slot].gateway_host = NULL;
250    }
251    reusable_connection[slot].gateway_port = connection->gateway_port;
252
253    if (NULL != connection->forward_host)
254    {
255       reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
256    }
257    else
258    {
259       reusable_connection[slot].forward_host = NULL;
260    }
261    reusable_connection[slot].forward_port = connection->forward_port;
262
263    privoxy_mutex_unlock(&connection_reuse_mutex);
264 }
265 #endif /* def FEATURE_CONNECTION_SHARING */
266
267
268 /*********************************************************************
269  *
270  * Function    :  mark_connection_closed
271  *
272  * Description : Marks a reused connection closed.
273  *
274  * Parameters  :
275  *          1  :  closed_connection = The connection to mark as closed.
276  *
277  * Returns     : void
278  *
279  *********************************************************************/
280 void mark_connection_closed(struct reusable_connection *closed_connection)
281 {
282    closed_connection->in_use = FALSE;
283    closed_connection->sfd = JB_INVALID_SOCKET;
284    freez(closed_connection->host);
285    closed_connection->port = 0;
286    closed_connection->timestamp = 0;
287    closed_connection->request_sent = 0;
288    closed_connection->response_received = 0;
289    closed_connection->keep_alive_timeout = 0;
290    closed_connection->requests_sent_total = 0;
291    closed_connection->forwarder_type = SOCKS_NONE;
292    freez(closed_connection->gateway_host);
293    closed_connection->gateway_port = 0;
294    freez(closed_connection->forward_host);
295    closed_connection->forward_port = 0;
296 }
297
298
299 #ifdef FEATURE_CONNECTION_SHARING
300 /*********************************************************************
301  *
302  * Function    :  forget_connection
303  *
304  * Description :  Removes a previously remembered connection from
305  *                the list of reusable connections.
306  *
307  * Parameters  :
308  *          1  :  sfd = The socket belonging to the connection in question.
309  *
310  * Returns     : void
311  *
312  *********************************************************************/
313 void forget_connection(jb_socket sfd)
314 {
315    unsigned int slot = 0;
316
317    assert(sfd != JB_INVALID_SOCKET);
318
319    privoxy_mutex_lock(&connection_reuse_mutex);
320
321    for (slot = 0; slot < SZ(reusable_connection); slot++)
322    {
323       if (reusable_connection[slot].sfd == sfd)
324       {
325          assert(reusable_connection[slot].in_use);
326
327          log_error(LOG_LEVEL_CONNECT,
328             "Forgetting socket %d for %s:%d in slot %d.",
329             sfd, reusable_connection[slot].host,
330             reusable_connection[slot].port, slot);
331          mark_connection_closed(&reusable_connection[slot]);
332          break;
333       }
334    }
335
336    privoxy_mutex_unlock(&connection_reuse_mutex);
337
338 }
339 #endif /* def FEATURE_CONNECTION_SHARING */
340
341
342 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
343 /*********************************************************************
344  *
345  * Function    :  connection_destination_matches
346  *
347  * Description :  Determines whether a remembered connection can
348  *                be reused. That is, whether the destination and
349  *                the forwarding settings match.
350  *
351  * Parameters  :
352  *          1  :  connection = The connection to check.
353  *          2  :  http = The destination for the connection.
354  *          3  :  fwd  = The forwarder settings.
355  *
356  * Returns     :  TRUE for yes, FALSE otherwise.
357  *
358  *********************************************************************/
359 int connection_destination_matches(const struct reusable_connection *connection,
360                                    const struct http_request *http,
361                                    const struct forward_spec *fwd)
362 {
363    if ((connection->forwarder_type != fwd->type)
364     || (connection->gateway_port   != fwd->gateway_port)
365     || (connection->forward_port   != fwd->forward_port)
366     || (connection->port           != http->port))
367    {
368       return FALSE;
369    }
370
371    if ((    (NULL != connection->gateway_host)
372          && (NULL != fwd->gateway_host)
373          && strcmpic(connection->gateway_host, fwd->gateway_host))
374        && (connection->gateway_host != fwd->gateway_host))
375    {
376       log_error(LOG_LEVEL_CONNECT,
377          "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
378          connection->gateway_host, fwd->gateway_host);
379       return FALSE;
380    }
381
382    if ((    (NULL != connection->forward_host)
383          && (NULL != fwd->forward_host)
384          && strcmpic(connection->forward_host, fwd->forward_host))
385       && (connection->forward_host != fwd->forward_host))
386    {
387       log_error(LOG_LEVEL_CONNECT,
388          "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
389          connection->forward_host, fwd->forward_host);
390       return FALSE;
391    }
392
393    return (!strcmpic(connection->host, http->host));
394
395 }
396 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
397
398
399 #ifdef FEATURE_CONNECTION_SHARING
400 /*********************************************************************
401  *
402  * Function    :  close_unusable_connections
403  *
404  * Description :  Closes remembered connections that have timed
405  *                out or have been closed on the other side.
406  *
407  * Parameters  :  none
408  *
409  * Returns     :  Number of connections that are still alive.
410  *
411  *********************************************************************/
412 int close_unusable_connections(void)
413 {
414    unsigned int slot = 0;
415    int connections_alive = 0;
416
417    privoxy_mutex_lock(&connection_reuse_mutex);
418
419    for (slot = 0; slot < SZ(reusable_connection); slot++)
420    {
421       if (!reusable_connection[slot].in_use
422          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
423       {
424          time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
425          time_t latency = (reusable_connection[slot].response_received -
426             reusable_connection[slot].request_sent) / 2;
427
428          if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
429          {
430             log_error(LOG_LEVEL_CONNECT,
431                "The connection to %s:%d in slot %d timed out. "
432                "Closing socket %d. Timeout is: %d. Assumed latency: %d.",
433                reusable_connection[slot].host,
434                reusable_connection[slot].port, slot,
435                reusable_connection[slot].sfd,
436                reusable_connection[slot].keep_alive_timeout,
437                latency);
438             close_socket(reusable_connection[slot].sfd);
439             mark_connection_closed(&reusable_connection[slot]);
440          }
441          else if (!socket_is_still_alive(reusable_connection[slot].sfd))
442          {
443             log_error(LOG_LEVEL_CONNECT,
444                "The connection to %s:%d in slot %d is no longer usable. "
445                "Closing socket %d.", reusable_connection[slot].host,
446                reusable_connection[slot].port, slot,
447                reusable_connection[slot].sfd);
448             close_socket(reusable_connection[slot].sfd);
449             mark_connection_closed(&reusable_connection[slot]);
450          }
451          else
452          {
453             connections_alive++;
454          }
455       }
456    }
457
458    privoxy_mutex_unlock(&connection_reuse_mutex);
459
460    return connections_alive;
461
462 }
463
464
465 /*********************************************************************
466  *
467  * Function    :  get_reusable_connection
468  *
469  * Description :  Returns an open socket to a previously remembered
470  *                open connection (if there is one).
471  *
472  * Parameters  :
473  *          1  :  http = The destination for the connection.
474  *          2  :  fwd  = The forwarder settings.
475  *
476  * Returns     :  JB_INVALID_SOCKET => No reusable connection found,
477  *                otherwise a usable socket.
478  *
479  *********************************************************************/
480 static jb_socket get_reusable_connection(const struct http_request *http,
481                                          const struct forward_spec *fwd)
482 {
483    jb_socket sfd = JB_INVALID_SOCKET;
484    unsigned int slot = 0;
485
486    close_unusable_connections();
487
488    privoxy_mutex_lock(&connection_reuse_mutex);
489
490    for (slot = 0; slot < SZ(reusable_connection); slot++)
491    {
492       if (!reusable_connection[slot].in_use
493          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
494       {
495          if (connection_destination_matches(&reusable_connection[slot], http, fwd))
496          {
497             reusable_connection[slot].in_use = TRUE;
498             sfd = reusable_connection[slot].sfd;
499             log_error(LOG_LEVEL_CONNECT,
500                "Found reusable socket %d for %s:%d in slot %d. Timestamp made %d "
501                "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
502                sfd, reusable_connection[slot].host, reusable_connection[slot].port,
503                slot, time(NULL) - reusable_connection[slot].timestamp,
504                reusable_connection[slot].keep_alive_timeout,
505                (int)(reusable_connection[slot].response_received -
506                reusable_connection[slot].request_sent),
507                reusable_connection[slot].requests_sent_total);
508             break;
509          }
510       }
511    }
512
513    privoxy_mutex_unlock(&connection_reuse_mutex);
514
515    return sfd;
516
517 }
518
519
520 /*********************************************************************
521  *
522  * Function    :  mark_connection_unused
523  *
524  * Description :  Gives a remembered connection free for reuse.
525  *
526  * Parameters  :
527  *          1  :  connection = The connection in question.
528  *
529  * Returns     :  TRUE => Socket found and marked as unused.
530  *                FALSE => Socket not found.
531  *
532  *********************************************************************/
533 static int mark_connection_unused(const struct reusable_connection *connection)
534 {
535    unsigned int slot = 0;
536    int socket_found = FALSE;
537
538    assert(connection->sfd != JB_INVALID_SOCKET);
539
540    privoxy_mutex_lock(&connection_reuse_mutex);
541
542    for (slot = 0; slot < SZ(reusable_connection); slot++)
543    {
544       if (reusable_connection[slot].sfd == connection->sfd)
545       {
546          assert(reusable_connection[slot].in_use);
547          socket_found = TRUE;
548          log_error(LOG_LEVEL_CONNECT,
549             "Marking open socket %d for %s:%d in slot %d as unused.",
550             connection->sfd, reusable_connection[slot].host,
551             reusable_connection[slot].port, slot);
552          reusable_connection[slot].in_use = 0;
553          reusable_connection[slot].timestamp = connection->timestamp;
554          break;
555       }
556    }
557
558    privoxy_mutex_unlock(&connection_reuse_mutex);
559
560    return socket_found;
561
562 }
563 #endif /* def FEATURE_CONNECTION_SHARING */
564
565
566 /*********************************************************************
567  *
568  * Function    :  forwarded_connect
569  *
570  * Description :  Connect to a specified web server, possibly via
571  *                a HTTP proxy and/or a SOCKS proxy.
572  *
573  * Parameters  :
574  *          1  :  fwd = the proxies to use when connecting.
575  *          2  :  http = the http request and apropos headers
576  *          3  :  csp = Current client state (buffers, headers, etc...)
577  *
578  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
579  *
580  *********************************************************************/
581 jb_socket forwarded_connect(const struct forward_spec *fwd,
582                             struct http_request *http,
583                             struct client_state *csp)
584 {
585    const char *dest_host;
586    int dest_port;
587    jb_socket sfd = JB_INVALID_SOCKET;
588
589 #ifdef FEATURE_CONNECTION_SHARING
590    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
591       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
592    {
593       sfd = get_reusable_connection(http, fwd);
594       if (JB_INVALID_SOCKET != sfd)
595       {
596          return sfd;
597       }
598    }
599 #endif /* def FEATURE_CONNECTION_SHARING */
600
601    /* Figure out if we need to connect to the web server or a HTTP proxy. */
602    if (fwd->forward_host)
603    {
604       /* HTTP proxy */
605       dest_host = fwd->forward_host;
606       dest_port = fwd->forward_port;
607    }
608    else
609    {
610       /* Web server */
611       dest_host = http->host;
612       dest_port = http->port;
613    }
614
615    /* Connect, maybe using a SOCKS proxy */
616    switch (fwd->type)
617    {
618       case SOCKS_NONE:
619       case FORWARD_WEBSERVER:
620          sfd = connect_to(dest_host, dest_port, csp);
621          break;
622       case SOCKS_4:
623       case SOCKS_4A:
624          sfd = socks4_connect(fwd, dest_host, dest_port, csp);
625          break;
626       case SOCKS_5:
627       case SOCKS_5T:
628          sfd = socks5_connect(fwd, dest_host, dest_port, csp);
629          break;
630       default:
631          /* Should never get here */
632          log_error(LOG_LEVEL_FATAL,
633             "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
634    }
635
636    if (JB_INVALID_SOCKET != sfd)
637    {
638       log_error(LOG_LEVEL_CONNECT,
639          "Created new connection to %s:%d on socket %d.",
640          http->host, http->port, sfd);
641    }
642
643    return sfd;
644
645 }
646
647
648 #ifdef FUZZ
649 /*********************************************************************
650  *
651  * Function    :  socks_fuzz
652  *
653  * Description :  Wrapper around socks[45]_connect() used for fuzzing.
654  *
655  * Parameters  :
656  *          1  :  csp = Current client state (buffers, headers, etc...)
657  *
658  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
659  *
660  *********************************************************************/
661 extern jb_err socks_fuzz(struct client_state *csp)
662 {
663    jb_socket socket;
664    static struct forward_spec fwd;
665    char target_host[] = "fuzz.example.org";
666    int target_port = 12345;
667
668    fwd.gateway_host = strdup_or_die("fuzz.example.org");
669    fwd.gateway_port = 12345;
670
671    fwd.type = SOCKS_4A;
672    socket = socks4_connect(&fwd, target_host, target_port, csp);
673
674    if (JB_INVALID_SOCKET != socket)
675    {
676       fwd.type = SOCKS_5;
677       socket = socks5_connect(&fwd, target_host, target_port, csp);
678    }
679
680    if (JB_INVALID_SOCKET == socket)
681    {
682       log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
683       return JB_ERR_PARSE;
684    }
685
686    log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
687
688    return JB_ERR_OK;
689
690 }
691 #endif
692
693 /*********************************************************************
694  *
695  * Function    :  socks4_connect
696  *
697  * Description :  Connect to the SOCKS server, and connect through
698  *                it to the specified server.   This handles
699  *                all the SOCKS negotiation, and returns a file
700  *                descriptor for a socket which can be treated as a
701  *                normal (non-SOCKS) socket.
702  *
703  *                Logged error messages are saved to csp->error_message
704  *                and later reused by error_response() for the CGI
705  *                message. strdup allocation failures are handled there.
706  *
707  * Parameters  :
708  *          1  :  fwd = Specifies the SOCKS proxy to use.
709  *          2  :  target_host = The final server to connect to.
710  *          3  :  target_port = The final port to connect to.
711  *          4  :  csp = Current client state (buffers, headers, etc...)
712  *
713  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
714  *
715  *********************************************************************/
716 static jb_socket socks4_connect(const struct forward_spec *fwd,
717                                 const char *target_host,
718                                 int target_port,
719                                 struct client_state *csp)
720 {
721    unsigned long web_server_addr;
722    char buf[BUFFER_SIZE];
723    struct socks_op    *c = (struct socks_op    *)buf;
724    struct socks_reply *s = (struct socks_reply *)buf;
725    size_t n;
726    size_t csiz;
727    jb_socket sfd;
728    int err = 0;
729    char *errstr = NULL;
730
731    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
732    {
733       /* XXX: Shouldn't the config file parser prevent this? */
734       errstr = "NULL gateway host specified.";
735       err = 1;
736    }
737
738    if (fwd->gateway_port <= 0)
739    {
740       errstr = "invalid gateway port specified.";
741       err = 1;
742    }
743
744    if (err)
745    {
746       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
747       csp->error_message = strdup(errstr);
748       errno = EINVAL;
749       return(JB_INVALID_SOCKET);
750    }
751
752    /* build a socks request for connection to the web server */
753
754    strlcpy(&(c->userid), socks_userid, sizeof(buf) - sizeof(struct socks_op));
755
756    csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
757
758    switch (fwd->type)
759    {
760       case SOCKS_4:
761          web_server_addr = resolve_hostname_to_ip(target_host);
762          if (web_server_addr == INADDR_NONE)
763          {
764             errstr = "could not resolve target host";
765             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
766             err = 1;
767          }
768          else
769          {
770             web_server_addr = htonl(web_server_addr);
771          }
772          break;
773       case SOCKS_4A:
774          web_server_addr = 0x00000001;
775          n = csiz + strlen(target_host) + 1;
776          if (n > sizeof(buf))
777          {
778             errno = EINVAL;
779             errstr = "buffer cbuf too small.";
780             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
781             err = 1;
782          }
783          else
784          {
785             strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
786             /*
787              * What we forward to the socks4a server should have the
788              * size of socks_op, plus the length of the userid plus
789              * its \0 byte (which we don't have to add because the
790              * first byte of the userid is counted twice as it's also
791              * part of sock_op) minus the padding bytes (which are part
792              * of the userid as well), plus the length of the target_host
793              * (which is stored csiz bytes after the beginning of the buffer),
794              * plus another \0 byte.
795              */
796             assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
797             csiz = n;
798          }
799          break;
800       default:
801          /* Should never get here */
802          log_error(LOG_LEVEL_FATAL,
803             "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
804          /* Not reached */
805          return(JB_INVALID_SOCKET);
806    }
807
808    if (err)
809    {
810       csp->error_message = strdup(errstr);
811       return(JB_INVALID_SOCKET);
812    }
813
814    c->vn          = 4;
815    c->cd          = 1;
816    c->dstport[0]  = (unsigned char)((target_port       >> 8 ) & 0xff);
817    c->dstport[1]  = (unsigned char)((target_port            ) & 0xff);
818    c->dstip[0]    = (unsigned char)((web_server_addr   >> 24) & 0xff);
819    c->dstip[1]    = (unsigned char)((web_server_addr   >> 16) & 0xff);
820    c->dstip[2]    = (unsigned char)((web_server_addr   >>  8) & 0xff);
821    c->dstip[3]    = (unsigned char)((web_server_addr        ) & 0xff);
822
823 #ifdef FUZZ
824    sfd = 0;
825 #else
826    /* pass the request to the socks server */
827    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
828
829    if (sfd == JB_INVALID_SOCKET)
830    {
831       /* The error an its reason have already been logged by connect_to()  */
832       return(JB_INVALID_SOCKET);
833    }
834    else if (write_socket(sfd, (char *)c, csiz))
835    {
836       errstr = "SOCKS4 negotiation write failed.";
837       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
838       err = 1;
839       close_socket(sfd);
840    }
841    else if (!data_is_available(sfd, csp->config->socket_timeout))
842    {
843       if (socket_is_still_alive(sfd))
844       {
845          errstr = "SOCKS4 negotiation timed out";
846       }
847       else
848       {
849          errstr = "SOCKS4 negotiation got aborted by the server";
850       }
851       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
852       err = 1;
853       close_socket(sfd);
854    }
855    else
856 #endif
857        if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
858    {
859       errstr = "SOCKS4 negotiation read failed.";
860       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
861       err = 1;
862       close_socket(sfd);
863    }
864
865    if (err)
866    {
867       csp->error_message = strdup(errstr);
868       return(JB_INVALID_SOCKET);
869    }
870
871    switch (s->cd)
872    {
873       case SOCKS4_REQUEST_GRANTED:
874          return(sfd);
875       case SOCKS4_REQUEST_REJECT:
876          errstr = "SOCKS request rejected or failed.";
877          errno = EINVAL;
878          break;
879       case SOCKS4_REQUEST_IDENT_FAILED:
880          errstr = "SOCKS request rejected because "
881             "SOCKS server cannot connect to identd on the client.";
882          errno = EACCES;
883          break;
884       case SOCKS4_REQUEST_IDENT_CONFLICT:
885          errstr = "SOCKS request rejected because "
886             "the client program and identd report "
887             "different user-ids.";
888          errno = EACCES;
889          break;
890       default:
891          errno = ENOENT;
892          snprintf(buf, sizeof(buf),
893             "SOCKS request rejected for reason code %d.", s->cd);
894          errstr = buf;
895    }
896
897    log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
898    csp->error_message = strdup(errstr);
899    close_socket(sfd);
900
901    return(JB_INVALID_SOCKET);
902
903 }
904
905 /*********************************************************************
906  *
907  * Function    :  translate_socks5_error
908  *
909  * Description :  Translates a SOCKS errors to a string.
910  *
911  * Parameters  :
912  *          1  :  socks_error = The error code to translate.
913  *
914  * Returns     :  The string translation.
915  *
916  *********************************************************************/
917 static const char *translate_socks5_error(int socks_error)
918 {
919    switch (socks_error)
920    {
921       /* XXX: these should be more descriptive */
922       case SOCKS5_REQUEST_FAILED:
923          return "SOCKS5 request failed";
924       case SOCKS5_REQUEST_DENIED:
925          return "SOCKS5 request denied";
926       case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
927          return "SOCKS5 network unreachable";
928       case SOCKS5_REQUEST_HOST_UNREACHABLE:
929          return "SOCKS5 destination host unreachable";
930       case SOCKS5_REQUEST_CONNECTION_REFUSED:
931          return "SOCKS5 connection refused";
932       case SOCKS5_REQUEST_TTL_EXPIRED:
933          return "SOCKS5 TTL expired";
934       case SOCKS5_REQUEST_PROTOCOL_ERROR:
935          return "SOCKS5 client protocol error";
936       case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
937          return "SOCKS5 domain names unsupported";
938       case SOCKS5_REQUEST_GRANTED:
939          return "everything's peachy";
940       default:
941          return "SOCKS5 negotiation protocol error";
942    }
943 }
944
945
946 /*********************************************************************
947  *
948  * Function    :  socks5_connect
949  *
950  * Description :  Connect to the SOCKS server, and connect through
951  *                it to the specified server.   This handles
952  *                all the SOCKS negotiation, and returns a file
953  *                descriptor for a socket which can be treated as a
954  *                normal (non-SOCKS) socket.
955  *
956  * Parameters  :
957  *          1  :  fwd = Specifies the SOCKS proxy to use.
958  *          2  :  target_host = The final server to connect to.
959  *          3  :  target_port = The final port to connect to.
960  *          4  :  csp = Current client state (buffers, headers, etc...)
961  *
962  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
963  *
964  *********************************************************************/
965 static jb_socket socks5_connect(const struct forward_spec *fwd,
966                                 const char *target_host,
967                                 int target_port,
968                                 struct client_state *csp)
969 {
970 #define SIZE_SOCKS5_REPLY_IPV4 10
971 #define SIZE_SOCKS5_REPLY_IPV6 22
972 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
973    int err = 0;
974    char cbuf[300];
975    char sbuf[SIZE_SOCKS5_REPLY_IPV6];
976    size_t client_pos = 0;
977    int server_size = 0;
978    size_t hostlen = 0;
979    jb_socket sfd;
980    const char *errstr = NULL;
981
982    assert(fwd->gateway_host);
983    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
984    {
985       errstr = "NULL gateway host specified";
986       err = 1;
987    }
988
989    if (fwd->gateway_port <= 0)
990    {
991       /*
992        * XXX: currently this can't happen because in
993        * case of invalid gateway ports we use the defaults.
994        * Of course we really shouldn't do that.
995        */
996       errstr = "invalid gateway port specified";
997       err = 1;
998    }
999
1000    hostlen = strlen(target_host);
1001    if (hostlen > (size_t)255)
1002    {
1003       errstr = "target host name is longer than 255 characters";
1004       err = 1;
1005    }
1006
1007    if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1008    {
1009       /* Should never get here */
1010       log_error(LOG_LEVEL_FATAL,
1011          "SOCKS5 impossible internal error - bad SOCKS type");
1012       err = 1;
1013    }
1014
1015    if (err)
1016    {
1017       errno = EINVAL;
1018       assert(errstr != NULL);
1019       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1020       csp->error_message = strdup(errstr);
1021       return(JB_INVALID_SOCKET);
1022    }
1023
1024 #ifdef FUZZ
1025    sfd = 0;
1026    if (!err && read_socket(sfd, sbuf, 2) != 2)
1027 #else
1028    /* pass the request to the socks server */
1029    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1030
1031    if (sfd == JB_INVALID_SOCKET)
1032    {
1033       errstr = "socks5 server unreachable";
1034       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1035       /* Free the generic error message provided by connect_to() */
1036       freez(csp->error_message);
1037       csp->error_message = strdup(errstr);
1038       return(JB_INVALID_SOCKET);
1039    }
1040
1041    client_pos = 0;
1042    cbuf[client_pos++] = '\x05'; /* Version */
1043
1044    if (fwd->auth_username && fwd->auth_password)
1045    {
1046       cbuf[client_pos++] = '\x02'; /* Two authentication methods supported */
1047       cbuf[client_pos++] = '\x02'; /* Username/password */
1048    }
1049    else
1050    {
1051       cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1052    }
1053    cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1054
1055    if (write_socket(sfd, cbuf, client_pos))
1056    {
1057       errstr = "SOCKS5 negotiation write failed";
1058       csp->error_message = strdup(errstr);
1059       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1060       close_socket(sfd);
1061       return(JB_INVALID_SOCKET);
1062    }
1063    if (!data_is_available(sfd, csp->config->socket_timeout))
1064    {
1065       if (socket_is_still_alive(sfd))
1066       {
1067          errstr = "SOCKS5 negotiation timed out";
1068       }
1069       else
1070       {
1071          errstr = "SOCKS5 negotiation got aborted by the server";
1072       }
1073       err = 1;
1074    }
1075
1076    if (!err && read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1077 #endif
1078    {
1079       errstr = "SOCKS5 negotiation read failed";
1080       err = 1;
1081    }
1082
1083    if (!err && (sbuf[0] != '\x05'))
1084    {
1085       errstr = "SOCKS5 negotiation protocol version error";
1086       err = 1;
1087    }
1088
1089    if (!err && (sbuf[1] == '\xff'))
1090    {
1091       errstr = "SOCKS5 authentication required";
1092       err = 1;
1093    }
1094
1095    if (!err && (sbuf[1] == '\x02'))
1096    {
1097       /* check cbuf overflow */
1098       size_t auth_len = strlen(fwd->auth_username) + strlen(fwd->auth_password) + 3;
1099       if (auth_len > sizeof(cbuf))
1100       {
1101          errstr = "SOCKS5 username and/or password too long";
1102          err = 1;
1103       }
1104
1105       if (!err)
1106       {
1107          client_pos = 0;
1108          cbuf[client_pos++] = '\x01'; /* Version */
1109          cbuf[client_pos++] = (char)strlen(fwd->auth_username);
1110
1111          memcpy(cbuf + client_pos, fwd->auth_username, strlen(fwd->auth_username));
1112          client_pos += strlen(fwd->auth_username);
1113          cbuf[client_pos++] = (char)strlen(fwd->auth_password);
1114          memcpy(cbuf + client_pos, fwd->auth_password, strlen(fwd->auth_password));
1115          client_pos += strlen(fwd->auth_password);
1116
1117          if (write_socket(sfd, cbuf, client_pos))
1118          {
1119             errstr = "SOCKS5 negotiation auth write failed";
1120             csp->error_message = strdup(errstr);
1121             log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1122             close_socket(sfd);
1123             return(JB_INVALID_SOCKET);
1124          }
1125
1126          if (read_socket(sfd, sbuf, sizeof(sbuf)) != 2)
1127          {
1128             errstr = "SOCKS5 negotiation auth read failed";
1129             err = 1;
1130          }
1131       }
1132
1133       if (!err && (sbuf[1] != '\x00'))
1134       {
1135          errstr = "SOCKS5 authentication failed";
1136          err = 1;
1137       }
1138    }
1139    else if (!err && (sbuf[1] != '\x00'))
1140    {
1141       errstr = "SOCKS5 negotiation protocol error";
1142       err = 1;
1143    }
1144
1145    if (err)
1146    {
1147       assert(errstr != NULL);
1148       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1149       csp->error_message = strdup(errstr);
1150       close_socket(sfd);
1151       errno = EINVAL;
1152       return(JB_INVALID_SOCKET);
1153    }
1154
1155    client_pos = 0;
1156    cbuf[client_pos++] = '\x05'; /* Version */
1157    cbuf[client_pos++] = '\x01'; /* TCP connect */
1158    cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1159    cbuf[client_pos++] = '\x03'; /* Address is domain name */
1160    cbuf[client_pos++] = (char)(hostlen & 0xffu);
1161    assert(sizeof(cbuf) - client_pos > (size_t)255);
1162    /* Using strncpy because we really want the nul byte padding. */
1163    strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos);
1164    client_pos += (hostlen & 0xffu);
1165    cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1166    cbuf[client_pos++] = (char)((target_port     ) & 0xff);
1167
1168 #ifndef FUZZ
1169    if (write_socket(sfd, cbuf, client_pos))
1170    {
1171       errstr = "SOCKS5 negotiation write failed";
1172       csp->error_message = strdup(errstr);
1173       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1174       close_socket(sfd);
1175       errno = EINVAL;
1176       return(JB_INVALID_SOCKET);
1177    }
1178
1179    /*
1180     * Optimistically send the HTTP request with the initial
1181     * SOCKS request if the user enabled the use of Tor extensions,
1182     * the CONNECT method isn't being used (in which case the client
1183     * doesn't send data until it gets our 200 response) and the
1184     * client request has actually been completely read already.
1185     */
1186    if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1187       && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1188    {
1189       char *client_headers = list_to_text(csp->headers);
1190       size_t header_length;
1191
1192       if (client_headers == NULL)
1193       {
1194          log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers");
1195       }
1196       list_remove_all(csp->headers);
1197       header_length= strlen(client_headers);
1198
1199       log_error(LOG_LEVEL_CONNECT,
1200          "Optimistically sending %d bytes of client headers intended for %s",
1201          header_length, csp->http->hostport);
1202
1203       if (write_socket(sfd, client_headers, header_length))
1204       {
1205          log_error(LOG_LEVEL_CONNECT,
1206             "optimistically writing header to: %s failed: %E", csp->http->hostport);
1207          freez(client_headers);
1208          return(JB_INVALID_SOCKET);
1209       }
1210       freez(client_headers);
1211       if (csp->expected_client_content_length != 0)
1212       {
1213          unsigned long long buffered_request_bytes =
1214             (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1215          log_error(LOG_LEVEL_CONNECT,
1216             "Optimistically sending %llu bytes of client body. Expected %llu",
1217             csp->expected_client_content_length, buffered_request_bytes);
1218          assert(csp->expected_client_content_length == buffered_request_bytes);
1219          if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1220          {
1221             log_error(LOG_LEVEL_CONNECT,
1222                "optimistically writing %llu bytes of client body to: %s failed: %E",
1223                buffered_request_bytes, csp->http->hostport);
1224             return(JB_INVALID_SOCKET);
1225          }
1226          clear_iob(csp->client_iob);
1227       }
1228    }
1229 #endif
1230
1231    server_size = read_socket(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4);
1232    if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1233    {
1234       errstr = "SOCKS5 negotiation read failed";
1235    }
1236    else
1237    {
1238       if (sbuf[0] != '\x05')
1239       {
1240          errstr = "SOCKS5 negotiation protocol version error";
1241       }
1242       else if (sbuf[2] != '\x00')
1243       {
1244          errstr = "SOCKS5 negotiation protocol error";
1245       }
1246       else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1247       {
1248          errstr = translate_socks5_error(sbuf[1]);
1249       }
1250       else
1251       {
1252          if (sbuf[3] == '\x04')
1253          {
1254             /*
1255              * The address field contains an IPv6 address
1256              * which means we didn't get the whole reply
1257              * yet. Read and discard the rest of it to make
1258              * sure it isn't treated as HTTP data later on.
1259              */
1260             server_size = read_socket(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE);
1261             if (server_size != SOCKS5_REPLY_DIFFERENCE)
1262             {
1263                errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1264             }
1265          }
1266          else if (sbuf[3] != '\x01')
1267          {
1268              errstr = "SOCKS5 reply contains unsupported address type";
1269          }
1270          if (errstr == NULL)
1271          {
1272             return(sfd);
1273          }
1274       }
1275    }
1276
1277    assert(errstr != NULL);
1278    csp->error_message = strdup(errstr);
1279    log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1280    close_socket(sfd);
1281    errno = EINVAL;
1282
1283    return(JB_INVALID_SOCKET);
1284
1285 }
1286
1287 /*
1288   Local Variables:
1289   tab-width: 3
1290   end:
1291 */