Debian Codegraph @

src/cowboy_http3.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 %% A key difference between cowboy_http2 and cowboy_http3
16 %% is that HTTP/3 streams are QUIC streams and therefore
17 %% much of the connection state is handled outside of
18 %% Cowboy.
19
20 -module(cowboy_http3).
21
22 -ifdef(COWBOY_QUICER).
23
24 -export([init/4]).
25
26 %% Temporary callback to do sendfile over QUIC.
27 -export([send/2]).
28
29 %% @todo Graceful shutdown? Linger? Timeouts? Frame rates? PROXY header?
30 -type opts() :: #{
31 compress_buffering => boolean(),
32 compress_threshold => non_neg_integer(),
33 connection_type => worker | supervisor,
34 enable_connect_protocol => boolean(),
35 env => cowboy_middleware:env(),
36 logger => module(),
37 max_decode_blocked_streams => 0..16#3fffffffffffffff,
38 max_decode_table_size => 0..16#3fffffffffffffff,
39 max_encode_blocked_streams => 0..16#3fffffffffffffff,
40 max_encode_table_size => 0..16#3fffffffffffffff,
41 max_ignored_frame_size_received => non_neg_integer() | infinity,
42 metrics_callback => cowboy_metrics_h:metrics_callback(),
43 metrics_req_filter => fun((cowboy_req:req()) -> map()),
44 metrics_resp_headers_filter => fun((cowboy:http_headers()) -> cowboy:http_headers()),
45 middlewares => [module()],
46 shutdown_timeout => timeout(),
47 stream_handlers => [module()],
48 tracer_callback => cowboy_tracer_h:tracer_callback(),
49 tracer_flags => [atom()],
50 tracer_match_specs => cowboy_tracer_h:tracer_match_specs(),
51 %% Open ended because configured stream handlers might add options.
52 _ => _
53 }.
54 -export_type([opts/0]).
55
56 %% HTTP/3 or WebTransport stream.
57 %%
58 %% WebTransport sessions involve one bidirectional CONNECT stream
59 %% that must stay open (and can be used for signaling using the
60 %% Capsule Protocol) and an application-defined number of
61 %% unidirectional and bidirectional streams, as well as datagrams.
62 %%
63 %% WebTransport sessions run in the CONNECT request process and
64 %% all events related to the session is sent there as a message.
65 %% The pid of the process is kept in the state.
66 -record(stream, {
67 id :: cow_http3:stream_id(),
68
69 %% Whether the stream is currently in a special state.
70 status :: header | {unidi, control | encoder | decoder}
71 | normal | {data | ignore, non_neg_integer()} | stopping
72 | {relaying, normal | {data, non_neg_integer()}, pid()}
73 | {webtransport_session, normal | {ignore, non_neg_integer()}}
74 | {webtransport_stream, cow_http3:stream_id()},
75
76 %% Stream buffer.
77 buffer = <<>> :: binary(),
78
79 %% Stream state.
80 state = undefined :: undefined | {module(), any()}
81 }).
82
83 -record(state, {
84 parent :: pid(),
85 ref :: ranch:ref(),
86 conn :: cowboy_quicer:quicer_connection_handle(),
87 opts = #{} :: opts(),
88
89 %% Remote address and port for the connection.
90 peer = undefined :: {inet:ip_address(), inet:port_number()},
91
92 %% Local address and port for the connection.
93 sock = undefined :: {inet:ip_address(), inet:port_number()},
94
95 %% Client certificate.
96 cert :: undefined | binary(),
97
98 %% HTTP/3 state machine.
99 http3_machine :: cow_http3_machine:http3_machine(),
100
101 %% Specially handled local unidi streams.
102 local_control_id = undefined :: undefined | cow_http3:stream_id(),
103 local_encoder_id = undefined :: undefined | cow_http3:stream_id(),
104 local_decoder_id = undefined :: undefined | cow_http3:stream_id(),
105
106 %% Bidirectional streams used for requests and responses,
107 %% as well as unidirectional streams initiated by the client.
108 streams = #{} :: #{cow_http3:stream_id() => #stream{}},
109
110 %% Lingering streams that were recently reset. We may receive
111 %% pending data or messages for these streams a short while
112 %% after they have been reset.
113 lingering_streams = [] :: [non_neg_integer()],
114
115 %% Streams can spawn zero or more children which are then managed
116 %% by this module if operating as a supervisor.
117 children = cowboy_children:init() :: cowboy_children:children()
118 }).
119
120 -spec init(pid(), ranch:ref(), cowboy_quicer:quicer_connection_handle(), opts())
121 -> no_return().
122
123 init(Parent, Ref, Conn, Opts) ->
124 {ok, SettingsBin, HTTP3Machine0} = cow_http3_machine:init(server, Opts),
125 %% Immediately open a control, encoder and decoder stream.
126 %% @todo An endpoint MAY avoid creating an encoder stream if it will not be used (for example, if its encoder does not wish to use the dynamic table or if the maximum size of the dynamic table permitted by the peer is zero).
127 %% @todo An endpoint MAY avoid creating a decoder stream if its decoder sets the maximum capacity of the dynamic table to zero.
128 {ok, ControlID} = maybe_socket_error(undefined,
129 cowboy_quicer:start_unidi_stream(Conn, [<<0>>, SettingsBin]),
130 'A socket error occurred when opening the control stream.'),
131 {ok, EncoderID} = maybe_socket_error(undefined,
132 cowboy_quicer:start_unidi_stream(Conn, <<2>>),
133 'A socket error occurred when opening the encoder stream.'),
134 {ok, DecoderID} = maybe_socket_error(undefined,
135 cowboy_quicer:start_unidi_stream(Conn, <<3>>),
136 'A socket error occurred when opening the encoder stream.'),
137 %% Set the control, encoder and decoder streams in the machine.
138 HTTP3Machine = cow_http3_machine:init_unidi_local_streams(
139 ControlID, EncoderID, DecoderID, HTTP3Machine0),
140 %% Get the peername/sockname/cert.
141 {ok, Peer} = maybe_socket_error(undefined, cowboy_quicer:peername(Conn),
142 'A socket error occurred when retrieving the peer name.'),
143 {ok, Sock} = maybe_socket_error(undefined, cowboy_quicer:sockname(Conn),
144 'A socket error occurred when retrieving the sock name.'),
145 CertResult = case cowboy_quicer:peercert(Conn) of
146 {error, no_peercert} ->
147 {ok, undefined};
148 Cert0 ->
149 Cert0
150 end,
151 {ok, Cert} = maybe_socket_error(undefined, CertResult,
152 'A socket error occurred when retrieving the client TLS certificate.'),
153 %% Quick! Let's go!
154 loop(#state{parent=Parent, ref=Ref, conn=Conn,
155 opts=Opts, peer=Peer, sock=Sock, cert=Cert,
156 http3_machine=HTTP3Machine, local_control_id=ControlID,
157 local_encoder_id=EncoderID, local_decoder_id=DecoderID}).
158
159 loop(State0=#state{opts=Opts, children=Children}) ->
160 receive
161 Msg when element(1, Msg) =:= quic ->
162 handle_quic_msg(State0, Msg);
163 %% Timeouts.
164 {timeout, Ref, {shutdown, Pid}} ->
165 cowboy_children:shutdown_timeout(Children, Ref, Pid),
166 loop(State0);
167 %% Messages pertaining to a stream.
168 {{Pid, StreamID}, Msg} when Pid =:= self() ->
169 loop(info(State0, StreamID, Msg));
170 {'$cowboy_relay_command', {Pid, StreamID}, RelayCommand} when Pid =:= self() ->
171 loop(relay_command(State0, StreamID, RelayCommand));
172 %% WebTransport commands.
173 {'$webtransport_commands', SessionID, Commands} ->
174 loop(webtransport_commands(State0, SessionID, Commands));
175 %% Exit signal from children.
176 Msg = {'EXIT', Pid, _} ->
177 loop(down(State0, Pid, Msg));
178 Msg ->
179 cowboy:log(warning, "Received stray message ~p.", [Msg], Opts),
180 loop(State0)
181 end.
182
183 handle_quic_msg(State0=#state{opts=Opts}, Msg) ->
184 case cowboy_quicer:handle(Msg) of
185 {data, StreamID, IsFin, Data} ->
186 parse(State0, StreamID, Data, IsFin);
187 {datagram, Data} ->
188 parse_datagram(State0, Data);
189 {stream_started, StreamID, StreamType} ->
190 State = stream_new_remote(State0, StreamID, StreamType),
191 loop(State);
192 {stream_closed, StreamID, ErrorCode} ->
193 State = stream_closed(State0, StreamID, ErrorCode),
194 loop(State);
195 {peer_send_shutdown, StreamID} ->
196 State = stream_peer_send_shutdown(State0, StreamID),
197 loop(State);
198 closed ->
199 %% @todo Different error reason if graceful?
200 Reason = {socket_error, closed, 'The socket has been closed.'},
201 terminate(State0, Reason);
202 ok ->
203 loop(State0);
204 unknown ->
205 cowboy:log(warning, "Received unknown QUIC message ~p.", [Msg], Opts),
206 loop(State0);
207 {socket_error, Reason} ->
208 terminate(State0, {socket_error, Reason,
209 'An error has occurred on the socket.'})
210 end.
211
212 parse(State=#state{opts=Opts}, StreamID, Data, IsFin) ->
213 case stream_get(State, StreamID) of
214 Stream=#stream{buffer= <<>>} ->
215 parse1(State, Stream, Data, IsFin);
216 Stream=#stream{buffer=Buffer} ->
217 Stream1 = Stream#stream{buffer= <<>>},
218 parse1(stream_store(State, Stream1),
219 Stream1, <<Buffer/binary, Data/binary>>, IsFin);
220 %% Pending data for a stream that has been reset. Ignore.
221 error ->
222 case is_lingering_stream(State, StreamID) of
223 true ->
224 ok;
225 false ->
226 %% We avoid logging the data as it could be quite large.
227 cowboy:log(warning, "Received data for unknown stream ~p.",
228 [StreamID], Opts)
229 end,
230 loop(State)
231 end.
232
233 parse1(State, Stream=#stream{status=header}, Data, IsFin) ->
234 parse_unidirectional_stream_header(State, Stream, Data, IsFin);
235 parse1(State=#state{http3_machine=HTTP3Machine0},
236 #stream{status={unidi, Type}, id=StreamID}, Data, IsFin)
237 when Type =:= encoder; Type =:= decoder ->
238 case cow_http3_machine:unidi_data(Data, IsFin, StreamID, HTTP3Machine0) of
239 {ok, Instrs, HTTP3Machine} ->
240 loop(send_instructions(State#state{http3_machine=HTTP3Machine}, Instrs));
241 {error, Error={connection_error, _, _}, HTTP3Machine} ->
242 terminate(State#state{http3_machine=HTTP3Machine}, Error)
243 end;
244 %% @todo Handle when IsFin = fin which must terminate the WT session.
245 parse1(State=#state{conn=Conn}, Stream=#stream{id=SessionID, status=
246 {webtransport_session, normal}}, Data, IsFin) ->
247 case cow_capsule:parse(Data) of
248 {ok, wt_drain_session, Rest} ->
249 webtransport_event(State, SessionID, close_initiated),
250 parse1(State, Stream, Rest, IsFin);
251 {ok, {wt_close_session, AppCode, AppMsg}, Rest} ->
252 %% This event will be handled specially and lead
253 %% to the termination of the session process.
254 webtransport_event(State, SessionID, {closed, AppCode, AppMsg}),
255 %% Shutdown the CONNECT stream immediately.
256 cowboy_quicer:shutdown_stream(Conn, SessionID),
257 %% @todo Will we receive a {stream_closed,...} after that?
258 %% If any data is received past that point this is an error.
259 %% @todo Don't crash, error out properly.
260 <<>> = Rest,
261 loop(webtransport_terminate_session(State, Stream));
262 more ->
263 loop(stream_store(State, Stream#stream{buffer=Data}));
264 %% Ignore unhandled/unknown capsules.
265 %% @todo Do this when cow_capsule includes some.
266 % {ok, _, Rest} ->
267 % parse1(State, Stream, Rest, IsFin);
268 % {ok, Rest} ->
269 % parse1(State, Stream, Rest, IsFin);
270 %% @todo Make the max length configurable?
271 {skip, Len} when Len =< 8192 ->
272 loop(stream_store(State, Stream#stream{
273 status={webtransport_session, {ignore, Len}}}));
274 {skip, Len} ->
275 %% @todo What should be done on capsule error?
276 error({todo, capsule_too_long, Len});
277 error ->
278 %% @todo What should be done on capsule error?
279 error({todo, capsule_error, Data})
280 end;
281 parse1(State, Stream=#stream{status=
282 {webtransport_session, {ignore, Len}}}, Data, IsFin) ->
283 case Data of
284 <<_:Len/unit:8, Rest/bits>> ->
285 parse1(State, Stream#stream{status={webtransport_session, normal}}, Rest, IsFin);
286 _ ->
287 loop(stream_store(State, Stream#stream{
288 status={webtransport_session, {ignore, Len - byte_size(Data)}}}))
289 end;
290 parse1(State, #stream{id=StreamID, status={webtransport_stream, SessionID}}, Data, IsFin) ->
291 webtransport_event(State, SessionID, {stream_data, StreamID, IsFin, Data}),
292 %% No need to store the stream again, WT streams don't get changed here.
293 loop(State);
294 parse1(State, Stream=#stream{status={data, Len}, id=StreamID}, Data, IsFin) ->
295 DataLen = byte_size(Data),
296 if
297 DataLen < Len ->
298 %% We don't have the full frame but this is the end of the
299 %% data we have. So FrameIsFin is equivalent to IsFin here.
300 loop(frame(State, Stream#stream{status={data, Len - DataLen}}, {data, Data}, IsFin));
301 true ->
302 <<Data1:Len/binary, Rest/bits>> = Data,
303 FrameIsFin = is_fin(IsFin, Rest),
304 parse(frame(State, Stream#stream{status=normal}, {data, Data1}, FrameIsFin),
305 StreamID, Rest, IsFin)
306 end;
307 %% This clause mirrors the {data, Len} clause.
308 parse1(State, Stream=#stream{status={relaying, {data, Len}, RelayPid}, id=StreamID},
309 Data, IsFin) ->
310 DataLen = byte_size(Data),
311 if
312 DataLen < Len ->
313 %% We don't have the full frame but this is the end of the
314 %% data we have. So FrameIsFin is equivalent to IsFin here.
315 loop(frame(State, Stream#stream{status={relaying, {data, Len - DataLen}, RelayPid}},
316 {data, Data}, IsFin));
317 true ->
318 <<Data1:Len/binary, Rest/bits>> = Data,
319 FrameIsFin = is_fin(IsFin, Rest),
320 parse(frame(State, Stream#stream{status={relaying, normal, RelayPid}},
321 {data, Data1}, FrameIsFin), StreamID, Rest, IsFin)
322 end;
323 parse1(State, Stream=#stream{status={ignore, Len}, id=StreamID}, Data, IsFin) ->
324 DataLen = byte_size(Data),
325 if
326 DataLen < Len ->
327 loop(stream_store(State, Stream#stream{status={ignore, Len - DataLen}}));
328 true ->
329 <<_:Len/binary, Rest/bits>> = Data,
330 parse(stream_store(State, Stream#stream{status=normal}),
331 StreamID, Rest, IsFin)
332 end;
333 %% @todo Clause that discards receiving data for stopping streams.
334 %% We may receive a few more frames after we abort receiving.
335 parse1(State=#state{opts=Opts}, Stream=#stream{status=Status0, id=StreamID}, Data, IsFin) ->
336 case cow_http3:parse(Data) of
337 {ok, Frame, Rest} ->
338 FrameIsFin = is_fin(IsFin, Rest),
339 parse(frame(State, Stream, Frame, FrameIsFin), StreamID, Rest, IsFin);
340 %% The WebTransport stream header is not a real frame.
341 {webtransport_stream_header, SessionID, Rest} ->
342 become_webtransport_stream(State, Stream, bidi, SessionID, Rest, IsFin);
343 {more, Frame = {data, _}, Len} ->
344 %% We're at the end of the data so FrameIsFin is equivalent to IsFin.
345 case IsFin of
346 nofin when element(1, Status0) =:= relaying ->
347 %% The stream will be stored at the end of processing commands.
348 Status = setelement(2, Status0, {data, Len}),
349 loop(frame(State, Stream#stream{status=Status}, Frame, nofin));
350 nofin ->
351 %% The stream will be stored at the end of processing commands.
352 loop(frame(State, Stream#stream{status={data, Len}}, Frame, nofin));
353 fin ->
354 terminate(State, {connection_error, h3_frame_error,
355 'Last frame on stream was truncated. (RFC9114 7.1)'})
356 end;
357 {more, ignore, Len} ->
358 %% @todo This setting should be tested.
359 %%
360 %% While the default value doesn't warrant doing a streaming ignore
361 %% (and could work just fine with the 'more' clause), this value
362 %% is configurable and users may want to set it large.
363 MaxIgnoredLen = maps:get(max_ignored_frame_size_received, Opts, 16384),
364 %% We're at the end of the data so FrameIsFin is equivalent to IsFin.
365 case IsFin of
366 nofin when Len < MaxIgnoredLen ->
367 %% We are not processing commands so we must store the stream.
368 %% We also call ignored_frame here; we will not need to call
369 %% it again when ignoring the rest of the data.
370 Stream1 = Stream#stream{status={ignore, Len}},
371 State1 = ignored_frame(State, Stream1),
372 loop(stream_store(State1, Stream1));
373 nofin ->
374 terminate(State, {connection_error, h3_excessive_load,
375 'Ignored frame larger than limit. (RFC9114 10.5)'});
376 fin ->
377 terminate(State, {connection_error, h3_frame_error,
378 'Last frame on stream was truncated. (RFC9114 7.1)'})
379 end;
380 {ignore, Rest} ->
381 parse(ignored_frame(State, Stream), StreamID, Rest, IsFin);
382 Error = {connection_error, _, _} ->
383 terminate(State, Error);
384 more when Data =:= <<>> ->
385 %% The buffer was already reset to <<>>.
386 loop(stream_store(State, Stream));
387 more ->
388 %% We're at the end of the data so FrameIsFin is equivalent to IsFin.
389 case IsFin of
390 nofin ->
391 loop(stream_store(State, Stream#stream{buffer=Data}));
392 fin ->
393 terminate(State, {connection_error, h3_frame_error,
394 'Last frame on stream was truncated. (RFC9114 7.1)'})
395 end
396 end.
397
398 %% We may receive multiple frames in a single QUIC packet.
399 %% The FIN flag applies to the QUIC packet, not to the frame.
400 %% We must therefore only consider the frame to have a FIN
401 %% flag if there's no data remaining to be read.
402 is_fin(fin, <<>>) -> fin;
403 is_fin(_, _) -> nofin.
404
405 parse_unidirectional_stream_header(State0=#state{http3_machine=HTTP3Machine0},
406 Stream0=#stream{id=StreamID}, Data, IsFin) ->
407 case cow_http3:parse_unidi_stream_header(Data) of
408 {ok, Type, Rest} when Type =:= control; Type =:= encoder; Type =:= decoder ->
409 case cow_http3_machine:set_unidi_remote_stream_type(
410 StreamID, Type, HTTP3Machine0) of
411 {ok, HTTP3Machine} ->
412 State = State0#state{http3_machine=HTTP3Machine},
413 Stream = Stream0#stream{status={unidi, Type}},
414 parse(stream_store(State, Stream), StreamID, Rest, IsFin);
415 {error, Error={connection_error, _, _}, HTTP3Machine} ->
416 terminate(State0#state{http3_machine=HTTP3Machine}, Error)
417 end;
418 %% @todo Perhaps do this in cow_http3_machine directly.
419 {ok, push, _} ->
420 terminate(State0, {connection_error, h3_stream_creation_error,
421 'Only servers can push. (RFC9114 6.2.2)'});
422 {ok, {webtransport, SessionID}, Rest} ->
423 become_webtransport_stream(State0, Stream0, unidi, SessionID, Rest, IsFin);
424 %% Unknown stream types must be ignored. We choose to abort the
425 %% stream instead of reading and discarding the incoming data.
426 {undefined, _} ->
427 loop(stream_abort_receive(State0, Stream0, h3_stream_creation_error));
428 %% Very unlikely to happen but WebTransport headers may be fragmented
429 %% as they are more than one byte. The fin flag in this case is an error,
430 %% but because it happens in WebTransport application data (the Session ID)
431 %% we only reset the impacted stream and not the entire connection.
432 more when IsFin =:= fin ->
433 loop(stream_abort_receive(State0, Stream0, h3_stream_creation_error));
434 more ->
435 loop(stream_store(State0, Stream0#stream{buffer=Data}))
436 end.
437
438 frame(State=#state{http3_machine=HTTP3Machine0},
439 Stream=#stream{id=StreamID}, Frame, IsFin) ->
440 case cow_http3_machine:frame(Frame, IsFin, StreamID, HTTP3Machine0) of
441 {ok, HTTP3Machine} ->
442 State#state{http3_machine=HTTP3Machine};
443 {ok, {data, Data}, HTTP3Machine} ->
444 data_frame(State#state{http3_machine=HTTP3Machine}, Stream, IsFin, Data);
445 {ok, {headers, Headers, PseudoHeaders, BodyLen}, Instrs, HTTP3Machine} ->
446 headers_frame(send_instructions(State#state{http3_machine=HTTP3Machine}, Instrs),
447 Stream, IsFin, Headers, PseudoHeaders, BodyLen);
448 {ok, {trailers, _Trailers}, Instrs, HTTP3Machine} ->
449 %% @todo Propagate trailers.
450 send_instructions(State#state{http3_machine=HTTP3Machine}, Instrs);
451 {ok, GoAway={goaway, _}, HTTP3Machine} ->
452 goaway(State#state{http3_machine=HTTP3Machine}, GoAway);
453 {error, Error={stream_error, _Reason, _Human}, Instrs, HTTP3Machine} ->
454 State1 = send_instructions(State#state{http3_machine=HTTP3Machine}, Instrs),
455 reset_stream(State1, Stream, Error);
456 {error, Error={connection_error, _, _}, HTTP3Machine} ->
457 terminate(State#state{http3_machine=HTTP3Machine}, Error)
458 end.
459
460 data_frame(State, Stream=#stream{status={relaying, _, RelayPid}, id=StreamID}, IsFin, Data) ->
461 RelayPid ! {'$cowboy_relay_data', {self(), StreamID}, IsFin, Data},
462 stream_store(State, Stream);
463 data_frame(State=#state{opts=Opts},
464 Stream=#stream{id=StreamID, state=StreamState0}, IsFin, Data) ->
465 try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
466 {Commands, StreamState} ->
467 commands(State, Stream#stream{state=StreamState}, Commands)
468 catch Class:Exception:Stacktrace ->
469 cowboy:log(cowboy_stream:make_error_log(data,
470 [StreamID, IsFin, Data, StreamState0],
471 Class, Exception, Stacktrace), Opts),
472 reset_stream(State, Stream, {internal_error, {Class, Exception},
473 'Unhandled exception in cowboy_stream:data/4.'})
474 end.
475
476 headers_frame(State, Stream, IsFin, Headers,
477 PseudoHeaders=#{method := <<"CONNECT">>}, _)
478 when map_size(PseudoHeaders) =:= 2 ->
479 early_error(State, Stream, IsFin, Headers, PseudoHeaders, 501,
480 'The CONNECT method is currently not implemented. (RFC7231 4.3.6)');
481 headers_frame(State, Stream, IsFin, Headers,
482 PseudoHeaders=#{method := <<"TRACE">>}, _) ->
483 early_error(State, Stream, IsFin, Headers, PseudoHeaders, 501,
484 'The TRACE method is currently not implemented. (RFC9114 4.4, RFC7231 4.3.8)');
485 headers_frame(State, Stream, IsFin, Headers, PseudoHeaders=#{authority := Authority}, BodyLen) ->
486 headers_frame_parse_host(State, Stream, IsFin, Headers, PseudoHeaders, BodyLen, Authority);
487 headers_frame(State, Stream, IsFin, Headers, PseudoHeaders, BodyLen) ->
488 case lists:keyfind(<<"host">>, 1, Headers) of
489 {_, Authority} ->
490 headers_frame_parse_host(State, Stream, IsFin, Headers, PseudoHeaders, BodyLen, Authority);
491 _ ->
492 reset_stream(State, Stream, {stream_error, h3_message_error,
493 'Requests translated from HTTP/1.1 must include a host header. (RFC7540 8.1.2.3, RFC7230 5.4)'})
494 end.
495
496 headers_frame_parse_host(State=#state{ref=Ref, peer=Peer, sock=Sock, cert=Cert},
497 Stream=#stream{id=StreamID}, IsFin, Headers,
498 PseudoHeaders=#{method := Method, scheme := Scheme, path := PathWithQs},
499 BodyLen, Authority) ->
500 try cow_http_hd:parse_host(Authority) of
501 {Host, Port0} ->
502 Port = ensure_port(Scheme, Port0),
503 case cow_http:parse_fullpath(PathWithQs) of
504 {<<>>, _} ->
505 reset_stream(State, Stream, {stream_error, h3_message_error,
506 'The path component must not be empty. (RFC7540 8.1.2.3)'});
507 {Path, Qs} ->
508 Req0 = #{
509 ref => Ref,
510 pid => self(),
511 streamid => StreamID,
512 peer => Peer,
513 sock => Sock,
514 cert => Cert,
515 method => Method,
516 scheme => Scheme,
517 host => Host,
518 port => Port,
519 path => Path,
520 qs => Qs,
521 version => 'HTTP/3',
522 headers => headers_to_map(Headers, #{}),
523 has_body => IsFin =:= nofin,
524 body_length => BodyLen
525 },
526 %% We add the protocol information for extended CONNECTs.
527 Req = case PseudoHeaders of
528 #{protocol := Protocol} -> Req0#{protocol => Protocol};
529 _ -> Req0
530 end,
531 headers_frame(State, Stream, Req)
532 end
533 catch _:_ ->
534 reset_stream(State, Stream, {stream_error, h3_message_error,
535 'The :authority pseudo-header is invalid. (RFC7540 8.1.2.3)'})
536 end.
537
538 %% @todo Copied from cowboy_http2.
539 %% @todo How to handle "http"?
540 ensure_port(<<"http">>, undefined) -> 80;
541 ensure_port(<<"https">>, undefined) -> 443;
542 ensure_port(_, Port) -> Port.
543
544 %% @todo Copied from cowboy_http2.
545 %% This function is necessary to properly handle duplicate headers
546 %% and the special-case cookie header.
547 headers_to_map([], Acc) ->
548 Acc;
549 headers_to_map([{Name, Value}|Tail], Acc0) ->
550 Acc = case Acc0 of
551 %% The cookie header does not use proper HTTP header lists.
552 #{Name := Value0} when Name =:= <<"cookie">> ->
553 Acc0#{Name => << Value0/binary, "; ", Value/binary >>};
554 #{Name := Value0} ->
555 Acc0#{Name => << Value0/binary, ", ", Value/binary >>};
556 _ ->
557 Acc0#{Name => Value}
558 end,
559 headers_to_map(Tail, Acc).
560
561 %% @todo WebTransport CONNECT requests must have extra checks on settings.
562 %% @todo We may also need to defer them if we didn't get settings.
563 headers_frame(State=#state{opts=Opts}, Stream=#stream{id=StreamID}, Req) ->
564 try cowboy_stream:init(StreamID, Req, Opts) of
565 {Commands, StreamState} ->
566 commands(State, Stream#stream{state=StreamState}, Commands)
567 catch Class:Exception:Stacktrace ->
568 cowboy:log(cowboy_stream:make_error_log(init,
569 [StreamID, Req, Opts],
570 Class, Exception, Stacktrace), Opts),
571 reset_stream(State, Stream, {internal_error, {Class, Exception},
572 'Unhandled exception in cowboy_stream:init/3.'})
573 end.
574
575 early_error(State0=#state{ref=Ref, opts=Opts, peer=Peer},
576 Stream=#stream{id=StreamID}, _IsFin, Headers, #{method := Method},
577 StatusCode0, HumanReadable) ->
578 %% We automatically terminate the stream but it is not an error
579 %% per se (at least not in the first implementation).
580 Reason = {stream_error, h3_no_error, HumanReadable},
581 %% The partial Req is minimal for now. We only have one case
582 %% where it can be called (when a method is completely disabled).
583 PartialReq = #{
584 ref => Ref,
585 peer => Peer,
586 method => Method,
587 headers => headers_to_map(Headers, #{})
588 },
589 Resp = {response, StatusCode0, RespHeaders0=#{<<"content-length">> => <<"0">>}, <<>>},
590 try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts) of
591 {response, StatusCode, RespHeaders, RespBody} ->
592 send_response(State0, Stream, StatusCode, RespHeaders, RespBody)
593 catch Class:Exception:Stacktrace ->
594 cowboy:log(cowboy_stream:make_error_log(early_error,
595 [StreamID, Reason, PartialReq, Resp, Opts],
596 Class, Exception, Stacktrace), Opts),
597 %% We still need to send an error response, so send what we initially
598 %% wanted to send. It's better than nothing.
599 send_headers(State0, Stream, fin, StatusCode0, RespHeaders0)
600 end.
601
602 %% Datagrams.
603
604 parse_datagram(State, Data0) ->
605 {SessionID, Data} = cow_http3:parse_datagram(Data0),
606 case stream_get(State, SessionID) of
607 #stream{status={webtransport_session, _}} ->
608 webtransport_event(State, SessionID, {datagram, Data}),
609 loop(State);
610 _ ->
611 error(todo) %% @todo Might be a future WT session or an error.
612 end.
613
614 %% Erlang messages.
615
616 down(State0=#state{opts=Opts, children=Children0}, Pid, Msg) ->
617 State = case cowboy_children:down(Children0, Pid) of
618 %% The stream was terminated already.
619 {ok, undefined, Children} ->
620 State0#state{children=Children};
621 %% The stream is still running.
622 {ok, StreamID, Children} ->
623 info(State0#state{children=Children}, StreamID, Msg);
624 %% The process was unknown.
625 error ->
626 cowboy:log(warning, "Received EXIT signal ~p for unknown process ~p.~n",
627 [Msg, Pid], Opts),
628 State0
629 end,
630 if
631 %% @todo
632 % State#state.http2_status =:= closing, State#state.streams =:= #{} ->
633 % terminate(State, {stop, normal, 'The connection is going away.'});
634 true ->
635 State
636 end.
637
638 info(State=#state{opts=Opts, http3_machine=_HTTP3Machine}, StreamID, Msg) ->
639 case stream_get(State, StreamID) of
640 Stream=#stream{state=StreamState0} ->
641 try cowboy_stream:info(StreamID, Msg, StreamState0) of
642 {Commands, StreamState} ->
643 commands(State, Stream#stream{state=StreamState}, Commands)
644 catch Class:Exception:Stacktrace ->
645 cowboy:log(cowboy_stream:make_error_log(info,
646 [StreamID, Msg, StreamState0],
647 Class, Exception, Stacktrace), Opts),
648 reset_stream(State, Stream, {internal_error, {Class, Exception},
649 'Unhandled exception in cowboy_stream:info/3.'})
650 end;
651 error ->
652 case is_lingering_stream(State, StreamID) of
653 true ->
654 ok;
655 false ->
656 cowboy:log(warning, "Received message ~p for unknown stream ~p.",
657 [Msg, StreamID], Opts)
658 end,
659 State
660 end.
661
662 %% Stream handler commands.
663
664 commands(State, Stream, []) ->
665 stream_store(State, Stream);
666 %% Error responses are sent only if a response wasn't sent already.
667 commands(State=#state{http3_machine=HTTP3Machine}, Stream=#stream{id=StreamID},
668 [{error_response, StatusCode, Headers, Body}|Tail]) ->
669 case cow_http3_machine:get_bidi_stream_local_state(StreamID, HTTP3Machine) of
670 {ok, idle} ->
671 commands(State, Stream, [{response, StatusCode, Headers, Body}|Tail]);
672 _ ->
673 commands(State, Stream, Tail)
674 end;
675 %% Send an informational response.
676 commands(State0, Stream, [{inform, StatusCode, Headers}|Tail]) ->
677 State = send_headers(State0, Stream, idle, StatusCode, Headers),
678 commands(State, Stream, Tail);
679 %% Send response headers.
680 commands(State0, Stream, [{response, StatusCode, Headers, Body}|Tail]) ->
681 State = send_response(State0, Stream, StatusCode, Headers, Body),
682 commands(State, Stream, Tail);
683 %% Send response headers.
684 commands(State0, Stream, [{headers, StatusCode, Headers}|Tail]) ->
685 State = send_headers(State0, Stream, nofin, StatusCode, Headers),
686 commands(State, Stream, Tail);
687 %%% Send a response body chunk.
688 commands(State0=#state{conn=Conn}, Stream=#stream{id=StreamID}, [{data, IsFin, Data}|Tail]) ->
689 _ = case Data of
690 {sendfile, Offset, Bytes, Path} ->
691 %% Temporary solution to do sendfile over QUIC.
692 {ok, _} = ranch_transport:sendfile(?MODULE, {Conn, StreamID},
693 Path, Offset, Bytes, []),
694 ok = maybe_socket_error(State0,
695 cowboy_quicer:send(Conn, StreamID, cow_http3:data(<<>>), IsFin));
696 _ ->
697 ok = maybe_socket_error(State0,
698 cowboy_quicer:send(Conn, StreamID, cow_http3:data(Data), IsFin))
699 end,
700 State = maybe_send_is_fin(State0, Stream, IsFin),
701 commands(State, Stream, Tail);
702 %%% Send trailers.
703 commands(State0=#state{conn=Conn, http3_machine=HTTP3Machine0},
704 Stream=#stream{id=StreamID}, [{trailers, Trailers}|Tail]) ->
705 State = case cow_http3_machine:prepare_trailers(
706 StreamID, HTTP3Machine0, maps:to_list(Trailers)) of
707 {trailers, HeaderBlock, Instrs, HTTP3Machine} ->
708 State1 = send_instructions(State0#state{http3_machine=HTTP3Machine}, Instrs),
709 ok = maybe_socket_error(State1,
710 cowboy_quicer:send(Conn, StreamID, cow_http3:headers(HeaderBlock), fin)),
711 State1;
712 {no_trailers, HTTP3Machine} ->
713 ok = maybe_socket_error(State0,
714 cowboy_quicer:send(Conn, StreamID, cow_http3:data(<<>>), fin)),
715 State0#state{http3_machine=HTTP3Machine}
716 end,
717 commands(State, Stream, Tail);
718 %% Send a push promise.
719 %%
720 %% @todo Responses sent as a result of a push_promise request
721 %% must not send push_promise frames themselves.
722 %%
723 %% @todo We should not send push_promise frames when we are
724 %% in the closing http2_status.
725 %commands(State0=#state{socket=Socket, transport=Transport, http3_machine=HTTP3Machine0},
726 % Stream, [{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) ->
727 % Authority = case {Scheme, Port} of
728 % {<<"http">>, 80} -> Host;
729 % {<<"https">>, 443} -> Host;
730 % _ -> iolist_to_binary([Host, $:, integer_to_binary(Port)])
731 % end,
732 % PathWithQs = iolist_to_binary(case Qs of
733 % <<>> -> Path;
734 % _ -> [Path, $?, Qs]
735 % end),
736 % PseudoHeaders = #{
737 % method => Method,
738 % scheme => Scheme,
739 % authority => Authority,
740 % path => PathWithQs
741 % },
742 % %% We need to make sure the header value is binary before we can
743 % %% create the Req object, as it expects them to be flat.
744 % Headers = maps:to_list(maps:map(fun(_, V) -> iolist_to_binary(V) end, Headers0)),
745 % %% @todo
746 % State = case cow_http2_machine:prepare_push_promise(StreamID, HTTP3Machine0,
747 % PseudoHeaders, Headers) of
748 % {ok, PromisedStreamID, HeaderBlock, HTTP3Machine} ->
749 % Transport:send(Socket, cow_http2:push_promise(
750 % StreamID, PromisedStreamID, HeaderBlock)),
751 % headers_frame(State0#state{http3_machine=HTTP2Machine},
752 % PromisedStreamID, fin, Headers, PseudoHeaders, 0);
753 % {error, no_push} ->
754 % State0
755 % end,
756 % commands(State, Stream, Tail);
757 %%% Read the request body.
758 %commands(State0=#state{flow=Flow, streams=Streams}, Stream, [{flow, Size}|Tail]) ->
759 commands(State, Stream, [{flow, _Size}|Tail]) ->
760 %% @todo We should tell the QUIC stream to increase its window size.
761 % #{StreamID := Stream=#stream{flow=StreamFlow}} = Streams,
762 % State = update_window(State0#state{flow=Flow + Size,
763 % streams=Streams#{StreamID => Stream#stream{flow=StreamFlow + Size}}},
764 % StreamID),
765 commands(State, Stream, Tail);
766 %% Supervise a child process.
767 commands(State=#state{children=Children}, Stream=#stream{id=StreamID},
768 [{spawn, Pid, Shutdown}|Tail]) ->
769 commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)},
770 Stream, Tail);
771 %% Error handling.
772 commands(State, Stream, [Error = {internal_error, _, _}|_Tail]) ->
773 %% @todo Do we want to run the commands after an internal_error?
774 %% @todo Do we even allow commands after?
775 %% @todo Only reset when the stream still exists.
776 reset_stream(State, Stream, Error);
777 %% Use a different protocol within the stream (CONNECT :protocol).
778 %% @todo Make sure we error out when the feature is disabled.
779 commands(State0, Stream0=#stream{id=StreamID},
780 [{switch_protocol, Headers, cowboy_webtransport, WTState=#{}}|Tail]) ->
781 State = info(stream_store(State0, Stream0), StreamID, {headers, 200, Headers}),
782 #state{http3_machine=HTTP3Machine0} = State,
783 Stream1 = #stream{state=StreamState} = stream_get(State, StreamID),
784 %% The stream becomes a WT session at that point. It is the
785 %% parent stream of all streams in this WT session. The
786 %% cowboy_stream state is kept because it will be needed
787 %% to terminate the stream properly.
788 HTTP3Machine = cow_http3_machine:become_webtransport_session(StreamID, HTTP3Machine0),
789 Stream = Stream1#stream{
790 status={webtransport_session, normal},
791 state={cowboy_webtransport, WTState#{stream_state => StreamState}}
792 },
793 %% @todo We must propagate the buffer to capsule handling if any.
794 commands(State#state{http3_machine=HTTP3Machine}, Stream, Tail);
795 %% There are two data_delivery: stream_handlers and relay.
796 %% The former just has the data go through stream handlers
797 %% like normal requests. The latter relays data directly.
798 commands(State0, Stream0=#stream{id=StreamID},
799 [{switch_protocol, Headers, _Mod, ModState=#{data_delivery := relay}}|Tail]) ->
800 State = info(stream_store(State0, Stream0), StreamID, {headers, 200, Headers}),
801 Stream1 = #stream{status=normal} = stream_get(State, StreamID),
802 #{data_delivery_pid := RelayPid} = ModState,
803 %% We do not set data_delivery_flow because it is managed by quicer
804 %% and we do not have an easy way to modify it.
805 Stream = Stream1#stream{status={relaying, normal, RelayPid}},
806 commands(State, Stream, Tail);
807 commands(State0, Stream0=#stream{id=StreamID},
808 [{switch_protocol, Headers, _Mod, _ModState}|Tail]) ->
809 State = info(stream_store(State0, Stream0), StreamID, {headers, 200, Headers}),
810 Stream = stream_get(State, StreamID),
811 commands(State, Stream, Tail);
812 %% Set options dynamically.
813 commands(State, Stream, [{set_options, _Opts}|Tail]) ->
814 commands(State, Stream, Tail);
815 commands(State, Stream, [stop|_Tail]) ->
816 %% @todo Do we want to run the commands after a stop?
817 %% @todo Do we even allow commands after?
818 stop_stream(State, Stream);
819 %% Log event.
820 commands(State=#state{opts=Opts}, Stream, [Log={log, _, _, _}|Tail]) ->
821 cowboy:log(Log, Opts),
822 commands(State, Stream, Tail).
823
824 send_response(State0=#state{conn=Conn, http3_machine=HTTP3Machine0},
825 Stream=#stream{id=StreamID}, StatusCode, Headers, Body) ->
826 Size = case Body of
827 {sendfile, _, Bytes0, _} -> Bytes0;
828 _ -> iolist_size(Body)
829 end,
830 case Size of
831 0 ->
832 State = send_headers(State0, Stream, fin, StatusCode, Headers),
833 maybe_send_is_fin(State, Stream, fin);
834 _ ->
835 %% @todo Add a test for HEAD to make sure we don't send the body when
836 %% returning {response...} from a stream handler (or {headers...} then {data...}).
837 {ok, _IsFin, HeaderBlock, Instrs, HTTP3Machine}
838 = cow_http3_machine:prepare_headers(StreamID, HTTP3Machine0, nofin,
839 #{status => cow_http:status_to_integer(StatusCode)},
840 headers_to_list(Headers)),
841 State = send_instructions(State0#state{http3_machine=HTTP3Machine}, Instrs),
842 %% @todo It might be better to do async sends.
843 _ = case Body of
844 {sendfile, Offset, Bytes, Path} ->
845 ok = maybe_socket_error(State,
846 cowboy_quicer:send(Conn, StreamID, cow_http3:headers(HeaderBlock))),
847 %% Temporary solution to do sendfile over QUIC.
848 {ok, _} = maybe_socket_error(State,
849 ranch_transport:sendfile(?MODULE, {Conn, StreamID},
850 Path, Offset, Bytes, [])),
851 ok = maybe_socket_error(State,
852 cowboy_quicer:send(Conn, StreamID, cow_http3:data(<<>>), fin));
853 _ ->
854 ok = maybe_socket_error(State,
855 cowboy_quicer:send(Conn, StreamID, [
856 cow_http3:headers(HeaderBlock),
857 cow_http3:data(Body)
858 ], fin))
859 end,
860 maybe_send_is_fin(State, Stream, fin)
861 end.
862
863 maybe_send_is_fin(State=#state{http3_machine=HTTP3Machine0},
864 Stream=#stream{id=StreamID}, fin) ->
865 HTTP3Machine = cow_http3_machine:close_bidi_stream_for_sending(StreamID, HTTP3Machine0),
866 maybe_terminate_stream(State#state{http3_machine=HTTP3Machine}, Stream);
867 maybe_send_is_fin(State, _, _) ->
868 State.
869
870 %% Temporary callback to do sendfile over QUIC.
871 -spec send({cowboy_quicer:quicer_connection_handle(), cow_http3:stream_id()},
872 iodata()) -> ok | {error, any()}.
873
874 send({Conn, StreamID}, IoData) ->
875 cowboy_quicer:send(Conn, StreamID, cow_http3:data(IoData)).
876
877 send_headers(State0=#state{conn=Conn, http3_machine=HTTP3Machine0},
878 #stream{id=StreamID}, IsFin0, StatusCode, Headers) ->
879 {ok, IsFin, HeaderBlock, Instrs, HTTP3Machine}
880 = cow_http3_machine:prepare_headers(StreamID, HTTP3Machine0, IsFin0,
881 #{status => cow_http:status_to_integer(StatusCode)},
882 headers_to_list(Headers)),
883 State = send_instructions(State0#state{http3_machine=HTTP3Machine}, Instrs),
884 ok = maybe_socket_error(State,
885 cowboy_quicer:send(Conn, StreamID, cow_http3:headers(HeaderBlock), IsFin)),
886 State.
887
888 %% The set-cookie header is special; we can only send one cookie per header.
889 headers_to_list(Headers0=#{<<"set-cookie">> := SetCookies}) ->
890 Headers = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
891 Headers ++ [{<<"set-cookie">>, Value} || Value <- SetCookies];
892 headers_to_list(Headers) ->
893 maps:to_list(Headers).
894
895 %% @todo We would open unidi streams here if we only open on-demand.
896 %% No instructions.
897 send_instructions(State, undefined) ->
898 State;
899 %% Decoder instructions.
900 send_instructions(State=#state{conn=Conn, local_decoder_id=DecoderID},
901 {decoder_instructions, DecData}) ->
902 ok = maybe_socket_error(State,
903 cowboy_quicer:send(Conn, DecoderID, DecData)),
904 State;
905 %% Encoder instructions.
906 send_instructions(State=#state{conn=Conn, local_encoder_id=EncoderID},
907 {encoder_instructions, EncData}) ->
908 ok = maybe_socket_error(State,
909 cowboy_quicer:send(Conn, EncoderID, EncData)),
910 State.
911
912 %% Relay data delivery commands.
913
914 relay_command(State, StreamID, DataCmd = {data, _, _}) ->
915 Stream = stream_get(State, StreamID),
916 commands(State, Stream, [DataCmd]);
917 relay_command(State=#state{conn=Conn}, StreamID, active) ->
918 ok = maybe_socket_error(State,
919 cowboy_quicer:setopt(Conn, StreamID, active, true)),
920 State;
921 relay_command(State=#state{conn=Conn}, StreamID, passive) ->
922 ok = maybe_socket_error(State,
923 cowboy_quicer:setopt(Conn, StreamID, active, false)),
924 State.
925
926 %% We mark the stream as being a WebTransport stream
927 %% and then continue parsing the data as a WebTransport
928 %% stream. This function is common for incoming unidi
929 %% and bidi streams.
930 become_webtransport_stream(State0=#state{http3_machine=HTTP3Machine0},
931 Stream0=#stream{id=StreamID}, StreamType, SessionID, Rest, IsFin) ->
932 case cow_http3_machine:become_webtransport_stream(StreamID, SessionID, HTTP3Machine0) of
933 {ok, HTTP3Machine} ->
934 State = State0#state{http3_machine=HTTP3Machine},
935 Stream = Stream0#stream{status={webtransport_stream, SessionID}},
936 webtransport_event(State, SessionID, {stream_open, StreamID, StreamType}),
937 %% We don't need to parse the remaining data if there isn't any.
938 case {Rest, IsFin} of
939 {<<>>, nofin} -> loop(stream_store(State, Stream));
940 _ -> parse(stream_store(State, Stream), StreamID, Rest, IsFin)
941 end
942 %% @todo Error conditions.
943 end.
944
945 webtransport_event(State, SessionID, Event) ->
946 #stream{
947 status={webtransport_session, _},
948 state={cowboy_webtransport, #{session_pid := SessionPid}}
949 } = stream_get(State, SessionID),
950 SessionPid ! {'$webtransport_event', SessionID, Event},
951 ok.
952
953 webtransport_commands(State, SessionID, Commands) ->
954 case stream_get(State, SessionID) of
955 Session = #stream{status={webtransport_session, _}} ->
956 wt_commands(State, Session, Commands);
957 %% The stream has been terminated, ignore pending commands.
958 error ->
959 State
960 end.
961
962 wt_commands(State, _, []) ->
963 State;
964 wt_commands(State0=#state{conn=Conn}, Session=#stream{id=SessionID},
965 [{open_stream, OpenStreamRef, StreamType, InitialData}|Tail]) ->
966 %% Because opening the stream involves sending a short header
967 %% we necessarily write data. The InitialData variable allows
968 %% providing additional data to be sent in the same packet.
969 StartF = case StreamType of
970 bidi -> start_bidi_stream;
971 unidi -> start_unidi_stream
972 end,
973 Header = cow_http3:webtransport_stream_header(SessionID, StreamType),
974 case cowboy_quicer:StartF(Conn, [Header, InitialData]) of
975 {ok, StreamID} ->
976 %% @todo Pass Session directly?
977 webtransport_event(State0, SessionID,
978 {opened_stream_id, OpenStreamRef, StreamID}),
979 State = stream_new_local(State0, StreamID, StreamType,
980 {webtransport_stream, SessionID}),
981 wt_commands(State, Session, Tail)
982 %% @todo Handle errors.
983 end;
984 wt_commands(State, Session, [{close_stream, StreamID, Code}|Tail]) ->
985 %% @todo Check that StreamID belongs to Session.
986 error({todo, State, Session, [{close_stream, StreamID, Code}|Tail]});
987 wt_commands(State=#state{conn=Conn}, Session=#stream{id=SessionID},
988 [{send, datagram, Data}|Tail]) ->
989 case cowboy_quicer:send_datagram(Conn, cow_http3:datagram(SessionID, Data)) of
990 ok ->
991 wt_commands(State, Session, Tail)
992 %% @todo Handle errors.
993 end;
994 wt_commands(State=#state{conn=Conn}, Session, [{send, StreamID, Data}|Tail]) ->
995 %% @todo Check that StreamID belongs to Session.
996 case cowboy_quicer:send(Conn, StreamID, Data, nofin) of
997 ok ->
998 wt_commands(State, Session, Tail)
999 %% @todo Handle errors.
1000 end;
1001 wt_commands(State=#state{conn=Conn}, Session, [{send, StreamID, IsFin, Data}|Tail]) ->
1002 %% @todo Check that StreamID belongs to Session.
1003 case cowboy_quicer:send(Conn, StreamID, Data, IsFin) of
1004 ok ->
1005 wt_commands(State, Session, Tail)
1006 %% @todo Handle errors.
1007 end;
1008 wt_commands(State=#state{conn=Conn}, Session=#stream{id=SessionID}, [initiate_close|Tail]) ->
1009 %% We must send a WT_DRAIN_SESSION capsule on the CONNECT stream.
1010 Capsule = cow_capsule:wt_drain_session(),
1011 case cowboy_quicer:send(Conn, SessionID, Capsule, nofin) of
1012 ok ->
1013 wt_commands(State, Session, Tail)
1014 %% @todo Handle errors.
1015 end;
1016 wt_commands(State0=#state{conn=Conn}, Session=#stream{id=SessionID}, [Cmd|Tail])
1017 when Cmd =:= close; element(1, Cmd) =:= close ->
1018 %% We must send a WT_CLOSE_SESSION capsule on the CONNECT stream.
1019 {AppCode, AppMsg} = case Cmd of
1020 close -> {0, <<>>};
1021 {close, AppCode0} -> {AppCode0, <<>>};
1022 {close, AppCode0, AppMsg0} -> {AppCode0, AppMsg0}
1023 end,
1024 Capsule = cow_capsule:wt_close_session(AppCode, AppMsg),
1025 case cowboy_quicer:send(Conn, SessionID, Capsule, fin) of
1026 ok ->
1027 State = webtransport_terminate_session(State0, Session),
1028 %% @todo Because the handler is in a separate process
1029 %% we must wait for it to stop and eventually
1030 %% kill the process if it takes too long.
1031 %% @todo We may need to fully close the CONNECT stream (if remote doesn't reset it).
1032 wt_commands(State, Session, Tail)
1033 %% @todo Handle errors.
1034 end.
1035
1036 webtransport_terminate_session(State=#state{conn=Conn, http3_machine=HTTP3Machine0,
1037 streams=Streams0, lingering_streams=Lingering0}, #stream{id=SessionID}) ->
1038 %% Reset/abort the WT streams.
1039 Streams = maps:filtermap(fun
1040 (_, #stream{id=StreamID, status={webtransport_session, _}})
1041 when StreamID =:= SessionID ->
1042 %% We remove the session stream but do the shutdown outside this function.
1043 false;
1044 (StreamID, #stream{status={webtransport_stream, StreamSessionID}})
1045 when StreamSessionID =:= SessionID ->
1046 cowboy_quicer:shutdown_stream(Conn, StreamID,
1047 both, cow_http3:error_to_code(wt_session_gone)),
1048 false;
1049 (_, _) ->
1050 true
1051 end, Streams0),
1052 %% Keep the streams in lingering state.
1053 %% We only keep up to 100 streams in this state. @todo Make it configurable?
1054 Terminated = maps:keys(Streams0) -- maps:keys(Streams),
1055 Lingering = lists:sublist(Terminated ++ Lingering0, 100),
1056 %% Update the HTTP3 state machine.
1057 HTTP3Machine = cow_http3_machine:close_webtransport_session(SessionID, HTTP3Machine0),
1058 State#state{
1059 http3_machine=HTTP3Machine,
1060 streams=Streams,
1061 lingering_streams=Lingering
1062 }.
1063
1064 stream_peer_send_shutdown(State=#state{conn=Conn}, StreamID) ->
1065 case stream_get(State, StreamID) of
1066 %% Cleanly terminating the CONNECT stream is equivalent
1067 %% to an application error code of 0 and empty message.
1068 Stream = #stream{status={webtransport_session, _}} ->
1069 webtransport_event(State, StreamID, {closed, 0, <<>>}),
1070 %% Shutdown the CONNECT stream fully.
1071 cowboy_quicer:shutdown_stream(Conn, StreamID),
1072 webtransport_terminate_session(State, Stream);
1073 _ ->
1074 State
1075 end.
1076
1077 reset_stream(State0=#state{conn=Conn, http3_machine=HTTP3Machine0},
1078 Stream=#stream{id=StreamID}, Error) ->
1079 Reason = case Error of
1080 {internal_error, _, _} -> h3_internal_error;
1081 {stream_error, Reason0, _} -> Reason0
1082 end,
1083 %% @todo Do we want to close both sides?
1084 %% @todo Should we close the send side if the receive side was already closed?
1085 cowboy_quicer:shutdown_stream(Conn, StreamID,
1086 both, cow_http3:error_to_code(Reason)),
1087 State1 = case cow_http3_machine:reset_stream(StreamID, HTTP3Machine0) of
1088 {ok, HTTP3Machine} ->
1089 terminate_stream(State0#state{http3_machine=HTTP3Machine}, Stream, Error);
1090 {error, not_found} ->
1091 terminate_stream(State0, Stream, Error)
1092 end,
1093 %% @todo
1094 % case reset_rate(State1) of
1095 % {ok, State} ->
1096 % State;
1097 % error ->
1098 % terminate(State1, {connection_error, enhance_your_calm,
1099 % 'Stream reset rate larger than configuration allows. Flood? (CVE-2019-9514)'})
1100 % end.
1101 State1.
1102
1103 stop_stream(State0=#state{http3_machine=HTTP3Machine}, Stream=#stream{id=StreamID}) ->
1104 %% We abort reading when stopping the stream but only
1105 %% if the client was not finished sending data.
1106 %% We mark the stream as 'stopping' either way.
1107 State = case cow_http3_machine:get_bidi_stream_remote_state(StreamID, HTTP3Machine) of
1108 {ok, fin} ->
1109 stream_store(State0, Stream#stream{status=stopping});
1110 {error, not_found} ->
1111 stream_store(State0, Stream#stream{status=stopping});
1112 _ ->
1113 stream_abort_receive(State0, Stream, h3_no_error)
1114 end,
1115 %% Then we may need to send a response or terminate it
1116 %% if the stream handler did not do so already.
1117 case cow_http3_machine:get_bidi_stream_local_state(StreamID, HTTP3Machine) of
1118 %% When the stream terminates normally (without resetting the stream)
1119 %% and no response was sent, we need to send a proper response back to the client.
1120 {ok, idle} ->
1121 info(State, StreamID, {response, 204, #{}, <<>>});
1122 %% When a response was sent but not terminated, we need to close the stream.
1123 %% We send a final DATA frame to complete the stream.
1124 {ok, nofin} ->
1125 info(State, StreamID, {data, fin, <<>>});
1126 %% When a response was sent fully we can terminate the stream,
1127 %% regardless of the stream being in half-closed or closed state.
1128 _ ->
1129 terminate_stream(State, Stream, normal)
1130 end.
1131
1132 maybe_terminate_stream(State, Stream=#stream{status=stopping}) ->
1133 terminate_stream(State, Stream, normal);
1134 %% The Stream will be stored in the State at the end of commands processing.
1135 maybe_terminate_stream(State, _) ->
1136 State.
1137
1138 terminate_stream(State=#state{streams=Streams0, children=Children0},
1139 #stream{id=StreamID, state=StreamState}, Reason) ->
1140 Streams = maps:remove(StreamID, Streams0),
1141 terminate_stream_handler(State, StreamID, Reason, StreamState),
1142 Children = cowboy_children:shutdown(Children0, StreamID),
1143 stream_linger(State#state{streams=Streams, children=Children}, StreamID).
1144
1145 terminate_stream_handler(#state{opts=Opts}, StreamID, Reason, StreamState) ->
1146 try
1147 cowboy_stream:terminate(StreamID, Reason, StreamState)
1148 catch Class:Exception:Stacktrace ->
1149 cowboy:log(cowboy_stream:make_error_log(terminate,
1150 [StreamID, Reason, StreamState],
1151 Class, Exception, Stacktrace), Opts)
1152 end.
1153
1154 ignored_frame(State=#state{http3_machine=HTTP3Machine0}, #stream{id=StreamID}) ->
1155 case cow_http3_machine:ignored_frame(StreamID, HTTP3Machine0) of
1156 {ok, HTTP3Machine} ->
1157 State#state{http3_machine=HTTP3Machine};
1158 {error, Error={connection_error, _, _}, HTTP3Machine} ->
1159 terminate(State#state{http3_machine=HTTP3Machine}, Error)
1160 end.
1161
1162 stream_abort_receive(State=#state{conn=Conn}, Stream=#stream{id=StreamID}, Reason) ->
1163 cowboy_quicer:shutdown_stream(Conn, StreamID,
1164 receiving, cow_http3:error_to_code(Reason)),
1165 stream_store(State, Stream#stream{status=stopping}).
1166
1167 %% @todo Graceful connection shutdown.
1168 %% We terminate the connection immediately if it hasn't fully been initialized.
1169 -spec goaway(#state{}, {goaway, _}) -> no_return().
1170 goaway(State, {goaway, _}) ->
1171 terminate(State, {stop, goaway, 'The connection is going away.'}).
1172
1173 %% Function copied from cowboy_http.
1174 maybe_socket_error(State, {error, closed}) ->
1175 terminate(State, {socket_error, closed, 'The socket has been closed.'});
1176 maybe_socket_error(State, Reason) ->
1177 maybe_socket_error(State, Reason, 'An error has occurred on the socket.').
1178
1179 maybe_socket_error(_, Result = ok, _) ->
1180 Result;
1181 maybe_socket_error(_, Result = {ok, _}, _) ->
1182 Result;
1183 maybe_socket_error(State, {error, Reason}, Human) ->
1184 terminate(State, {socket_error, Reason, Human}).
1185
1186 -spec terminate(#state{} | undefined, _) -> no_return().
1187 terminate(undefined, Reason) ->
1188 exit({shutdown, Reason});
1189 terminate(State=#state{conn=Conn, %http3_status=Status,
1190 %http3_machine=HTTP3Machine,
1191 streams=Streams, children=Children}, Reason) ->
1192 % if
1193 % Status =:= connected; Status =:= closing_initiated ->
1194 %% @todo
1195 % %% We are terminating so it's OK if we can't send the GOAWAY anymore.
1196 % _ = cowboy_quicer:send(Conn, ControlID, cow_http3:goaway(
1197 % cow_http3_machine:get_last_streamid(HTTP3Machine))),
1198 %% We already sent the GOAWAY frame.
1199 % Status =:= closing ->
1200 % ok
1201 % end,
1202 terminate_all_streams(State, maps:to_list(Streams), Reason),
1203 cowboy_children:terminate(Children),
1204 % terminate_linger(State),
1205 _ = cowboy_quicer:shutdown(Conn, cow_http3:error_to_code(terminate_reason(Reason))),
1206 exit({shutdown, Reason}).
1207
1208 terminate_reason({connection_error, Reason, _}) -> Reason;
1209 terminate_reason({stop, _, _}) -> h3_no_error;
1210 terminate_reason({socket_error, _, _}) -> h3_internal_error.
1211 %terminate_reason({internal_error, _, _}) -> internal_error.
1212
1213 terminate_all_streams(_, [], _) ->
1214 ok;
1215 terminate_all_streams(State, [{StreamID, #stream{state=StreamState}}|Tail], Reason) ->
1216 terminate_stream_handler(State, StreamID, Reason, StreamState),
1217 terminate_all_streams(State, Tail, Reason).
1218
1219 stream_get(#state{streams=Streams}, StreamID) ->
1220 maps:get(StreamID, Streams, error).
1221
1222 stream_new_local(State, StreamID, StreamType, Status) ->
1223 stream_new(State, StreamID, StreamType, unidi_local, Status).
1224
1225 stream_new_remote(State, StreamID, StreamType) ->
1226 Status = case StreamType of
1227 unidi -> header;
1228 bidi -> normal
1229 end,
1230 stream_new(State, StreamID, StreamType, unidi_remote, Status).
1231
1232 stream_new(State=#state{http3_machine=HTTP3Machine0, streams=Streams},
1233 StreamID, StreamType, UnidiType, Status) ->
1234 {HTTP3Machine, Status} = case StreamType of
1235 unidi ->
1236 {cow_http3_machine:init_unidi_stream(StreamID, UnidiType, HTTP3Machine0),
1237 Status};
1238 bidi ->
1239 {cow_http3_machine:init_bidi_stream(StreamID, HTTP3Machine0),
1240 Status}
1241 end,
1242 Stream = #stream{id=StreamID, status=Status},
1243 State#state{http3_machine=HTTP3Machine, streams=Streams#{StreamID => Stream}}.
1244
1245 %% Stream closed message for a local (write-only) unidi stream.
1246 stream_closed(State=#state{local_control_id=StreamID}, StreamID, _) ->
1247 stream_closed1(State, StreamID);
1248 stream_closed(State=#state{local_encoder_id=StreamID}, StreamID, _) ->
1249 stream_closed1(State, StreamID);
1250 stream_closed(State=#state{local_decoder_id=StreamID}, StreamID, _) ->
1251 stream_closed1(State, StreamID);
1252 stream_closed(State=#state{opts=Opts,
1253 streams=Streams0, children=Children0}, StreamID, ErrorCode) ->
1254 case maps:take(StreamID, Streams0) of
1255 %% In the WT session's case, streams will be
1256 %% removed in webtransport_terminate_session.
1257 {Stream=#stream{status={webtransport_session, _}}, _} ->
1258 webtransport_event(State, StreamID, closed_abruptly),
1259 webtransport_terminate_session(State, Stream);
1260 {#stream{state=undefined}, Streams} ->
1261 %% Unidi stream has no handler/children.
1262 stream_closed1(State#state{streams=Streams}, StreamID);
1263 %% We only stop bidi streams if the stream was closed with an error
1264 %% or the stream was already in the process of stopping.
1265 {#stream{status=Status, state=StreamState}, Streams}
1266 when Status =:= stopping; ErrorCode =/= 0 ->
1267 terminate_stream_handler(State, StreamID, closed, StreamState),
1268 Children = cowboy_children:shutdown(Children0, StreamID),
1269 stream_closed1(State#state{streams=Streams, children=Children}, StreamID);
1270 %% Don't remove a stream that terminated properly but
1271 %% has chosen to remain up (custom stream handlers).
1272 {_, _} ->
1273 stream_closed1(State, StreamID);
1274 %% Stream closed message for a stream that has been reset. Ignore.
1275 error ->
1276 case is_lingering_stream(State, StreamID) of
1277 true ->
1278 ok;
1279 false ->
1280 %% We avoid logging the data as it could be quite large.
1281 cowboy:log(warning, "Received stream_closed for unknown stream ~p. ~p ~p",
1282 [StreamID, self(), Streams0], Opts)
1283 end,
1284 State
1285 end.
1286
1287 stream_closed1(State=#state{http3_machine=HTTP3Machine0}, StreamID) ->
1288 case cow_http3_machine:close_stream(StreamID, HTTP3Machine0) of
1289 {ok, HTTP3Machine} ->
1290 State#state{http3_machine=HTTP3Machine};
1291 {error, Error={connection_error, _, _}, HTTP3Machine} ->
1292 terminate(State#state{http3_machine=HTTP3Machine}, Error)
1293 end.
1294
1295 stream_store(State=#state{streams=Streams}, Stream=#stream{id=StreamID}) ->
1296 State#state{streams=Streams#{StreamID => Stream}}.
1297
1298 stream_linger(State=#state{lingering_streams=Lingering0}, StreamID) ->
1299 %% We only keep up to 100 streams in this state. @todo Make it configurable?
1300 Lingering = [StreamID|lists:sublist(Lingering0, 100 - 1)],
1301 State#state{lingering_streams=Lingering}.
1302
1303 is_lingering_stream(#state{lingering_streams=Lingering}, StreamID) ->
1304 lists:member(StreamID, Lingering).
1305
1306 -endif.