Skip to content

Commit

Permalink
Configure the new listener extensively
Browse files Browse the repository at this point in the history
Prepare all knowledge of the tls configuration, whether to use ranch's
reuseport extension, and pass to ranch all other parameters that were
present in the c2s listener config.
  • Loading branch information
NelsonVides committed Aug 11, 2022
1 parent 21861e7 commit c46aeb4
Showing 1 changed file with 36 additions and 8 deletions.
44 changes: 36 additions & 8 deletions src/c2s/mongoose_c2s_listener.erl
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
%% backwards compatibility, process iq-session
-export([process_iq/5]).

-type options() :: #{atom() => any()}.
-type options() :: #{module := module(),
atom() => any()}.

%% mongoose_listener
-spec socket_type() -> mongoose_listener:socket_type().
Expand Down Expand Up @@ -48,10 +49,18 @@ init(#{module := Module} = Opts) ->
[ gen_iq_handler:add_iq_handler_for_domain(
HostType, ?NS_SESSION, ejabberd_sm, fun ?MODULE:process_iq/5, #{}, no_queue)
|| HostType <- ?ALL_HOST_TYPES],
{Transport, TransportOpts} = transport(Opts),
Child = ranch:child_spec(?MODULE, Transport, TransportOpts, Module, Opts),
TransportOpts = prepare_socket_opts(Opts),
ListenerId = mongoose_listener_config:listener_id(Opts),
OptsWithTlsConfig = process_tls_opts(Opts),
Child = ranch:child_spec(ListenerId, ranch_tcp, TransportOpts, Module, OptsWithTlsConfig),
{ok, {#{strategy => one_for_one, intensity => 100, period => 1}, [Child]}}.

process_tls_opts(Opts = #{tls := TlsOpts}) ->
ReadyTlsOpts = just_tls:make_ssl_opts(TlsOpts),
Opts#{tls := TlsOpts#{opts => ReadyTlsOpts}};
process_tls_opts(Opts) ->
Opts.

listener_child_spec(ListenerId, Opts) ->
#{id => ListenerId,
start => {?MODULE, start_link, [Opts]},
Expand All @@ -60,8 +69,27 @@ listener_child_spec(ListenerId, Opts) ->
type => supervisor,
modules => [?MODULE]}.

transport(#{port := Port, tls := #{mode := tls, opts := SOpts},
hibernate_after := HibernateAfterTimeout}) ->
{ranch_ssl, #{socket_opts => [{port, Port}, {hibernate_after, HibernateAfterTimeout} | SOpts]}};
transport(#{port := Port}) ->
{ranch_tcp, #{socket_opts => [{port, Port}]}}.
prepare_socket_opts(#{port := Port,
ip_version := IPVersion,
ip_tuple := IPTuple,
backlog := Backlog,
num_acceptors := NumAcceptors,
max_connections := MaxConnections,
reuseport := ReusePort}) ->
SocketOpts = [{nodelay, true},
{keepalive, true},
{ip, IPTuple},
{port, Port},
{backlog, Backlog},
mongoose_listener_config:address_family(IPVersion)
| maybe_reuseport(ReusePort)],
#{max_connections => MaxConnections,
num_acceptors => NumAcceptors,
num_listen_sockets => num_listen_sockets(ReusePort),
socket_opts => SocketOpts}.

maybe_reuseport(false) -> [];
maybe_reuseport(true) -> [{raw, 1, 15, <<1:32/native>>}].

num_listen_sockets(false) -> 1;
num_listen_sockets(true) -> erlang:system_info(schedulers_online).

0 comments on commit c46aeb4

Please sign in to comment.