| 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_http2). |
| 16 |
|
| 17 |
-export([init/6]). |
| 18 |
-export([init/10]). |
| 19 |
-export([init/12]). |
| 20 |
-export([loop/2]). |
| 21 |
|
| 22 |
-export([system_continue/3]). |
| 23 |
-export([system_terminate/4]). |
| 24 |
-export([system_code_change/4]). |
| 25 |
|
| 26 |
-type opts() :: #{ |
| 27 |
active_n => pos_integer(), |
| 28 |
alpn_default_protocol => http | http2, |
| 29 |
compress_buffering => boolean(), |
| 30 |
compress_threshold => non_neg_integer(), |
| 31 |
connection_type => worker | supervisor, |
| 32 |
connection_window_margin_size => 0..16#7fffffff, |
| 33 |
connection_window_update_threshold => 0..16#7fffffff, |
| 34 |
dynamic_buffer => false | {pos_integer(), pos_integer()}, |
| 35 |
dynamic_buffer_initial_average => non_neg_integer(), |
| 36 |
dynamic_buffer_initial_size => pos_integer(), |
| 37 |
enable_connect_protocol => boolean(), |
| 38 |
env => cowboy_middleware:env(), |
| 39 |
goaway_initial_timeout => timeout(), |
| 40 |
goaway_complete_timeout => timeout(), |
| 41 |
hibernate => boolean(), |
| 42 |
idle_timeout => timeout(), |
| 43 |
inactivity_timeout => timeout(), |
| 44 |
initial_connection_window_size => 65535..16#7fffffff, |
| 45 |
initial_stream_window_size => 0..16#7fffffff, |
| 46 |
linger_timeout => timeout(), |
| 47 |
logger => module(), |
| 48 |
max_authority_length => non_neg_integer(), |
| 49 |
max_cancel_stream_rate => {pos_integer(), timeout()}, |
| 50 |
max_concurrent_streams => non_neg_integer() | infinity, |
| 51 |
max_connection_buffer_size => non_neg_integer(), |
| 52 |
max_connection_window_size => 0..16#7fffffff, |
| 53 |
max_decode_table_size => non_neg_integer(), |
| 54 |
max_encode_table_size => non_neg_integer(), |
| 55 |
max_fragmented_header_block_size => 16384..16#7fffffff, |
| 56 |
max_frame_size_received => 16384..16777215, |
| 57 |
max_frame_size_sent => 16384..16777215 | infinity, |
| 58 |
max_headers => non_neg_integer(), |
| 59 |
max_received_frame_rate => {pos_integer(), timeout()}, |
| 60 |
max_reset_stream_rate => {pos_integer(), timeout()}, |
| 61 |
max_stream_buffer_size => non_neg_integer(), |
| 62 |
max_stream_window_size => 0..16#7fffffff, |
| 63 |
metrics_callback => cowboy_metrics_h:metrics_callback(), |
| 64 |
metrics_req_filter => fun((cowboy_req:req()) -> map()), |
| 65 |
metrics_resp_headers_filter => fun((cowboy:http_headers()) -> cowboy:http_headers()), |
| 66 |
middlewares => [module()], |
| 67 |
preface_timeout => timeout(), |
| 68 |
protocols => [http | http2], |
| 69 |
proxy_header => boolean(), |
| 70 |
reset_idle_timeout_on_send => boolean(), |
| 71 |
sendfile => boolean(), |
| 72 |
settings_timeout => timeout(), |
| 73 |
shutdown_timeout => timeout(), |
| 74 |
stream_handlers => [module()], |
| 75 |
stream_window_data_threshold => 0..16#7fffffff, |
| 76 |
stream_window_margin_size => 0..16#7fffffff, |
| 77 |
stream_window_update_threshold => 0..16#7fffffff, |
| 78 |
tracer_callback => cowboy_tracer_h:tracer_callback(), |
| 79 |
tracer_flags => [atom()], |
| 80 |
tracer_match_specs => cowboy_tracer_h:tracer_match_specs(), |
| 81 |
%% Open ended because configured stream handlers might add options. |
| 82 |
_ => _ |
| 83 |
}. |
| 84 |
-export_type([opts/0]). |
| 85 |
|
| 86 |
-record(stream, { |
| 87 |
%% Whether the stream is currently in a special state. |
| 88 |
%% |
| 89 |
%% - The running state is the normal state of a stream. |
| 90 |
%% - The relaying state is used by extended CONNECT protocols to |
| 91 |
%% use a 'relay' data_delivery method. |
| 92 |
%% - The stopping state indicates the stream used the 'stop' command. |
| 93 |
status = running :: running | {relaying, non_neg_integer(), pid()} | stopping, |
| 94 |
|
| 95 |
%% Flow requested for this stream. |
| 96 |
flow = 0 :: non_neg_integer(), |
| 97 |
|
| 98 |
%% Stream state. |
| 99 |
state :: {module, any()} |
| 100 |
}). |
| 101 |
|
| 102 |
%% We don't want to reset the idle timeout too often, |
| 103 |
%% so we don't reset it on data. Instead we reset the |
| 104 |
%% number of ticks we have observed. We divide the |
| 105 |
%% timeout value by a value and that value becomes |
| 106 |
%% the number of ticks at which point we can drop |
| 107 |
%% the connection. This value is the number of ticks. |
| 108 |
-define(IDLE_TIMEOUT_TICKS, 10). |
| 109 |
|
| 110 |
-record(state, { |
| 111 |
parent = undefined :: pid(), |
| 112 |
ref :: ranch:ref(), |
| 113 |
socket = undefined :: inet:socket(), |
| 114 |
transport :: module(), |
| 115 |
proxy_header :: undefined | ranch_proxy_header:proxy_info(), |
| 116 |
opts = #{} :: opts(), |
| 117 |
|
| 118 |
%% Timer for idle_timeout; also used for goaway timers. |
| 119 |
timer = undefined :: undefined | reference(), |
| 120 |
idle_timeout_num = 0 :: 0..?IDLE_TIMEOUT_TICKS, |
| 121 |
|
| 122 |
%% Remote address and port for the connection. |
| 123 |
peer = undefined :: {inet:ip_address(), inet:port_number()}, |
| 124 |
|
| 125 |
%% Local address and port for the connection. |
| 126 |
sock = undefined :: {inet:ip_address(), inet:port_number()}, |
| 127 |
|
| 128 |
%% Client certificate (TLS only). |
| 129 |
cert :: undefined | binary(), |
| 130 |
|
| 131 |
%% HTTP/2 state machine. |
| 132 |
http2_status :: sequence | settings | upgrade | connected | closing_initiated | closing, |
| 133 |
http2_machine :: cow_http2_machine:http2_machine(), |
| 134 |
|
| 135 |
%% HTTP/2 frame rate flood protection. |
| 136 |
frame_rate_num :: undefined | pos_integer(), |
| 137 |
frame_rate_time :: undefined | integer(), |
| 138 |
|
| 139 |
%% HTTP/2 reset stream flood protection. |
| 140 |
reset_rate_num :: undefined | pos_integer(), |
| 141 |
reset_rate_time :: undefined | integer(), |
| 142 |
|
| 143 |
%% HTTP/2 rapid reset attack protection. |
| 144 |
cancel_rate_num :: undefined | pos_integer(), |
| 145 |
cancel_rate_time :: undefined | integer(), |
| 146 |
|
| 147 |
%% Flow requested for all streams. |
| 148 |
flow = 0 :: non_neg_integer(), |
| 149 |
|
| 150 |
%% Dynamic buffer moving average and current buffer size. |
| 151 |
dynamic_buffer_size :: pos_integer() | false, |
| 152 |
dynamic_buffer_moving_average :: float(), |
| 153 |
|
| 154 |
%% Currently active HTTP/2 streams. Streams may be initiated either |
| 155 |
%% by the client or by the server through PUSH_PROMISE frames. |
| 156 |
streams = #{} :: #{cow_http2:streamid() => #stream{}}, |
| 157 |
|
| 158 |
%% Streams can spawn zero or more children which are then managed |
| 159 |
%% by this module if operating as a supervisor. |
| 160 |
children = cowboy_children:init() :: cowboy_children:children() |
| 161 |
}). |
| 162 |
|
| 163 |
-spec init(pid(), ranch:ref(), inet:socket(), module(), |
| 164 |
ranch_proxy_header:proxy_info() | undefined, cowboy:opts()) -> no_return(). |
| 165 |
|
| 166 |
init(Parent, Ref, Socket, Transport, ProxyHeader, Opts) -> |
| 167 |
{ok, Peer} = maybe_socket_error(undefined, Transport:peername(Socket), |
| 168 |
'A socket error occurred when retrieving the peer name.'), |
| 169 |
{ok, Sock} = maybe_socket_error(undefined, Transport:sockname(Socket), |
| 170 |
'A socket error occurred when retrieving the sock name.'), |
| 171 |
CertResult = case Transport:name() of |
| 172 |
ssl -> |
| 173 |
case ssl:peercert(Socket) of |
| 174 |
{error, no_peercert} -> |
| 175 |
{ok, undefined}; |
| 176 |
Cert0 -> |
| 177 |
Cert0 |
| 178 |
end; |
| 179 |
_ -> |
| 180 |
{ok, undefined} |
| 181 |
end, |
| 182 |
{ok, Cert} = maybe_socket_error(undefined, CertResult, |
| 183 |
'A socket error occurred when retrieving the client TLS certificate.'), |
| 184 |
init(Parent, Ref, Socket, Transport, ProxyHeader, Opts, Peer, Sock, Cert, <<>>). |
| 185 |
|
| 186 |
-spec init(pid(), ranch:ref(), inet:socket(), module(), |
| 187 |
ranch_proxy_header:proxy_info() | undefined, cowboy:opts(), |
| 188 |
{inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()}, |
| 189 |
binary() | undefined, binary()) -> no_return(). |
| 190 |
|
| 191 |
init(Parent, Ref, Socket, Transport, ProxyHeader, Opts, Peer, Sock, Cert, Buffer) -> |
| 192 |
DynamicBuffer = init_dynamic_buffer_size(Opts), |
| 193 |
{ok, Preface, HTTP2Machine} = cow_http2_machine:init(server, Opts), |
| 194 |
%% Send the preface before doing all the init in case we get a socket error. |
| 195 |
ok = maybe_socket_error(undefined, Transport:send(Socket, Preface)), |
| 196 |
State = set_idle_timeout(init_rate_limiting(#state{parent=Parent, ref=Ref, socket=Socket, |
| 197 |
transport=Transport, proxy_header=ProxyHeader, |
| 198 |
opts=Opts, peer=Peer, sock=Sock, cert=Cert, |
| 199 |
dynamic_buffer_size=DynamicBuffer, |
| 200 |
dynamic_buffer_moving_average=maps:get(dynamic_buffer_initial_average, Opts, 0.0), |
| 201 |
http2_status=sequence, http2_machine=HTTP2Machine}), 0), |
| 202 |
safe_setopts_active(State), |
| 203 |
case Buffer of |
| 204 |
<<>> -> before_loop(State, Buffer); |
| 205 |
_ -> parse(State, Buffer) |
| 206 |
end. |
| 207 |
|
| 208 |
init_rate_limiting(State0) -> |
| 209 |
CurrentTime = erlang:monotonic_time(millisecond), |
| 210 |
State1 = init_frame_rate_limiting(State0, CurrentTime), |
| 211 |
State2 = init_reset_rate_limiting(State1, CurrentTime), |
| 212 |
init_cancel_rate_limiting(State2, CurrentTime). |
| 213 |
|
| 214 |
init_frame_rate_limiting(State=#state{opts=Opts}, CurrentTime) -> |
| 215 |
{FrameRateNum, FrameRatePeriod} = maps:get(max_received_frame_rate, Opts, {10000, 10000}), |
| 216 |
State#state{ |
| 217 |
frame_rate_num=FrameRateNum, frame_rate_time=add_period(CurrentTime, FrameRatePeriod) |
| 218 |
}. |
| 219 |
|
| 220 |
init_reset_rate_limiting(State=#state{opts=Opts}, CurrentTime) -> |
| 221 |
{ResetRateNum, ResetRatePeriod} = maps:get(max_reset_stream_rate, Opts, {10, 10000}), |
| 222 |
State#state{ |
| 223 |
reset_rate_num=ResetRateNum, reset_rate_time=add_period(CurrentTime, ResetRatePeriod) |
| 224 |
}. |
| 225 |
|
| 226 |
init_cancel_rate_limiting(State=#state{opts=Opts}, CurrentTime) -> |
| 227 |
{CancelRateNum, CancelRatePeriod} = maps:get(max_cancel_stream_rate, Opts, {500, 10000}), |
| 228 |
State#state{ |
| 229 |
cancel_rate_num=CancelRateNum, cancel_rate_time=add_period(CurrentTime, CancelRatePeriod) |
| 230 |
}. |
| 231 |
|
| 232 |
add_period(_, infinity) -> infinity; |
| 233 |
add_period(Time, Period) -> Time + Period. |
| 234 |
|
| 235 |
%% @todo Add an argument for the request body. |
| 236 |
-spec init(pid(), ranch:ref(), inet:socket(), module(), |
| 237 |
ranch_proxy_header:proxy_info() | undefined, cowboy:opts(), |
| 238 |
{inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()}, |
| 239 |
binary() | undefined, binary(), map() | undefined, cowboy_req:req()) -> no_return(). |
| 240 |
|
| 241 |
init(Parent, Ref, Socket, Transport, ProxyHeader, Opts, Peer, Sock, Cert, Buffer, |
| 242 |
_Settings, Req=#{method := Method}) -> |
| 243 |
DynamicBuffer = init_dynamic_buffer_size(Opts), |
| 244 |
{ok, Preface, HTTP2Machine0} = cow_http2_machine:init(server, Opts), |
| 245 |
{ok, StreamID, HTTP2Machine} |
| 246 |
= cow_http2_machine:init_upgrade_stream(Method, HTTP2Machine0), |
| 247 |
State0 = #state{parent=Parent, ref=Ref, socket=Socket, |
| 248 |
transport=Transport, proxy_header=ProxyHeader, |
| 249 |
opts=Opts, peer=Peer, sock=Sock, cert=Cert, |
| 250 |
dynamic_buffer_size=DynamicBuffer, |
| 251 |
dynamic_buffer_moving_average=maps:get(dynamic_buffer_initial_average, Opts, 0.0), |
| 252 |
http2_status=upgrade, http2_machine=HTTP2Machine}, |
| 253 |
State1 = headers_frame(State0#state{ |
| 254 |
http2_machine=HTTP2Machine}, StreamID, Req), |
| 255 |
%% We assume that the upgrade will be applied. A stream handler |
| 256 |
%% must not prevent the normal operations of the server. |
| 257 |
State2 = info(State1, 1, {switch_protocol, #{ |
| 258 |
<<"connection">> => <<"Upgrade">>, |
| 259 |
<<"upgrade">> => <<"h2c">> |
| 260 |
}, ?MODULE, undefined}), %% @todo undefined or #{}? |
| 261 |
State = set_idle_timeout(init_rate_limiting(State2#state{http2_status=sequence}), 0), |
| 262 |
%% In the case of HTTP/1.1 Upgrade we cannot send the Preface |
| 263 |
%% until we send the 101 response. |
| 264 |
ok = maybe_socket_error(State, Transport:send(Socket, Preface)), |
| 265 |
safe_setopts_active(State), |
| 266 |
case Buffer of |
| 267 |
<<>> -> before_loop(State, Buffer); |
| 268 |
_ -> parse(State, Buffer) |
| 269 |
end. |
| 270 |
|
| 271 |
-include("cowboy_dynamic_buffer.hrl"). |
| 272 |
|
| 273 |
%% Because HTTP/2 has flow control and Cowboy has other rate limiting |
| 274 |
%% mechanisms implemented, a very large active_n value should be fine, |
| 275 |
%% as long as the stream handlers do their work in a timely manner. |
| 276 |
%% However large active_n values reduce the impact of dynamic_buffer. |
| 277 |
setopts_active(#state{socket=Socket, transport=Transport, opts=Opts}) -> |
| 278 |
N = maps:get(active_n, Opts, 1), |
| 279 |
Transport:setopts(Socket, [{active, N}]). |
| 280 |
|
| 281 |
safe_setopts_active(State) -> |
| 282 |
ok = maybe_socket_error(State, setopts_active(State)). |
| 283 |
|
| 284 |
before_loop(State=#state{opts=#{hibernate := true}}, Buffer) -> |
| 285 |
proc_lib:hibernate(?MODULE, loop, [State, Buffer]); |
| 286 |
before_loop(State, Buffer) -> |
| 287 |
loop(State, Buffer). |
| 288 |
|
| 289 |
-spec loop(#state{}, binary()) -> no_return(). |
| 290 |
|
| 291 |
loop(State=#state{parent=Parent, socket=Socket, transport=Transport, |
| 292 |
opts=Opts, timer=TimerRef, children=Children}, Buffer) -> |
| 293 |
Messages = Transport:messages(), |
| 294 |
InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000), |
| 295 |
receive |
| 296 |
%% Socket messages. |
| 297 |
{OK, Socket, Data} when OK =:= element(1, Messages) -> |
| 298 |
State1 = maybe_resize_buffer(State, Data), |
| 299 |
parse(State1#state{idle_timeout_num=0}, << Buffer/binary, Data/binary >>); |
| 300 |
{Closed, Socket} when Closed =:= element(2, Messages) -> |
| 301 |
Reason = case State#state.http2_status of |
| 302 |
closing -> {stop, closed, 'The client is going away.'}; |
| 303 |
_ -> {socket_error, closed, 'The socket has been closed.'} |
| 304 |
end, |
| 305 |
terminate(State, Reason); |
| 306 |
{Error, Socket, Reason} when Error =:= element(3, Messages) -> |
| 307 |
terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'}); |
| 308 |
{Passive, Socket} when Passive =:= element(4, Messages); |
| 309 |
%% Hardcoded for compatibility with Ranch 1.x. |
| 310 |
Passive =:= tcp_passive; Passive =:= ssl_passive -> |
| 311 |
safe_setopts_active(State), |
| 312 |
before_loop(State, Buffer); |
| 313 |
%% System messages. |
| 314 |
{'EXIT', Parent, shutdown} -> |
| 315 |
Reason = {stop, {exit, shutdown}, 'Parent process requested shutdown.'}, |
| 316 |
before_loop(initiate_closing(State, Reason), Buffer); |
| 317 |
{'EXIT', Parent, Reason} -> |
| 318 |
terminate(State, {stop, {exit, Reason}, 'Parent process terminated.'}); |
| 319 |
{system, From, Request} -> |
| 320 |
sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer}); |
| 321 |
%% Timeouts. |
| 322 |
{timeout, TimerRef, idle_timeout} -> |
| 323 |
tick_idle_timeout(State, Buffer); |
| 324 |
{timeout, Ref, {shutdown, Pid}} -> |
| 325 |
cowboy_children:shutdown_timeout(Children, Ref, Pid), |
| 326 |
before_loop(State, Buffer); |
| 327 |
{timeout, TRef, {cow_http2_machine, Name}} -> |
| 328 |
before_loop(timeout(State, Name, TRef), Buffer); |
| 329 |
{timeout, TimerRef, {goaway_initial_timeout, Reason}} -> |
| 330 |
before_loop(closing(State, Reason), Buffer); |
| 331 |
{timeout, TimerRef, {goaway_complete_timeout, Reason}} -> |
| 332 |
terminate(State, {stop, stop_reason(Reason), |
| 333 |
'Graceful shutdown timed out.'}); |
| 334 |
%% Messages pertaining to a stream. |
| 335 |
{{Pid, StreamID}, Msg} when Pid =:= self() -> |
| 336 |
before_loop(info(State, StreamID, Msg), Buffer); |
| 337 |
{'$cowboy_relay_command', {Pid, StreamID}, RelayCommand} when Pid =:= self() -> |
| 338 |
before_loop(relay_command(State, StreamID, RelayCommand), Buffer); |
| 339 |
%% Exit signal from children. |
| 340 |
Msg = {'EXIT', Pid, _} -> |
| 341 |
before_loop(down(State, Pid, Msg), Buffer); |
| 342 |
%% Calls from supervisor module. |
| 343 |
{'$gen_call', From, Call} -> |
| 344 |
cowboy_children:handle_supervisor_call(Call, From, Children, ?MODULE), |
| 345 |
before_loop(State, Buffer); |
| 346 |
Msg -> |
| 347 |
cowboy:log(warning, "Received stray message ~p.", [Msg], Opts), |
| 348 |
before_loop(State, Buffer) |
| 349 |
after InactivityTimeout -> |
| 350 |
terminate(State, {internal_error, timeout, 'No message or data received before timeout.'}) |
| 351 |
end. |
| 352 |
|
| 353 |
tick_idle_timeout(State=#state{idle_timeout_num=?IDLE_TIMEOUT_TICKS}, _) -> |
| 354 |
terminate(State, {stop, timeout, |
| 355 |
'Connection idle longer than configuration allows.'}); |
| 356 |
tick_idle_timeout(State=#state{idle_timeout_num=TimeoutNum}, Buffer) -> |
| 357 |
before_loop(set_idle_timeout(State, TimeoutNum + 1), Buffer). |
| 358 |
|
| 359 |
set_idle_timeout(State=#state{http2_status=Status, timer=TimerRef}, _) |
| 360 |
when Status =:= closing_initiated orelse Status =:= closing, |
| 361 |
TimerRef =/= undefined -> |
| 362 |
State; |
| 363 |
set_idle_timeout(State=#state{opts=Opts}, TimeoutNum) -> |
| 364 |
case maps:get(idle_timeout, Opts, 60000) of |
| 365 |
infinity -> |
| 366 |
State#state{timer=undefined}; |
| 367 |
Timeout -> |
| 368 |
set_timeout(State#state{idle_timeout_num=TimeoutNum}, |
| 369 |
Timeout div ?IDLE_TIMEOUT_TICKS, idle_timeout) |
| 370 |
end. |
| 371 |
|
| 372 |
set_timeout(State=#state{timer=TimerRef0}, Timeout, Message) -> |
| 373 |
ok = case TimerRef0 of |
| 374 |
undefined -> ok; |
| 375 |
_ -> erlang:cancel_timer(TimerRef0, [{async, true}, {info, false}]) |
| 376 |
end, |
| 377 |
TimerRef = case Timeout of |
| 378 |
infinity -> undefined; |
| 379 |
Timeout -> erlang:start_timer(Timeout, self(), Message) |
| 380 |
end, |
| 381 |
State#state{timer=TimerRef}. |
| 382 |
|
| 383 |
maybe_reset_idle_timeout(State=#state{opts=Opts}) -> |
| 384 |
case maps:get(reset_idle_timeout_on_send, Opts, false) of |
| 385 |
true -> |
| 386 |
State#state{idle_timeout_num=0}; |
| 387 |
false -> |
| 388 |
State |
| 389 |
end. |
| 390 |
|
| 391 |
%% HTTP/2 protocol parsing. |
| 392 |
|
| 393 |
parse(State=#state{http2_status=sequence}, Data) -> |
| 394 |
case cow_http2:parse_sequence(Data) of |
| 395 |
{ok, Rest} -> |
| 396 |
parse(State#state{http2_status=settings}, Rest); |
| 397 |
more -> |
| 398 |
before_loop(State, Data); |
| 399 |
Error = {connection_error, _, _} -> |
| 400 |
terminate(State, Error) |
| 401 |
end; |
| 402 |
parse(State=#state{http2_status=Status, http2_machine=HTTP2Machine, streams=Streams}, Data) -> |
| 403 |
MaxFrameSize = cow_http2_machine:get_local_setting(max_frame_size, HTTP2Machine), |
| 404 |
case cow_http2:parse(Data, MaxFrameSize) of |
| 405 |
{ok, Frame, Rest} -> |
| 406 |
parse(frame_rate(State, Frame), Rest); |
| 407 |
{ignore, Rest} -> |
| 408 |
parse(frame_rate(State, ignore), Rest); |
| 409 |
{stream_error, StreamID, Reason, Human, Rest} -> |
| 410 |
parse(reset_stream(State, StreamID, {stream_error, Reason, Human}), Rest); |
| 411 |
Error = {connection_error, _, _} -> |
| 412 |
terminate(State, Error); |
| 413 |
%% Terminate the connection if we are closing and all streams have completed. |
| 414 |
more when Status =:= closing, Streams =:= #{} -> |
| 415 |
terminate(State, {stop, normal, 'The connection is going away.'}); |
| 416 |
more -> |
| 417 |
before_loop(State, Data) |
| 418 |
end. |
| 419 |
|
| 420 |
%% Frame rate flood protection. |
| 421 |
|
| 422 |
frame_rate(State0=#state{frame_rate_num=Num0, frame_rate_time=Time}, Frame) -> |
| 423 |
{Result, State} = case Num0 - 1 of |
| 424 |
0 -> |
| 425 |
CurrentTime = erlang:monotonic_time(millisecond), |
| 426 |
if |
| 427 |
CurrentTime < Time -> |
| 428 |
{error, State0}; |
| 429 |
true -> |
| 430 |
%% When the option has a period of infinity we cannot reach this clause. |
| 431 |
{ok, init_frame_rate_limiting(State0, CurrentTime)} |
| 432 |
end; |
| 433 |
Num -> |
| 434 |
{ok, State0#state{frame_rate_num=Num}} |
| 435 |
end, |
| 436 |
case {Result, Frame} of |
| 437 |
{ok, ignore} -> ignored_frame(State); |
| 438 |
{ok, _} -> frame(State, Frame); |
| 439 |
{error, _} -> terminate(State, {connection_error, enhance_your_calm, |
| 440 |
'Frame rate larger than configuration allows. Flood? (CVE-2019-9512, CVE-2019-9515, CVE-2019-9518)'}) |
| 441 |
end. |
| 442 |
|
| 443 |
%% Frames received. |
| 444 |
|
| 445 |
%% We do nothing when receiving a lingering DATA frame. |
| 446 |
%% We already removed the stream flow from the connection |
| 447 |
%% flow and are therefore already accounting for the window |
| 448 |
%% being reduced by these frames. |
| 449 |
frame(State=#state{http2_machine=HTTP2Machine0}, Frame) -> |
| 450 |
case cow_http2_machine:frame(Frame, HTTP2Machine0) of |
| 451 |
{ok, HTTP2Machine} -> |
| 452 |
maybe_ack(State#state{http2_machine=HTTP2Machine}, Frame); |
| 453 |
{ok, {data, StreamID, IsFin, Data}, HTTP2Machine} -> |
| 454 |
data_frame(State#state{http2_machine=HTTP2Machine}, StreamID, IsFin, Data); |
| 455 |
{ok, {headers, StreamID, IsFin, Headers, PseudoHeaders, BodyLen}, HTTP2Machine} -> |
| 456 |
headers_frame(State#state{http2_machine=HTTP2Machine}, |
| 457 |
StreamID, IsFin, Headers, PseudoHeaders, BodyLen); |
| 458 |
{ok, {trailers, _StreamID, _Trailers}, HTTP2Machine} -> |
| 459 |
%% @todo Propagate trailers. |
| 460 |
State#state{http2_machine=HTTP2Machine}; |
| 461 |
{ok, {rst_stream, StreamID, Reason}, HTTP2Machine} -> |
| 462 |
rst_stream_frame(State#state{http2_machine=HTTP2Machine}, StreamID, Reason); |
| 463 |
{ok, GoAway={goaway, _, _, _}, HTTP2Machine} -> |
| 464 |
goaway(State#state{http2_machine=HTTP2Machine}, GoAway); |
| 465 |
{send, SendData, HTTP2Machine} -> |
| 466 |
%% We may need to send an alarm for each of the streams sending data. |
| 467 |
State1 = lists:foldl( |
| 468 |
fun({StreamID, _, _}, S) -> maybe_send_data_alarm(S, HTTP2Machine0, StreamID) end, |
| 469 |
send_data(maybe_ack(State#state{http2_machine=HTTP2Machine}, Frame), SendData, []), |
| 470 |
SendData), |
| 471 |
maybe_reset_idle_timeout(State1); |
| 472 |
{error, {stream_error, StreamID, Reason, Human}, HTTP2Machine} -> |
| 473 |
reset_stream(State#state{http2_machine=HTTP2Machine}, |
| 474 |
StreamID, {stream_error, Reason, Human}); |
| 475 |
{error, Error={connection_error, _, _}, HTTP2Machine} -> |
| 476 |
terminate(State#state{http2_machine=HTTP2Machine}, Error) |
| 477 |
end. |
| 478 |
|
| 479 |
%% We use this opportunity to mark the HTTP/2 status as connected |
| 480 |
%% if we were still waiting for a SETTINGS frame. |
| 481 |
maybe_ack(State=#state{http2_status=settings}, Frame) -> |
| 482 |
maybe_ack(State#state{http2_status=connected}, Frame); |
| 483 |
%% We do not reset the idle timeout on send here because we are |
| 484 |
%% sending data as a consequence of receiving data, which means |
| 485 |
%% we already resetted the idle timeout. |
| 486 |
maybe_ack(State=#state{socket=Socket, transport=Transport}, Frame) -> |
| 487 |
case Frame of |
| 488 |
{settings, _} -> |
| 489 |
ok = maybe_socket_error(State, Transport:send(Socket, cow_http2:settings_ack())); |
| 490 |
{ping, Opaque} -> |
| 491 |
ok = maybe_socket_error(State, Transport:send(Socket, cow_http2:ping_ack(Opaque))); |
| 492 |
_ -> ok |
| 493 |
end, |
| 494 |
State. |
| 495 |
|
| 496 |
data_frame(State0=#state{opts=Opts, flow=Flow0, streams=Streams}, StreamID, IsFin, Data) -> |
| 497 |
case Streams of |
| 498 |
#{StreamID := Stream=#stream{status=running, flow=StreamFlow, state=StreamState0}} -> |
| 499 |
try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of |
| 500 |
{Commands, StreamState} -> |
| 501 |
%% Remove the amount of data received from the flow. |
| 502 |
%% We may receive more data than we requested. We ensure |
| 503 |
%% that the flow value doesn't go lower than 0. |
| 504 |
Size = byte_size(Data), |
| 505 |
Flow = max(0, Flow0 - Size), |
| 506 |
%% We would normally update the window when changing the flow |
| 507 |
%% value. But because we are running commands, which themselves |
| 508 |
%% may update the window, and we want to avoid updating the |
| 509 |
%% window twice in a row, we first run the commands and then |
| 510 |
%% only update the window a flow command was executed. We know |
| 511 |
%% that it was because the flow value changed in the state. |
| 512 |
State1 = State0#state{flow=Flow, |
| 513 |
streams=Streams#{StreamID => Stream#stream{ |
| 514 |
flow=max(0, StreamFlow - Size), state=StreamState}}}, |
| 515 |
State = commands(State1, StreamID, Commands), |
| 516 |
case State of |
| 517 |
%% No flow command was executed. We must update the window |
| 518 |
%% because we changed the flow value earlier. |
| 519 |
#state{flow=Flow} -> |
| 520 |
update_window(State, StreamID); |
| 521 |
%% Otherwise the window was updated already. |
| 522 |
_ -> |
| 523 |
State |
| 524 |
end |
| 525 |
catch Class:Exception:Stacktrace -> |
| 526 |
cowboy:log(cowboy_stream:make_error_log(data, |
| 527 |
[StreamID, IsFin, Data, StreamState0], |
| 528 |
Class, Exception, Stacktrace), Opts), |
| 529 |
reset_stream(State0, StreamID, {internal_error, {Class, Exception}, |
| 530 |
'Unhandled exception in cowboy_stream:data/4.'}) |
| 531 |
end; |
| 532 |
%% Stream handlers are not used for the data when relaying. |
| 533 |
#{StreamID := #stream{status={relaying, _, RelayPid}}} -> |
| 534 |
RelayPid ! {'$cowboy_relay_data', {self(), StreamID}, IsFin, Data}, |
| 535 |
%% We keep a steady flow using the configured flow value. |
| 536 |
%% Because we do not change the 'flow' value the update_window/2 |
| 537 |
%% function will always maintain this value (of course with |
| 538 |
%% thresholds applying). |
| 539 |
update_window(State0, StreamID); |
| 540 |
%% We ignore DATA frames for streams that are stopping. |
| 541 |
#{} -> |
| 542 |
State0 |
| 543 |
end. |
| 544 |
|
| 545 |
headers_frame(State, StreamID, IsFin, Headers, |
| 546 |
PseudoHeaders=#{method := <<"CONNECT">>}, _) |
| 547 |
when map_size(PseudoHeaders) =:= 2 -> |
| 548 |
early_error(State, StreamID, IsFin, Headers, PseudoHeaders, 501, |
| 549 |
'The CONNECT method is currently not implemented. (RFC7231 4.3.6)'); |
| 550 |
headers_frame(State, StreamID, IsFin, Headers, |
| 551 |
PseudoHeaders=#{method := <<"TRACE">>}, _) -> |
| 552 |
early_error(State, StreamID, IsFin, Headers, PseudoHeaders, 501, |
| 553 |
'The TRACE method is currently not implemented. (RFC7231 4.3.8)'); |
| 554 |
headers_frame(State, StreamID, IsFin, Headers, PseudoHeaders=#{authority := Authority}, BodyLen) -> |
| 555 |
case lists:keyfind(<<"host">>, 1, Headers) of |
| 556 |
false -> |
| 557 |
headers_frame_parse_host(State, StreamID, IsFin, Headers, PseudoHeaders, BodyLen, Authority); |
| 558 |
{_, Authority} -> |
| 559 |
headers_frame_parse_host(State, StreamID, IsFin, Headers, PseudoHeaders, BodyLen, Authority); |
| 560 |
{_, _} -> |
| 561 |
reset_stream(State, StreamID, {stream_error, protocol_error, |
| 562 |
'The host header is different than the :authority pseudo-header. (RFC9113 8.3.1)'}) |
| 563 |
end; |
| 564 |
headers_frame(State, StreamID, IsFin, Headers, PseudoHeaders, BodyLen) -> |
| 565 |
case lists:keyfind(<<"host">>, 1, Headers) of |
| 566 |
{_, Authority} -> |
| 567 |
headers_frame_parse_host(State, StreamID, IsFin, Headers, PseudoHeaders, BodyLen, Authority); |
| 568 |
_ -> |
| 569 |
reset_stream(State, StreamID, {stream_error, protocol_error, |
| 570 |
'Requests translated from HTTP/1.1 must include a host header. (RFC7540 8.1.2.3, RFC7230 5.4)'}) |
| 571 |
end. |
| 572 |
|
| 573 |
headers_frame_parse_host(State=#state{opts=Opts}, StreamID, IsFin, Headers, PseudoHeaders, BodyLen, Authority) -> |
| 574 |
case byte_size(Authority) > maps:get(max_authority_length, Opts, 255) of |
| 575 |
true -> |
| 576 |
reset_stream(State, StreamID, {stream_error, protocol_error, |
| 577 |
'The request authority is longer than configuration allows. (RFC7540 8.1.2.3)'}); |
| 578 |
false -> |
| 579 |
headers_frame_parse_host1(State, StreamID, IsFin, Headers, PseudoHeaders, BodyLen, Authority) |
| 580 |
end. |
| 581 |
|
| 582 |
headers_frame_parse_host1(State=#state{ref=Ref, peer=Peer, sock=Sock, cert=Cert, proxy_header=ProxyHeader}, |
| 583 |
StreamID, IsFin, Headers, PseudoHeaders=#{method := Method, scheme := Scheme, path := PathWithQs}, |
| 584 |
BodyLen, Authority) -> |
| 585 |
try cow_http_hd:parse_host(Authority) of |
| 586 |
{Host, Port0} -> |
| 587 |
Port = ensure_port(Scheme, Port0), |
| 588 |
case cow_http:parse_fullpath(PathWithQs) of |
| 589 |
{<<>>, _} -> |
| 590 |
reset_stream(State, StreamID, {stream_error, protocol_error, |
| 591 |
'The path component must not be empty. (RFC7540 8.1.2.3)'}); |
| 592 |
{Path, Qs} -> |
| 593 |
Req0 = #{ |
| 594 |
ref => Ref, |
| 595 |
pid => self(), |
| 596 |
streamid => StreamID, |
| 597 |
peer => Peer, |
| 598 |
sock => Sock, |
| 599 |
cert => Cert, |
| 600 |
method => Method, |
| 601 |
scheme => Scheme, |
| 602 |
host => Host, |
| 603 |
port => Port, |
| 604 |
path => Path, |
| 605 |
qs => Qs, |
| 606 |
version => 'HTTP/2', |
| 607 |
headers => headers_to_map(Headers, #{}), |
| 608 |
has_body => IsFin =:= nofin, |
| 609 |
body_length => BodyLen |
| 610 |
}, |
| 611 |
%% We add the PROXY header information if any. |
| 612 |
Req1 = case ProxyHeader of |
| 613 |
undefined -> Req0; |
| 614 |
_ -> Req0#{proxy_header => ProxyHeader} |
| 615 |
end, |
| 616 |
%% We add the protocol information for extended CONNECTs. |
| 617 |
Req = case PseudoHeaders of |
| 618 |
#{protocol := Protocol} -> Req1#{protocol => Protocol}; |
| 619 |
_ -> Req1 |
| 620 |
end, |
| 621 |
headers_frame(State, StreamID, Req) |
| 622 |
end |
| 623 |
catch _:_ -> |
| 624 |
reset_stream(State, StreamID, {stream_error, protocol_error, |
| 625 |
'The :authority pseudo-header is invalid. (RFC7540 8.1.2.3)'}) |
| 626 |
end. |
| 627 |
|
| 628 |
ensure_port(<<"http">>, undefined) -> 80; |
| 629 |
ensure_port(<<"https">>, undefined) -> 443; |
| 630 |
ensure_port(_, Port) -> Port. |
| 631 |
|
| 632 |
%% This function is necessary to properly handle duplicate headers |
| 633 |
%% and the special-case cookie header. |
| 634 |
headers_to_map([], Acc) -> |
| 635 |
Acc; |
| 636 |
headers_to_map([{Name, Value}|Tail], Acc0) -> |
| 637 |
Acc = case Acc0 of |
| 638 |
%% The cookie header does not use proper HTTP header lists. |
| 639 |
#{Name := Value0} when Name =:= <<"cookie">> -> |
| 640 |
Acc0#{Name => << Value0/binary, "; ", Value/binary >>}; |
| 641 |
#{Name := Value0} -> |
| 642 |
Acc0#{Name => << Value0/binary, ", ", Value/binary >>}; |
| 643 |
_ -> |
| 644 |
Acc0#{Name => Value} |
| 645 |
end, |
| 646 |
headers_to_map(Tail, Acc). |
| 647 |
|
| 648 |
headers_frame(State=#state{opts=Opts, streams=Streams}, StreamID, Req) -> |
| 649 |
try cowboy_stream:init(StreamID, Req, Opts) of |
| 650 |
{Commands, StreamState} -> |
| 651 |
commands(State#state{ |
| 652 |
streams=Streams#{StreamID => #stream{state=StreamState}}}, |
| 653 |
StreamID, Commands) |
| 654 |
catch Class:Exception:Stacktrace -> |
| 655 |
cowboy:log(cowboy_stream:make_error_log(init, |
| 656 |
[StreamID, Req, Opts], |
| 657 |
Class, Exception, Stacktrace), Opts), |
| 658 |
reset_stream(State, StreamID, {internal_error, {Class, Exception}, |
| 659 |
'Unhandled exception in cowboy_stream:init/3.'}) |
| 660 |
end. |
| 661 |
|
| 662 |
early_error(State0=#state{ref=Ref, opts=Opts, peer=Peer}, |
| 663 |
StreamID, _IsFin, Headers, #{method := Method}, |
| 664 |
StatusCode0, HumanReadable) -> |
| 665 |
%% We automatically terminate the stream but it is not an error |
| 666 |
%% per se (at least not in the first implementation). |
| 667 |
Reason = {stream_error, no_error, HumanReadable}, |
| 668 |
%% The partial Req is minimal for now. We only have one case |
| 669 |
%% where it can be called (when a method is completely disabled). |
| 670 |
%% @todo Fill in the other elements. |
| 671 |
PartialReq = #{ |
| 672 |
ref => Ref, |
| 673 |
peer => Peer, |
| 674 |
method => Method, |
| 675 |
headers => headers_to_map(Headers, #{}) |
| 676 |
}, |
| 677 |
RespHeaders0 = #{<<"content-length">> => <<"0">>}, |
| 678 |
Resp = {response, StatusCode0, RespHeaders0, <<>>}, |
| 679 |
try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts) of |
| 680 |
{response, StatusCode, RespHeaders, RespBody} -> |
| 681 |
case maybe_invalid_response_headers(RespHeaders, State0) of |
| 682 |
error_terminate -> |
| 683 |
reset_stream(State0, StreamID, |
| 684 |
{internal_error, invalid_response_header, |
| 685 |
'An invalid response header was detected.'}); |
| 686 |
ok -> |
| 687 |
send_response(State0, StreamID, StatusCode, RespHeaders, RespBody) |
| 688 |
end |
| 689 |
catch Class:Exception:Stacktrace -> |
| 690 |
cowboy:log(cowboy_stream:make_error_log(early_error, |
| 691 |
[StreamID, Reason, PartialReq, Resp, Opts], |
| 692 |
Class, Exception, Stacktrace), Opts), |
| 693 |
%% We still need to send an error response, so send what we initially |
| 694 |
%% wanted to send. It's better than nothing. |
| 695 |
send_headers(State0, StreamID, fin, StatusCode0, RespHeaders0) |
| 696 |
end. |
| 697 |
|
| 698 |
rst_stream_frame(State=#state{streams=Streams0, children=Children0}, StreamID, Reason) -> |
| 699 |
case maps:take(StreamID, Streams0) of |
| 700 |
{#stream{state=StreamState}, Streams} -> |
| 701 |
terminate_stream_handler(State, StreamID, Reason, StreamState), |
| 702 |
Children = cowboy_children:shutdown(Children0, StreamID), |
| 703 |
cancel_rate_limit(State#state{streams=Streams, children=Children}); |
| 704 |
error -> |
| 705 |
State |
| 706 |
end. |
| 707 |
|
| 708 |
cancel_rate_limit(State0=#state{cancel_rate_num=Num0, cancel_rate_time=Time}) -> |
| 709 |
case Num0 - 1 of |
| 710 |
0 -> |
| 711 |
CurrentTime = erlang:monotonic_time(millisecond), |
| 712 |
if |
| 713 |
CurrentTime < Time -> |
| 714 |
terminate(State0, {connection_error, enhance_your_calm, |
| 715 |
'Stream cancel rate larger than configuration allows. Flood? (CVE-2023-44487)'}); |
| 716 |
true -> |
| 717 |
%% When the option has a period of infinity we cannot reach this clause. |
| 718 |
init_cancel_rate_limiting(State0, CurrentTime) |
| 719 |
end; |
| 720 |
Num -> |
| 721 |
State0#state{cancel_rate_num=Num} |
| 722 |
end. |
| 723 |
|
| 724 |
ignored_frame(State=#state{http2_machine=HTTP2Machine0}) -> |
| 725 |
case cow_http2_machine:ignored_frame(HTTP2Machine0) of |
| 726 |
{ok, HTTP2Machine} -> |
| 727 |
State#state{http2_machine=HTTP2Machine}; |
| 728 |
{error, Error={connection_error, _, _}, HTTP2Machine} -> |
| 729 |
terminate(State#state{http2_machine=HTTP2Machine}, Error) |
| 730 |
end. |
| 731 |
|
| 732 |
%% HTTP/2 timeouts. |
| 733 |
|
| 734 |
timeout(State=#state{http2_machine=HTTP2Machine0}, Name, TRef) -> |
| 735 |
case cow_http2_machine:timeout(Name, TRef, HTTP2Machine0) of |
| 736 |
{ok, HTTP2Machine} -> |
| 737 |
State#state{http2_machine=HTTP2Machine}; |
| 738 |
{error, Error={connection_error, _, _}, HTTP2Machine} -> |
| 739 |
terminate(State#state{http2_machine=HTTP2Machine}, Error) |
| 740 |
end. |
| 741 |
|
| 742 |
%% Erlang messages. |
| 743 |
|
| 744 |
down(State0=#state{opts=Opts, children=Children0}, Pid, Msg) -> |
| 745 |
State = case cowboy_children:down(Children0, Pid) of |
| 746 |
%% The stream was terminated already. |
| 747 |
{ok, undefined, Children} -> |
| 748 |
State0#state{children=Children}; |
| 749 |
%% The stream is still running. |
| 750 |
{ok, StreamID, Children} -> |
| 751 |
info(State0#state{children=Children}, StreamID, Msg); |
| 752 |
%% The process was unknown. |
| 753 |
error -> |
| 754 |
cowboy:log(warning, "Received EXIT signal ~p for unknown process ~p.~n", |
| 755 |
[Msg, Pid], Opts), |
| 756 |
State0 |
| 757 |
end, |
| 758 |
if |
| 759 |
State#state.http2_status =:= closing, State#state.streams =:= #{} -> |
| 760 |
terminate(State, {stop, normal, 'The connection is going away.'}); |
| 761 |
true -> |
| 762 |
State |
| 763 |
end. |
| 764 |
|
| 765 |
info(State=#state{opts=Opts, http2_machine=HTTP2Machine, streams=Streams}, StreamID, Msg) -> |
| 766 |
case Streams of |
| 767 |
#{StreamID := Stream=#stream{state=StreamState0}} -> |
| 768 |
try cowboy_stream:info(StreamID, Msg, StreamState0) of |
| 769 |
{Commands, StreamState} -> |
| 770 |
commands(State#state{streams=Streams#{StreamID => Stream#stream{state=StreamState}}}, |
| 771 |
StreamID, Commands) |
| 772 |
catch Class:Exception:Stacktrace -> |
| 773 |
cowboy:log(cowboy_stream:make_error_log(info, |
| 774 |
[StreamID, Msg, StreamState0], |
| 775 |
Class, Exception, Stacktrace), Opts), |
| 776 |
reset_stream(State, StreamID, {internal_error, {Class, Exception}, |
| 777 |
'Unhandled exception in cowboy_stream:info/3.'}) |
| 778 |
end; |
| 779 |
_ -> |
| 780 |
case cow_http2_machine:is_lingering_stream(StreamID, HTTP2Machine) of |
| 781 |
true -> |
| 782 |
ok; |
| 783 |
false -> |
| 784 |
cowboy:log(warning, "Received message ~p for unknown stream ~p.", |
| 785 |
[Msg, StreamID], Opts) |
| 786 |
end, |
| 787 |
State |
| 788 |
end. |
| 789 |
|
| 790 |
%% Stream handler commands. |
| 791 |
%% |
| 792 |
%% @todo Kill the stream if it tries to send a response, headers, |
| 793 |
%% data or push promise when the stream is closed or half-closed. |
| 794 |
|
| 795 |
commands(State, _, []) -> |
| 796 |
State; |
| 797 |
%% Error responses are sent only if a response wasn't sent already. |
| 798 |
commands(State=#state{http2_machine=HTTP2Machine}, StreamID, |
| 799 |
[{error_response, StatusCode, Headers, Body}|Tail]) -> |
| 800 |
case cow_http2_machine:get_stream_local_state(StreamID, HTTP2Machine) of |
| 801 |
{ok, idle, _} -> |
| 802 |
commands(State, StreamID, [{response, StatusCode, Headers, Body}|Tail]); |
| 803 |
_ -> |
| 804 |
commands(State, StreamID, Tail) |
| 805 |
end; |
| 806 |
%% Send an informational response. |
| 807 |
commands(State0, StreamID, [{inform, StatusCode, Headers}|Tail]) -> |
| 808 |
case maybe_invalid_response_headers(Headers, State0) of |
| 809 |
error_terminate -> |
| 810 |
reset_stream(State0, StreamID, |
| 811 |
{internal_error, invalid_response_header, |
| 812 |
'An invalid response header was detected in an informational response.'}); |
| 813 |
ok -> |
| 814 |
State1 = send_headers(State0, StreamID, idle, StatusCode, Headers), |
| 815 |
State = maybe_reset_idle_timeout(State1), |
| 816 |
commands(State, StreamID, Tail) |
| 817 |
end; |
| 818 |
%% Send response headers. |
| 819 |
commands(State0, StreamID, [{response, StatusCode, Headers, Body}|Tail]) -> |
| 820 |
case maybe_invalid_response_headers(Headers, State0) of |
| 821 |
error_terminate -> |
| 822 |
reset_stream(State0, StreamID, |
| 823 |
{internal_error, invalid_response_header, |
| 824 |
'An invalid response header was detected.'}); |
| 825 |
ok -> |
| 826 |
State1 = send_response(State0, StreamID, StatusCode, Headers, Body), |
| 827 |
State = maybe_reset_idle_timeout(State1), |
| 828 |
commands(State, StreamID, Tail) |
| 829 |
end; |
| 830 |
%% Send response headers. |
| 831 |
commands(State0, StreamID, [{headers, StatusCode, Headers}|Tail]) -> |
| 832 |
case maybe_invalid_response_headers(Headers, State0) of |
| 833 |
error_terminate -> |
| 834 |
reset_stream(State0, StreamID, |
| 835 |
{internal_error, invalid_response_header, |
| 836 |
'An invalid response header was detected.'}); |
| 837 |
ok -> |
| 838 |
State1 = send_headers(State0, StreamID, nofin, StatusCode, Headers), |
| 839 |
State = maybe_reset_idle_timeout(State1), |
| 840 |
commands(State, StreamID, Tail) |
| 841 |
end; |
| 842 |
%% Send a response body chunk. |
| 843 |
commands(State0, StreamID, [{data, IsFin, Data}|Tail]) -> |
| 844 |
State = case maybe_send_data(State0, StreamID, IsFin, Data, []) of |
| 845 |
{data_sent, State1} -> |
| 846 |
maybe_reset_idle_timeout(State1); |
| 847 |
{no_data_sent, State1} -> |
| 848 |
State1 |
| 849 |
end, |
| 850 |
commands(State, StreamID, Tail); |
| 851 |
%% Send trailers. |
| 852 |
commands(State0, StreamID, [{trailers, Trailers}|Tail]) -> |
| 853 |
case maybe_invalid_response_headers(Trailers, State0) of |
| 854 |
error_terminate -> |
| 855 |
reset_stream(State0, StreamID, |
| 856 |
{internal_error, invalid_response_header, |
| 857 |
'An invalid response header was detected in trailers.'}); |
| 858 |
ok -> |
| 859 |
State = case maybe_send_data(State0, StreamID, fin, |
| 860 |
{trailers, maps:to_list(Trailers)}, []) of |
| 861 |
{data_sent, State1} -> |
| 862 |
maybe_reset_idle_timeout(State1); |
| 863 |
{no_data_sent, State1} -> |
| 864 |
State1 |
| 865 |
end, |
| 866 |
commands(State, StreamID, Tail) |
| 867 |
end; |
| 868 |
%% Send a push promise. |
| 869 |
%% |
| 870 |
%% @todo Responses sent as a result of a push_promise request |
| 871 |
%% must not send push_promise frames themselves. |
| 872 |
%% |
| 873 |
%% @todo We should not send push_promise frames when we are |
| 874 |
%% in the closing http2_status. |
| 875 |
commands(State0=#state{socket=Socket, transport=Transport, http2_machine=HTTP2Machine0}, |
| 876 |
StreamID, [{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) -> |
| 877 |
case maybe_invalid_response_headers(Headers0, State0) of |
| 878 |
error_terminate -> |
| 879 |
reset_stream(State0, StreamID, |
| 880 |
{internal_error, invalid_response_header, |
| 881 |
'An invalid response header was detected in push promise.'}); |
| 882 |
ok -> |
| 883 |
Authority = case {Scheme, Port} of |
| 884 |
{<<"http">>, 80} -> Host; |
| 885 |
{<<"https">>, 443} -> Host; |
| 886 |
_ -> iolist_to_binary([Host, $:, integer_to_binary(Port)]) |
| 887 |
end, |
| 888 |
PathWithQs = iolist_to_binary(case Qs of |
| 889 |
<<>> -> Path; |
| 890 |
_ -> [Path, $?, Qs] |
| 891 |
end), |
| 892 |
PseudoHeaders = #{ |
| 893 |
method => Method, |
| 894 |
scheme => Scheme, |
| 895 |
authority => Authority, |
| 896 |
path => PathWithQs |
| 897 |
}, |
| 898 |
%% We need to make sure the header value is binary before we can |
| 899 |
%% create the Req object, as it expects them to be flat. |
| 900 |
Headers = maps:to_list(maps:map(fun(_, V) -> iolist_to_binary(V) end, Headers0)), |
| 901 |
State = case cow_http2_machine:prepare_push_promise(StreamID, HTTP2Machine0, |
| 902 |
PseudoHeaders, Headers) of |
| 903 |
{ok, PromisedStreamID, HeaderBlock, HTTP2Machine} -> |
| 904 |
State1 = State0#state{http2_machine=HTTP2Machine}, |
| 905 |
ok = maybe_socket_error(State1, Transport:send(Socket, |
| 906 |
cow_http2:push_promise(StreamID, PromisedStreamID, HeaderBlock))), |
| 907 |
State2 = maybe_reset_idle_timeout(State1), |
| 908 |
headers_frame(State2, PromisedStreamID, fin, Headers, PseudoHeaders, 0); |
| 909 |
{error, no_push} -> |
| 910 |
State0 |
| 911 |
end, |
| 912 |
commands(State, StreamID, Tail) |
| 913 |
end; |
| 914 |
%% Read the request body. |
| 915 |
commands(State0=#state{flow=Flow, streams=Streams}, StreamID, [{flow, Size}|Tail]) -> |
| 916 |
#{StreamID := Stream=#stream{flow=StreamFlow}} = Streams, |
| 917 |
State = update_window(State0#state{flow=Flow + Size, |
| 918 |
streams=Streams#{StreamID => Stream#stream{flow=StreamFlow + Size}}}, |
| 919 |
StreamID), |
| 920 |
commands(State, StreamID, Tail); |
| 921 |
%% Supervise a child process. |
| 922 |
commands(State=#state{children=Children}, StreamID, [{spawn, Pid, Shutdown}|Tail]) -> |
| 923 |
commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)}, |
| 924 |
StreamID, Tail); |
| 925 |
%% Error handling. |
| 926 |
commands(State, StreamID, [Error = {internal_error, _, _}|_Tail]) -> |
| 927 |
%% @todo Do we want to run the commands after an internal_error? |
| 928 |
%% @todo Do we even allow commands after? |
| 929 |
%% @todo Only reset when the stream still exists. |
| 930 |
reset_stream(State, StreamID, Error); |
| 931 |
%% Upgrade to HTTP/2. This is triggered by cowboy_http2 itself. |
| 932 |
%% |
| 933 |
%% We do not need to reset the idle timeout on send because it |
| 934 |
%% hasn't been set yet. This is called from init/12. |
| 935 |
commands(State=#state{socket=Socket, transport=Transport, http2_status=upgrade}, |
| 936 |
StreamID, [{switch_protocol, Headers, ?MODULE, _}|Tail]) -> |
| 937 |
case maybe_invalid_response_headers(Headers, State) of |
| 938 |
error_terminate -> |
| 939 |
reset_stream(State, StreamID, |
| 940 |
{internal_error, invalid_response_header, |
| 941 |
'An invalid response header was detected when upgrading to HTTP/2.'}); |
| 942 |
ok -> |
| 943 |
%% @todo This 101 response needs to be passed through stream handlers. |
| 944 |
ok = maybe_socket_error(State, Transport:send(Socket, |
| 945 |
cow_http:response(101, 'HTTP/1.1', maps:to_list(Headers)))), |
| 946 |
commands(State, StreamID, Tail) |
| 947 |
end; |
| 948 |
%% Use a different protocol within the stream (CONNECT :protocol). |
| 949 |
%% @todo Make sure we error out when the feature is disabled. |
| 950 |
%% There are two data_delivery: stream_handlers and relay. |
| 951 |
%% The former just has the data go through stream handlers |
| 952 |
%% like normal requests. The latter relays data directly. |
| 953 |
%% |
| 954 |
%% @todo When relaying there might be some data that is |
| 955 |
%% in stream handlers and that need to be received, |
| 956 |
%% depending on whether the protocol sends data |
| 957 |
%% before processing the response. |
| 958 |
commands(State0=#state{flow=Flow, streams=Streams}, StreamID, |
| 959 |
[{switch_protocol, Headers, _Mod, ModState=#{data_delivery := relay}}|Tail]) -> |
| 960 |
case maybe_invalid_response_headers(Headers, State0) of |
| 961 |
error_terminate -> |
| 962 |
reset_stream(State0, StreamID, |
| 963 |
{internal_error, invalid_response_header, |
| 964 |
'An invalid response header was detected when switching protocols.'}); |
| 965 |
ok -> |
| 966 |
State1 = info(State0, StreamID, {headers, 200, Headers}), |
| 967 |
#{StreamID := Stream} = Streams, |
| 968 |
#{data_delivery_pid := RelayPid} = ModState, |
| 969 |
%% WINDOW_UPDATE frames updating the window will be sent after |
| 970 |
%% the first DATA frame has been received. |
| 971 |
RelayFlow = maps:get(data_delivery_flow, ModState, 131072), |
| 972 |
State = State1#state{flow=Flow + RelayFlow, streams=Streams#{StreamID => Stream#stream{ |
| 973 |
status={relaying, RelayFlow, RelayPid}, |
| 974 |
flow=RelayFlow}}}, |
| 975 |
commands(State, StreamID, Tail) |
| 976 |
end; |
| 977 |
commands(State0, StreamID, [{switch_protocol, Headers, _Mod, _ModState}|Tail]) -> |
| 978 |
case maybe_invalid_response_headers(Headers, State0) of |
| 979 |
error_terminate -> |
| 980 |
reset_stream(State0, StreamID, |
| 981 |
{internal_error, invalid_response_header, |
| 982 |
'An invalid response header was detected when switching protocols.'}); |
| 983 |
ok -> |
| 984 |
State = info(State0, StreamID, {headers, 200, Headers}), |
| 985 |
commands(State, StreamID, Tail) |
| 986 |
end; |
| 987 |
%% Set options dynamically. |
| 988 |
commands(State, StreamID, [{set_options, _Opts}|Tail]) -> |
| 989 |
commands(State, StreamID, Tail); |
| 990 |
commands(State, StreamID, [stop|_Tail]) -> |
| 991 |
%% @todo Do we want to run the commands after a stop? |
| 992 |
%% @todo Do we even allow commands after? |
| 993 |
stop_stream(State, StreamID); |
| 994 |
%% Log event. |
| 995 |
commands(State=#state{opts=Opts}, StreamID, [Log={log, _, _, _}|Tail]) -> |
| 996 |
cowboy:log(Log, Opts), |
| 997 |
commands(State, StreamID, Tail). |
| 998 |
|
| 999 |
%% Relay data delivery commands. |
| 1000 |
|
| 1001 |
relay_command(State, StreamID, DataCmd = {data, _, _}) -> |
| 1002 |
commands(State, StreamID, [DataCmd]); |
| 1003 |
%% When going active mode again we set the RelayFlow again |
| 1004 |
%% and update the window if necessary. |
| 1005 |
relay_command(State=#state{flow=Flow, streams=Streams}, StreamID, active) -> |
| 1006 |
#{StreamID := Stream} = Streams, |
| 1007 |
#stream{status={relaying, RelayFlow, _}} = Stream, |
| 1008 |
update_window(State#state{flow=Flow + RelayFlow, |
| 1009 |
streams=Streams#{StreamID => Stream#stream{flow=RelayFlow}}}, |
| 1010 |
StreamID); |
| 1011 |
%% When going passive mode we don't update the window |
| 1012 |
%% since we have not incremented it. |
| 1013 |
relay_command(State=#state{flow=Flow, streams=Streams}, StreamID, passive) -> |
| 1014 |
#{StreamID := Stream} = Streams, |
| 1015 |
#stream{flow=StreamFlow} = Stream, |
| 1016 |
State#state{flow=Flow - StreamFlow, |
| 1017 |
streams=Streams#{StreamID => Stream#stream{flow=0}}}. |
| 1018 |
|
| 1019 |
%% Tentatively update the window after the flow was updated. |
| 1020 |
|
| 1021 |
update_window(State0=#state{socket=Socket, transport=Transport, |
| 1022 |
http2_machine=HTTP2Machine0, flow=Flow, streams=Streams}, StreamID) -> |
| 1023 |
{Data1, HTTP2Machine2} = case cow_http2_machine:ensure_window(Flow, HTTP2Machine0) of |
| 1024 |
ok -> {<<>>, HTTP2Machine0}; |
| 1025 |
{ok, Increment1, HTTP2Machine1} -> {cow_http2:window_update(Increment1), HTTP2Machine1} |
| 1026 |
end, |
| 1027 |
{Data2, HTTP2Machine} = case Streams of |
| 1028 |
#{StreamID := #stream{flow=StreamFlow}} -> |
| 1029 |
case cow_http2_machine:ensure_window(StreamID, StreamFlow, HTTP2Machine2) of |
| 1030 |
ok -> |
| 1031 |
{<<>>, HTTP2Machine2}; |
| 1032 |
{ok, Increment2, HTTP2Machine3} -> |
| 1033 |
{cow_http2:window_update(StreamID, Increment2), HTTP2Machine3} |
| 1034 |
end; |
| 1035 |
_ -> |
| 1036 |
%% Don't update the stream's window if it stopped. |
| 1037 |
{<<>>, HTTP2Machine2} |
| 1038 |
end, |
| 1039 |
State = State0#state{http2_machine=HTTP2Machine}, |
| 1040 |
case {Data1, Data2} of |
| 1041 |
{<<>>, <<>>} -> |
| 1042 |
State; |
| 1043 |
_ -> |
| 1044 |
ok = maybe_socket_error(State, Transport:send(Socket, [Data1, Data2])), |
| 1045 |
maybe_reset_idle_timeout(State) |
| 1046 |
end. |
| 1047 |
|
| 1048 |
%% Send the response, trailers or data. |
| 1049 |
|
| 1050 |
send_response(State0=#state{http2_machine=HTTP2Machine0}, StreamID, StatusCode, Headers, Body) -> |
| 1051 |
Size = case Body of |
| 1052 |
{sendfile, _, Bytes, _} -> Bytes; |
| 1053 |
_ -> iolist_size(Body) |
| 1054 |
end, |
| 1055 |
case Size of |
| 1056 |
0 -> |
| 1057 |
State = send_headers(State0, StreamID, fin, StatusCode, Headers), |
| 1058 |
maybe_terminate_stream(State, StreamID, fin); |
| 1059 |
_ -> |
| 1060 |
%% @todo Add a test for HEAD to make sure we don't send the body when |
| 1061 |
%% returning {response...} from a stream handler (or {headers...} then {data...}). |
| 1062 |
{ok, _IsFin, HeaderBlock, HTTP2Machine} |
| 1063 |
= cow_http2_machine:prepare_headers(StreamID, HTTP2Machine0, nofin, |
| 1064 |
#{status => cow_http:status_to_integer(StatusCode)}, |
| 1065 |
headers_to_list(Headers)), |
| 1066 |
{_, State} = maybe_send_data(State0#state{http2_machine=HTTP2Machine}, |
| 1067 |
StreamID, fin, Body, [cow_http2:headers(StreamID, nofin, HeaderBlock)]), |
| 1068 |
State |
| 1069 |
end. |
| 1070 |
|
| 1071 |
send_headers(State0=#state{socket=Socket, transport=Transport, |
| 1072 |
http2_machine=HTTP2Machine0}, StreamID, IsFin0, StatusCode, Headers) -> |
| 1073 |
{ok, IsFin, HeaderBlock, HTTP2Machine} |
| 1074 |
= cow_http2_machine:prepare_headers(StreamID, HTTP2Machine0, IsFin0, |
| 1075 |
#{status => cow_http:status_to_integer(StatusCode)}, |
| 1076 |
headers_to_list(Headers)), |
| 1077 |
State = State0#state{http2_machine=HTTP2Machine}, |
| 1078 |
ok = maybe_socket_error(State, Transport:send(Socket, |
| 1079 |
cow_http2:headers(StreamID, IsFin, HeaderBlock))), |
| 1080 |
State. |
| 1081 |
|
| 1082 |
%% The set-cookie header is special; we can only send one cookie per header. |
| 1083 |
headers_to_list(Headers0=#{<<"set-cookie">> := SetCookies}) -> |
| 1084 |
Headers = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)), |
| 1085 |
Headers ++ [{<<"set-cookie">>, Value} || Value <- SetCookies]; |
| 1086 |
headers_to_list(Headers) -> |
| 1087 |
maps:to_list(Headers). |
| 1088 |
|
| 1089 |
maybe_invalid_response_headers(Headers, #state{opts=Opts}) -> |
| 1090 |
cowboy_http:validate_response_headers(Headers, Opts). |
| 1091 |
|
| 1092 |
maybe_send_data(State0=#state{socket=Socket, transport=Transport, |
| 1093 |
http2_machine=HTTP2Machine0}, StreamID, IsFin, Data0, Prefix) -> |
| 1094 |
Data = case is_tuple(Data0) of |
| 1095 |
false -> {data, Data0}; |
| 1096 |
true -> Data0 |
| 1097 |
end, |
| 1098 |
case cow_http2_machine:send_or_queue_data(StreamID, HTTP2Machine0, IsFin, Data) of |
| 1099 |
{ok, HTTP2Machine} -> |
| 1100 |
State1 = State0#state{http2_machine=HTTP2Machine}, |
| 1101 |
%% If we have prefix data (like a HEADERS frame) we need to send it |
| 1102 |
%% even if we do not send any DATA frames. |
| 1103 |
WasDataSent = case Prefix of |
| 1104 |
[] -> |
| 1105 |
no_data_sent; |
| 1106 |
_ -> |
| 1107 |
ok = maybe_socket_error(State1, Transport:send(Socket, Prefix)), |
| 1108 |
data_sent |
| 1109 |
end, |
| 1110 |
State = maybe_send_data_alarm(State1, HTTP2Machine0, StreamID), |
| 1111 |
{WasDataSent, State}; |
| 1112 |
{send, SendData, HTTP2Machine} -> |
| 1113 |
State = #state{http2_status=Status, streams=Streams} |
| 1114 |
= send_data(State0#state{http2_machine=HTTP2Machine}, SendData, Prefix), |
| 1115 |
%% Terminate the connection if we are closing and all streams have completed. |
| 1116 |
if |
| 1117 |
Status =:= closing, Streams =:= #{} -> |
| 1118 |
terminate(State, {stop, normal, 'The connection is going away.'}); |
| 1119 |
true -> |
| 1120 |
{data_sent, maybe_send_data_alarm(State, HTTP2Machine0, StreamID)} |
| 1121 |
end |
| 1122 |
end. |
| 1123 |
|
| 1124 |
send_data(State0=#state{socket=Socket, transport=Transport, opts=Opts}, SendData, Prefix) -> |
| 1125 |
{Acc, State} = prepare_data(State0, SendData, [], Prefix), |
| 1126 |
_ = [case Data of |
| 1127 |
{sendfile, Offset, Bytes, Path} -> |
| 1128 |
%% When sendfile is disabled we explicitly use the fallback. |
| 1129 |
{ok, _} = maybe_socket_error(State, |
| 1130 |
case maps:get(sendfile, Opts, true) of |
| 1131 |
true -> Transport:sendfile(Socket, Path, Offset, Bytes); |
| 1132 |
false -> ranch_transport:sendfile(Transport, Socket, Path, Offset, Bytes, []) |
| 1133 |
end |
| 1134 |
), |
| 1135 |
ok; |
| 1136 |
_ -> |
| 1137 |
ok = maybe_socket_error(State, Transport:send(Socket, Data)) |
| 1138 |
end || Data <- Acc], |
| 1139 |
send_data_terminate(State, SendData). |
| 1140 |
|
| 1141 |
send_data_terminate(State, []) -> |
| 1142 |
State; |
| 1143 |
send_data_terminate(State0, [{StreamID, IsFin, _}|Tail]) -> |
| 1144 |
State = maybe_terminate_stream(State0, StreamID, IsFin), |
| 1145 |
send_data_terminate(State, Tail). |
| 1146 |
|
| 1147 |
prepare_data(State, [], Acc, []) -> |
| 1148 |
{lists:reverse(Acc), State}; |
| 1149 |
prepare_data(State, [], Acc, Buffer) -> |
| 1150 |
{lists:reverse([lists:reverse(Buffer)|Acc]), State}; |
| 1151 |
prepare_data(State0, [{StreamID, IsFin, SendData}|Tail], Acc0, Buffer0) -> |
| 1152 |
{Acc, Buffer, State} = prepare_data(State0, StreamID, IsFin, SendData, Acc0, Buffer0), |
| 1153 |
prepare_data(State, Tail, Acc, Buffer). |
| 1154 |
|
| 1155 |
prepare_data(State, _, _, [], Acc, Buffer) -> |
| 1156 |
{Acc, Buffer, State}; |
| 1157 |
prepare_data(State0, StreamID, IsFin, [FrameData|Tail], Acc, Buffer) -> |
| 1158 |
FrameIsFin = case Tail of |
| 1159 |
[] -> IsFin; |
| 1160 |
_ -> nofin |
| 1161 |
end, |
| 1162 |
case prepare_data_frame(State0, StreamID, FrameIsFin, FrameData) of |
| 1163 |
{{MoreData, Sendfile}, State} when is_tuple(Sendfile) -> |
| 1164 |
case Buffer of |
| 1165 |
[] -> |
| 1166 |
prepare_data(State, StreamID, IsFin, Tail, |
| 1167 |
[Sendfile, MoreData|Acc], []); |
| 1168 |
_ -> |
| 1169 |
prepare_data(State, StreamID, IsFin, Tail, |
| 1170 |
[Sendfile, lists:reverse([MoreData|Buffer])|Acc], []) |
| 1171 |
end; |
| 1172 |
{MoreData, State} -> |
| 1173 |
prepare_data(State, StreamID, IsFin, Tail, |
| 1174 |
Acc, [MoreData|Buffer]) |
| 1175 |
end. |
| 1176 |
|
| 1177 |
prepare_data_frame(State, StreamID, IsFin, {data, Data}) -> |
| 1178 |
{cow_http2:data(StreamID, IsFin, Data), |
| 1179 |
State}; |
| 1180 |
prepare_data_frame(State, StreamID, IsFin, Sendfile={sendfile, _, Bytes, _}) -> |
| 1181 |
{{cow_http2:data_header(StreamID, IsFin, Bytes), Sendfile}, |
| 1182 |
State}; |
| 1183 |
%% The stream is terminated in cow_http2_machine:prepare_trailers. |
| 1184 |
prepare_data_frame(State=#state{http2_machine=HTTP2Machine0}, |
| 1185 |
StreamID, nofin, {trailers, Trailers}) -> |
| 1186 |
{ok, HeaderBlock, HTTP2Machine} |
| 1187 |
= cow_http2_machine:prepare_trailers(StreamID, HTTP2Machine0, Trailers), |
| 1188 |
{cow_http2:headers(StreamID, fin, HeaderBlock), |
| 1189 |
State#state{http2_machine=HTTP2Machine}}. |
| 1190 |
|
| 1191 |
%% After we have sent or queued data we may need to set or clear an alarm. |
| 1192 |
%% We do this by comparing the HTTP2Machine buffer state before/after for |
| 1193 |
%% the relevant streams. |
| 1194 |
maybe_send_data_alarm(State=#state{opts=Opts, http2_machine=HTTP2Machine}, HTTP2Machine0, StreamID) -> |
| 1195 |
ConnBufferSizeBefore = cow_http2_machine:get_connection_local_buffer_size(HTTP2Machine0), |
| 1196 |
ConnBufferSizeAfter = cow_http2_machine:get_connection_local_buffer_size(HTTP2Machine), |
| 1197 |
{ok, StreamBufferSizeBefore} = cow_http2_machine:get_stream_local_buffer_size(StreamID, HTTP2Machine0), |
| 1198 |
%% When the stream ends up closed after it finished sending data, |
| 1199 |
%% we do not want to trigger an alarm. We act as if the buffer |
| 1200 |
%% size did not change. |
| 1201 |
StreamBufferSizeAfter = case cow_http2_machine:get_stream_local_buffer_size(StreamID, HTTP2Machine) of |
| 1202 |
{ok, BSA} -> BSA; |
| 1203 |
{error, closed} -> StreamBufferSizeBefore |
| 1204 |
end, |
| 1205 |
MaxConnBufferSize = maps:get(max_connection_buffer_size, Opts, 16000000), |
| 1206 |
MaxStreamBufferSize = maps:get(max_stream_buffer_size, Opts, 8000000), |
| 1207 |
%% I do not want to document these internal events yet. I am not yet |
| 1208 |
%% convinced it should be {alarm, Name, on|off} and not {internal_event, E} |
| 1209 |
%% or something else entirely. Though alarms are probably right. |
| 1210 |
if |
| 1211 |
ConnBufferSizeBefore >= MaxConnBufferSize, ConnBufferSizeAfter < MaxConnBufferSize -> |
| 1212 |
connection_alarm(State, connection_buffer_full, off); |
| 1213 |
ConnBufferSizeBefore < MaxConnBufferSize, ConnBufferSizeAfter >= MaxConnBufferSize -> |
| 1214 |
connection_alarm(State, connection_buffer_full, on); |
| 1215 |
StreamBufferSizeBefore >= MaxStreamBufferSize, StreamBufferSizeAfter < MaxStreamBufferSize -> |
| 1216 |
stream_alarm(State, StreamID, stream_buffer_full, off); |
| 1217 |
StreamBufferSizeBefore < MaxStreamBufferSize, StreamBufferSizeAfter >= MaxStreamBufferSize -> |
| 1218 |
stream_alarm(State, StreamID, stream_buffer_full, on); |
| 1219 |
true -> |
| 1220 |
State |
| 1221 |
end. |
| 1222 |
|
| 1223 |
connection_alarm(State0=#state{streams=Streams}, Name, Value) -> |
| 1224 |
lists:foldl(fun(StreamID, State) -> |
| 1225 |
stream_alarm(State, StreamID, Name, Value) |
| 1226 |
end, State0, maps:keys(Streams)). |
| 1227 |
|
| 1228 |
stream_alarm(State, StreamID, Name, Value) -> |
| 1229 |
info(State, StreamID, {alarm, Name, Value}). |
| 1230 |
|
| 1231 |
%% Terminate a stream or the connection. |
| 1232 |
|
| 1233 |
%% We may have to cancel streams even if we receive multiple |
| 1234 |
%% GOAWAY frames as the LastStreamID value may be lower than |
| 1235 |
%% the one previously received. |
| 1236 |
%% |
| 1237 |
%% We do not reset the idle timeout on send here. We already |
| 1238 |
%% disabled it if we initiated shutdown; and we already reset |
| 1239 |
%% it if the client sent a GOAWAY frame. |
| 1240 |
goaway(State0=#state{socket=Socket, transport=Transport, http2_machine=HTTP2Machine0, |
| 1241 |
http2_status=Status, streams=Streams0}, {goaway, LastStreamID, Reason, _}) |
| 1242 |
when Status =:= connected; Status =:= closing_initiated; Status =:= closing -> |
| 1243 |
Streams = goaway_streams(State0, maps:to_list(Streams0), LastStreamID, |
| 1244 |
{stop, {goaway, Reason}, 'The connection is going away.'}, []), |
| 1245 |
State1 = State0#state{streams=maps:from_list(Streams)}, |
| 1246 |
if |
| 1247 |
Status =:= connected; Status =:= closing_initiated -> |
| 1248 |
{OurLastStreamID, HTTP2Machine} = |
| 1249 |
cow_http2_machine:set_last_streamid(HTTP2Machine0), |
| 1250 |
State = State1#state{http2_status=closing, http2_machine=HTTP2Machine}, |
| 1251 |
ok = maybe_socket_error(State, Transport:send(Socket, |
| 1252 |
cow_http2:goaway(OurLastStreamID, no_error, <<>>))), |
| 1253 |
State; |
| 1254 |
true -> |
| 1255 |
State1 |
| 1256 |
end; |
| 1257 |
%% We terminate the connection immediately if it hasn't fully been initialized. |
| 1258 |
goaway(State, {goaway, _, Reason, _}) -> |
| 1259 |
terminate(State, {stop, {goaway, Reason}, 'The connection is going away.'}). |
| 1260 |
|
| 1261 |
%% Cancel client-initiated streams that are above LastStreamID. |
| 1262 |
goaway_streams(_, [], _, _, Acc) -> |
| 1263 |
Acc; |
| 1264 |
goaway_streams(State, [{StreamID, #stream{state=StreamState}}|Tail], LastStreamID, Reason, Acc) |
| 1265 |
when StreamID > LastStreamID, (StreamID rem 2) =:= 0 -> |
| 1266 |
terminate_stream_handler(State, StreamID, Reason, StreamState), |
| 1267 |
goaway_streams(State, Tail, LastStreamID, Reason, Acc); |
| 1268 |
goaway_streams(State, [Stream|Tail], LastStreamID, Reason, Acc) -> |
| 1269 |
goaway_streams(State, Tail, LastStreamID, Reason, [Stream|Acc]). |
| 1270 |
|
| 1271 |
%% A server that is attempting to gracefully shut down a connection SHOULD send |
| 1272 |
%% an initial GOAWAY frame with the last stream identifier set to 2^31-1 and a |
| 1273 |
%% NO_ERROR code. This signals to the client that a shutdown is imminent and |
| 1274 |
%% that initiating further requests is prohibited. After allowing time for any |
| 1275 |
%% in-flight stream creation (at least one round-trip time), the server can send |
| 1276 |
%% another GOAWAY frame with an updated last stream identifier. This ensures |
| 1277 |
%% that a connection can be cleanly shut down without losing requests. |
| 1278 |
|
| 1279 |
-spec initiate_closing(#state{}, _) -> #state{}. |
| 1280 |
|
| 1281 |
initiate_closing(State=#state{http2_status=connected, socket=Socket, |
| 1282 |
transport=Transport, opts=Opts}, Reason) -> |
| 1283 |
ok = maybe_socket_error(State, Transport:send(Socket, |
| 1284 |
cow_http2:goaway(16#7fffffff, no_error, <<>>))), |
| 1285 |
Timeout = maps:get(goaway_initial_timeout, Opts, 1000), |
| 1286 |
Message = {goaway_initial_timeout, Reason}, |
| 1287 |
set_timeout(State#state{http2_status=closing_initiated}, Timeout, Message); |
| 1288 |
initiate_closing(State=#state{http2_status=Status}, _Reason) |
| 1289 |
when Status =:= closing_initiated; Status =:= closing -> |
| 1290 |
%% This happens if sys:terminate/2,3 is called twice or if the supervisor |
| 1291 |
%% tells us to shutdown after sys:terminate/2,3 is called or vice versa. |
| 1292 |
State; |
| 1293 |
initiate_closing(State, Reason) -> |
| 1294 |
terminate(State, {stop, stop_reason(Reason), 'The connection is going away.'}). |
| 1295 |
|
| 1296 |
%% Switch to 'closing' state and stop accepting new streams. |
| 1297 |
|
| 1298 |
-spec closing(#state{}, Reason :: term()) -> #state{}. |
| 1299 |
|
| 1300 |
closing(State=#state{streams=Streams}, Reason) when Streams =:= #{} -> |
| 1301 |
terminate(State, Reason); |
| 1302 |
closing(State0=#state{http2_status=closing_initiated, |
| 1303 |
http2_machine=HTTP2Machine0, socket=Socket, transport=Transport}, |
| 1304 |
Reason) -> |
| 1305 |
%% Stop accepting new streams. |
| 1306 |
{LastStreamID, HTTP2Machine} = |
| 1307 |
cow_http2_machine:set_last_streamid(HTTP2Machine0), |
| 1308 |
State = State0#state{http2_status=closing, http2_machine=HTTP2Machine}, |
| 1309 |
ok = maybe_socket_error(State, Transport:send(Socket, |
| 1310 |
cow_http2:goaway(LastStreamID, no_error, <<>>))), |
| 1311 |
closing(State, Reason); |
| 1312 |
closing(State=#state{http2_status=closing, opts=Opts}, Reason) -> |
| 1313 |
%% If client sent GOAWAY, we may already be in 'closing' but without the |
| 1314 |
%% goaway complete timeout set. |
| 1315 |
Timeout = maps:get(goaway_complete_timeout, Opts, 3000), |
| 1316 |
Message = {goaway_complete_timeout, Reason}, |
| 1317 |
set_timeout(State, Timeout, Message). |
| 1318 |
|
| 1319 |
stop_reason({stop, Reason, _}) -> Reason; |
| 1320 |
stop_reason(Reason) -> Reason. |
| 1321 |
|
| 1322 |
%% Function copied from cowboy_http. |
| 1323 |
maybe_socket_error(State, {error, closed}) -> |
| 1324 |
terminate(State, {socket_error, closed, 'The socket has been closed.'}); |
| 1325 |
maybe_socket_error(State, Reason) -> |
| 1326 |
maybe_socket_error(State, Reason, 'An error has occurred on the socket.'). |
| 1327 |
|
| 1328 |
maybe_socket_error(_, Result = ok, _) -> |
| 1329 |
Result; |
| 1330 |
maybe_socket_error(_, Result = {ok, _}, _) -> |
| 1331 |
Result; |
| 1332 |
maybe_socket_error(State, {error, Reason}, Human) -> |
| 1333 |
terminate(State, {socket_error, Reason, Human}). |
| 1334 |
|
| 1335 |
-spec terminate(#state{} | undefined, _) -> no_return(). |
| 1336 |
|
| 1337 |
terminate(undefined, Reason) -> |
| 1338 |
exit({shutdown, Reason}); |
| 1339 |
terminate(State=#state{socket=Socket, transport=Transport, http2_status=Status, |
| 1340 |
http2_machine=HTTP2Machine, streams=Streams, children=Children}, Reason) |
| 1341 |
when Status =:= connected; Status =:= closing_initiated; Status =:= closing -> |
| 1342 |
%% @todo We might want to optionally send the Reason value |
| 1343 |
%% as debug data in the GOAWAY frame here. Perhaps more. |
| 1344 |
if |
| 1345 |
Status =:= connected; Status =:= closing_initiated -> |
| 1346 |
%% We are terminating so it's OK if we can't send the GOAWAY anymore. |
| 1347 |
_ = Transport:send(Socket, cow_http2:goaway( |
| 1348 |
cow_http2_machine:get_last_streamid(HTTP2Machine), |
| 1349 |
terminate_reason(Reason), <<>>)); |
| 1350 |
%% We already sent the GOAWAY frame. |
| 1351 |
Status =:= closing -> |
| 1352 |
ok |
| 1353 |
end, |
| 1354 |
terminate_all_streams(State, maps:to_list(Streams), Reason), |
| 1355 |
cowboy_children:terminate(Children), |
| 1356 |
%% @todo Don't linger on connection errors. |
| 1357 |
terminate_linger(State), |
| 1358 |
exit({shutdown, Reason}); |
| 1359 |
%% We are not fully connected so we can just terminate the connection. |
| 1360 |
terminate(_State, Reason) -> |
| 1361 |
exit({shutdown, Reason}). |
| 1362 |
|
| 1363 |
terminate_reason({connection_error, Reason, _}) -> Reason; |
| 1364 |
terminate_reason({stop, _, _}) -> no_error; |
| 1365 |
terminate_reason({socket_error, _, _}) -> internal_error; |
| 1366 |
terminate_reason({internal_error, _, _}) -> internal_error. |
| 1367 |
|
| 1368 |
terminate_all_streams(_, [], _) -> |
| 1369 |
ok; |
| 1370 |
terminate_all_streams(State, [{StreamID, #stream{state=StreamState}}|Tail], Reason) -> |
| 1371 |
terminate_stream_handler(State, StreamID, Reason, StreamState), |
| 1372 |
terminate_all_streams(State, Tail, Reason). |
| 1373 |
|
| 1374 |
%% This code is copied from cowboy_http. |
| 1375 |
terminate_linger(State=#state{socket=Socket, transport=Transport, opts=Opts}) -> |
| 1376 |
case Transport:shutdown(Socket, write) of |
| 1377 |
ok -> |
| 1378 |
case maps:get(linger_timeout, Opts, 1000) of |
| 1379 |
0 -> |
| 1380 |
ok; |
| 1381 |
infinity -> |
| 1382 |
terminate_linger_before_loop(State, undefined, Transport:messages()); |
| 1383 |
Timeout -> |
| 1384 |
TimerRef = erlang:start_timer(Timeout, self(), linger_timeout), |
| 1385 |
terminate_linger_before_loop(State, TimerRef, Transport:messages()) |
| 1386 |
end; |
| 1387 |
{error, _} -> |
| 1388 |
ok |
| 1389 |
end. |
| 1390 |
|
| 1391 |
terminate_linger_before_loop(State, TimerRef, Messages) -> |
| 1392 |
%% We may already be in active mode when we do this |
| 1393 |
%% but it's OK because we are shutting down anyway. |
| 1394 |
%% |
| 1395 |
%% We specially handle the socket error to terminate |
| 1396 |
%% when an error occurs. |
| 1397 |
case setopts_active(State) of |
| 1398 |
ok -> |
| 1399 |
terminate_linger_loop(State, TimerRef, Messages); |
| 1400 |
{error, _} -> |
| 1401 |
ok |
| 1402 |
end. |
| 1403 |
|
| 1404 |
terminate_linger_loop(State=#state{socket=Socket}, TimerRef, Messages) -> |
| 1405 |
receive |
| 1406 |
{OK, Socket, _} when OK =:= element(1, Messages) -> |
| 1407 |
terminate_linger_loop(State, TimerRef, Messages); |
| 1408 |
{Closed, Socket} when Closed =:= element(2, Messages) -> |
| 1409 |
ok; |
| 1410 |
{Error, Socket, _} when Error =:= element(3, Messages) -> |
| 1411 |
ok; |
| 1412 |
{Passive, Socket} when Passive =:= tcp_passive; Passive =:= ssl_passive -> |
| 1413 |
terminate_linger_before_loop(State, TimerRef, Messages); |
| 1414 |
{timeout, TimerRef, linger_timeout} -> |
| 1415 |
ok; |
| 1416 |
_ -> |
| 1417 |
terminate_linger_loop(State, TimerRef, Messages) |
| 1418 |
end. |
| 1419 |
|
| 1420 |
%% @todo Don't send an RST_STREAM if one was already sent. |
| 1421 |
%% |
| 1422 |
%% When resetting the stream we are technically sending data |
| 1423 |
%% on the socket. However due to implementation complexities |
| 1424 |
%% we do not attempt to reset the idle timeout on send. |
| 1425 |
reset_stream(State0=#state{socket=Socket, transport=Transport, |
| 1426 |
http2_machine=HTTP2Machine0}, StreamID, Error) -> |
| 1427 |
Reason = case Error of |
| 1428 |
{internal_error, _, _} -> internal_error; |
| 1429 |
{stream_error, Reason0, _} -> Reason0 |
| 1430 |
end, |
| 1431 |
ok = maybe_socket_error(State0, Transport:send(Socket, |
| 1432 |
cow_http2:rst_stream(StreamID, Reason))), |
| 1433 |
State1 = case cow_http2_machine:reset_stream(StreamID, HTTP2Machine0) of |
| 1434 |
{ok, HTTP2Machine} -> |
| 1435 |
terminate_stream(State0#state{http2_machine=HTTP2Machine}, StreamID, Error); |
| 1436 |
{error, not_found} -> |
| 1437 |
terminate_stream(State0, StreamID, Error) |
| 1438 |
end, |
| 1439 |
case reset_rate(State1) of |
| 1440 |
{ok, State} -> |
| 1441 |
State; |
| 1442 |
error -> |
| 1443 |
terminate(State1, {connection_error, enhance_your_calm, |
| 1444 |
'Stream reset rate larger than configuration allows. Flood? (CVE-2019-9514)'}) |
| 1445 |
end. |
| 1446 |
|
| 1447 |
reset_rate(State0=#state{reset_rate_num=Num0, reset_rate_time=Time}) -> |
| 1448 |
case Num0 - 1 of |
| 1449 |
0 -> |
| 1450 |
CurrentTime = erlang:monotonic_time(millisecond), |
| 1451 |
if |
| 1452 |
CurrentTime < Time -> |
| 1453 |
error; |
| 1454 |
true -> |
| 1455 |
%% When the option has a period of infinity we cannot reach this clause. |
| 1456 |
{ok, init_reset_rate_limiting(State0, CurrentTime)} |
| 1457 |
end; |
| 1458 |
Num -> |
| 1459 |
{ok, State0#state{reset_rate_num=Num}} |
| 1460 |
end. |
| 1461 |
|
| 1462 |
stop_stream(State=#state{http2_machine=HTTP2Machine}, StreamID) -> |
| 1463 |
case cow_http2_machine:get_stream_local_state(StreamID, HTTP2Machine) of |
| 1464 |
%% When the stream terminates normally (without sending RST_STREAM) |
| 1465 |
%% and no response was sent, we need to send a proper response back to the client. |
| 1466 |
%% We delay the termination of the stream until the response is fully sent. |
| 1467 |
{ok, idle, _} -> |
| 1468 |
info(stopping(State, StreamID), StreamID, {response, 204, #{}, <<>>}); |
| 1469 |
%% When a response was sent but not terminated, we need to close the stream. |
| 1470 |
%% We delay the termination of the stream until the response is fully sent. |
| 1471 |
{ok, nofin, fin} -> |
| 1472 |
stopping(State, StreamID); |
| 1473 |
%% We only send a final DATA frame if there isn't one queued yet. |
| 1474 |
{ok, nofin, _} -> |
| 1475 |
info(stopping(State, StreamID), StreamID, {data, fin, <<>>}); |
| 1476 |
%% When a response was sent fully we can terminate the stream, |
| 1477 |
%% regardless of the stream being in half-closed or closed state. |
| 1478 |
_ -> |
| 1479 |
terminate_stream(State, StreamID) |
| 1480 |
end. |
| 1481 |
|
| 1482 |
stopping(State=#state{streams=Streams}, StreamID) -> |
| 1483 |
#{StreamID := Stream} = Streams, |
| 1484 |
State#state{streams=Streams#{StreamID => Stream#stream{status=stopping}}}. |
| 1485 |
|
| 1486 |
%% If we finished sending data and the stream is stopping, terminate it. |
| 1487 |
maybe_terminate_stream(State=#state{streams=Streams}, StreamID, fin) -> |
| 1488 |
case Streams of |
| 1489 |
#{StreamID := #stream{status=stopping}} -> |
| 1490 |
terminate_stream(State, StreamID); |
| 1491 |
_ -> |
| 1492 |
State |
| 1493 |
end; |
| 1494 |
maybe_terminate_stream(State, _, _) -> |
| 1495 |
State. |
| 1496 |
|
| 1497 |
%% When the stream stops normally without reading the request |
| 1498 |
%% body fully we need to tell the client to stop sending it. |
| 1499 |
%% We do this by sending an RST_STREAM with reason NO_ERROR. (RFC7540 8.1.0) |
| 1500 |
terminate_stream(State0=#state{socket=Socket, transport=Transport, |
| 1501 |
http2_machine=HTTP2Machine0}, StreamID) -> |
| 1502 |
State = case cow_http2_machine:get_stream_local_state(StreamID, HTTP2Machine0) of |
| 1503 |
{ok, fin, _} -> |
| 1504 |
ok = maybe_socket_error(State0, Transport:send(Socket, |
| 1505 |
cow_http2:rst_stream(StreamID, no_error))), |
| 1506 |
{ok, HTTP2Machine} = cow_http2_machine:reset_stream(StreamID, HTTP2Machine0), |
| 1507 |
State0#state{http2_machine=HTTP2Machine}; |
| 1508 |
{error, closed} -> |
| 1509 |
State0 |
| 1510 |
end, |
| 1511 |
terminate_stream(State, StreamID, normal). |
| 1512 |
|
| 1513 |
%% We remove the stream flow from the connection flow. Any further |
| 1514 |
%% data received for this stream is therefore fully contained within |
| 1515 |
%% the extra window we allocated for this stream. |
| 1516 |
terminate_stream(State=#state{flow=Flow, streams=Streams0, children=Children0}, StreamID, Reason) -> |
| 1517 |
case maps:take(StreamID, Streams0) of |
| 1518 |
{#stream{flow=StreamFlow, state=StreamState}, Streams} -> |
| 1519 |
terminate_stream_handler(State, StreamID, Reason, StreamState), |
| 1520 |
Children = cowboy_children:shutdown(Children0, StreamID), |
| 1521 |
State#state{flow=Flow - StreamFlow, streams=Streams, children=Children}; |
| 1522 |
error -> |
| 1523 |
State |
| 1524 |
end. |
| 1525 |
|
| 1526 |
terminate_stream_handler(#state{opts=Opts}, StreamID, Reason, StreamState) -> |
| 1527 |
try |
| 1528 |
cowboy_stream:terminate(StreamID, Reason, StreamState) |
| 1529 |
catch Class:Exception:Stacktrace -> |
| 1530 |
cowboy:log(cowboy_stream:make_error_log(terminate, |
| 1531 |
[StreamID, Reason, StreamState], |
| 1532 |
Class, Exception, Stacktrace), Opts) |
| 1533 |
end. |
| 1534 |
|
| 1535 |
%% System callbacks. |
| 1536 |
|
| 1537 |
-spec system_continue(_, _, {#state{}, binary()}) -> no_return(). |
| 1538 |
|
| 1539 |
system_continue(_, _, {State, Buffer}) -> |
| 1540 |
before_loop(State, Buffer). |
| 1541 |
|
| 1542 |
-spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return(). |
| 1543 |
|
| 1544 |
system_terminate(Reason0, _, _, {State, Buffer}) -> |
| 1545 |
Reason = {stop, {exit, Reason0}, 'sys:terminate/2,3 was called.'}, |
| 1546 |
before_loop(initiate_closing(State, Reason), Buffer). |
| 1547 |
|
| 1548 |
-spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}. |
| 1549 |
|
| 1550 |
system_code_change(Misc, _, _, _) -> |
| 1551 |
{ok, Misc}. |