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