1%% Copyright (c) 2011-2017, 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
15-module(ranch_acceptor).
16
17-export([start_link/3]).
18-export([loop/3]).
19
20-spec start_link(inet:socket(), module(), pid())
21 -> {ok, pid()}.
22start_link(LSocket, Transport, ConnsSup) ->
23 Pid = spawn_link(?MODULE, loop, [LSocket, Transport, ConnsSup]),
24 {ok, Pid}.
25
26-spec loop(inet:socket(), module(), pid()) -> no_return().
27loop(LSocket, Transport, ConnsSup) ->
28 _ = case Transport:accept(LSocket, infinity) of
29 {ok, CSocket} ->
30 case Transport:controlling_process(CSocket, ConnsSup) of
31 ok ->
32 %% This call will not return until process has been started
33 %% AND we are below the maximum number of connections.
34 ranch_conns_sup:start_protocol(ConnsSup, CSocket);
35 {error, _} ->
36 Transport:close(CSocket)
37 end;
38 %% Reduce the accept rate if we run out of file descriptors.
39 %% We can't accept anymore anyway, so we might as well wait
40 %% a little for the situation to resolve itself.
41 {error, emfile} ->
42 error_logger:warning_msg("Ranch acceptor reducing accept rate: out of file descriptors~n"),
43 receive after 0xFF -> ok end;
44 %% We want to crash if the listening socket got closed.
45 {error, Reason} when Reason =/= closed ->
46 ok
47 end,
48 flush(),
49 ?MODULE:loop(LSocket, Transport, ConnsSup).
50
51flush() ->
52 receive Msg ->
53 error_logger:error_msg(
54 "Ranch acceptor received unexpected message: ~p~n",
55 [Msg]),
56 flush()
57 after 0 ->
58 ok
59 end.
60'http://example.com?a='
61-include("incdir/more_records.hrl").
62