ranch.erl 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. %% Copyright (c) 2011-2016, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(ranch).
  15. -export([start_listener/6]).
  16. -export([stop_listener/1]).
  17. -export([child_spec/6]).
  18. -export([accept_ack/1]).
  19. -export([remove_connection/1]).
  20. -export([get_addr/1]).
  21. -export([get_port/1]).
  22. -export([get_max_connections/1]).
  23. -export([set_max_connections/2]).
  24. -export([get_protocol_options/1]).
  25. -export([set_protocol_options/2]).
  26. -export([info/0]).
  27. -export([procs/2]).
  28. -export([filter_options/3]).
  29. -export([set_option_default/3]).
  30. -export([require/1]).
  31. -type max_conns() :: non_neg_integer() | infinity.
  32. -export_type([max_conns/0]).
  33. -type opt() :: {ack_timeout, timeout()}
  34. | {connection_type, worker | supervisor}
  35. | {max_connections, max_conns()}
  36. | {shutdown, timeout() | brutal_kill}
  37. | {socket, any()}.
  38. -export_type([opt/0]).
  39. -type ref() :: any().
  40. -export_type([ref/0]).
  41. -spec start_listener(ref(), non_neg_integer(), module(), any(), module(), any())
  42. -> supervisor:startchild_ret().
  43. start_listener(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts)
  44. when is_integer(NumAcceptors) andalso is_atom(Transport)
  45. andalso is_atom(Protocol) ->
  46. _ = code:ensure_loaded(Transport),
  47. case erlang:function_exported(Transport, name, 0) of
  48. false ->
  49. {error, badarg};
  50. true ->
  51. Res = supervisor:start_child(ranch_sup, child_spec(Ref, NumAcceptors,
  52. Transport, TransOpts, Protocol, ProtoOpts)),
  53. Socket = proplists:get_value(socket, TransOpts),
  54. case Res of
  55. {ok, Pid} when Socket =/= undefined ->
  56. %% Give ownership of the socket to ranch_acceptors_sup
  57. %% to make sure the socket stays open as long as the
  58. %% listener is alive. If the socket closes however there
  59. %% will be no way to recover because we don't know how
  60. %% to open it again.
  61. Children = supervisor:which_children(Pid),
  62. {_, AcceptorsSup, _, _}
  63. = lists:keyfind(ranch_acceptors_sup, 1, Children),
  64. %%% Note: the catch is here because SSL crashes when you change
  65. %%% the controlling process of a listen socket because of a bug.
  66. %%% The bug will be fixed in R16.
  67. catch Transport:controlling_process(Socket, AcceptorsSup);
  68. _ ->
  69. ok
  70. end,
  71. maybe_started(Res)
  72. end.
  73. maybe_started({error, {{shutdown,
  74. {failed_to_start_child, ranch_acceptors_sup,
  75. {listen_error, _, Reason}}}, _}} = Error) ->
  76. start_error(Reason, Error);
  77. maybe_started(Res) ->
  78. Res.
  79. start_error(E=eaddrinuse, _) -> {error, E};
  80. start_error(E=no_cert, _) -> {error, E};
  81. start_error(_, Error) -> Error.
  82. -spec stop_listener(ref()) -> ok | {error, not_found}.
  83. stop_listener(Ref) ->
  84. case supervisor:terminate_child(ranch_sup, {ranch_listener_sup, Ref}) of
  85. ok ->
  86. _ = supervisor:delete_child(ranch_sup, {ranch_listener_sup, Ref}),
  87. ranch_server:cleanup_listener_opts(Ref);
  88. {error, Reason} ->
  89. {error, Reason}
  90. end.
  91. -spec child_spec(ref(), non_neg_integer(), module(), any(), module(), any())
  92. -> supervisor:child_spec().
  93. child_spec(Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts)
  94. when is_integer(NumAcceptors) andalso is_atom(Transport)
  95. andalso is_atom(Protocol) ->
  96. {{ranch_listener_sup, Ref}, {ranch_listener_sup, start_link, [
  97. Ref, NumAcceptors, Transport, TransOpts, Protocol, ProtoOpts
  98. ]}, permanent, infinity, supervisor, [ranch_listener_sup]}.
  99. -spec accept_ack(ref()) -> ok.
  100. accept_ack(Ref) ->
  101. receive {shoot, Ref, Transport, Socket, AckTimeout} ->
  102. Transport:accept_ack(Socket, AckTimeout)
  103. end.
  104. -spec remove_connection(ref()) -> ok.
  105. remove_connection(Ref) ->
  106. ConnsSup = ranch_server:get_connections_sup(Ref),
  107. ConnsSup ! {remove_connection, Ref, self()},
  108. ok.
  109. -spec get_addr(ref()) -> {inet:ip_address(), inet:port_number()}.
  110. get_addr(Ref) ->
  111. ranch_server:get_addr(Ref).
  112. -spec get_port(ref()) -> inet:port_number().
  113. get_port(Ref) ->
  114. {_, Port} = get_addr(Ref),
  115. Port.
  116. -spec get_max_connections(ref()) -> max_conns().
  117. get_max_connections(Ref) ->
  118. ranch_server:get_max_connections(Ref).
  119. -spec set_max_connections(ref(), max_conns()) -> ok.
  120. set_max_connections(Ref, MaxConnections) ->
  121. ranch_server:set_max_connections(Ref, MaxConnections).
  122. -spec get_protocol_options(ref()) -> any().
  123. get_protocol_options(Ref) ->
  124. ranch_server:get_protocol_options(Ref).
  125. -spec set_protocol_options(ref(), any()) -> ok.
  126. set_protocol_options(Ref, Opts) ->
  127. ranch_server:set_protocol_options(Ref, Opts).
  128. -spec info() -> [{any(), [{atom(), any()}]}].
  129. info() ->
  130. Children = supervisor:which_children(ranch_sup),
  131. [{Ref, listener_info(Ref, Pid)}
  132. || {{ranch_listener_sup, Ref}, Pid, _, [_]} <- Children].
  133. listener_info(Ref, Pid) ->
  134. [_, NumAcceptors, Transport, TransOpts, Protocol, _] = listener_start_args(Ref),
  135. ConnsSup = ranch_server:get_connections_sup(Ref),
  136. {IP, Port} = get_addr(Ref),
  137. MaxConns = get_max_connections(Ref),
  138. ProtoOpts = get_protocol_options(Ref),
  139. [
  140. {pid, Pid},
  141. {ip, IP},
  142. {port, Port},
  143. {num_acceptors, NumAcceptors},
  144. {max_connections, MaxConns},
  145. {active_connections, ranch_conns_sup:active_connections(ConnsSup)},
  146. {all_connections, proplists:get_value(active, supervisor:count_children(ConnsSup))},
  147. {transport, Transport},
  148. {transport_options, TransOpts},
  149. {protocol, Protocol},
  150. {protocol_options, ProtoOpts}
  151. ].
  152. listener_start_args(Ref) ->
  153. case erlang:function_exported(supervisor, get_childspec, 2) of
  154. true ->
  155. %% Can't use map syntax before R18.
  156. {ok, Map} = supervisor:get_childspec(ranch_sup, {ranch_listener_sup, Ref}),
  157. {ranch_listener_sup, start_link, StartArgs} = maps:get(start, Map),
  158. StartArgs;
  159. false ->
  160. %% Awful solution for compatibility with R16 and R17.
  161. {status, _, _, [_, _, _, _, [_, _,
  162. {data, [{_, {state, _, _, Children, _, _, _, _, _, _}}]}]]}
  163. = sys:get_status(ranch_sup),
  164. [StartArgs] = [StartArgs || {child, _, {ranch_listener_sup, ChildRef},
  165. {ranch_listener_sup, start_link, StartArgs}, _, _, _, _}
  166. <- Children, ChildRef =:= Ref],
  167. StartArgs
  168. end.
  169. -spec procs(ref(), acceptors | connections) -> [pid()].
  170. procs(Ref, acceptors) ->
  171. procs1(Ref, ranch_acceptors_sup);
  172. procs(Ref, connections) ->
  173. procs1(Ref, ranch_conns_sup).
  174. procs1(Ref, Sup) ->
  175. {_, ListenerSup, _, _} = lists:keyfind({ranch_listener_sup, Ref}, 1,
  176. supervisor:which_children(ranch_sup)),
  177. {_, SupPid, _, _} = lists:keyfind(Sup, 1,
  178. supervisor:which_children(ListenerSup)),
  179. [Pid || {_, Pid, _, _} <- supervisor:which_children(SupPid)].
  180. -spec filter_options([inet | inet6 | {atom(), any()} | {raw, any(), any(), any()}],
  181. [atom()], Acc) -> Acc when Acc :: [any()].
  182. filter_options(UserOptions, DisallowedKeys, DefaultOptions) ->
  183. AllowedOptions = filter_user_options(UserOptions, DisallowedKeys),
  184. lists:foldl(fun merge_options/2, DefaultOptions, AllowedOptions).
  185. %% 2-tuple options.
  186. filter_user_options([Opt = {Key, _}|Tail], DisallowedKeys) ->
  187. case lists:member(Key, DisallowedKeys) of
  188. false ->
  189. [Opt|filter_user_options(Tail, DisallowedKeys)];
  190. true ->
  191. filter_options_warning(Opt),
  192. filter_user_options(Tail, DisallowedKeys)
  193. end;
  194. %% Special option forms.
  195. filter_user_options([inet|Tail], AllowedKeys) ->
  196. [inet|filter_user_options(Tail, AllowedKeys)];
  197. filter_user_options([inet6|Tail], AllowedKeys) ->
  198. [inet6|filter_user_options(Tail, AllowedKeys)];
  199. filter_user_options([Opt = {raw, _, _, _}|Tail], AllowedKeys) ->
  200. [Opt|filter_user_options(Tail, AllowedKeys)];
  201. filter_user_options([Opt|Tail], DisallowedKeys) ->
  202. filter_options_warning(Opt),
  203. filter_user_options(Tail, DisallowedKeys);
  204. filter_user_options([], _) ->
  205. [].
  206. filter_options_warning(Opt) ->
  207. error_logger:warning_msg("Transport option ~p unknown or invalid.~n", [Opt]).
  208. merge_options({Key, _} = Option, OptionList) ->
  209. lists:keystore(Key, 1, OptionList, Option);
  210. merge_options(Option, OptionList) ->
  211. [Option|OptionList].
  212. -spec set_option_default(Opts, atom(), any())
  213. -> Opts when Opts :: [{atom(), any()}].
  214. set_option_default(Opts, Key, Value) ->
  215. case lists:keymember(Key, 1, Opts) of
  216. true -> Opts;
  217. false -> [{Key, Value}|Opts]
  218. end.
  219. -spec require([atom()]) -> ok.
  220. require([]) ->
  221. ok;
  222. require([App|Tail]) ->
  223. case application:start(App) of
  224. ok -> ok;
  225. {error, {already_started, App}} -> ok
  226. end,
  227. require(Tail).