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