From 25214694dc69c70ed730e75d9efc1a3ece77dfe2 Mon Sep 17 00:00:00 2001 From: Jan Uhlig Date: Fri, 17 May 2024 13:11:03 +0200 Subject: [PATCH] Improve peer info detection for extended error reason --- src/ranch.erl | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/ranch.erl b/src/ranch.erl index 8093b292cd..b3d6bfdd65 100644 --- a/src/ranch.erl +++ b/src/ranch.erl @@ -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()}. @@ -301,8 +302,9 @@ 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) -> @@ -310,7 +312,7 @@ handshake_transport(Transport, Fun, CSocket, undefined, 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; @@ -318,10 +320,7 @@ handshake_result(Result, Ref, Transport, CSocket, Timeout) -> 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. @@ -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