| 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_tls). |
| 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(), ssl:sslsocket(), 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 |
case ssl:negotiated_protocol(Socket) of |
| 39 |
{ok, <<"h2">>} -> |
| 40 |
init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, cowboy_http2); |
| 41 |
_ -> %% http/1.1 or no protocol negotiated. |
| 42 |
Protocol = case maps:get(alpn_default_protocol, Opts, http) of |
| 43 |
http -> cowboy_http; |
| 44 |
http2 -> cowboy_http2 |
| 45 |
end, |
| 46 |
init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, Protocol) |
| 47 |
end. |
| 48 |
|
| 49 |
init(Parent, Ref, Socket, Transport, ProxyInfo, Opts, Protocol) -> |
| 50 |
_ = case maps:get(connection_type, Opts, supervisor) of |
| 51 |
worker -> ok; |
| 52 |
supervisor -> process_flag(trap_exit, true) |
| 53 |
end, |
| 54 |
Protocol:init(Parent, Ref, Socket, Transport, ProxyInfo, Opts). |
| 55 |
|
| 56 |
get_proxy_info(Ref, #{proxy_header := true}) -> |
| 57 |
case ranch:recv_proxy_header(Ref, 1000) of |
| 58 |
{ok, ProxyInfo} -> ProxyInfo; |
| 59 |
{error, _} -> exit({shutdown, closed}); |
| 60 |
{error, protocol_error, HumanReadable} -> |
| 61 |
exit({shutdown, {connection_error, protocol_error, HumanReadable}}) |
| 62 |
end; |
| 63 |
get_proxy_info(_, _) -> |
| 64 |
undefined. |