| 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). |
| 16 |
|
| 17 |
-export([start_clear/3]). |
| 18 |
-export([start_tls/3]). |
| 19 |
-export([stop_listener/1]). |
| 20 |
-export([get_env/2]). |
| 21 |
-export([get_env/3]). |
| 22 |
-export([set_env/3]). |
| 23 |
|
| 24 |
-ifdef(COWBOY_QUICER). |
| 25 |
-export([start_quic/3]). |
| 26 |
|
| 27 |
%% Don't warn about the bad quicer specs. |
| 28 |
-dialyzer([{nowarn_function, start_quic/3}]). |
| 29 |
-endif. |
| 30 |
|
| 31 |
%% Internal. |
| 32 |
-export([log/2]). |
| 33 |
-export([log/4]). |
| 34 |
|
| 35 |
-type opts() :: cowboy_http:opts() | cowboy_http2:opts(). |
| 36 |
-export_type([opts/0]). |
| 37 |
|
| 38 |
-type fields() :: [atom() |
| 39 |
| {atom(), cowboy_constraints:constraint() | [cowboy_constraints:constraint()]} |
| 40 |
| {atom(), cowboy_constraints:constraint() | [cowboy_constraints:constraint()], any()}]. |
| 41 |
-export_type([fields/0]). |
| 42 |
|
| 43 |
-type http_headers() :: #{binary() => iodata()}. |
| 44 |
-export_type([http_headers/0]). |
| 45 |
|
| 46 |
-type http_status() :: non_neg_integer() | binary(). |
| 47 |
-export_type([http_status/0]). |
| 48 |
|
| 49 |
-type http_version() :: 'HTTP/2' | 'HTTP/1.1' | 'HTTP/1.0'. |
| 50 |
-export_type([http_version/0]). |
| 51 |
|
| 52 |
-spec start_clear(ranch:ref(), ranch:opts(), opts()) |
| 53 |
-> {ok, pid()} | {error, any()}. |
| 54 |
|
| 55 |
start_clear(Ref, TransOpts0, ProtoOpts0) -> |
| 56 |
TransOpts1 = ranch:normalize_opts(TransOpts0), |
| 57 |
{TransOpts2, DynamicBuffer} = ensure_dynamic_buffer(TransOpts1, ProtoOpts0), |
| 58 |
{TransOpts, ConnectionType} = ensure_connection_type(TransOpts2), |
| 59 |
ProtoOpts = ProtoOpts0#{ |
| 60 |
connection_type => ConnectionType, |
| 61 |
dynamic_buffer => DynamicBuffer |
| 62 |
}, |
| 63 |
ranch:start_listener(Ref, ranch_tcp, TransOpts, cowboy_clear, ProtoOpts). |
| 64 |
|
| 65 |
-spec start_tls(ranch:ref(), ranch:opts(), opts()) |
| 66 |
-> {ok, pid()} | {error, any()}. |
| 67 |
|
| 68 |
start_tls(Ref, TransOpts0, ProtoOpts0) -> |
| 69 |
TransOpts1 = ranch:normalize_opts(TransOpts0), |
| 70 |
{TransOpts2, DynamicBuffer} = ensure_dynamic_buffer(TransOpts1, ProtoOpts0), |
| 71 |
TransOpts3 = ensure_alpn(TransOpts2), |
| 72 |
{TransOpts, ConnectionType} = ensure_connection_type(TransOpts3), |
| 73 |
ProtoOpts = ProtoOpts0#{ |
| 74 |
connection_type => ConnectionType, |
| 75 |
dynamic_buffer => DynamicBuffer |
| 76 |
}, |
| 77 |
ranch:start_listener(Ref, ranch_ssl, TransOpts, cowboy_tls, ProtoOpts). |
| 78 |
|
| 79 |
-ifdef(COWBOY_QUICER). |
| 80 |
|
| 81 |
%% @todo Experimental function to start a barebone QUIC listener. |
| 82 |
%% This will need to be reworked to be closer to Ranch |
| 83 |
%% listeners and provide equivalent features. |
| 84 |
%% |
| 85 |
%% @todo Better type for transport options. Might require fixing quicer types. |
| 86 |
|
| 87 |
-spec start_quic(ranch:ref(), #{socket_opts => [{atom(), _}]}, cowboy_http3:opts()) |
| 88 |
-> {ok, pid()}. |
| 89 |
|
| 90 |
%% @todo Implement dynamic_buffer for HTTP/3 if/when it applies. |
| 91 |
start_quic(Ref, TransOpts, ProtoOpts) -> |
| 92 |
{ok, _} = application:ensure_all_started(quicer), |
| 93 |
Parent = self(), |
| 94 |
SocketOpts0 = maps:get(socket_opts, TransOpts, []), |
| 95 |
{Port, SocketOpts2} = case lists:keytake(port, 1, SocketOpts0) of |
| 96 |
{value, {port, Port0}, SocketOpts1} -> |
| 97 |
{Port0, SocketOpts1}; |
| 98 |
false -> |
| 99 |
{port_0(), SocketOpts0} |
| 100 |
end, |
| 101 |
SocketOpts = [ |
| 102 |
{alpn, ["h3"]}, %% @todo Why not binary? |
| 103 |
%% We only need 3 for control and QPACK enc/dec, |
| 104 |
%% but we need more for WebTransport. %% @todo Use 3 if WT is disabled. |
| 105 |
{peer_unidi_stream_count, 100}, |
| 106 |
{peer_bidi_stream_count, 100}, |
| 107 |
%% For WebTransport. |
| 108 |
%% @todo We probably don't want it enabled if WT isn't used. |
| 109 |
{datagram_send_enabled, 1}, |
| 110 |
{datagram_receive_enabled, 1} |
| 111 |
|SocketOpts2], |
| 112 |
_ListenerPid = spawn(fun() -> |
| 113 |
{ok, Listener} = quicer:listen(Port, SocketOpts), |
| 114 |
Parent ! {ok, Listener}, |
| 115 |
_AcceptorPid = [spawn(fun AcceptLoop() -> |
| 116 |
{ok, Conn} = quicer:accept(Listener, []), |
| 117 |
Pid = spawn(fun() -> |
| 118 |
receive go -> ok end, |
| 119 |
%% We have to do the handshake after handing control of |
| 120 |
%% the connection otherwise streams may come in before |
| 121 |
%% the controlling process is changed and messages will |
| 122 |
%% not be sent to the correct process. |
| 123 |
{ok, Conn} = quicer:handshake(Conn), |
| 124 |
process_flag(trap_exit, true), %% @todo Only if supervisor though. |
| 125 |
try cowboy_http3:init(Parent, Ref, Conn, ProtoOpts) |
| 126 |
catch |
| 127 |
exit:{shutdown,_} -> ok; |
| 128 |
C:E:S -> log(error, "CRASH ~p:~p:~p", [C,E,S], ProtoOpts) |
| 129 |
end |
| 130 |
end), |
| 131 |
ok = quicer:controlling_process(Conn, Pid), |
| 132 |
Pid ! go, |
| 133 |
AcceptLoop() |
| 134 |
end) || _ <- lists:seq(1, 20)], |
| 135 |
%% Listener process must not terminate. |
| 136 |
receive after infinity -> ok end |
| 137 |
end), |
| 138 |
receive |
| 139 |
{ok, Listener} -> |
| 140 |
{ok, Listener} |
| 141 |
end. |
| 142 |
|
| 143 |
%% Select a random UDP port using gen_udp because quicer |
| 144 |
%% does not provide equivalent functionality. Taken from |
| 145 |
%% quicer test suites. |
| 146 |
port_0() -> |
| 147 |
{ok, Socket} = gen_udp:open(0, [{reuseaddr, true}]), |
| 148 |
{ok, {_, Port}} = inet:sockname(Socket), |
| 149 |
gen_udp:close(Socket), |
| 150 |
case os:type() of |
| 151 |
{unix, darwin} -> |
| 152 |
%% Apparently macOS doesn't free the port immediately. |
| 153 |
timer:sleep(500); |
| 154 |
_ -> |
| 155 |
ok |
| 156 |
end, |
| 157 |
Port. |
| 158 |
|
| 159 |
-endif. |
| 160 |
|
| 161 |
ensure_alpn(TransOpts) -> |
| 162 |
SocketOpts = maps:get(socket_opts, TransOpts, []), |
| 163 |
TransOpts#{socket_opts => [ |
| 164 |
{alpn_preferred_protocols, [<<"h2">>, <<"http/1.1">>]} |
| 165 |
|SocketOpts]}. |
| 166 |
|
| 167 |
ensure_connection_type(TransOpts=#{connection_type := ConnectionType}) -> |
| 168 |
{TransOpts, ConnectionType}; |
| 169 |
ensure_connection_type(TransOpts) -> |
| 170 |
{TransOpts#{connection_type => supervisor}, supervisor}. |
| 171 |
|
| 172 |
%% Dynamic buffer was set; accept transport options as-is. |
| 173 |
%% Note that initial 'buffer' size may be lower than dynamic buffer allows. |
| 174 |
ensure_dynamic_buffer(TransOpts, #{dynamic_buffer := DynamicBuffer}) -> |
| 175 |
{TransOpts, DynamicBuffer}; |
| 176 |
%% Dynamic buffer was not set; define default dynamic buffer |
| 177 |
%% only if 'buffer' size was not configured. In that case we |
| 178 |
%% set the 'buffer' size to the lowest value. |
| 179 |
ensure_dynamic_buffer(TransOpts=#{socket_opts := SocketOpts}, _) -> |
| 180 |
case proplists:get_value(buffer, SocketOpts, undefined) of |
| 181 |
undefined -> |
| 182 |
{TransOpts#{socket_opts => [{buffer, 512}|SocketOpts]}, {512, 131072}}; |
| 183 |
_ -> |
| 184 |
{TransOpts, false} |
| 185 |
end. |
| 186 |
|
| 187 |
-spec stop_listener(ranch:ref()) -> ok | {error, not_found}. |
| 188 |
|
| 189 |
stop_listener(Ref) -> |
| 190 |
ranch:stop_listener(Ref). |
| 191 |
|
| 192 |
-spec get_env(ranch:ref(), atom()) -> ok. |
| 193 |
|
| 194 |
get_env(Ref, Name) -> |
| 195 |
Opts = ranch:get_protocol_options(Ref), |
| 196 |
Env = maps:get(env, Opts, #{}), |
| 197 |
maps:get(Name, Env). |
| 198 |
|
| 199 |
-spec get_env(ranch:ref(), atom(), any()) -> ok. |
| 200 |
|
| 201 |
get_env(Ref, Name, Default) -> |
| 202 |
Opts = ranch:get_protocol_options(Ref), |
| 203 |
Env = maps:get(env, Opts, #{}), |
| 204 |
maps:get(Name, Env, Default). |
| 205 |
|
| 206 |
-spec set_env(ranch:ref(), atom(), any()) -> ok. |
| 207 |
|
| 208 |
set_env(Ref, Name, Value) -> |
| 209 |
Opts = ranch:get_protocol_options(Ref), |
| 210 |
Env = maps:get(env, Opts, #{}), |
| 211 |
Opts2 = maps:put(env, maps:put(Name, Value, Env), Opts), |
| 212 |
ok = ranch:set_protocol_options(Ref, Opts2). |
| 213 |
|
| 214 |
%% Internal. |
| 215 |
|
| 216 |
-spec log({log, logger:level(), io:format(), list()}, opts()) -> ok. |
| 217 |
|
| 218 |
log({log, Level, Format, Args}, Opts) -> |
| 219 |
log(Level, Format, Args, Opts). |
| 220 |
|
| 221 |
-spec log(logger:level(), io:format(), list(), opts()) -> ok. |
| 222 |
|
| 223 |
log(Level, Format, Args, #{logger := Logger}) |
| 224 |
when Logger =/= error_logger -> |
| 225 |
_ = Logger:Level(Format, Args), |
| 226 |
ok; |
| 227 |
%% We use error_logger by default. Because error_logger does |
| 228 |
%% not have all the levels we accept we have to do some |
| 229 |
%% mapping to error_logger functions. |
| 230 |
log(Level, Format, Args, _) -> |
| 231 |
Function = case Level of |
| 232 |
emergency -> error_msg; |
| 233 |
alert -> error_msg; |
| 234 |
critical -> error_msg; |
| 235 |
error -> error_msg; |
| 236 |
warning -> warning_msg; |
| 237 |
notice -> warning_msg; |
| 238 |
info -> info_msg; |
| 239 |
debug -> info_msg |
| 240 |
end, |
| 241 |
error_logger:Function(Format, Args). |