| 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 |
%% @todo To enable WebTransport the following options need to be set: |
| 16 |
%% |
| 17 |
%% QUIC: |
| 18 |
%% - max_datagram_frame_size > 0 |
| 19 |
%% |
| 20 |
%% HTTP/3: |
| 21 |
%% - SETTINGS_H3_DATAGRAM = 1 |
| 22 |
%% - SETTINGS_ENABLE_CONNECT_PROTOCOL = 1 |
| 23 |
%% - SETTINGS_WT_MAX_SESSIONS >= 1 |
| 24 |
|
| 25 |
%% Cowboy supports versions 07 through 13 of the WebTransport drafts. |
| 26 |
%% Cowboy also has some compatibility with version 02. |
| 27 |
%% |
| 28 |
%% WebTransport CONNECT requests go through cowboy_stream as normal |
| 29 |
%% and then an upgrade/switch_protocol is issued (just like Websocket). |
| 30 |
%% After that point none of the events go through cowboy_stream except |
| 31 |
%% the final terminate event. The request process becomes the process |
| 32 |
%% handling all events in the WebTransport session. |
| 33 |
%% |
| 34 |
%% WebTransport sessions can be ended via a command, via a crash or |
| 35 |
%% exit, via the closing of the connection (client or server inititated), |
| 36 |
%% via the client ending the session (mirroring the command) or via |
| 37 |
%% the client terminating the CONNECT stream. |
| 38 |
-module(cowboy_webtransport). |
| 39 |
|
| 40 |
-export([upgrade/4]). |
| 41 |
-export([upgrade/5]). |
| 42 |
|
| 43 |
%% cowboy_stream. |
| 44 |
-export([info/3]). |
| 45 |
-export([terminate/3]). |
| 46 |
|
| 47 |
-type stream_type() :: unidi | bidi. |
| 48 |
-type open_stream_ref() :: any(). |
| 49 |
|
| 50 |
-type event() :: |
| 51 |
{stream_open, cow_http3:stream_id(), stream_type()} | |
| 52 |
{opened_stream_id, open_stream_ref(), cow_http3:stream_id()} | |
| 53 |
{stream_data, cow_http3:stream_id(), cow_http:fin(), binary()} | |
| 54 |
{datagram, binary()} | |
| 55 |
close_initiated. |
| 56 |
|
| 57 |
-type commands() :: [ |
| 58 |
{open_stream, open_stream_ref(), stream_type(), iodata()} | |
| 59 |
{close_stream, cow_http3:stream_id(), cow_http3:wt_app_error_code()} | |
| 60 |
{send, cow_http3:stream_id() | datagram, iodata()} | |
| 61 |
initiate_close | |
| 62 |
close | |
| 63 |
{close, cow_http3:wt_app_error_code()} | |
| 64 |
{close, cow_http3:wt_app_error_code(), iodata()} |
| 65 |
]. |
| 66 |
-export_type([commands/0]). |
| 67 |
|
| 68 |
-type call_result(State) :: {commands(), State} | {commands(), State, hibernate}. |
| 69 |
|
| 70 |
-callback init(Req, any()) |
| 71 |
-> {ok | module(), Req, any()} |
| 72 |
| {module(), Req, any(), any()} |
| 73 |
when Req::cowboy_req:req(). |
| 74 |
|
| 75 |
-callback webtransport_init(State) |
| 76 |
-> call_result(State) when State::any(). |
| 77 |
-optional_callbacks([webtransport_init/1]). |
| 78 |
|
| 79 |
-callback webtransport_handle(event(), State) |
| 80 |
-> call_result(State) when State::any(). |
| 81 |
-optional_callbacks([webtransport_handle/2]). |
| 82 |
|
| 83 |
-callback webtransport_info(any(), State) |
| 84 |
-> call_result(State) when State::any(). |
| 85 |
-optional_callbacks([webtransport_info/2]). |
| 86 |
|
| 87 |
-callback terminate(any(), cowboy_req:req(), any()) -> ok. |
| 88 |
-optional_callbacks([terminate/3]). |
| 89 |
|
| 90 |
-type opts() :: #{ |
| 91 |
req_filter => fun((cowboy_req:req()) -> map()) |
| 92 |
}. |
| 93 |
-export_type([opts/0]). |
| 94 |
|
| 95 |
-record(state, { |
| 96 |
id :: cow_http3:stream_id(), |
| 97 |
parent :: pid(), |
| 98 |
opts = #{} :: opts(), |
| 99 |
handler :: module(), |
| 100 |
hibernate = false :: boolean(), |
| 101 |
req = #{} :: map() |
| 102 |
}). |
| 103 |
|
| 104 |
%% This function mirrors a similar function for Websocket. |
| 105 |
|
| 106 |
-spec is_upgrade_request(cowboy_req:req()) -> boolean(). |
| 107 |
|
| 108 |
is_upgrade_request(#{version := Version, method := <<"CONNECT">>, protocol := Protocol}) |
| 109 |
when Version =:= 'HTTP/3' -> |
| 110 |
%% @todo scheme MUST BE "https" |
| 111 |
<<"webtransport">> =:= cowboy_bstr:to_lower(Protocol); |
| 112 |
|
| 113 |
is_upgrade_request(_) -> |
| 114 |
false. |
| 115 |
|
| 116 |
%% Stream process. |
| 117 |
|
| 118 |
-spec upgrade(Req, Env, module(), any()) |
| 119 |
-> {ok, Req, Env} |
| 120 |
when Req::cowboy_req:req(), Env::cowboy_middleware:env(). |
| 121 |
|
| 122 |
upgrade(Req, Env, Handler, HandlerState) -> |
| 123 |
upgrade(Req, Env, Handler, HandlerState, #{}). |
| 124 |
|
| 125 |
-spec upgrade(Req, Env, module(), any(), opts()) |
| 126 |
-> {ok, Req, Env} |
| 127 |
when Req::cowboy_req:req(), Env::cowboy_middleware:env(). |
| 128 |
|
| 129 |
%% @todo Immediately crash if a response has already been sent. |
| 130 |
upgrade(Req=#{version := 'HTTP/3', pid := Pid, streamid := StreamID}, Env, Handler, HandlerState, Opts) -> |
| 131 |
FilteredReq = case maps:get(req_filter, Opts, undefined) of |
| 132 |
undefined -> maps:with([method, version, scheme, host, port, path, qs, peer], Req); |
| 133 |
FilterFun -> FilterFun(Req) |
| 134 |
end, |
| 135 |
State = #state{id=StreamID, parent=Pid, opts=Opts, handler=Handler, req=FilteredReq}, |
| 136 |
%% @todo Must ensure the relevant settings are enabled (QUIC and H3). |
| 137 |
%% Either we check them BEFORE, or we check them when the handler |
| 138 |
%% is OK to initiate a webtransport session. Probably need to |
| 139 |
%% check them BEFORE as we need to become (takeover) the webtransport process |
| 140 |
%% after we are done with the upgrade. Maybe in cow_http3_machine but |
| 141 |
%% it doesn't have QUIC settings currently (max_datagram_size). |
| 142 |
case is_upgrade_request(Req) of |
| 143 |
true -> |
| 144 |
Headers = cowboy_req:response_headers(#{}, Req), |
| 145 |
Pid ! {{Pid, StreamID}, {switch_protocol, Headers, ?MODULE, |
| 146 |
#{session_pid => self()}}}, |
| 147 |
webtransport_init(State, HandlerState); |
| 148 |
%% Use 501 Not Implemented to mirror the recommendation in |
| 149 |
%% by RFC9220 3 (WebSockets Upgrade over HTTP/3). |
| 150 |
false -> |
| 151 |
%% @todo I don't think terminate will be called. |
| 152 |
{ok, cowboy_req:reply(501, Req), Env} |
| 153 |
end. |
| 154 |
|
| 155 |
webtransport_init(State=#state{handler=Handler}, HandlerState) -> |
| 156 |
case erlang:function_exported(Handler, webtransport_init, 1) of |
| 157 |
true -> handler_call(State, HandlerState, webtransport_init, undefined); |
| 158 |
false -> before_loop(State, HandlerState) |
| 159 |
end. |
| 160 |
|
| 161 |
before_loop(State=#state{hibernate=true}, HandlerState) -> |
| 162 |
proc_lib:hibernate(?MODULE, loop, [State#state{hibernate=false}, HandlerState]); |
| 163 |
before_loop(State, HandlerState) -> |
| 164 |
loop(State, HandlerState). |
| 165 |
|
| 166 |
-spec loop(#state{}, any()) -> no_return(). |
| 167 |
|
| 168 |
loop(State=#state{id=SessionID, parent=Parent}, HandlerState) -> |
| 169 |
receive |
| 170 |
{'$webtransport_event', SessionID, Event={closed, _, _}} -> |
| 171 |
terminate_proc(State, HandlerState, Event); |
| 172 |
{'$webtransport_event', SessionID, Event=closed_abruptly} -> |
| 173 |
terminate_proc(State, HandlerState, Event); |
| 174 |
{'$webtransport_event', SessionID, Event} -> |
| 175 |
handler_call(State, HandlerState, webtransport_handle, Event); |
| 176 |
%% Timeouts. |
| 177 |
%% @todo idle_timeout |
| 178 |
% {timeout, TRef, ?MODULE} -> |
| 179 |
% tick_idle_timeout(State, HandlerState, ParseState); |
| 180 |
% {timeout, OlderTRef, ?MODULE} when is_reference(OlderTRef) -> |
| 181 |
% before_loop(State, HandlerState, ParseState); |
| 182 |
%% System messages. |
| 183 |
{'EXIT', Parent, Reason} -> |
| 184 |
%% @todo We should exit gracefully. |
| 185 |
exit(Reason); |
| 186 |
{system, From, Request} -> |
| 187 |
sys:handle_system_msg(Request, From, Parent, ?MODULE, [], |
| 188 |
{State, HandlerState}); |
| 189 |
%% Calls from supervisor module. |
| 190 |
{'$gen_call', From, Call} -> |
| 191 |
cowboy_children:handle_supervisor_call(Call, From, [], ?MODULE), |
| 192 |
before_loop(State, HandlerState); |
| 193 |
Message -> |
| 194 |
handler_call(State, HandlerState, webtransport_info, Message) |
| 195 |
end. |
| 196 |
|
| 197 |
handler_call(State=#state{handler=Handler}, HandlerState, Callback, Message) -> |
| 198 |
try case Callback of |
| 199 |
webtransport_init -> Handler:webtransport_init(HandlerState); |
| 200 |
_ -> Handler:Callback(Message, HandlerState) |
| 201 |
end of |
| 202 |
{Commands, HandlerState2} when is_list(Commands) -> |
| 203 |
handler_call_result(State, HandlerState2, Commands); |
| 204 |
{Commands, HandlerState2, hibernate} when is_list(Commands) -> |
| 205 |
handler_call_result(State#state{hibernate=true}, HandlerState2, Commands) |
| 206 |
catch Class:Reason:Stacktrace -> |
| 207 |
%% @todo Do we need to send a close? Let cowboy_http3 detect and handle it? |
| 208 |
handler_terminate(State, HandlerState, {crash, Class, Reason}), |
| 209 |
erlang:raise(Class, Reason, Stacktrace) |
| 210 |
end. |
| 211 |
|
| 212 |
handler_call_result(State0, HandlerState, Commands) -> |
| 213 |
case commands(Commands, State0, ok, []) of |
| 214 |
{ok, State} -> |
| 215 |
before_loop(State, HandlerState); |
| 216 |
{stop, State} -> |
| 217 |
terminate_proc(State, HandlerState, stop) |
| 218 |
end. |
| 219 |
|
| 220 |
%% We accumulate the commands that must be sent to the connection process |
| 221 |
%% because we want to send everything into one message. Other commands are |
| 222 |
%% processed immediately. |
| 223 |
|
| 224 |
commands([], State, Res, []) -> |
| 225 |
{Res, State}; |
| 226 |
commands([], State=#state{id=SessionID, parent=Pid}, Res, Commands) -> |
| 227 |
Pid ! {'$webtransport_commands', SessionID, lists:reverse(Commands)}, |
| 228 |
{Res, State}; |
| 229 |
%% {open_stream, OpenStreamRef, StreamType, InitialData}. |
| 230 |
commands([Command={open_stream, _, _, _}|Tail], State, Res, Acc) -> |
| 231 |
commands(Tail, State, Res, [Command|Acc]); |
| 232 |
%% {close_stream, StreamID, Code}. |
| 233 |
commands([Command={close_stream, _, _}|Tail], State, Res, Acc) -> |
| 234 |
commands(Tail, State, Res, [Command|Acc]); |
| 235 |
%% @todo We must reject send to a remote unidi stream. |
| 236 |
%% {send, StreamID | datagram, Data}. |
| 237 |
commands([Command={send, _, _}|Tail], State, Res, Acc) -> |
| 238 |
commands(Tail, State, Res, [Command|Acc]); |
| 239 |
%% {send, StreamID, IsFin, Data}. |
| 240 |
commands([Command={send, _, _, _}|Tail], State, Res, Acc) -> |
| 241 |
commands(Tail, State, Res, [Command|Acc]); |
| 242 |
%% initiate_close - DRAIN_WT_SESSION |
| 243 |
commands([Command=initiate_close|Tail], State, Res, Acc) -> |
| 244 |
commands(Tail, State, Res, [Command|Acc]); |
| 245 |
%% close | {close, Code} | {close, Code, Msg} - CLOSE_WT_SESSION |
| 246 |
%% @todo At this point the handler must not issue stream or send commands. |
| 247 |
commands([Command=close|Tail], State, _, Acc) -> |
| 248 |
commands(Tail, State, stop, [Command|Acc]); |
| 249 |
commands([Command={close, _}|Tail], State, _, Acc) -> |
| 250 |
commands(Tail, State, stop, [Command|Acc]); |
| 251 |
commands([Command={close, _, _}|Tail], State, _, Acc) -> |
| 252 |
commands(Tail, State, stop, [Command|Acc]). |
| 253 |
%% @todo A set_options command could be useful to increase the number of allowed streams |
| 254 |
%% or other forms of flow control. Alternatively a flow command. Or both. |
| 255 |
%% @todo A shutdown_reason command could be useful for the same reasons as Websocekt. |
| 256 |
|
| 257 |
-spec terminate_proc(_, _, _) -> no_return(). |
| 258 |
|
| 259 |
terminate_proc(State, HandlerState, Reason) -> |
| 260 |
handler_terminate(State, HandlerState, Reason), |
| 261 |
%% @todo This is what should be done if shutdown_reason gets implemented. |
| 262 |
% case Shutdown of |
| 263 |
% normal -> exit(normal); |
| 264 |
% _ -> exit({shutdown, Shutdown}) |
| 265 |
% end. |
| 266 |
exit(normal). |
| 267 |
|
| 268 |
handler_terminate(#state{handler=Handler, req=Req}, HandlerState, Reason) -> |
| 269 |
cowboy_handler:terminate(Reason, Req, HandlerState, Handler). |
| 270 |
|
| 271 |
%% cowboy_stream callbacks. |
| 272 |
%% |
| 273 |
%% We shortcut stream handlers but still need to process some events |
| 274 |
%% such as process exiting or termination. We implement the relevant |
| 275 |
%% callbacks here. Note that as far as WebTransport is concerned, |
| 276 |
%% receiving stream data here would be an error therefore the data |
| 277 |
%% callback is not implemented. |
| 278 |
%% |
| 279 |
%% @todo Better type than map() for the cowboy_stream state. |
| 280 |
%% @todo Is this really useful? |
| 281 |
|
| 282 |
-spec info(cowboy_stream:streamid(), any(), State) |
| 283 |
-> {cowboy_stream:commands(), State} when State::map(). |
| 284 |
|
| 285 |
info(StreamID, Msg, WTState=#{stream_state := StreamState0}) -> |
| 286 |
{Commands, StreamState} = cowboy_stream:info(StreamID, Msg, StreamState0), |
| 287 |
{Commands, WTState#{stream_state => StreamState}}. |
| 288 |
|
| 289 |
-spec terminate(cowboy_stream:streamid(), cowboy_stream:reason(), map()) |
| 290 |
-> any(). |
| 291 |
|
| 292 |
terminate(StreamID, Reason, #{stream_state := StreamState}) -> |
| 293 |
cowboy_stream:terminate(StreamID, Reason, StreamState). |