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