Skip to content

Commit

Permalink
Improve peer info detection for extended error reason
Browse files Browse the repository at this point in the history
  • Loading branch information
juhlig committed May 17, 2024
1 parent 8e90a7e commit 2521469
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/ranch.erl
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,9 @@ handshake(Ref, Opts) ->

handshake1(Ref, Opts) ->
receive {handshake, Ref, Transport, CSocket, Timeout} ->
PeerInfo = get_peer_info(Transport, CSocket, undefined),
Handshake = handshake_transport(Transport, handshake, CSocket, Opts, Timeout),
handshake_result(Handshake, Ref, Transport, CSocket, Timeout)
handshake_result(Handshake, Ref, Transport, CSocket, PeerInfo, Timeout)
end.

-spec handshake_continue(ref()) -> {ok, ranch_transport:socket()}.
Expand All @@ -301,27 +302,25 @@ handshake_continue(Ref, Opts) ->

handshake_continue1(Ref, Opts) ->
receive {handshake_continue, Ref, Transport, CSocket, Timeout} ->
PeerInfo = get_peer_info(Transport, CSocket, undefined),
Handshake = handshake_transport(Transport, handshake_continue, CSocket, Opts, Timeout),
handshake_result(Handshake, Ref, Transport, CSocket, Timeout)
handshake_result(Handshake, Ref, Transport, CSocket, PeerInfo, Timeout)
end.

handshake_transport(Transport, Fun, CSocket, undefined, Timeout) ->
Transport:Fun(CSocket, Timeout);
handshake_transport(Transport, Fun, CSocket, {opts, Opts}, Timeout) ->
Transport:Fun(CSocket, Opts, Timeout).

handshake_result(Result, Ref, Transport, CSocket, Timeout) ->
handshake_result(Result, Ref, Transport, CSocket, PeerInfo0, Timeout) ->
case Result of
OK = {ok, _} ->
OK;
{ok, CSocket2, Info} ->
self() ! {handshake_continue, Ref, Transport, CSocket2, Timeout},
{continue, Info};
{error, Reason} ->
PeerInfo = case Transport:peername(CSocket) of
{ok, Peer} -> Peer;
{error, _} -> undefined
end,
PeerInfo = get_peer_info(Transport, CSocket, PeerInfo0),
ok = Transport:close(CSocket),
exit({shutdown, {Reason, PeerInfo}})
end.
Expand All @@ -332,6 +331,12 @@ handshake_cancel(Ref) ->
Transport:handshake_cancel(CSocket)
end.

get_peer_info(Transport, Socket, Default) ->
case Transport:peername(Socket) of
{ok, Peer} -> Peer;
{error, _} -> Default
end.

%% Unlike handshake/2 this function always return errors because
%% the communication between the proxy and the server are expected
%% to be reliable. If there is a problem while receiving the proxy
Expand Down

0 comments on commit 2521469

Please sign in to comment.