Skip to content

Commit

Permalink
rbreaking change: prefer IPV6
Browse files Browse the repository at this point in the history
This change implements the happy eyeballs strategy to bnring better support of IPv6 for hackney.

It follows the recommendations iof the RFC 8305. https://datatracker.ietf.org/doc/html/rfc8305
  • Loading branch information
benoitc committed Feb 21, 2024
1 parent 7ae3831 commit 87aeb8e
Show file tree
Hide file tree
Showing 11 changed files with 720 additions and 42 deletions.
3 changes: 3 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,6 @@ Copyright (c) 2009, Erlang Training and Consulting Ltd.
Copyright (C) 1998 - 2014, Daniel Stenberg, <[email protected]>, et al.

*) hackney_trace (C) 2015 under the Erlang Public LicensE

*) hackney_cidr is based on inet_cidr 1.2.1. vendored for customer purpose.
Copyright (c) 2024, Enki Multimedia , MIT License
3 changes: 3 additions & 0 deletions rebar.lock
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{"1.2.0",
[{<<"certifi">>,{pkg,<<"certifi">>,<<"2.12.0">>},0},
{<<"idna">>,{pkg,<<"idna">>,<<"6.1.1">>},0},
{<<"inet_cidr">>,{pkg,<<"erl_cidr">>,<<"1.2.1">>},0},
{<<"metrics">>,{pkg,<<"metrics">>,<<"1.0.1">>},0},
{<<"mimerl">>,{pkg,<<"mimerl">>,<<"1.2.0">>},0},
{<<"parse_trans">>,{pkg,<<"parse_trans">>,<<"3.4.1">>},0},
Expand All @@ -10,6 +11,7 @@
{pkg_hash,[
{<<"certifi">>, <<"2D1CCA2EC95F59643862AF91F001478C9863C2AC9CB6E2F89780BFD8DE987329">>},
{<<"idna">>, <<"8A63070E9F7D0C62EB9D9FCB360A7DE382448200FBBD1B106CC96D3D8099DF8D">>},
{<<"inet_cidr">>, <<"921BB463BCF10EAD937AE491E5BCAC2823E550B339A9893AC6574518553CC067">>},
{<<"metrics">>, <<"25F094DEA2CDA98213CECC3AEFF09E940299D950904393B2A29D191C346A8486">>},
{<<"mimerl">>, <<"67E2D3F571088D5CFD3E550C383094B47159F3EEE8FFA08E64106CDF5E981BE3">>},
{<<"parse_trans">>, <<"6E6AA8167CB44CC8F39441D05193BE6E6F4E7C2946CB2759F015F8C56B76E5FF">>},
Expand All @@ -18,6 +20,7 @@
{pkg_hash_ext,[
{<<"certifi">>, <<"EE68D85DF22E554040CDB4BE100F33873AC6051387BAF6A8F6CE82272340FF1C">>},
{<<"idna">>, <<"92376EB7894412ED19AC475E4A86F7B413C1B9FBB5BD16DCCD57934157944CEA">>},
{<<"inet_cidr">>, <<"FCF5D51B1CC1B26D1748AB39F9B614AB445AD17172A9396D48C6B5C15EA9EFCF">>},
{<<"metrics">>, <<"69B09ADDDC4F74A40716AE54D140F93BEB0FB8978D8636EADED0C31B6F099F16">>},
{<<"mimerl">>, <<"F278585650AA581986264638EBF698F8BB19DF297F66AD91B18910DFC6E19323">>},
{<<"parse_trans">>, <<"620A406CE75DADA827B82E453C19CF06776BE266F5A67CFF34E1EF2CBB60E49A">>},
Expand Down
20 changes: 3 additions & 17 deletions src/hackney_connection.erl
Original file line number Diff line number Diff line change
Expand Up @@ -102,27 +102,13 @@ connect_options(hackney_local_tcp, _Host, ClientOptions) ->
proplists:get_value(connect_options, ClientOptions, []);

connect_options(Transport, Host, ClientOptions) ->
ConnectOpts0 = proplists:get_value(connect_options, ClientOptions, []),

%% handle ipv6
ConnectOpts1 = case lists:member(inet, ConnectOpts0) orelse
lists:member(inet6, ConnectOpts0) of
true ->
ConnectOpts0;
false ->
case hackney_util:is_ipv6(Host) of
true ->
[inet6 | ConnectOpts0];
false ->
ConnectOpts0
end
end,
ConnectOpts = proplists:get_value(connect_options, ClientOptions, []),

case Transport of
hackney_ssl ->
ConnectOpts1 ++ ssl_opts(Host, ClientOptions);
[{ssl_options, ssl_opts(Host, ClientOptions)} | ConnectOpts];
_ ->
ConnectOpts1
ConnectOpts
end.


Expand Down
72 changes: 72 additions & 0 deletions src/hackney_happy.erl
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
-module(hackney_happy).

-export([connect/3, connect/4]).

-include("hackney_internal.hrl").
-include_lib("kernel/include/inet.hrl").

-define(TIMEOUT, 250).
-define(CONNECT_TIMEOUT, 5000).

connect(Hostname, Port, Opts) ->
connect(Hostname, Port, Opts, ?CONNECT_TIMEOUT).

connect(Hostname, Port, Opts, Timeout) ->
case hackney_cidr:is_ipv6(Hostname) of
true ->
?report_debug("connect using IPv6", [{hostname, Hostname}, {port, Port}]),
gen_tcp:connect(Hostname, Port, [inet6 | Opts], Timeout);
false ->
case hackney_cidr:is_ipv4(Hostname) of
true ->
?report_debug("connect using IPv4", [{hostname, Hostname}, {port, Port}]),
gen_tcp:connect(Hostname, Port, [inet | Opts], Timeout);
false ->
?report_debug("happy eyeballs, try to connect using IPv6", [{hostname, Hostname}, {port, Port}]),
Self = self(),
Addrs = getaddrs(Hostname),
Pid = spawn_link( fun() -> try_connect(Addrs, Port, Opts, Self, {error, nxdomain}) end),
MRef = erlang:monitor(process, Pid),
receive
{happy_connect, OK} ->
erlang:demonitor(MRef, [flush]),
OK;
{'DOWN', MRef, _Type, _Pid, Info} ->
{'error', {'connect_error', Info}}
after Timeout ->
erlang:demonitor(MRef, [flush]),
{error, connect_timeout}
end
end
end.

getaddrs(Hostname) ->
IP6Addrs = [{Addr, 'inet6'} || Addr <- getbyname(Hostname, 'aaaa')],
IP4Addrs = [{Addr, 'inet'} || Addr <- getbyname(Hostname, 'a')],
IP6Addrs ++ IP4Addrs.

getbyname(Hostname, Type) ->
case (catch inet_res:getbyname(Hostname, Type)) of
{'ok', #hostent{h_addr_list=AddrList}} -> lists:usort(AddrList);
{error, _Reason} -> [];
Else ->
%% ERLANG 22 has an issue when g matching somee DNS server messages
?report_debug("DNS error", [{hostname, Hostname}
,{type, Type}
,{error, Else}]),
[]
end.

try_connect([], _Port, _Opts, ServerPid, LastError) ->
?report_trace("happy eyeball: failed to connect", [{error, LastError}]),
ServerPid ! {hackney_happy, LastError};
try_connect([{IP, Type} | Rest], Port, Opts, ServerPid, _LastError) ->
?report_trace("try to connect", [{ip, IP}, {type, Type}]),
case gen_tcp:connect(IP, Port, [Type | Opts], ?TIMEOUT) of
{ok, Socket} = OK ->
?report_trace("success to connect", [{ip, IP}, {type, Type}]),
ok = gen_tcp:controlling_process(Socket, ServerPid),
ServerPid ! {happy_connect, OK};
Error ->
try_connect(Rest, Port, Opts, ServerPid, Error)
end.
2 changes: 1 addition & 1 deletion src/hackney_http_connect.erl
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ connect(ProxyHost, ProxyPort, Opts, Timeout)
ConnectOpts = hackney_util:filter_options(Opts, AcceptedOpts, BaseOpts),

%% connect to the proxy, and upgrade the socket if needed.
case gen_tcp:connect(ProxyHost, ProxyPort, ConnectOpts) of
case hackney_happy:connect(ProxyHost, ProxyPort, ConnectOpts) of
{ok, Socket} ->
case do_handshake(Socket, Host, Port, Opts) of
ok ->
Expand Down
8 changes: 4 additions & 4 deletions src/hackney_pool.erl
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,13 @@ checkout(Host, Port, Transport, Client) ->
Requester = self(),
try
do_checkout(Requester, Host, Port, Transport, Client)
catch _:_ ->
catch _:Error ->
?report_trace("pool: checkout failure", [{error, Error}]),
{error, checkout_failure}
end.

do_checkout(Requester, Host, _Port, Transport, #client{options=Opts,
mod_metrics=Metrics}=Client) ->
mod_metrics=Metrics}=Client) ->
ConnectTimeout = proplists:get_value(connect_timeout, Opts, 8000),
%% Fall back to using connect_timeout if checkout_timeout is not set
CheckoutTimeout = proplists:get_value(checkout_timeout, Opts, ConnectTimeout),
Expand All @@ -78,7 +79,6 @@ do_checkout(Requester, Host, _Port, Transport, #client{options=Opts,
Pool = find_pool(PoolName, Opts),
case catch gen_server:call(Pool, {checkout, Connection, Requester, RequestRef}, CheckoutTimeout) of
{ok, Socket, Owner} ->

%% stats
?report_debug("reuse a connection", [{pool, PoolName}]),
_ = metrics:update_meter(Metrics, [hackney_pool, PoolName, take_rate], 1),
Expand All @@ -105,7 +105,7 @@ do_checkout(Requester, Host, _Port, Transport, #client{options=Opts,
_ = metrics:increment_counter(Metrics, [hackney, Host, connect_timeout]),
{error, timeout};
Error ->
?report_trace("connect error", []),
?report_trace("connect error", [{pool, PoolName}, {error, Error}]),
_ = metrics:increment_counter(Metrics, [hackney, Host, connect_error]),
Error
end;
Expand Down
2 changes: 1 addition & 1 deletion src/hackney_socks5.erl
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ connect(Host, Port, Opts, Timeout) when is_list(Host), is_integer(Port),
ConnectOpts = hackney_util:filter_options(Opts, AcceptedOpts, BaseOpts),

%% connect to the socks 5 proxy
case gen_tcp:connect(ProxyHost, ProxyPort, ConnectOpts, Timeout) of
case hackney_happy:connect(ProxyHost, ProxyPort, ConnectOpts, Timeout) of
{ok, Socket} ->
case do_handshake(Socket, Host, Port, Opts) of
ok ->
Expand Down
30 changes: 12 additions & 18 deletions src/hackney_ssl.erl
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,7 @@
%% @doc Atoms used to identify messages in {active, once | true} mode.
messages(_) -> {ssl, ssl_closed, ssl_error}.

%% @doc The ssl:connect/4 (and related) doesn't work with textual representation
%% of IP addresses. It accepts either a string with a DNS-resolvable name or a
%% tuple with parts of an IP as numbers. This function attempts to parse given
%% string and either returns such tuple, or the string if it's impossible to
%% parse.
parse_address(Host) when is_list(Host) ->
case inet:parse_address(Host) of
{ok, Address} -> Address;
{error, _} -> Host
end.



check_hostname_opts(Host0) ->
Expand Down Expand Up @@ -134,14 +125,17 @@ find(_Fun, []) ->
connect(Host, Port, Opts) ->
connect(Host, Port, Opts, infinity).

connect(Host, Port, Opts, Timeout) when is_list(Host), is_integer(Port),
(Timeout =:= infinity orelse is_integer(Timeout)) ->
BaseOpts = [binary, {active, false}, {packet, raw},
{secure_renegotiate, true},
{reuse_sessions, true}],
Opts1 = hackney_util:merge_opts(BaseOpts, Opts),
%% connect
ssl:connect(parse_address(Host), Port, Opts1, Timeout).
connect(Host, Port, Opts0, Timeout) when is_list(Host), is_integer(Port),
(Timeout =:= 5000 orelse is_integer(Timeout)) ->
SSLOpts = [{secure_renegotiate, true}, proplists:get_value(ssl_options, Opts0)],
BaseOpts = [binary, {active, false}, {packet, raw}],
Opts1 = hackney_util:merge_opts(BaseOpts, proplists:delete(ssl_options, Opts0)),
case hackney_happy:connect(Host, Port, Opts1, Timeout) of
{ok, Sock} ->
ssl:connect(Sock, SSLOpts);
Error ->
Error
end.



Expand Down
2 changes: 1 addition & 1 deletion src/hackney_tcp.erl
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ connect(Host, Port, Opts, Timeout) when is_list(Host), is_integer(Port),
BaseOpts = [binary, {active, false}, {packet, raw}],
Opts1 = hackney_util:merge_opts(BaseOpts, Opts),
%% connect
gen_tcp:connect(Host, Port, Opts1, Timeout).
hackney_happy:connect(Host, Port, Opts1, Timeout).

recv(Socket, Length) ->
recv(Socket, Length, infinity).
Expand Down
Loading

0 comments on commit 87aeb8e

Please sign in to comment.