Fix message dropping issue on server

The sockets were initially set to active, which meant that data
received immediately after the TLS handshake (before the socket was
transferred to the handle_connection process) were received by the
acceptor process and hence were not handled.
This commit is contained in:
Camden Dixie O'Brien 2025-02-25 15:57:26 +00:00
parent 538405fec9
commit 53857bc613

View File

@ -14,12 +14,12 @@ start_link(Port, CertDir) ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [Port, CertDir], []).
init([Port, CertDir]) ->
TcpOpts = [binary, inet6, {active, false}, {reuseaddr, true}],
SslOpts = [{certfile, filename:join([CertDir, "server.pem"])},
{cacertfile, filename:join([CertDir, "ca.pem"])},
{verify, verify_peer},
{fail_if_no_peer_cert, true}],
{ok, Socket} =
ssl:listen(Port, [binary, inet6, {active, true} | SslOpts]),
{ok, Socket} = ssl:listen(Port, TcpOpts ++ SslOpts),
Pid = spawn_link(fun() -> acceptor_loop(Socket) end),
{ok, #state{socket = Socket, acceptor = Pid}}.
@ -49,7 +49,6 @@ acceptor_loop(Socket) ->
Pid = spawn(
fun() -> handle_connection(ClientSocket) end),
ok = ssl:controlling_process(ClientSocket, Pid),
ssl:setopts(ClientSocket, [{active, true}]),
acceptor_loop(Socket);
{error, _Reason} ->
acceptor_loop(Socket)
@ -59,10 +58,17 @@ acceptor_loop(Socket) ->
end.
handle_connection(Socket) ->
ssl:setopts(Socket, [{active, true}]),
handle_connection_loop(Socket).
handle_connection_loop(Socket) ->
receive
{ssl, Socket, Data} ->
ssl:send(Socket, Data),
handle_connection(Socket);
handle_client_msg(Socket, Data),
handle_connection_loop(Socket);
{ssl_closed, Socket} ->
ok
end.
handle_client_msg(Socket, Msg) ->
ssl:send(Socket, Msg).