Debian Codegraph @

src/cowboy_clear.erl

raw
1 %% Copyright (c) Loïc Hoguin <[email protected]>
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(cowboy_clear).
16 -behavior(ranch_protocol).
17
18 -export([start_link/3]).
19 -export([start_link/4]).
20 -export([connection_process/4]).
21
22 %% Ranch 1.
23 -spec start_link(ranch:ref(), inet:socket(), module(), cowboy:opts()) -> {ok, pid()}.
24 start_link(Ref, _Socket, Transport, Opts) ->
25 start_link(Ref, Transport, Opts).
26
27 %% Ranch 2.
28 -spec start_link(ranch:ref(), module(), cowboy:opts()) -> {ok, pid()}.
29 start_link(Ref, Transport, Opts) ->
30 Pid = proc_lib:spawn_link(?MODULE, connection_process,
31 [self(), Ref, Transport, Opts]),
32 {ok, Pid}.
33
34 -spec connection_process(pid(), ranch:ref(), module(), cowboy:opts()) -> ok.
35 connection_process(Parent, Ref, Transport, Opts) ->
36 ProxyInfo = get_proxy_info(Ref, Opts),
37 {ok, Socket} = ranch:handshake(Ref),
38 %% Use cowboy_http2 directly only when 'http' is missing.
39 Protocol = case maps:get(protocols, Opts, [http2, http]) of
40 [http2] -> cowboy_http2;
41 [_|_] -> cowboy_http
42 end,
43 init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, Protocol).
44
45 init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, Protocol) ->
46 _ = case maps:get(connection_type, Opts, supervisor) of
47 worker -> ok;
48 supervisor -> process_flag(trap_exit, true)
49 end,
50 Protocol:init(Parent, Ref, Socket, Transport, ProxyInfo, Opts).
51
52 get_proxy_info(Ref, #{proxy_header := true}) ->
53 case ranch:recv_proxy_header(Ref, 1000) of
54 {ok, ProxyInfo} -> ProxyInfo;
55 {error, _} -> exit({shutdown, closed});
56 {error, protocol_error, HumanReadable} ->
57 exit({shutdown, {connection_error, protocol_error, HumanReadable}})
58 end;
59 get_proxy_info(_, _) ->
60 undefined.