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