wolfSSL: Use LIBWOLFSSL_VERSION_HEX to decide whether or not to use WOLFSSL_X509_V_OK
[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-2023 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].auth_username == NULL);
235    assert(reusable_connection[slot].auth_password == NULL);
236    assert(reusable_connection[slot].forwarder_type == SOCKS_NONE);
237    assert(reusable_connection[slot].forward_host == NULL);
238    assert(reusable_connection[slot].forward_port == 0);
239
240    reusable_connection[slot].forwarder_type = connection->forwarder_type;
241    if (NULL != connection->gateway_host)
242    {
243       reusable_connection[slot].gateway_host = strdup_or_die(connection->gateway_host);
244    }
245    else
246    {
247       reusable_connection[slot].gateway_host = NULL;
248    }
249    reusable_connection[slot].gateway_port = connection->gateway_port;
250    if (NULL != connection->auth_username)
251    {
252       reusable_connection[slot].auth_username = strdup_or_die(connection->auth_username);
253    }
254    else
255    {
256       reusable_connection[slot].auth_username = NULL;
257    }
258    if (NULL != connection->auth_password)
259    {
260       reusable_connection[slot].auth_password = strdup_or_die(connection->auth_password);
261    }
262    else
263    {
264       reusable_connection[slot].auth_password = NULL;
265    }
266
267    if (NULL != connection->forward_host)
268    {
269       reusable_connection[slot].forward_host = strdup_or_die(connection->forward_host);
270    }
271    else
272    {
273       reusable_connection[slot].forward_host = NULL;
274    }
275    reusable_connection[slot].forward_port = connection->forward_port;
276
277    privoxy_mutex_unlock(&connection_reuse_mutex);
278 }
279 #endif /* def FEATURE_CONNECTION_SHARING */
280
281
282 /*********************************************************************
283  *
284  * Function    :  mark_connection_closed
285  *
286  * Description : Marks a reused connection closed.
287  *
288  * Parameters  :
289  *          1  :  closed_connection = The connection to mark as closed.
290  *
291  * Returns     : void
292  *
293  *********************************************************************/
294 void mark_connection_closed(struct reusable_connection *closed_connection)
295 {
296    closed_connection->in_use = FALSE;
297    closed_connection->sfd = JB_INVALID_SOCKET;
298    freez(closed_connection->host);
299    closed_connection->port = 0;
300    closed_connection->timestamp = 0;
301    closed_connection->request_sent = 0;
302    closed_connection->response_received = 0;
303    closed_connection->keep_alive_timeout = 0;
304    closed_connection->requests_sent_total = 0;
305    closed_connection->forwarder_type = SOCKS_NONE;
306    freez(closed_connection->gateway_host);
307    closed_connection->gateway_port = 0;
308    freez(closed_connection->auth_username);
309    freez(closed_connection->auth_password);
310    freez(closed_connection->forward_host);
311    closed_connection->forward_port = 0;
312 }
313
314
315 #ifdef FEATURE_CONNECTION_SHARING
316 /*********************************************************************
317  *
318  * Function    :  forget_connection
319  *
320  * Description :  Removes a previously remembered connection from
321  *                the list of reusable connections.
322  *
323  * Parameters  :
324  *          1  :  sfd = The socket belonging to the connection in question.
325  *
326  * Returns     : void
327  *
328  *********************************************************************/
329 void forget_connection(jb_socket sfd)
330 {
331    unsigned int slot = 0;
332
333    assert(sfd != JB_INVALID_SOCKET);
334
335    privoxy_mutex_lock(&connection_reuse_mutex);
336
337    for (slot = 0; slot < SZ(reusable_connection); slot++)
338    {
339       if (reusable_connection[slot].sfd == sfd)
340       {
341          assert(reusable_connection[slot].in_use);
342
343          log_error(LOG_LEVEL_CONNECT,
344             "Forgetting socket %d for %s:%d in slot %d.",
345             sfd, reusable_connection[slot].host,
346             reusable_connection[slot].port, slot);
347          mark_connection_closed(&reusable_connection[slot]);
348          break;
349       }
350    }
351
352    privoxy_mutex_unlock(&connection_reuse_mutex);
353
354 }
355 #endif /* def FEATURE_CONNECTION_SHARING */
356
357
358 #ifdef FEATURE_CONNECTION_KEEP_ALIVE
359 /*********************************************************************
360  *
361  * Function    :  string_or_none
362  *
363  * Description :  Returns a given string or "none" if a NULL pointer
364  *                is given.
365  *                Helper function for connection_destination_matches().
366  *
367  * Parameters  :
368  *          1  :  string = The string to check.
369  *
370  * Returns     :  The string if non-NULL, "none" otherwise.
371  *
372  *********************************************************************/
373 static const char *string_or_none(const char *string)
374 {
375    return(string != NULL ? string : "none");
376 }
377
378
379 /*********************************************************************
380  *
381  * Function    :  connection_detail_matches
382  *
383  * Description :  Helper function for connection_destination_matches().
384  *                Compares strings which can be NULL.
385  *
386  * Parameters  :
387  *          1  :  connection_detail = The connection detail to compare.
388  *          2  :  fowarder_detail = The forwarder detail to compare.
389  *
390  * Returns     :  TRUE for yes, FALSE otherwise.
391  *
392  *********************************************************************/
393 static int connection_detail_matches(const char *connection_detail,
394                                      const char *forwarder_detail)
395 {
396    if (connection_detail == NULL && forwarder_detail == NULL)
397    {
398       /* Both details are unset. */
399       return TRUE;
400    }
401
402    if ((connection_detail == NULL && forwarder_detail != NULL)
403     || (connection_detail != NULL && forwarder_detail == NULL))
404    {
405       /* Only one detail isn't set. */
406       return FALSE;
407    }
408
409    /* Both details are set, but do they match? */
410    return(!strcmpic(connection_detail, forwarder_detail));
411
412 }
413
414
415 /*********************************************************************
416  *
417  * Function    :  connection_destination_matches
418  *
419  * Description :  Determines whether a remembered connection can
420  *                be reused. That is, whether the destination and
421  *                the forwarding settings match.
422  *
423  * Parameters  :
424  *          1  :  connection = The connection to check.
425  *          2  :  http = The destination for the connection.
426  *          3  :  fwd  = The forwarder settings.
427  *
428  * Returns     :  TRUE for yes, FALSE otherwise.
429  *
430  *********************************************************************/
431 int connection_destination_matches(const struct reusable_connection *connection,
432                                    const struct http_request *http,
433                                    const struct forward_spec *fwd)
434 {
435    if ((connection->forwarder_type != fwd->type)
436     || (connection->gateway_port   != fwd->gateway_port)
437     || (connection->forward_port   != fwd->forward_port)
438     || (connection->port           != http->port))
439    {
440       return FALSE;
441    }
442
443    if (!connection_detail_matches(connection->gateway_host, fwd->gateway_host))
444    {
445       log_error(LOG_LEVEL_CONNECT,
446          "Gateway mismatch. Previous gateway: %s. Current gateway: %s",
447          string_or_none(connection->gateway_host),
448          string_or_none(fwd->gateway_host));
449       return FALSE;
450    }
451
452    if (!connection_detail_matches(connection->auth_username, fwd->auth_username))
453    {
454       log_error(LOG_LEVEL_CONNECT, "Socks user name mismatch. "
455          "Previous user name: %s. Current user name: %s",
456          string_or_none(connection->auth_username),
457          string_or_none(fwd->auth_username));
458       return FALSE;
459    }
460
461    if (!connection_detail_matches(connection->auth_password, fwd->auth_password))
462    {
463       log_error(LOG_LEVEL_CONNECT, "Socks user name mismatch. "
464          "Previous password: %s. Current password: %s",
465          string_or_none(connection->auth_password),
466          string_or_none(fwd->auth_password));
467       return FALSE;
468    }
469
470    if (!connection_detail_matches(connection->forward_host, fwd->forward_host))
471    {
472       log_error(LOG_LEVEL_CONNECT,
473          "Forwarding proxy mismatch. Previous proxy: %s. Current proxy: %s",
474          string_or_none(connection->forward_host),
475          string_or_none(fwd->forward_host));
476       return FALSE;
477    }
478
479    return (!strcmpic(connection->host, http->host));
480
481 }
482 #endif /* def FEATURE_CONNECTION_KEEP_ALIVE */
483
484
485 #ifdef FEATURE_CONNECTION_SHARING
486 /*********************************************************************
487  *
488  * Function    :  close_unusable_connections
489  *
490  * Description :  Closes remembered connections that have timed
491  *                out or have been closed on the other side.
492  *
493  * Parameters  :  none
494  *
495  * Returns     :  Number of connections that are still alive.
496  *
497  *********************************************************************/
498 int close_unusable_connections(void)
499 {
500    unsigned int slot = 0;
501    int connections_alive = 0;
502
503    privoxy_mutex_lock(&connection_reuse_mutex);
504
505    for (slot = 0; slot < SZ(reusable_connection); slot++)
506    {
507       if (!reusable_connection[slot].in_use
508          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
509       {
510          time_t time_open = time(NULL) - reusable_connection[slot].timestamp;
511          time_t latency = (reusable_connection[slot].response_received -
512             reusable_connection[slot].request_sent) / 2;
513
514          if (reusable_connection[slot].keep_alive_timeout < time_open + latency)
515          {
516             log_error(LOG_LEVEL_CONNECT,
517                "The connection to %s:%d in slot %d timed out. "
518                "Closing socket %d. Timeout is: %d. Assumed latency: %ld.",
519                reusable_connection[slot].host,
520                reusable_connection[slot].port, slot,
521                reusable_connection[slot].sfd,
522                reusable_connection[slot].keep_alive_timeout,
523                latency);
524             close_socket(reusable_connection[slot].sfd);
525             mark_connection_closed(&reusable_connection[slot]);
526          }
527          else if (!socket_is_still_alive(reusable_connection[slot].sfd))
528          {
529             log_error(LOG_LEVEL_CONNECT,
530                "The connection to %s:%d in slot %d is no longer usable. "
531                "Closing socket %d.", reusable_connection[slot].host,
532                reusable_connection[slot].port, slot,
533                reusable_connection[slot].sfd);
534             close_socket(reusable_connection[slot].sfd);
535             mark_connection_closed(&reusable_connection[slot]);
536          }
537          else
538          {
539             connections_alive++;
540          }
541       }
542    }
543
544    privoxy_mutex_unlock(&connection_reuse_mutex);
545
546    return connections_alive;
547
548 }
549
550
551 /*********************************************************************
552  *
553  * Function    :  get_reusable_connection
554  *
555  * Description :  Returns an open socket to a previously remembered
556  *                open connection (if there is one).
557  *
558  * Parameters  :
559  *          1  :  http = The destination for the connection.
560  *          2  :  fwd  = The forwarder settings.
561  *
562  * Returns     :  JB_INVALID_SOCKET => No reusable connection found,
563  *                otherwise a usable socket.
564  *
565  *********************************************************************/
566 static jb_socket get_reusable_connection(const struct http_request *http,
567                                          const struct forward_spec *fwd)
568 {
569    jb_socket sfd = JB_INVALID_SOCKET;
570    unsigned int slot = 0;
571
572    close_unusable_connections();
573
574    privoxy_mutex_lock(&connection_reuse_mutex);
575
576    for (slot = 0; slot < SZ(reusable_connection); slot++)
577    {
578       if (!reusable_connection[slot].in_use
579          && (JB_INVALID_SOCKET != reusable_connection[slot].sfd))
580       {
581          if (connection_destination_matches(&reusable_connection[slot], http, fwd))
582          {
583             reusable_connection[slot].in_use = TRUE;
584             sfd = reusable_connection[slot].sfd;
585             log_error(LOG_LEVEL_CONNECT,
586                "Found reusable socket %d for %s:%d in slot %d. Timestamp made %ld "
587                "seconds ago. Timeout: %d. Latency: %d. Requests served: %d",
588                sfd, reusable_connection[slot].host, reusable_connection[slot].port,
589                slot, time(NULL) - reusable_connection[slot].timestamp,
590                reusable_connection[slot].keep_alive_timeout,
591                (int)(reusable_connection[slot].response_received -
592                reusable_connection[slot].request_sent),
593                reusable_connection[slot].requests_sent_total);
594             break;
595          }
596       }
597    }
598
599    privoxy_mutex_unlock(&connection_reuse_mutex);
600
601    return sfd;
602
603 }
604
605
606 /*********************************************************************
607  *
608  * Function    :  mark_connection_unused
609  *
610  * Description :  Gives a remembered connection free for reuse.
611  *
612  * Parameters  :
613  *          1  :  connection = The connection in question.
614  *
615  * Returns     :  TRUE => Socket found and marked as unused.
616  *                FALSE => Socket not found.
617  *
618  *********************************************************************/
619 static int mark_connection_unused(const struct reusable_connection *connection)
620 {
621    unsigned int slot = 0;
622    int socket_found = FALSE;
623
624    assert(connection->sfd != JB_INVALID_SOCKET);
625
626    privoxy_mutex_lock(&connection_reuse_mutex);
627
628    for (slot = 0; slot < SZ(reusable_connection); slot++)
629    {
630       if (reusable_connection[slot].sfd == connection->sfd)
631       {
632          assert(reusable_connection[slot].in_use);
633          socket_found = TRUE;
634          log_error(LOG_LEVEL_CONNECT,
635             "Marking open socket %d for %s:%d in slot %d as unused.",
636             connection->sfd, reusable_connection[slot].host,
637             reusable_connection[slot].port, slot);
638          reusable_connection[slot].in_use = 0;
639          reusable_connection[slot].timestamp = connection->timestamp;
640          break;
641       }
642    }
643
644    privoxy_mutex_unlock(&connection_reuse_mutex);
645
646    return socket_found;
647
648 }
649 #endif /* def FEATURE_CONNECTION_SHARING */
650
651
652 /*********************************************************************
653  *
654  * Function    :  forwarded_connect
655  *
656  * Description :  Connect to a specified web server, possibly via
657  *                a HTTP proxy and/or a SOCKS proxy.
658  *
659  * Parameters  :
660  *          1  :  fwd = the proxies to use when connecting.
661  *          2  :  http = the http request and apropos headers
662  *          3  :  csp = Current client state (buffers, headers, etc...)
663  *
664  * Returns     :  JB_INVALID_SOCKET => failure, else it is the socket file descriptor.
665  *
666  *********************************************************************/
667 jb_socket forwarded_connect(const struct forward_spec *fwd,
668                             struct http_request *http,
669                             struct client_state *csp)
670 {
671    const char *dest_host;
672    int dest_port;
673    jb_socket sfd = JB_INVALID_SOCKET;
674
675 #ifdef FEATURE_CONNECTION_SHARING
676    if ((csp->config->feature_flags & RUNTIME_FEATURE_CONNECTION_SHARING)
677       && !(csp->flags & CSP_FLAG_SERVER_SOCKET_TAINTED))
678    {
679       sfd = get_reusable_connection(http, fwd);
680       if (JB_INVALID_SOCKET != sfd)
681       {
682          return sfd;
683       }
684    }
685 #endif /* def FEATURE_CONNECTION_SHARING */
686
687    /* Figure out if we need to connect to the web server or a HTTP proxy. */
688    if (fwd->forward_host)
689    {
690       /* HTTP proxy */
691       dest_host = fwd->forward_host;
692       dest_port = fwd->forward_port;
693    }
694    else
695    {
696       /* Web server */
697       dest_host = http->host;
698       dest_port = http->port;
699    }
700
701    /* Connect, maybe using a SOCKS proxy */
702    switch (fwd->type)
703    {
704       case SOCKS_NONE:
705       case FORWARD_WEBSERVER:
706          sfd = connect_to(dest_host, dest_port, csp);
707          break;
708       case SOCKS_4:
709       case SOCKS_4A:
710          sfd = socks4_connect(fwd, dest_host, dest_port, csp);
711          break;
712       case SOCKS_5:
713       case SOCKS_5T:
714          sfd = socks5_connect(fwd, dest_host, dest_port, csp);
715          break;
716       default:
717          /* Should never get here */
718          log_error(LOG_LEVEL_FATAL,
719             "Internal error in forwarded_connect(). Bad proxy type: %d", fwd->type);
720    }
721
722    if (JB_INVALID_SOCKET != sfd)
723    {
724       log_error(LOG_LEVEL_CONNECT,
725          "Created new connection to %s:%d on socket %d.",
726          http->host, http->port, sfd);
727    }
728
729    return sfd;
730
731 }
732
733
734 #ifdef FUZZ
735 /*********************************************************************
736  *
737  * Function    :  socks_fuzz
738  *
739  * Description :  Wrapper around socks[45]_connect() used for fuzzing.
740  *
741  * Parameters  :
742  *          1  :  csp = Current client state (buffers, headers, etc...)
743  *
744  * Returns     :  JB_ERR_OK or JB_ERR_PARSE
745  *
746  *********************************************************************/
747 extern jb_err socks_fuzz(struct client_state *csp)
748 {
749    jb_socket socket;
750    static struct forward_spec fwd;
751    char target_host[] = "fuzz.example.org";
752    int target_port = 12345;
753
754    fwd.gateway_host = strdup_or_die("fuzz.example.org");
755    fwd.gateway_port = 12345;
756
757    fwd.type = SOCKS_4A;
758    socket = socks4_connect(&fwd, target_host, target_port, csp);
759
760    if (JB_INVALID_SOCKET != socket)
761    {
762       fwd.type = SOCKS_5;
763       socket = socks5_connect(&fwd, target_host, target_port, csp);
764    }
765
766    if (JB_INVALID_SOCKET == socket)
767    {
768       log_error(LOG_LEVEL_ERROR, "%s", csp->error_message);
769       return JB_ERR_PARSE;
770    }
771
772    log_error(LOG_LEVEL_INFO, "Input looks like an acceptable socks response");
773
774    return JB_ERR_OK;
775
776 }
777 #endif
778
779 /*********************************************************************
780  *
781  * Function    :  socks4_connect
782  *
783  * Description :  Connect to the SOCKS server, and connect through
784  *                it to the specified server.   This handles
785  *                all the SOCKS negotiation, and returns a file
786  *                descriptor for a socket which can be treated as a
787  *                normal (non-SOCKS) socket.
788  *
789  *                Logged error messages are saved to csp->error_message
790  *                and later reused by error_response() for the CGI
791  *                message. strdup allocation failures are handled there.
792  *
793  * Parameters  :
794  *          1  :  fwd = Specifies the SOCKS proxy to use.
795  *          2  :  target_host = The final server to connect to.
796  *          3  :  target_port = The final port to connect to.
797  *          4  :  csp = Current client state (buffers, headers, etc...)
798  *
799  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
800  *
801  *********************************************************************/
802 static jb_socket socks4_connect(const struct forward_spec *fwd,
803                                 const char *target_host,
804                                 int target_port,
805                                 struct client_state *csp)
806 {
807    unsigned long web_server_addr;
808    char buf[BUFFER_SIZE];
809    struct socks_op    *c = (struct socks_op    *)buf;
810    struct socks_reply *s = (struct socks_reply *)buf;
811    size_t n;
812    size_t csiz;
813    jb_socket sfd;
814    int err = 0;
815    char *errstr = NULL;
816
817    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
818    {
819       /* XXX: Shouldn't the config file parser prevent this? */
820       errstr = "NULL gateway host specified.";
821       err = 1;
822    }
823
824    if (fwd->gateway_port <= 0)
825    {
826       errstr = "invalid gateway port specified.";
827       err = 1;
828    }
829
830    if (err)
831    {
832       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
833       csp->error_message = strdup(errstr);
834       errno = EINVAL;
835       return(JB_INVALID_SOCKET);
836    }
837
838    /* build a socks request for connection to the web server */
839
840    /*
841     * The more straightforward &(c->userid) destination pointer can
842     * cause some gcc versions to misidentify the size of the destination
843     * buffer, tripping the runtime check of glibc's source fortification.
844     */
845    strlcpy(buf + offsetof(struct socks_op, userid), socks_userid,
846       sizeof(buf) - sizeof(struct socks_op));
847
848    csiz = sizeof(*c) + sizeof(socks_userid) - sizeof(c->userid) - sizeof(c->padding);
849
850    switch (fwd->type)
851    {
852       case SOCKS_4:
853          web_server_addr = resolve_hostname_to_ip(target_host);
854          if (web_server_addr == INADDR_NONE)
855          {
856             errstr = "could not resolve target host";
857             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s %s", errstr, target_host);
858             err = 1;
859          }
860          else
861          {
862             web_server_addr = htonl(web_server_addr);
863          }
864          break;
865       case SOCKS_4A:
866          web_server_addr = 0x00000001;
867          n = csiz + strlen(target_host) + 1;
868          if (n > sizeof(buf))
869          {
870             errno = EINVAL;
871             errstr = "buffer cbuf too small.";
872             log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
873             err = 1;
874          }
875          else
876          {
877             strlcpy(buf + csiz, target_host, sizeof(buf) - sizeof(struct socks_op) - csiz);
878             /*
879              * What we forward to the socks4a server should have the
880              * size of socks_op, plus the length of the userid plus
881              * its \0 byte (which we don't have to add because the
882              * first byte of the userid is counted twice as it's also
883              * part of sock_op) minus the padding bytes (which are part
884              * of the userid as well), plus the length of the target_host
885              * (which is stored csiz bytes after the beginning of the buffer),
886              * plus another \0 byte.
887              */
888             assert(n == sizeof(struct socks_op) + strlen(&(c->userid)) - sizeof(c->padding) + strlen(buf + csiz) + 1);
889             csiz = n;
890          }
891          break;
892       default:
893          /* Should never get here */
894          log_error(LOG_LEVEL_FATAL,
895             "socks4_connect: SOCKS4 impossible internal error - bad SOCKS type.");
896          /* Not reached */
897          return(JB_INVALID_SOCKET);
898    }
899
900    if (err)
901    {
902       csp->error_message = strdup(errstr);
903       return(JB_INVALID_SOCKET);
904    }
905
906    c->vn          = 4;
907    c->cd          = 1;
908    c->dstport[0]  = (unsigned char)((target_port       >> 8 ) & 0xff);
909    c->dstport[1]  = (unsigned char)((target_port            ) & 0xff);
910    c->dstip[0]    = (unsigned char)((web_server_addr   >> 24) & 0xff);
911    c->dstip[1]    = (unsigned char)((web_server_addr   >> 16) & 0xff);
912    c->dstip[2]    = (unsigned char)((web_server_addr   >>  8) & 0xff);
913    c->dstip[3]    = (unsigned char)((web_server_addr        ) & 0xff);
914
915 #ifdef FUZZ
916    sfd = 0;
917 #else
918    /* pass the request to the socks server */
919    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
920
921    if (sfd == JB_INVALID_SOCKET)
922    {
923       /* The error an its reason have already been logged by connect_to()  */
924       return(JB_INVALID_SOCKET);
925    }
926    else if (write_socket(sfd, (char *)c, csiz))
927    {
928       errstr = "SOCKS4 negotiation write failed.";
929       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
930       err = 1;
931       close_socket(sfd);
932    }
933    else if (!data_is_available(sfd, csp->config->socket_timeout))
934    {
935       if (socket_is_still_alive(sfd))
936       {
937          errstr = "SOCKS4 negotiation timed out";
938       }
939       else
940       {
941          errstr = "SOCKS4 negotiation got aborted by the server";
942       }
943       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
944       err = 1;
945       close_socket(sfd);
946    }
947    else
948 #endif
949        if (read_socket(sfd, buf, sizeof(buf)) != sizeof(*s))
950    {
951       errstr = "SOCKS4 negotiation read failed.";
952       log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
953       err = 1;
954       close_socket(sfd);
955    }
956
957    if (err)
958    {
959       csp->error_message = strdup(errstr);
960       return(JB_INVALID_SOCKET);
961    }
962
963    switch (s->cd)
964    {
965       case SOCKS4_REQUEST_GRANTED:
966          return(sfd);
967       case SOCKS4_REQUEST_REJECT:
968          errstr = "SOCKS request rejected or failed.";
969          errno = EINVAL;
970          break;
971       case SOCKS4_REQUEST_IDENT_FAILED:
972          errstr = "SOCKS request rejected because "
973             "SOCKS server cannot connect to identd on the client.";
974          errno = EACCES;
975          break;
976       case SOCKS4_REQUEST_IDENT_CONFLICT:
977          errstr = "SOCKS request rejected because "
978             "the client program and identd report "
979             "different user-ids.";
980          errno = EACCES;
981          break;
982       default:
983          errno = ENOENT;
984          snprintf(buf, sizeof(buf),
985             "SOCKS request rejected for reason code %d.", s->cd);
986          errstr = buf;
987    }
988
989    log_error(LOG_LEVEL_CONNECT, "socks4_connect: %s", errstr);
990    csp->error_message = strdup(errstr);
991    close_socket(sfd);
992
993    return(JB_INVALID_SOCKET);
994
995 }
996
997 /*********************************************************************
998  *
999  * Function    :  translate_socks5_error
1000  *
1001  * Description :  Translates a SOCKS errors to a string.
1002  *
1003  * Parameters  :
1004  *          1  :  socks_error = The error code to translate.
1005  *
1006  * Returns     :  The string translation.
1007  *
1008  *********************************************************************/
1009 static const char *translate_socks5_error(int socks_error)
1010 {
1011    switch (socks_error)
1012    {
1013       /* XXX: these should be more descriptive */
1014       case SOCKS5_REQUEST_FAILED:
1015          return "SOCKS5 request failed";
1016       case SOCKS5_REQUEST_DENIED:
1017          return "SOCKS5 request denied";
1018       case SOCKS5_REQUEST_NETWORK_UNREACHABLE:
1019          return "SOCKS5 network unreachable";
1020       case SOCKS5_REQUEST_HOST_UNREACHABLE:
1021          return "SOCKS5 destination host unreachable";
1022       case SOCKS5_REQUEST_CONNECTION_REFUSED:
1023          return "SOCKS5 connection refused";
1024       case SOCKS5_REQUEST_TTL_EXPIRED:
1025          return "SOCKS5 TTL expired";
1026       case SOCKS5_REQUEST_PROTOCOL_ERROR:
1027          return "SOCKS5 client protocol error";
1028       case SOCKS5_REQUEST_BAD_ADDRESS_TYPE:
1029          return "SOCKS5 domain names unsupported";
1030       case SOCKS5_REQUEST_GRANTED:
1031          return "everything's peachy";
1032       default:
1033          return "SOCKS5 negotiation protocol error";
1034    }
1035 }
1036
1037
1038 /*********************************************************************
1039  *
1040  * Function    :  convert_ipv4_address_to_bytes
1041  *
1042  * Description :  Converts an IPv4 address from string to bytes.
1043  *
1044  * Parameters  :
1045  *          1  :  address = The IPv4 address string to convert.
1046  *          2  :  buf = The buffer to write the bytes to.
1047  *                      Must be at least four bytes long.
1048  *
1049  * Returns     :  JB_ERR_OK on success, JB_ERR_PARSE otherwise.
1050  *
1051  *********************************************************************/
1052 static jb_err convert_ipv4_address_to_bytes(const char *address, char *buf)
1053 {
1054    int i;
1055    const char *p = address;
1056
1057    for (i = 0; i < 4; i++)
1058    {
1059       unsigned byte;
1060       if (1 != sscanf(p, "%u", &byte))
1061       {
1062          return JB_ERR_PARSE;
1063       }
1064       if (byte > 255)
1065       {
1066          return JB_ERR_PARSE;
1067       }
1068       buf[i] = (char)byte;
1069       if (i < 3)
1070       {
1071          p = strstr(p, ".");
1072          if (p == NULL)
1073          {
1074             return JB_ERR_PARSE;
1075          }
1076          p++;
1077       }
1078    }
1079
1080    return JB_ERR_OK;
1081
1082 }
1083
1084
1085 /*********************************************************************
1086  *
1087  * Function    :  read_socks_reply
1088  *
1089  * Description :  Read from a socket connected to a socks server.
1090  *
1091  * Parameters  :
1092  *          1  :  sfd = file descriptor of the socket to read
1093  *          2  :  buf = pointer to buffer where data will be written
1094  *                Must be >= len bytes long.
1095  *          3  :  len = maximum number of bytes to read
1096  *          4  :  timeout = Number of seconds to wait.
1097  *
1098  * Returns     :  On success, the number of bytes read is returned (zero
1099  *                indicates end of file), and the file position is advanced
1100  *                by this number.  It is not an error if this number is
1101  *                smaller than the number of bytes requested; this may hap-
1102  *                pen for example because fewer bytes are actually available
1103  *                right now (maybe because we were close to end-of-file, or
1104  *                because we are reading from a pipe, or from a terminal,
1105  *                or because read() was interrupted by a signal).  On error,
1106  *                -1 is returned, and errno is set appropriately.  In this
1107  *                case it is left unspecified whether the file position (if
1108  *                any) changes.
1109  *
1110  *********************************************************************/
1111 static int read_socks_reply(jb_socket sfd, char *buf, int len, int timeout)
1112 {
1113    if (!data_is_available(sfd, timeout))
1114    {
1115       if (socket_is_still_alive(sfd))
1116       {
1117          log_error(LOG_LEVEL_ERROR,
1118             "The socks connection timed out after %d seconds.", timeout);
1119       }
1120       else
1121       {
1122          log_error(LOG_LEVEL_ERROR, "The socks server hung "
1123             "up the connection without sending a response.");
1124       }
1125       return -1;
1126    }
1127
1128    return read_socket(sfd, buf, len);
1129
1130 }
1131
1132
1133 /*********************************************************************
1134  *
1135  * Function    :  socks5_connect
1136  *
1137  * Description :  Connect to the SOCKS server, and connect through
1138  *                it to the specified server.   This handles
1139  *                all the SOCKS negotiation, and returns a file
1140  *                descriptor for a socket which can be treated as a
1141  *                normal (non-SOCKS) socket.
1142  *
1143  * Parameters  :
1144  *          1  :  fwd = Specifies the SOCKS proxy to use.
1145  *          2  :  target_host = The final server to connect to.
1146  *          3  :  target_port = The final port to connect to.
1147  *          4  :  csp = Current client state (buffers, headers, etc...)
1148  *
1149  * Returns     :  JB_INVALID_SOCKET => failure, else a socket file descriptor.
1150  *
1151  *********************************************************************/
1152 static jb_socket socks5_connect(const struct forward_spec *fwd,
1153                                 const char *target_host,
1154                                 int target_port,
1155                                 struct client_state *csp)
1156 {
1157 #define SIZE_SOCKS5_REPLY_IPV4 10
1158 #define SIZE_SOCKS5_REPLY_IPV6 22
1159 #define SIZE_SOCKS5_REPLY_DOMAIN 300
1160 #define SOCKS5_REPLY_DIFFERENCE (SIZE_SOCKS5_REPLY_IPV6 - SIZE_SOCKS5_REPLY_IPV4)
1161    int err = 0;
1162    char cbuf[300];
1163    char sbuf[SIZE_SOCKS5_REPLY_DOMAIN];
1164    size_t client_pos = 0;
1165    int server_size = 0;
1166    size_t hostlen = 0;
1167    jb_socket sfd;
1168    const char *errstr = NULL;
1169
1170    assert(fwd->gateway_host);
1171    if ((fwd->gateway_host == NULL) || (*fwd->gateway_host == '\0'))
1172    {
1173       errstr = "NULL gateway host specified";
1174       err = 1;
1175    }
1176
1177    if (fwd->gateway_port <= 0)
1178    {
1179       /*
1180        * XXX: currently this can't happen because in
1181        * case of invalid gateway ports we use the defaults.
1182        * Of course we really shouldn't do that.
1183        */
1184       errstr = "invalid gateway port specified";
1185       err = 1;
1186    }
1187
1188    hostlen = strlen(target_host);
1189    if (hostlen > (size_t)255)
1190    {
1191       errstr = "target host name is longer than 255 characters";
1192       err = 1;
1193    }
1194
1195    if ((fwd->type != SOCKS_5) && (fwd->type != SOCKS_5T))
1196    {
1197       /* Should never get here */
1198       log_error(LOG_LEVEL_FATAL,
1199          "SOCKS5 impossible internal error - bad SOCKS type");
1200       err = 1;
1201    }
1202
1203    if (err)
1204    {
1205       errno = EINVAL;
1206       assert(errstr != NULL);
1207       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1208       csp->error_message = strdup(errstr);
1209       return(JB_INVALID_SOCKET);
1210    }
1211
1212 #ifdef FUZZ
1213    sfd = 0;
1214    if (!err && read_socket(sfd, sbuf, 2) != 2)
1215 #else
1216    /* pass the request to the socks server */
1217    sfd = connect_to(fwd->gateway_host, fwd->gateway_port, csp);
1218
1219    if (sfd == JB_INVALID_SOCKET)
1220    {
1221       errstr = "socks5 server unreachable";
1222       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1223       /* Free the generic error message provided by connect_to() */
1224       freez(csp->error_message);
1225       csp->error_message = strdup(errstr);
1226       return(JB_INVALID_SOCKET);
1227    }
1228
1229    client_pos = 0;
1230    cbuf[client_pos++] = '\x05'; /* Version */
1231
1232    if (fwd->auth_username && fwd->auth_password)
1233    {
1234       cbuf[client_pos++] = '\x02'; /* Two authentication methods supported */
1235       cbuf[client_pos++] = '\x02'; /* Username/password */
1236    }
1237    else
1238    {
1239       cbuf[client_pos++] = '\x01'; /* One authentication method supported */
1240    }
1241    cbuf[client_pos++] = '\x00'; /* The no authentication authentication method */
1242
1243    if (write_socket(sfd, cbuf, client_pos))
1244    {
1245       errstr = "SOCKS5 negotiation write failed";
1246       csp->error_message = strdup(errstr);
1247       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1248       close_socket(sfd);
1249       return(JB_INVALID_SOCKET);
1250    }
1251    if (read_socks_reply(sfd, sbuf, sizeof(sbuf),
1252          csp->config->socket_timeout) != 2)
1253 #endif
1254    {
1255       errstr = "SOCKS5 negotiation read failed";
1256       err = 1;
1257    }
1258
1259    if (!err && (sbuf[0] != '\x05'))
1260    {
1261       errstr = "SOCKS5 negotiation protocol version error";
1262       err = 1;
1263    }
1264
1265    if (!err && (sbuf[1] == '\xff'))
1266    {
1267       errstr = "SOCKS5 authentication required";
1268       err = 1;
1269    }
1270
1271    if (!err && (sbuf[1] == '\x02'))
1272    {
1273       if (fwd->auth_username && fwd->auth_password)
1274       {
1275          /* check cbuf overflow */
1276          size_t auth_len = strlen(fwd->auth_username) + strlen(fwd->auth_password) + 3;
1277          if (auth_len > sizeof(cbuf))
1278          {
1279             errstr = "SOCKS5 username and/or password too long";
1280             err = 1;
1281          }
1282       }
1283       else
1284       {
1285          errstr = "SOCKS5 server requested authentication while "
1286             "no credentials are configured";
1287          err = 1;
1288       }
1289
1290       if (!err)
1291       {
1292          client_pos = 0;
1293          cbuf[client_pos++] = '\x01'; /* Version */
1294          cbuf[client_pos++] = (char)strlen(fwd->auth_username);
1295
1296          memcpy(cbuf + client_pos, fwd->auth_username, strlen(fwd->auth_username));
1297          client_pos += strlen(fwd->auth_username);
1298          cbuf[client_pos++] = (char)strlen(fwd->auth_password);
1299          memcpy(cbuf + client_pos, fwd->auth_password, strlen(fwd->auth_password));
1300          client_pos += strlen(fwd->auth_password);
1301
1302          if (write_socket(sfd, cbuf, client_pos))
1303          {
1304             errstr = "SOCKS5 negotiation auth write failed";
1305             csp->error_message = strdup(errstr);
1306             log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1307             close_socket(sfd);
1308             return(JB_INVALID_SOCKET);
1309          }
1310
1311          if (read_socks_reply(sfd, sbuf, sizeof(sbuf),
1312                csp->config->socket_timeout) != 2)
1313          {
1314             errstr = "SOCKS5 negotiation auth read failed";
1315             err = 1;
1316          }
1317       }
1318
1319       if (!err && (sbuf[1] != '\x00'))
1320       {
1321          errstr = "SOCKS5 authentication failed";
1322          err = 1;
1323       }
1324    }
1325    else if (!err && (sbuf[1] != '\x00'))
1326    {
1327       errstr = "SOCKS5 negotiation protocol error";
1328       err = 1;
1329    }
1330
1331    if (err)
1332    {
1333       assert(errstr != NULL);
1334       log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1335       csp->error_message = strdup(errstr);
1336       close_socket(sfd);
1337       errno = EINVAL;
1338       return(JB_INVALID_SOCKET);
1339    }
1340
1341    client_pos = 0;
1342    cbuf[client_pos++] = '\x05'; /* Version */
1343    cbuf[client_pos++] = '\x01'; /* TCP connect */
1344    cbuf[client_pos++] = '\x00'; /* Reserved, must be 0x00 */
1345    if (host_is_ip_address(target_host) && NULL == strstr(target_host, ":"))
1346    {
1347       cbuf[client_pos++] = '\x01'; /* Address is IPv4 address. */
1348       if (JB_ERR_OK != convert_ipv4_address_to_bytes(target_host, &cbuf[client_pos]))
1349       {
1350          errstr = "SOCKS5 error. Failed to convert target address to IP address";
1351          csp->error_message = strdup(errstr);
1352          log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1353          close_socket(sfd);
1354          errno = EINVAL;
1355          return(JB_INVALID_SOCKET);
1356       }
1357       client_pos += 4;
1358    }
1359    else
1360    {
1361       /*
1362        * XXX: This branch is currently also used for IPv6 addresses
1363        */
1364       cbuf[client_pos++] = '\x03'; /* Address is domain name. */
1365       cbuf[client_pos++] = (char)(hostlen & 0xffu);
1366       assert(sizeof(cbuf) - client_pos > (size_t)255);
1367       /* Using strncpy because we really want the nul byte padding. */
1368       strncpy(cbuf + client_pos, target_host, sizeof(cbuf) - client_pos - 1);
1369       client_pos += (hostlen & 0xffu);
1370    }
1371    cbuf[client_pos++] = (char)((target_port >> 8) & 0xff);
1372    cbuf[client_pos++] = (char)((target_port     ) & 0xff);
1373
1374 #ifndef FUZZ
1375    if (write_socket(sfd, cbuf, client_pos))
1376    {
1377       errstr = "SOCKS5 negotiation write failed";
1378       csp->error_message = strdup(errstr);
1379       log_error(LOG_LEVEL_CONNECT, "%s", errstr);
1380       close_socket(sfd);
1381       errno = EINVAL;
1382       return(JB_INVALID_SOCKET);
1383    }
1384
1385    /*
1386     * Optimistically send the HTTP request with the initial
1387     * SOCKS request if the user enabled the use of Tor extensions,
1388     * the CONNECT method isn't being used (in which case the client
1389     * doesn't send data until it gets our 200 response) and the
1390     * client request has actually been completely read already.
1391     */
1392    if ((fwd->type == SOCKS_5T) && (csp->http->ssl == 0)
1393       && (csp->flags & CSP_FLAG_CLIENT_REQUEST_COMPLETELY_READ))
1394    {
1395       char *client_headers = list_to_text(csp->headers);
1396       size_t header_length;
1397
1398       if (client_headers == NULL)
1399       {
1400          log_error(LOG_LEVEL_FATAL, "Out of memory rebuilding client headers.");
1401       }
1402       list_remove_all(csp->headers);
1403       header_length= strlen(client_headers);
1404
1405       log_error(LOG_LEVEL_CONNECT,
1406          "Optimistically sending %lu bytes of client headers intended for %s.",
1407          header_length, csp->http->hostport);
1408
1409       if (write_socket(sfd, client_headers, header_length))
1410       {
1411          log_error(LOG_LEVEL_CONNECT,
1412             "optimistically writing header to: %s failed: %E", csp->http->hostport);
1413          freez(client_headers);
1414          return(JB_INVALID_SOCKET);
1415       }
1416       freez(client_headers);
1417       if (csp->expected_client_content_length != 0)
1418       {
1419          unsigned long long buffered_request_bytes =
1420             (unsigned long long)(csp->client_iob->eod - csp->client_iob->cur);
1421          log_error(LOG_LEVEL_CONNECT,
1422             "Optimistically sending %llu bytes of client body. Expected %llu.",
1423             csp->expected_client_content_length, buffered_request_bytes);
1424          assert(csp->expected_client_content_length == buffered_request_bytes);
1425          if (write_socket(sfd, csp->client_iob->cur, buffered_request_bytes))
1426          {
1427             log_error(LOG_LEVEL_CONNECT,
1428                "optimistically writing %llu bytes of client body to: %s failed: %E",
1429                buffered_request_bytes, csp->http->hostport);
1430             return(JB_INVALID_SOCKET);
1431          }
1432          clear_iob(csp->client_iob);
1433       }
1434    }
1435 #endif
1436
1437    server_size = read_socks_reply(sfd, sbuf, SIZE_SOCKS5_REPLY_IPV4,
1438       csp->config->socket_timeout);
1439    if (server_size != SIZE_SOCKS5_REPLY_IPV4)
1440    {
1441       errstr = "SOCKS5 negotiation read failed";
1442    }
1443    else
1444    {
1445       if (sbuf[0] != '\x05')
1446       {
1447          errstr = "SOCKS5 negotiation protocol version error";
1448       }
1449       else if (sbuf[2] != '\x00')
1450       {
1451          errstr = "SOCKS5 negotiation protocol error";
1452       }
1453       else if (sbuf[1] != SOCKS5_REQUEST_GRANTED)
1454       {
1455          errstr = translate_socks5_error(sbuf[1]);
1456       }
1457       else
1458       {
1459          if (sbuf[3] == '\x04')
1460          {
1461             /*
1462              * The address field contains an IPv6 address
1463              * which means we didn't get the whole reply
1464              * yet. Read and discard the rest of it to make
1465              * sure it isn't treated as HTTP data later on.
1466              */
1467             server_size = read_socks_reply(sfd, sbuf, SOCKS5_REPLY_DIFFERENCE,
1468                csp->config->socket_timeout);
1469             if (server_size != SOCKS5_REPLY_DIFFERENCE)
1470             {
1471                errstr = "SOCKS5 negotiation read failed (IPv6 address)";
1472             }
1473          }
1474          else if (sbuf[3] == '\x03')
1475          {
1476             /*
1477              * The address field contains a domain name
1478              * which means we didn't get the whole reply
1479              * yet. Read and discard the rest of it to make
1480              * sure it isn't treated as HTTP data later on.
1481              */
1482             unsigned domain_length = (unsigned)sbuf[4];
1483             int bytes_left_to_read = 5 + (int)domain_length + 2 - SIZE_SOCKS5_REPLY_IPV4;
1484             if (bytes_left_to_read <= 0 || sizeof(sbuf) < bytes_left_to_read)
1485             {
1486                errstr = "SOCKS5 negotiation read failed (Invalid domain length)";
1487             }
1488             else
1489             {
1490                server_size = read_socks_reply(sfd, sbuf, bytes_left_to_read,
1491                   csp->config->socket_timeout);
1492                if (server_size != bytes_left_to_read)
1493                {
1494                   errstr = "SOCKS5 negotiation read failed (Domain name)";
1495                }
1496             }
1497          }
1498          else if (sbuf[3] != '\x01')
1499          {
1500             errstr = "SOCKS5 reply contains unsupported address type";
1501          }
1502          if (errstr == NULL)
1503          {
1504             return(sfd);
1505          }
1506       }
1507    }
1508
1509    assert(errstr != NULL);
1510    csp->error_message = strdup(errstr);
1511    log_error(LOG_LEVEL_CONNECT, "socks5_connect: %s", errstr);
1512    close_socket(sfd);
1513    errno = EINVAL;
1514
1515    return(JB_INVALID_SOCKET);
1516
1517 }
1518
1519 /*
1520   Local Variables:
1521   tab-width: 3
1522   end:
1523 */