2017-01-02 19:36:36 +01:00
|
|
|
%% Copyright (c) 2015-2017, Loïc Hoguin <essen@ninenines.eu>
|
2015-06-11 17:04:21 +02:00
|
|
|
%%
|
|
|
|
%% Permission to use, copy, modify, and/or distribute this software for any
|
|
|
|
%% purpose with or without fee is hereby granted, provided that the above
|
|
|
|
%% copyright notice and this permission notice appear in all copies.
|
|
|
|
%%
|
|
|
|
%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
|
|
|
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
|
|
|
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
|
|
|
%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
|
|
|
%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
|
|
|
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
|
|
|
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
|
|
|
|
|
|
|
-module(cowboy_http2).
|
|
|
|
|
2017-01-16 14:22:43 +01:00
|
|
|
-export([init/5]).
|
|
|
|
-export([init/9]).
|
2017-10-25 20:17:21 +01:00
|
|
|
-export([init/11]).
|
2015-06-11 17:04:21 +02:00
|
|
|
|
|
|
|
-export([system_continue/3]).
|
|
|
|
-export([system_terminate/4]).
|
|
|
|
-export([system_code_change/4]).
|
|
|
|
|
2017-05-05 13:48:25 +02:00
|
|
|
-type opts() :: #{
|
|
|
|
connection_type => worker | supervisor,
|
|
|
|
env => cowboy_middleware:env(),
|
|
|
|
inactivity_timeout => timeout(),
|
|
|
|
middlewares => [module()],
|
|
|
|
preface_timeout => timeout(),
|
|
|
|
shutdown_timeout => timeout(),
|
|
|
|
stream_handlers => [module()]
|
|
|
|
}.
|
|
|
|
-export_type([opts/0]).
|
|
|
|
|
2015-06-11 17:04:21 +02:00
|
|
|
-record(stream, {
|
|
|
|
id = undefined :: cowboy_stream:streamid(),
|
2017-01-16 14:22:43 +01:00
|
|
|
%% Stream handlers and their state.
|
2017-05-19 20:18:00 +02:00
|
|
|
state = undefined :: {module(), any()} | flush,
|
2017-12-04 18:21:10 +01:00
|
|
|
%% Request method.
|
|
|
|
method = undefined :: binary(),
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Whether we finished sending data.
|
2017-05-19 20:18:00 +02:00
|
|
|
local = idle :: idle | upgrade | cowboy_stream:fin() | flush,
|
|
|
|
%% Local flow control window (how much we can send).
|
|
|
|
local_window :: integer(),
|
|
|
|
%% Buffered data waiting for the flow control window to increase.
|
|
|
|
local_buffer = queue:new() :: queue:queue(
|
|
|
|
{cowboy_stream:fin(), non_neg_integer(), iolist()
|
|
|
|
| {sendfile, non_neg_integer(), pos_integer(), file:name_all()}}),
|
|
|
|
local_buffer_size = 0 :: non_neg_integer(),
|
2017-11-20 15:46:23 +01:00
|
|
|
local_trailers = undefined :: undefined | cowboy:http_headers(),
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Whether we finished receiving data.
|
2016-06-08 23:09:14 +02:00
|
|
|
remote = nofin :: cowboy_stream:fin(),
|
2017-05-19 20:18:00 +02:00
|
|
|
%% Remote flow control window (how much we accept to receive).
|
2017-11-15 14:58:49 +01:00
|
|
|
remote_window :: integer(),
|
|
|
|
%% Unparsed te header. Used to know if we can send trailers.
|
|
|
|
te :: undefined | binary()
|
2015-06-11 17:04:21 +02:00
|
|
|
}).
|
|
|
|
|
|
|
|
-type stream() :: #stream{}.
|
|
|
|
|
|
|
|
-record(state, {
|
|
|
|
parent = undefined :: pid(),
|
|
|
|
ref :: ranch:ref(),
|
|
|
|
socket = undefined :: inet:socket(),
|
|
|
|
transport :: module(),
|
2017-05-05 13:48:25 +02:00
|
|
|
opts = #{} :: opts(),
|
2015-06-11 17:04:21 +02:00
|
|
|
|
2016-06-20 17:28:59 +02:00
|
|
|
%% Remote address and port for the connection.
|
|
|
|
peer = undefined :: {inet:ip_address(), inet:port_number()},
|
|
|
|
|
2017-10-25 20:17:21 +01:00
|
|
|
%% Local address and port for the connection.
|
|
|
|
sock = undefined :: {inet:ip_address(), inet:port_number()},
|
|
|
|
|
|
|
|
%% Client certificate (TLS only).
|
|
|
|
cert :: undefined | binary(),
|
|
|
|
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Settings are separate for each endpoint. In addition, settings
|
|
|
|
%% must be acknowledged before they can be expected to be applied.
|
|
|
|
%%
|
|
|
|
%% @todo Since the ack is required, we must timeout if we don't receive it.
|
|
|
|
%% @todo I haven't put as much thought as I should have on this,
|
|
|
|
%% the final settings handling will be very different.
|
2017-02-25 20:05:31 +01:00
|
|
|
local_settings = #{
|
|
|
|
% header_table_size => 4096,
|
|
|
|
% enable_push => false, %% We are the server. Push is never enabled.
|
|
|
|
% max_concurrent_streams => infinity,
|
2017-05-19 20:18:00 +02:00
|
|
|
initial_window_size => 65535,
|
2017-02-25 20:05:31 +01:00
|
|
|
max_frame_size => 16384
|
|
|
|
% max_header_list_size => infinity
|
|
|
|
} :: map(),
|
2016-03-13 23:14:57 +01:00
|
|
|
%% @todo We need a TimerRef to do SETTINGS_TIMEOUT errors.
|
|
|
|
%% We need to be careful there. It's well possible that we send
|
|
|
|
%% two SETTINGS frames before we receive a SETTINGS ack.
|
2015-06-11 17:04:21 +02:00
|
|
|
next_settings = #{} :: undefined | map(), %% @todo perhaps set to undefined by default
|
2017-05-19 20:18:00 +02:00
|
|
|
remote_settings = #{
|
|
|
|
initial_window_size => 65535
|
|
|
|
} :: map(),
|
|
|
|
|
|
|
|
%% Connection-wide flow control window.
|
|
|
|
local_window = 65535 :: integer(), %% How much we can send.
|
|
|
|
remote_window = 65535 :: integer(), %% How much we accept to receive.
|
2015-06-11 17:04:21 +02:00
|
|
|
|
|
|
|
%% Stream identifiers.
|
2017-02-25 20:05:31 +01:00
|
|
|
client_streamid = 0 :: non_neg_integer(),
|
2015-06-11 17:04:21 +02:00
|
|
|
server_streamid = 2 :: pos_integer(),
|
|
|
|
|
|
|
|
%% Currently active HTTP/2 streams. Streams may be initiated either
|
|
|
|
%% by the client or by the server through PUSH_PROMISE frames.
|
|
|
|
streams = [] :: [stream()],
|
|
|
|
|
2017-10-23 14:49:33 +01:00
|
|
|
%% HTTP/2 streams that have been reset recently. We are expected
|
|
|
|
%% to keep receiving additional frames after sending an RST_STREAM.
|
|
|
|
lingering_streams = [] :: [cowboy_stream:streamid()],
|
|
|
|
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Streams can spawn zero or more children which are then managed
|
|
|
|
%% by this module if operating as a supervisor.
|
2017-08-08 16:59:33 +02:00
|
|
|
children = cowboy_children:init() :: cowboy_children:children(),
|
2015-06-11 17:04:21 +02:00
|
|
|
|
|
|
|
%% The client starts by sending a sequence of bytes as a preface,
|
|
|
|
%% followed by a potentially empty SETTINGS frame. Then the connection
|
|
|
|
%% is established and continues normally. An exception is when a HEADERS
|
|
|
|
%% frame is sent followed by CONTINUATION frames: no other frame can be
|
|
|
|
%% sent in between.
|
2018-03-01 14:49:57 +01:00
|
|
|
parse_state = undefined :: {preface, sequence, undefined | reference()}
|
2016-03-13 23:14:57 +01:00
|
|
|
| {preface, settings, reference()}
|
|
|
|
| normal
|
2015-06-11 17:04:21 +02:00
|
|
|
| {continuation, cowboy_stream:streamid(), cowboy_stream:fin(), binary()},
|
|
|
|
|
|
|
|
%% HPACK decoding and encoding state.
|
|
|
|
decode_state = cow_hpack:init() :: cow_hpack:state(),
|
|
|
|
encode_state = cow_hpack:init() :: cow_hpack:state()
|
|
|
|
}).
|
|
|
|
|
2017-01-16 14:22:43 +01:00
|
|
|
-spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts()) -> ok.
|
|
|
|
init(Parent, Ref, Socket, Transport, Opts) ->
|
2017-10-25 20:17:21 +01:00
|
|
|
Peer0 = Transport:peername(Socket),
|
|
|
|
Sock0 = Transport:sockname(Socket),
|
|
|
|
Cert1 = case Transport:name() of
|
|
|
|
ssl ->
|
|
|
|
case ssl:peercert(Socket) of
|
|
|
|
{error, no_peercert} ->
|
|
|
|
{ok, undefined};
|
|
|
|
Cert0 ->
|
|
|
|
Cert0
|
|
|
|
end;
|
|
|
|
_ ->
|
|
|
|
{ok, undefined}
|
|
|
|
end,
|
|
|
|
case {Peer0, Sock0, Cert1} of
|
|
|
|
{{ok, Peer}, {ok, Sock}, {ok, Cert}} ->
|
|
|
|
init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, <<>>);
|
|
|
|
{{error, Reason}, _, _} ->
|
|
|
|
terminate(undefined, {socket_error, Reason,
|
|
|
|
'A socket error occurred when retrieving the peer name.'});
|
|
|
|
{_, {error, Reason}, _} ->
|
|
|
|
terminate(undefined, {socket_error, Reason,
|
|
|
|
'A socket error occurred when retrieving the sock name.'});
|
|
|
|
{_, _, {error, Reason}} ->
|
|
|
|
terminate(undefined, {socket_error, Reason,
|
|
|
|
'A socket error occurred when retrieving the client TLS certificate.'})
|
2016-06-20 17:28:59 +02:00
|
|
|
end.
|
2016-03-10 23:30:49 +01:00
|
|
|
|
2017-01-16 14:22:43 +01:00
|
|
|
-spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
|
2017-10-25 20:17:21 +01:00
|
|
|
{inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()},
|
|
|
|
binary() | undefined, binary()) -> ok.
|
|
|
|
init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, Buffer) ->
|
2016-03-10 23:30:49 +01:00
|
|
|
State = #state{parent=Parent, ref=Ref, socket=Socket,
|
2017-10-25 20:17:21 +01:00
|
|
|
transport=Transport, opts=Opts, peer=Peer, sock=Sock, cert=Cert,
|
2016-03-13 23:14:57 +01:00
|
|
|
parse_state={preface, sequence, preface_timeout(Opts)}},
|
2016-03-10 23:30:49 +01:00
|
|
|
preface(State),
|
|
|
|
case Buffer of
|
|
|
|
<<>> -> before_loop(State, Buffer);
|
|
|
|
_ -> parse(State, Buffer)
|
|
|
|
end.
|
|
|
|
|
2016-03-12 18:25:35 +01:00
|
|
|
%% @todo Add an argument for the request body.
|
2017-01-16 14:22:43 +01:00
|
|
|
-spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
|
2017-10-25 20:17:21 +01:00
|
|
|
{inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()},
|
|
|
|
binary() | undefined, binary(), map() | undefined, cowboy_req:req()) -> ok.
|
|
|
|
init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, Buffer, _Settings, Req) ->
|
2016-03-12 18:25:35 +01:00
|
|
|
State0 = #state{parent=Parent, ref=Ref, socket=Socket,
|
2017-10-25 20:17:21 +01:00
|
|
|
transport=Transport, opts=Opts, peer=Peer, sock=Sock, cert=Cert,
|
2016-03-13 23:14:57 +01:00
|
|
|
parse_state={preface, sequence, preface_timeout(Opts)}},
|
2016-03-13 11:18:27 +01:00
|
|
|
%% @todo Apply settings.
|
2016-03-12 18:25:35 +01:00
|
|
|
%% StreamID from HTTP/1.1 Upgrade requests is always 1.
|
|
|
|
%% The stream is always in the half-closed (remote) state.
|
2017-04-18 14:06:34 +02:00
|
|
|
State1 = stream_handler_init(State0, 1, fin, upgrade, Req),
|
|
|
|
%% We assume that the upgrade will be applied. A stream handler
|
|
|
|
%% must not prevent the normal operations of the server.
|
|
|
|
State = info(State1, 1, {switch_protocol, #{
|
|
|
|
<<"connection">> => <<"Upgrade">>,
|
|
|
|
<<"upgrade">> => <<"h2c">>
|
|
|
|
}, ?MODULE, undefined}), %% @todo undefined or #{}?
|
|
|
|
preface(State),
|
2016-03-12 18:25:35 +01:00
|
|
|
case Buffer of
|
|
|
|
<<>> -> before_loop(State, Buffer);
|
|
|
|
_ -> parse(State, Buffer)
|
|
|
|
end.
|
|
|
|
|
2016-03-10 23:30:49 +01:00
|
|
|
preface(#state{socket=Socket, transport=Transport, next_settings=Settings}) ->
|
|
|
|
%% We send next_settings and use defaults until we get a ack.
|
2017-12-12 16:57:05 +01:00
|
|
|
Transport:send(Socket, cow_http2:settings(Settings)).
|
2015-06-11 17:04:21 +02:00
|
|
|
|
2016-03-13 23:14:57 +01:00
|
|
|
preface_timeout(Opts) ->
|
2018-03-01 14:49:57 +01:00
|
|
|
case maps:get(preface_timeout, Opts, 5000) of
|
|
|
|
infinity -> undefined;
|
|
|
|
PrefaceTimeout -> erlang:start_timer(PrefaceTimeout, self(), preface_timeout)
|
|
|
|
end.
|
2016-03-13 23:14:57 +01:00
|
|
|
|
2015-06-11 17:04:21 +02:00
|
|
|
%% @todo Add the timeout for last time since we heard of connection.
|
|
|
|
before_loop(State, Buffer) ->
|
|
|
|
loop(State, Buffer).
|
|
|
|
|
2016-03-13 23:14:57 +01:00
|
|
|
loop(State=#state{parent=Parent, socket=Socket, transport=Transport,
|
2017-05-05 13:48:25 +02:00
|
|
|
opts=Opts, children=Children, parse_state=PS}, Buffer) ->
|
2015-06-11 17:04:21 +02:00
|
|
|
Transport:setopts(Socket, [{active, once}]),
|
|
|
|
{OK, Closed, Error} = Transport:messages(),
|
2017-05-05 13:48:25 +02:00
|
|
|
InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000),
|
2015-06-11 17:04:21 +02:00
|
|
|
receive
|
|
|
|
%% Socket messages.
|
|
|
|
{OK, Socket, Data} ->
|
|
|
|
parse(State, << Buffer/binary, Data/binary >>);
|
|
|
|
{Closed, Socket} ->
|
|
|
|
terminate(State, {socket_error, closed, 'The socket has been closed.'});
|
|
|
|
{Error, Socket, Reason} ->
|
|
|
|
terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'});
|
|
|
|
%% System messages.
|
|
|
|
{'EXIT', Parent, Reason} ->
|
2018-03-13 11:19:13 +01:00
|
|
|
%% @todo We should exit gracefully.
|
2015-06-11 17:04:21 +02:00
|
|
|
exit(Reason);
|
|
|
|
{system, From, Request} ->
|
|
|
|
sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer});
|
2017-08-08 16:59:33 +02:00
|
|
|
%% Timeouts.
|
|
|
|
{timeout, Ref, {shutdown, Pid}} ->
|
|
|
|
cowboy_children:shutdown_timeout(Children, Ref, Pid),
|
|
|
|
loop(State, Buffer);
|
2016-03-13 23:14:57 +01:00
|
|
|
{timeout, TRef, preface_timeout} ->
|
|
|
|
case PS of
|
|
|
|
{preface, _, TRef} ->
|
|
|
|
terminate(State, {connection_error, protocol_error,
|
|
|
|
'The preface was not received in a reasonable amount of time.'});
|
|
|
|
_ ->
|
|
|
|
loop(State, Buffer)
|
|
|
|
end;
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Messages pertaining to a stream.
|
Initial commit with connection/streams
Breaking changes with previous commit. This is a very large change,
and I am giving up on making a single commit that fixes everything.
More commits will follow slowly adding back features, introducing
new tests and fixing the documentation.
This change contains most of the work toward unifying the interface
for handling both HTTP/1.1 and HTTP/2. HTTP/1.1 connections are now
no longer 1 process per connection; instead by default 1 process per
request is also created. This has a number of pros and cons.
Because it has cons, we also allow users to use a lower-level API
that acts on "streams" (requests/responses) directly at the connection
process-level. If performance is a concern, one can always write a
stream handler. The performance in this case will be even greater
than with Cowboy 1, although all the special handlers are unavailable.
When switching to Websocket, after the handler returns from init/2,
Cowboy stops the stream and the Websocket protocol takes over the
connection process. Websocket then calls websocket_init/2 for any
additional initialization such as timers, because the process is
different in init/2 and websocket_*/* functions. This however would
allow us to use websocket_init/2 for sending messages on connect,
instead of sending ourselves a message and be subject to races.
Note that websocket_init/2 is optional.
This is all a big change and while most of the tests pass, some
functionality currently doesn't. SPDY is broken and will be removed
soon in favor of HTTP/2. Automatic compression is currently disabled.
The cowboy_req interface probably still have a few functions that
need to be updated. The docs and examples do not refer the current
functionality anymore.
Everything will be fixed over time. Feedback is more than welcome.
Open a ticket!
2016-02-10 17:28:32 +01:00
|
|
|
{{Pid, StreamID}, Msg} when Pid =:= self() ->
|
2015-06-11 17:04:21 +02:00
|
|
|
loop(info(State, StreamID, Msg), Buffer);
|
|
|
|
%% Exit signal from children.
|
|
|
|
Msg = {'EXIT', Pid, _} ->
|
|
|
|
loop(down(State, Pid, Msg), Buffer);
|
|
|
|
%% Calls from supervisor module.
|
2018-03-13 10:40:14 +01:00
|
|
|
{'$gen_call', From, Call} ->
|
|
|
|
cowboy_children:handle_supervisor_call(Call, From, Children, ?MODULE),
|
2015-06-11 17:04:21 +02:00
|
|
|
loop(State, Buffer);
|
|
|
|
Msg ->
|
|
|
|
error_logger:error_msg("Received stray message ~p.", [Msg]),
|
|
|
|
loop(State, Buffer)
|
2017-05-05 13:48:25 +02:00
|
|
|
after InactivityTimeout ->
|
2015-06-11 17:04:21 +02:00
|
|
|
terminate(State, {internal_error, timeout, 'No message or data received before timeout.'})
|
|
|
|
end.
|
|
|
|
|
2016-03-13 23:14:57 +01:00
|
|
|
parse(State=#state{socket=Socket, transport=Transport, parse_state={preface, sequence, TRef}}, Data) ->
|
2015-06-11 17:04:21 +02:00
|
|
|
case Data of
|
|
|
|
<< "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n", Rest/bits >> ->
|
2016-03-13 23:14:57 +01:00
|
|
|
parse(State#state{parse_state={preface, settings, TRef}}, Rest);
|
2015-06-11 17:04:21 +02:00
|
|
|
_ when byte_size(Data) >= 24 ->
|
|
|
|
Transport:close(Socket),
|
|
|
|
exit({shutdown, {connection_error, protocol_error,
|
|
|
|
'The connection preface was invalid. (RFC7540 3.5)'}});
|
|
|
|
_ ->
|
2016-03-10 23:30:49 +01:00
|
|
|
Len = byte_size(Data),
|
|
|
|
<< Preface:Len/binary, _/bits >> = <<"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n">>,
|
|
|
|
case Data of
|
|
|
|
Preface ->
|
|
|
|
before_loop(State, Data);
|
|
|
|
_ ->
|
|
|
|
Transport:close(Socket),
|
|
|
|
exit({shutdown, {connection_error, protocol_error,
|
|
|
|
'The connection preface was invalid. (RFC7540 3.5)'}})
|
|
|
|
end
|
2015-06-11 17:04:21 +02:00
|
|
|
end;
|
|
|
|
%% @todo Perhaps instead of just more we can have {more, Len} to avoid all the checks.
|
2017-02-25 20:05:31 +01:00
|
|
|
parse(State=#state{local_settings=#{max_frame_size := MaxFrameSize},
|
|
|
|
parse_state=ParseState}, Data) ->
|
|
|
|
case cow_http2:parse(Data, MaxFrameSize) of
|
2015-06-11 17:04:21 +02:00
|
|
|
{ok, Frame, Rest} ->
|
|
|
|
case ParseState of
|
2016-03-13 23:14:57 +01:00
|
|
|
normal ->
|
|
|
|
parse(frame(State, Frame), Rest);
|
|
|
|
{preface, settings, TRef} ->
|
|
|
|
parse_settings_preface(State, Frame, Rest, TRef);
|
|
|
|
{continuation, _, _, _} ->
|
|
|
|
parse(continuation_frame(State, Frame), Rest)
|
2015-06-11 17:04:21 +02:00
|
|
|
end;
|
2017-11-27 19:00:35 +01:00
|
|
|
{ignore, _} when element(1, ParseState) =:= continuation ->
|
|
|
|
terminate(State, {connection_error, protocol_error,
|
|
|
|
'An invalid frame was received in the middle of a header block. (RFC7540 6.2)'});
|
2017-02-26 13:24:15 +01:00
|
|
|
{ignore, Rest} ->
|
|
|
|
parse(State, Rest);
|
2015-06-11 17:04:21 +02:00
|
|
|
{stream_error, StreamID, Reason, Human, Rest} ->
|
|
|
|
parse(stream_reset(State, StreamID, {stream_error, Reason, Human}), Rest);
|
|
|
|
Error = {connection_error, _, _} ->
|
|
|
|
terminate(State, Error);
|
|
|
|
more ->
|
|
|
|
before_loop(State, Data)
|
|
|
|
end.
|
|
|
|
|
2016-03-13 23:14:57 +01:00
|
|
|
parse_settings_preface(State, Frame={settings, _}, Rest, TRef) ->
|
2018-03-01 14:49:57 +01:00
|
|
|
ok = case TRef of
|
|
|
|
undefined -> ok;
|
|
|
|
_ -> erlang:cancel_timer(TRef, [{async, true}, {info, false}])
|
|
|
|
end,
|
2016-03-13 23:14:57 +01:00
|
|
|
parse(frame(State#state{parse_state=normal}, Frame), Rest);
|
|
|
|
parse_settings_preface(State, _, _, _) ->
|
|
|
|
terminate(State, {connection_error, protocol_error,
|
|
|
|
'The preface sequence must be followed by a SETTINGS frame. (RFC7540 3.5)'}).
|
|
|
|
|
2015-06-11 17:04:21 +02:00
|
|
|
%% @todo When we get a 'fin' we need to check if the stream had a 'fin' sent back
|
|
|
|
%% and terminate the stream if this is the end of it.
|
|
|
|
|
|
|
|
%% DATA frame.
|
2017-05-23 14:09:38 +02:00
|
|
|
frame(State=#state{client_streamid=LastStreamID}, {data, StreamID, _, _})
|
|
|
|
when StreamID > LastStreamID ->
|
|
|
|
terminate(State, {connection_error, protocol_error,
|
|
|
|
'DATA frame received on a stream in idle state. (RFC7540 5.1)'});
|
2017-10-23 14:49:33 +01:00
|
|
|
frame(State0=#state{remote_window=ConnWindow, streams=Streams, lingering_streams=Lingering},
|
2017-09-25 12:34:44 +02:00
|
|
|
{data, StreamID, IsFin, Data}) ->
|
2017-05-23 14:09:38 +02:00
|
|
|
DataLen = byte_size(Data),
|
|
|
|
State = State0#state{remote_window=ConnWindow - DataLen},
|
2016-06-16 19:46:57 +02:00
|
|
|
case lists:keyfind(StreamID, #stream.id, Streams) of
|
2017-09-25 12:55:30 +02:00
|
|
|
Stream = #stream{state=flush, remote=nofin, remote_window=StreamWindow} ->
|
|
|
|
after_commands(State, Stream#stream{remote=IsFin, remote_window=StreamWindow - DataLen});
|
2017-09-25 12:34:44 +02:00
|
|
|
Stream = #stream{state=StreamState0, remote=nofin, remote_window=StreamWindow} ->
|
2017-01-16 14:22:43 +01:00
|
|
|
try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
|
2015-06-11 17:04:21 +02:00
|
|
|
{Commands, StreamState} ->
|
2017-09-25 12:34:44 +02:00
|
|
|
commands(State, Stream#stream{state=StreamState, remote=IsFin,
|
|
|
|
remote_window=StreamWindow - DataLen}, Commands)
|
2017-09-21 12:53:21 +02:00
|
|
|
catch Class:Exception ->
|
|
|
|
cowboy_stream:report_error(data,
|
|
|
|
[StreamID, IsFin, Data, StreamState0],
|
|
|
|
Class, Exception, erlang:get_stacktrace()),
|
|
|
|
stream_reset(State, StreamID, {internal_error, {Class, Exception},
|
2017-09-27 14:17:27 +02:00
|
|
|
'Unhandled exception in cowboy_stream:data/4.'})
|
2015-06-11 17:04:21 +02:00
|
|
|
end;
|
2017-05-23 14:09:38 +02:00
|
|
|
#stream{remote=fin} ->
|
2015-06-11 17:04:21 +02:00
|
|
|
stream_reset(State, StreamID, {stream_error, stream_closed,
|
2017-05-23 14:09:38 +02:00
|
|
|
'DATA frame received for a half-closed (remote) stream. (RFC7540 5.1)'});
|
|
|
|
false ->
|
2017-10-23 14:49:33 +01:00
|
|
|
%% After we send an RST_STREAM frame and terminate a stream,
|
|
|
|
%% the client still might be sending us some more frames
|
|
|
|
%% until it can process this RST_STREAM. We therefore ignore
|
|
|
|
%% DATA frames received for such lingering streams.
|
|
|
|
case lists:member(StreamID, Lingering) of
|
|
|
|
true ->
|
|
|
|
State0;
|
|
|
|
false ->
|
|
|
|
terminate(State, {connection_error, stream_closed,
|
|
|
|
'DATA frame received for a closed stream. (RFC7540 5.1)'})
|
|
|
|
end
|
2015-06-11 17:04:21 +02:00
|
|
|
end;
|
2017-05-23 14:09:38 +02:00
|
|
|
%% HEADERS frame with invalid even-numbered streamid.
|
|
|
|
frame(State, {headers, StreamID, _, _, _}) when StreamID rem 2 =:= 0 ->
|
|
|
|
terminate(State, {connection_error, protocol_error,
|
|
|
|
'HEADERS frame received with even-numbered streamid. (RFC7540 5.1.1)'});
|
|
|
|
%% HEADERS frame received on (half-)closed stream.
|
2017-11-27 13:42:04 +01:00
|
|
|
%%
|
|
|
|
%% We always close the connection here to avoid having to decode
|
|
|
|
%% the headers to not waste resources on non-compliant clients.
|
2017-05-23 14:09:38 +02:00
|
|
|
frame(State=#state{client_streamid=LastStreamID}, {headers, StreamID, _, _, _})
|
|
|
|
when StreamID =< LastStreamID ->
|
2017-11-27 13:42:04 +01:00
|
|
|
terminate(State, {connection_error, stream_closed,
|
2017-05-23 14:09:38 +02:00
|
|
|
'HEADERS frame received on a stream in closed or half-closed state. (RFC7540 5.1)'});
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Single HEADERS frame headers block.
|
|
|
|
frame(State, {headers, StreamID, IsFin, head_fin, HeaderBlock}) ->
|
|
|
|
%% @todo We probably need to validate StreamID here and in 4 next clauses.
|
2017-07-26 17:31:12 +02:00
|
|
|
stream_decode_init(State, StreamID, IsFin, HeaderBlock);
|
2015-06-11 17:04:21 +02:00
|
|
|
%% HEADERS frame starting a headers block. Enter continuation mode.
|
|
|
|
frame(State, {headers, StreamID, IsFin, head_nofin, HeaderBlockFragment}) ->
|
|
|
|
State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
|
|
|
|
%% Single HEADERS frame headers block with priority.
|
|
|
|
frame(State, {headers, StreamID, IsFin, head_fin,
|
|
|
|
_IsExclusive, _DepStreamID, _Weight, HeaderBlock}) ->
|
|
|
|
%% @todo Handle priority.
|
2017-07-26 17:31:12 +02:00
|
|
|
stream_decode_init(State, StreamID, IsFin, HeaderBlock);
|
2015-06-11 17:04:21 +02:00
|
|
|
%% HEADERS frame starting a headers block. Enter continuation mode.
|
|
|
|
frame(State, {headers, StreamID, IsFin, head_nofin,
|
|
|
|
_IsExclusive, _DepStreamID, _Weight, HeaderBlockFragment}) ->
|
|
|
|
%% @todo Handle priority.
|
|
|
|
State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
|
|
|
|
%% PRIORITY frame.
|
|
|
|
frame(State, {priority, _StreamID, _IsExclusive, _DepStreamID, _Weight}) ->
|
|
|
|
%% @todo Validate StreamID?
|
|
|
|
%% @todo Handle priority.
|
|
|
|
State;
|
|
|
|
%% RST_STREAM frame.
|
2017-05-23 14:09:38 +02:00
|
|
|
frame(State=#state{client_streamid=LastStreamID}, {rst_stream, StreamID, _})
|
|
|
|
when StreamID > LastStreamID ->
|
|
|
|
terminate(State, {connection_error, protocol_error,
|
|
|
|
'RST_STREAM frame received on a stream in idle state. (RFC7540 5.1)'});
|
2015-06-11 17:04:21 +02:00
|
|
|
frame(State, {rst_stream, StreamID, Reason}) ->
|
2017-03-02 19:35:24 +01:00
|
|
|
stream_terminate(State, StreamID, {stream_error, Reason, 'Stream reset requested by client.'});
|
2015-06-11 17:04:21 +02:00
|
|
|
%% SETTINGS frame.
|
2017-11-27 22:49:50 +01:00
|
|
|
frame(State0=#state{socket=Socket, transport=Transport, remote_settings=Settings0},
|
2017-05-31 12:48:22 +02:00
|
|
|
{settings, Settings}) ->
|
2016-03-10 23:30:49 +01:00
|
|
|
Transport:send(Socket, cow_http2:settings_ack()),
|
2017-11-27 22:49:50 +01:00
|
|
|
State = State0#state{remote_settings=maps:merge(Settings0, Settings)},
|
|
|
|
case Settings of
|
|
|
|
#{initial_window_size := NewWindowSize} ->
|
|
|
|
OldWindowSize = maps:get(initial_window_size, Settings0, 65535),
|
|
|
|
update_stream_windows(State, NewWindowSize - OldWindowSize);
|
|
|
|
_ ->
|
|
|
|
State
|
|
|
|
end;
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Ack for a previously sent SETTINGS frame.
|
|
|
|
frame(State=#state{next_settings=_NextSettings}, settings_ack) ->
|
|
|
|
%% @todo Apply SETTINGS that require synchronization.
|
|
|
|
State;
|
|
|
|
%% Unexpected PUSH_PROMISE frame.
|
|
|
|
frame(State, {push_promise, _, _, _, _}) ->
|
|
|
|
terminate(State, {connection_error, protocol_error,
|
|
|
|
'PUSH_PROMISE frames MUST only be sent on a peer-initiated stream. (RFC7540 6.6)'});
|
|
|
|
%% PING frame.
|
|
|
|
frame(State=#state{socket=Socket, transport=Transport}, {ping, Opaque}) ->
|
|
|
|
Transport:send(Socket, cow_http2:ping_ack(Opaque)),
|
|
|
|
State;
|
|
|
|
%% Ack for a previously sent PING frame.
|
|
|
|
%%
|
|
|
|
%% @todo Might want to check contents but probably a waste of time.
|
|
|
|
frame(State, {ping_ack, _Opaque}) ->
|
|
|
|
State;
|
|
|
|
%% GOAWAY frame.
|
|
|
|
frame(State, Frame={goaway, _, _, _}) ->
|
|
|
|
terminate(State, {stop, Frame, 'Client is going away.'});
|
|
|
|
%% Connection-wide WINDOW_UPDATE frame.
|
2017-11-27 19:00:35 +01:00
|
|
|
frame(State=#state{local_window=ConnWindow}, {window_update, Increment})
|
2017-11-27 22:49:50 +01:00
|
|
|
when ConnWindow + Increment > 16#7fffffff ->
|
2017-11-27 19:00:35 +01:00
|
|
|
terminate(State, {connection_error, flow_control_error,
|
|
|
|
'The flow control window must not be greater than 2^31-1. (RFC7540 6.9.1)'});
|
2017-05-19 20:18:00 +02:00
|
|
|
frame(State=#state{local_window=ConnWindow}, {window_update, Increment}) ->
|
|
|
|
send_data(State#state{local_window=ConnWindow + Increment});
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Stream-specific WINDOW_UPDATE frame.
|
2017-05-23 14:09:38 +02:00
|
|
|
frame(State=#state{client_streamid=LastStreamID}, {window_update, StreamID, _})
|
|
|
|
when StreamID > LastStreamID ->
|
|
|
|
terminate(State, {connection_error, protocol_error,
|
|
|
|
'WINDOW_UPDATE frame received on a stream in idle state. (RFC7540 5.1)'});
|
2017-05-19 20:18:00 +02:00
|
|
|
frame(State0=#state{streams=Streams0}, {window_update, StreamID, Increment}) ->
|
|
|
|
case lists:keyfind(StreamID, #stream.id, Streams0) of
|
2017-11-27 22:49:50 +01:00
|
|
|
#stream{local_window=StreamWindow} when StreamWindow + Increment > 16#7fffffff ->
|
2017-11-27 19:00:35 +01:00
|
|
|
stream_reset(State0, StreamID, {stream_error, flow_control_error,
|
|
|
|
'The flow control window must not be greater than 2^31-1. (RFC7540 6.9.1)'});
|
2017-05-19 20:18:00 +02:00
|
|
|
Stream0 = #stream{local_window=StreamWindow} ->
|
|
|
|
{State, Stream} = send_data(State0,
|
|
|
|
Stream0#stream{local_window=StreamWindow + Increment}),
|
|
|
|
Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
|
|
|
|
State#state{streams=Streams};
|
2017-05-23 14:09:38 +02:00
|
|
|
%% @todo We must reject WINDOW_UPDATE frames on RST_STREAM closed streams.
|
2017-05-19 20:18:00 +02:00
|
|
|
false ->
|
|
|
|
%% WINDOW_UPDATE frames may be received for a short period of time
|
|
|
|
%% after a stream is closed. They must be ignored.
|
|
|
|
State0
|
|
|
|
end;
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Unexpected CONTINUATION frame.
|
|
|
|
frame(State, {continuation, _, _, _}) ->
|
|
|
|
terminate(State, {connection_error, protocol_error,
|
|
|
|
'CONTINUATION frames MUST be preceded by a HEADERS frame. (RFC7540 6.10)'}).
|
|
|
|
|
|
|
|
continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
|
2017-01-02 18:27:03 +01:00
|
|
|
{continuation, StreamID, head_fin, HeaderBlockFragment1}) ->
|
2017-07-26 17:31:12 +02:00
|
|
|
stream_decode_init(State#state{parse_state=normal}, StreamID, IsFin,
|
2015-06-11 17:04:21 +02:00
|
|
|
<< HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>);
|
|
|
|
continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
|
2017-01-02 18:27:03 +01:00
|
|
|
{continuation, StreamID, head_nofin, HeaderBlockFragment1}) ->
|
2015-06-11 17:04:21 +02:00
|
|
|
State#state{parse_state={continuation, StreamID, IsFin,
|
|
|
|
<< HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>}};
|
|
|
|
continuation_frame(State, _) ->
|
|
|
|
terminate(State, {connection_error, protocol_error,
|
2017-11-27 19:00:35 +01:00
|
|
|
'An invalid frame was received in the middle of a header block. (RFC7540 6.2)'}).
|
2015-06-11 17:04:21 +02:00
|
|
|
|
|
|
|
down(State=#state{children=Children0}, Pid, Msg) ->
|
2017-08-08 16:59:33 +02:00
|
|
|
case cowboy_children:down(Children0, Pid) of
|
|
|
|
%% The stream was terminated already.
|
|
|
|
{ok, undefined, Children} ->
|
|
|
|
State#state{children=Children};
|
|
|
|
%% The stream is still running.
|
|
|
|
{ok, StreamID, Children} ->
|
2015-06-11 17:04:21 +02:00
|
|
|
info(State#state{children=Children}, StreamID, Msg);
|
2017-08-08 16:59:33 +02:00
|
|
|
%% The process was unknown.
|
|
|
|
error ->
|
|
|
|
error_logger:error_msg("Received EXIT signal ~p for unknown process ~p.~n", [Msg, Pid]),
|
2015-06-11 17:04:21 +02:00
|
|
|
State
|
|
|
|
end.
|
|
|
|
|
2017-11-29 16:41:40 +01:00
|
|
|
info(State=#state{client_streamid=LastStreamID, streams=Streams}, StreamID, Msg) ->
|
2016-06-16 19:46:57 +02:00
|
|
|
case lists:keyfind(StreamID, #stream.id, Streams) of
|
2017-09-25 12:55:30 +02:00
|
|
|
#stream{state=flush} ->
|
|
|
|
error_logger:error_msg("Received message ~p for terminated stream ~p.", [Msg, StreamID]),
|
|
|
|
State;
|
2015-06-11 17:04:21 +02:00
|
|
|
Stream = #stream{state=StreamState0} ->
|
2017-01-16 14:22:43 +01:00
|
|
|
try cowboy_stream:info(StreamID, Msg, StreamState0) of
|
2015-06-11 17:04:21 +02:00
|
|
|
{Commands, StreamState} ->
|
2016-06-16 19:46:57 +02:00
|
|
|
commands(State, Stream#stream{state=StreamState}, Commands)
|
2017-09-21 12:53:21 +02:00
|
|
|
catch Class:Exception ->
|
|
|
|
cowboy_stream:report_error(info,
|
|
|
|
[StreamID, Msg, StreamState0],
|
|
|
|
Class, Exception, erlang:get_stacktrace()),
|
|
|
|
stream_reset(State, StreamID, {internal_error, {Class, Exception},
|
2017-09-27 14:17:27 +02:00
|
|
|
'Unhandled exception in cowboy_stream:info/3.'})
|
2015-06-11 17:04:21 +02:00
|
|
|
end;
|
2017-11-29 16:41:40 +01:00
|
|
|
false when StreamID =< LastStreamID ->
|
|
|
|
%% Streams that were reset by the client or streams that are
|
|
|
|
%% in the lingering state may still have Erlang messages going
|
|
|
|
%% around. In these cases we do not want to log anything.
|
|
|
|
State;
|
2015-06-11 17:04:21 +02:00
|
|
|
false ->
|
2017-11-29 16:41:40 +01:00
|
|
|
error_logger:error_msg("Received message ~p for unknown stream ~p.",
|
|
|
|
[Msg, StreamID]),
|
2015-06-11 17:04:21 +02:00
|
|
|
State
|
|
|
|
end.
|
|
|
|
|
2016-06-16 19:46:57 +02:00
|
|
|
commands(State, Stream, []) ->
|
|
|
|
after_commands(State, Stream);
|
2016-08-10 17:15:02 +02:00
|
|
|
%% Error responses are sent only if a response wasn't sent already.
|
|
|
|
commands(State, Stream=#stream{local=idle}, [{error_response, StatusCode, Headers, Body}|Tail]) ->
|
|
|
|
commands(State, Stream, [{response, StatusCode, Headers, Body}|Tail]);
|
|
|
|
commands(State, Stream, [{error_response, _, _, _}|Tail]) ->
|
|
|
|
commands(State, Stream, Tail);
|
2017-10-29 19:52:27 +00:00
|
|
|
%% Send an informational response.
|
2017-12-06 00:30:59 +01:00
|
|
|
commands(State0, Stream=#stream{local=idle}, [{inform, StatusCode, Headers}|Tail]) ->
|
|
|
|
State = send_headers(State0, Stream, StatusCode, Headers, fin),
|
|
|
|
commands(State, Stream, Tail);
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Send response headers.
|
|
|
|
%%
|
|
|
|
%% @todo Kill the stream if it sent a response when one has already been sent.
|
|
|
|
%% @todo Keep IsFin in the state.
|
|
|
|
%% @todo Same two things above apply to DATA, possibly promise too.
|
2017-12-06 00:30:59 +01:00
|
|
|
commands(State0, Stream0=#stream{local=idle},
|
|
|
|
[{response, StatusCode, Headers, Body}|Tail]) ->
|
|
|
|
{State, Stream} = send_response(State0, Stream0, StatusCode, Headers, Body),
|
|
|
|
commands(State, Stream, Tail);
|
2016-06-16 19:46:57 +02:00
|
|
|
%% @todo response when local!=idle
|
2017-09-25 13:52:58 +02:00
|
|
|
%% Send response headers.
|
2017-12-06 00:30:59 +01:00
|
|
|
commands(State0, Stream=#stream{method=Method, local=idle},
|
|
|
|
[{headers, StatusCode, Headers}|Tail]) ->
|
2017-12-04 18:21:10 +01:00
|
|
|
IsFin = case Method of
|
|
|
|
<<"HEAD">> -> fin;
|
|
|
|
_ -> nofin
|
|
|
|
end,
|
2017-12-06 00:30:59 +01:00
|
|
|
State = send_headers(State0, Stream, StatusCode, Headers, IsFin),
|
|
|
|
commands(State, Stream#stream{local=IsFin}, Tail);
|
2016-06-16 19:46:57 +02:00
|
|
|
%% @todo headers when local!=idle
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Send a response body chunk.
|
2017-05-19 20:18:00 +02:00
|
|
|
commands(State0, Stream0=#stream{local=nofin}, [{data, IsFin, Data}|Tail]) ->
|
|
|
|
{State, Stream} = send_data(State0, Stream0, IsFin, Data),
|
|
|
|
commands(State, Stream, Tail);
|
2016-06-16 19:46:57 +02:00
|
|
|
%% @todo data when local!=nofin
|
2017-11-15 14:58:49 +01:00
|
|
|
%% Send trailers.
|
|
|
|
commands(State0, Stream0=#stream{local=nofin, te=TE0}, [{trailers, Trailers}|Tail]) ->
|
|
|
|
%% We only accept TE headers containing exactly "trailers" (RFC7540 8.1.2.1).
|
|
|
|
TE = try cow_http_hd:parse_te(TE0) of
|
|
|
|
{trailers, []} -> trailers;
|
|
|
|
_ -> no_trailers
|
|
|
|
catch _:_ ->
|
|
|
|
%% If we can't parse the TE header, assume we can't send trailers.
|
|
|
|
no_trailers
|
|
|
|
end,
|
|
|
|
{State, Stream} = case TE of
|
|
|
|
trailers ->
|
|
|
|
send_data(State0, Stream0, fin, {trailers, Trailers});
|
|
|
|
no_trailers ->
|
|
|
|
send_data(State0, Stream0, fin, <<>>)
|
|
|
|
end,
|
|
|
|
commands(State, Stream, Tail);
|
2016-06-06 17:27:48 +02:00
|
|
|
%% Send a file.
|
2017-12-13 12:40:00 +01:00
|
|
|
%% @todo Add the sendfile command.
|
|
|
|
%commands(State0, Stream0=#stream{local=nofin},
|
|
|
|
% [{sendfile, IsFin, Offset, Bytes, Path}|Tail]) ->
|
|
|
|
% {State, Stream} = send_data(State0, Stream0, IsFin, {sendfile, Offset, Bytes, Path}),
|
|
|
|
% commands(State, Stream, Tail);
|
2016-06-16 19:46:57 +02:00
|
|
|
%% @todo sendfile when local!=nofin
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Send a push promise.
|
|
|
|
%%
|
|
|
|
%% @todo We need to keep track of what promises we made so that we don't
|
|
|
|
%% end up with an infinite loop of promises.
|
|
|
|
commands(State0=#state{socket=Socket, transport=Transport, server_streamid=PromisedStreamID,
|
2016-06-16 19:46:57 +02:00
|
|
|
encode_state=EncodeState0}, Stream=#stream{id=StreamID},
|
2016-08-10 11:49:31 +02:00
|
|
|
[{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) ->
|
|
|
|
Authority = case {Scheme, Port} of
|
|
|
|
{<<"http">>, 80} -> Host;
|
|
|
|
{<<"https">>, 443} -> Host;
|
2017-07-26 17:31:12 +02:00
|
|
|
_ -> iolist_to_binary([Host, $:, integer_to_binary(Port)])
|
2016-08-10 11:49:31 +02:00
|
|
|
end,
|
2017-11-30 15:01:01 +01:00
|
|
|
PathWithQs = iolist_to_binary(case Qs of
|
2016-08-10 11:49:31 +02:00
|
|
|
<<>> -> Path;
|
|
|
|
_ -> [Path, $?, Qs]
|
2017-11-30 15:01:01 +01:00
|
|
|
end),
|
2017-07-26 17:31:12 +02:00
|
|
|
%% We need to make sure the header value is binary before we can
|
|
|
|
%% pass it to stream_req_init, as it expects them to be flat.
|
|
|
|
Headers1 = maps:map(fun(_, V) -> iolist_to_binary(V) end, Headers0),
|
|
|
|
Headers = Headers1#{
|
|
|
|
<<":method">> => Method,
|
|
|
|
<<":scheme">> => Scheme,
|
|
|
|
<<":authority">> => Authority,
|
2017-11-30 15:01:01 +01:00
|
|
|
<<":path">> => PathWithQs},
|
2015-06-11 17:04:21 +02:00
|
|
|
{HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
|
|
|
|
Transport:send(Socket, cow_http2:push_promise(StreamID, PromisedStreamID, HeaderBlock)),
|
2017-07-26 17:31:12 +02:00
|
|
|
State = stream_req_init(State0#state{server_streamid=PromisedStreamID + 2,
|
2017-11-29 14:54:47 +01:00
|
|
|
encode_state=EncodeState}, PromisedStreamID, fin, Headers1, #{
|
|
|
|
method => Method,
|
|
|
|
scheme => Scheme,
|
|
|
|
authority => Authority,
|
2017-11-30 15:01:01 +01:00
|
|
|
path => PathWithQs
|
2017-11-29 14:54:47 +01:00
|
|
|
}),
|
2016-06-16 19:46:57 +02:00
|
|
|
commands(State, Stream, Tail);
|
2017-05-19 20:18:00 +02:00
|
|
|
commands(State=#state{socket=Socket, transport=Transport, remote_window=ConnWindow},
|
|
|
|
Stream=#stream{id=StreamID, remote_window=StreamWindow},
|
|
|
|
[{flow, Size}|Tail]) ->
|
|
|
|
Transport:send(Socket, [
|
|
|
|
cow_http2:window_update(Size),
|
|
|
|
cow_http2:window_update(StreamID, Size)
|
|
|
|
]),
|
|
|
|
commands(State#state{remote_window=ConnWindow + Size},
|
|
|
|
Stream#stream{remote_window=StreamWindow + Size}, Tail);
|
2015-06-11 17:04:21 +02:00
|
|
|
%% Supervise a child process.
|
2016-06-16 19:46:57 +02:00
|
|
|
commands(State=#state{children=Children}, Stream=#stream{id=StreamID},
|
2017-08-08 16:59:33 +02:00
|
|
|
[{spawn, Pid, Shutdown}|Tail]) ->
|
|
|
|
commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)},
|
|
|
|
Stream, Tail);
|
2016-06-06 17:28:35 +02:00
|
|
|
%% Error handling.
|
2016-06-16 19:46:57 +02:00
|
|
|
commands(State, Stream=#stream{id=StreamID}, [Error = {internal_error, _, _}|_Tail]) ->
|
|
|
|
%% @todo Do we want to run the commands after an internal_error?
|
|
|
|
%% @todo Do we even allow commands after?
|
2016-06-06 17:28:35 +02:00
|
|
|
%% @todo Only reset when the stream still exists.
|
2016-06-16 19:46:57 +02:00
|
|
|
stream_reset(after_commands(State, Stream), StreamID, Error);
|
2017-04-18 14:06:34 +02:00
|
|
|
%% Upgrade to HTTP/2. This is triggered by cowboy_http2 itself.
|
|
|
|
commands(State=#state{socket=Socket, transport=Transport},
|
|
|
|
Stream=#stream{local=upgrade}, [{switch_protocol, Headers, ?MODULE, _}|Tail]) ->
|
|
|
|
Transport:send(Socket, cow_http:response(101, 'HTTP/1.1', maps:to_list(Headers))),
|
|
|
|
commands(State, Stream#stream{local=idle}, Tail);
|
|
|
|
%% HTTP/2 has no support for the Upgrade mechanism.
|
2017-01-16 14:22:43 +01:00
|
|
|
commands(State, Stream, [{switch_protocol, _Headers, _Mod, _ModState}|Tail]) ->
|
2015-06-11 17:04:21 +02:00
|
|
|
%% @todo This is an error. Not sure what to do here yet.
|
2016-06-16 19:46:57 +02:00
|
|
|
commands(State, Stream, Tail);
|
|
|
|
commands(State, Stream=#stream{id=StreamID}, [stop|_Tail]) ->
|
2016-03-12 18:25:35 +01:00
|
|
|
%% @todo Do we want to run the commands after a stop?
|
2016-06-16 19:46:57 +02:00
|
|
|
%% @todo Do we even allow commands after?
|
|
|
|
stream_terminate(after_commands(State, Stream), StreamID, normal).
|
|
|
|
|
|
|
|
after_commands(State=#state{streams=Streams0}, Stream=#stream{id=StreamID}) ->
|
|
|
|
Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
|
|
|
|
State#state{streams=Streams}.
|
2015-06-11 17:04:21 +02:00
|
|
|
|
2017-12-06 00:30:59 +01:00
|
|
|
send_response(State0, Stream=#stream{method=Method}, StatusCode, Headers0, Body) ->
|
|
|
|
if
|
|
|
|
Method =:= <<"HEAD">>; Body =:= <<>> ->
|
|
|
|
State = send_headers(State0, Stream, StatusCode, Headers0, fin),
|
|
|
|
{State, Stream#stream{local=fin}};
|
|
|
|
true ->
|
|
|
|
State = send_headers(State0, Stream, StatusCode, Headers0, nofin),
|
|
|
|
%% send_data works with both sendfile and iolists.
|
|
|
|
send_data(State, Stream#stream{local=nofin}, fin, Body)
|
|
|
|
end.
|
|
|
|
|
|
|
|
send_headers(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
|
|
|
|
#stream{id=StreamID}, StatusCode, Headers0, IsFin) ->
|
|
|
|
Headers = Headers0#{<<":status">> => status(StatusCode)},
|
|
|
|
{HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
|
|
|
|
Transport:send(Socket, cow_http2:headers(StreamID, IsFin, HeaderBlock)),
|
|
|
|
State#state{encode_state=EncodeState}.
|
|
|
|
|
2016-08-10 11:49:31 +02:00
|
|
|
status(Status) when is_integer(Status) ->
|
|
|
|
integer_to_binary(Status);
|
|
|
|
status(<< H, T, U, _/bits >>) when H >= $1, H =< $9, T >= $0, T =< $9, U >= $0, U =< $9 ->
|
|
|
|
<< H, T, U >>.
|
|
|
|
|
2017-05-19 20:18:00 +02:00
|
|
|
%% @todo Should we ever want to implement the PRIORITY mechanism,
|
|
|
|
%% this would be the place to do it. Right now, we just go over
|
|
|
|
%% all streams and send what we can until either everything is
|
|
|
|
%% sent or we run out of space in the window.
|
|
|
|
send_data(State=#state{streams=Streams}) ->
|
|
|
|
resume_streams(State, Streams, []).
|
|
|
|
|
2017-11-27 22:49:50 +01:00
|
|
|
%% When SETTINGS_INITIAL_WINDOW_SIZE changes we need to update
|
|
|
|
%% the stream windows for all active streams and perhaps resume
|
|
|
|
%% sending data.
|
|
|
|
update_stream_windows(State=#state{streams=Streams0}, Increment) ->
|
|
|
|
Streams = [
|
|
|
|
S#stream{local_window=StreamWindow + Increment}
|
|
|
|
|| S=#stream{local_window=StreamWindow} <- Streams0],
|
|
|
|
resume_streams(State, Streams, []).
|
|
|
|
|
2017-05-19 20:18:00 +02:00
|
|
|
resume_streams(State, [], Acc) ->
|
|
|
|
State#state{streams=lists:reverse(Acc)};
|
|
|
|
%% While technically we should never get < 0 here, let's be on the safe side.
|
|
|
|
resume_streams(State=#state{local_window=ConnWindow}, Streams, Acc)
|
|
|
|
when ConnWindow =< 0 ->
|
|
|
|
State#state{streams=lists:reverse(Acc, Streams)};
|
|
|
|
%% We rely on send_data/2 to do all the necessary checks about the stream.
|
|
|
|
resume_streams(State0, [Stream0|Tail], Acc) ->
|
2017-10-23 14:49:33 +01:00
|
|
|
{State1, Stream} = send_data(State0, Stream0),
|
|
|
|
case Stream of
|
|
|
|
%% We are done flushing, remove the stream.
|
|
|
|
%% Maybe skip the request body if it was not fully read.
|
|
|
|
#stream{state=flush, local=fin} ->
|
|
|
|
State = maybe_skip_body(State1, Stream, normal),
|
|
|
|
resume_streams(State, Tail, Acc);
|
|
|
|
%% Keep the stream. Either the stream handler is still running,
|
|
|
|
%% or we are not finished flushing.
|
|
|
|
_ ->
|
|
|
|
resume_streams(State1, Tail, [Stream|Acc])
|
|
|
|
end.
|
2017-05-19 20:18:00 +02:00
|
|
|
|
2017-11-20 15:46:23 +01:00
|
|
|
send_data(State, Stream=#stream{local=Local, local_buffer_size=0, local_trailers=Trailers})
|
|
|
|
when (Trailers =/= undefined) andalso ((Local =:= idle) orelse (Local =:= nofin)) ->
|
|
|
|
send_trailers(State, Stream#stream{local_trailers=undefined}, Trailers);
|
2017-05-19 20:18:00 +02:00
|
|
|
%% @todo We might want to print an error if local=fin.
|
|
|
|
%%
|
|
|
|
%% @todo It's possible that the stream terminates. We must remove it.
|
|
|
|
send_data(State=#state{local_window=ConnWindow},
|
|
|
|
Stream=#stream{local=IsFin, local_window=StreamWindow, local_buffer_size=BufferSize})
|
|
|
|
when ConnWindow =< 0; IsFin =:= fin; StreamWindow =< 0; BufferSize =:= 0 ->
|
|
|
|
{State, Stream};
|
|
|
|
send_data(State0, Stream0=#stream{local_buffer=Q0, local_buffer_size=BufferSize}) ->
|
|
|
|
%% We know there is an item in the queue.
|
|
|
|
{{value, {IsFin, DataSize, Data}}, Q} = queue:out(Q0),
|
|
|
|
{State, Stream} = send_data(State0,
|
|
|
|
Stream0#stream{local_buffer=Q, local_buffer_size=BufferSize - DataSize},
|
2017-08-21 16:55:30 +02:00
|
|
|
IsFin, Data, in_r),
|
2017-05-19 20:18:00 +02:00
|
|
|
send_data(State, Stream).
|
|
|
|
|
2017-08-21 16:55:30 +02:00
|
|
|
send_data(State, Stream, IsFin, Data) ->
|
|
|
|
send_data(State, Stream, IsFin, Data, in).
|
|
|
|
|
2017-11-20 15:46:23 +01:00
|
|
|
%% We can send trailers immediately if the queue is empty, otherwise we queue.
|
|
|
|
%% We always send trailer frames even if the window is empty.
|
|
|
|
send_data(State, Stream=#stream{local_buffer_size=0}, fin, {trailers, Trailers}, _) ->
|
|
|
|
send_trailers(State, Stream, Trailers);
|
|
|
|
send_data(State, Stream, fin, {trailers, Trailers}, _) ->
|
|
|
|
{State, Stream#stream{local_trailers=Trailers}};
|
2017-05-19 20:18:00 +02:00
|
|
|
%% Send data immediately if we can, buffer otherwise.
|
|
|
|
%% @todo We might want to print an error if local=fin.
|
|
|
|
send_data(State=#state{local_window=ConnWindow},
|
2017-08-21 16:55:30 +02:00
|
|
|
Stream=#stream{local_window=StreamWindow}, IsFin, Data, In)
|
2017-05-19 20:18:00 +02:00
|
|
|
when ConnWindow =< 0; StreamWindow =< 0 ->
|
2017-08-21 16:55:30 +02:00
|
|
|
{State, queue_data(Stream, IsFin, Data, In)};
|
2017-05-19 20:18:00 +02:00
|
|
|
send_data(State=#state{socket=Socket, transport=Transport, local_window=ConnWindow},
|
2017-08-21 16:55:30 +02:00
|
|
|
Stream=#stream{id=StreamID, local_window=StreamWindow}, IsFin, Data, In) ->
|
2017-05-19 20:18:00 +02:00
|
|
|
MaxFrameSize = 16384, %% @todo Use the real SETTINGS_MAX_FRAME_SIZE set by the client.
|
2017-05-31 12:49:21 +02:00
|
|
|
MaxSendSize = min(min(ConnWindow, StreamWindow), MaxFrameSize),
|
2017-05-19 20:18:00 +02:00
|
|
|
case Data of
|
2017-05-31 12:49:21 +02:00
|
|
|
{sendfile, Offset, Bytes, Path} when Bytes =< MaxSendSize ->
|
2017-02-05 13:45:35 +01:00
|
|
|
Transport:send(Socket, cow_http2:data_header(StreamID, IsFin, Bytes)),
|
2017-05-19 20:18:00 +02:00
|
|
|
Transport:sendfile(Socket, Path, Offset, Bytes),
|
2017-05-31 12:49:21 +02:00
|
|
|
{State#state{local_window=ConnWindow - Bytes},
|
|
|
|
Stream#stream{local=IsFin, local_window=StreamWindow - Bytes}};
|
2017-05-19 20:18:00 +02:00
|
|
|
{sendfile, Offset, Bytes, Path} ->
|
2017-05-31 12:49:21 +02:00
|
|
|
Transport:send(Socket, cow_http2:data_header(StreamID, nofin, MaxSendSize)),
|
|
|
|
Transport:sendfile(Socket, Path, Offset, MaxSendSize),
|
|
|
|
send_data(State#state{local_window=ConnWindow - MaxSendSize},
|
|
|
|
Stream#stream{local_window=StreamWindow - MaxSendSize},
|
2017-08-21 16:55:30 +02:00
|
|
|
IsFin, {sendfile, Offset + MaxSendSize, Bytes - MaxSendSize, Path}, In);
|
2017-05-19 20:18:00 +02:00
|
|
|
Iolist0 ->
|
|
|
|
IolistSize = iolist_size(Iolist0),
|
|
|
|
if
|
2017-05-31 12:49:21 +02:00
|
|
|
IolistSize =< MaxSendSize ->
|
2017-05-19 20:18:00 +02:00
|
|
|
Transport:send(Socket, cow_http2:data(StreamID, IsFin, Iolist0)),
|
2017-05-31 12:49:21 +02:00
|
|
|
{State#state{local_window=ConnWindow - IolistSize},
|
|
|
|
Stream#stream{local=IsFin, local_window=StreamWindow - IolistSize}};
|
2017-05-19 20:18:00 +02:00
|
|
|
true ->
|
2017-05-31 12:49:21 +02:00
|
|
|
{Iolist, More} = cowboy_iolists:split(MaxSendSize, Iolist0),
|
2017-05-19 20:18:00 +02:00
|
|
|
Transport:send(Socket, cow_http2:data(StreamID, nofin, Iolist)),
|
2017-05-31 12:49:21 +02:00
|
|
|
send_data(State#state{local_window=ConnWindow - MaxSendSize},
|
|
|
|
Stream#stream{local_window=StreamWindow - MaxSendSize},
|
2017-08-21 16:55:30 +02:00
|
|
|
IsFin, More, In)
|
2017-05-19 20:18:00 +02:00
|
|
|
end
|
2017-02-05 13:45:35 +01:00
|
|
|
end.
|
|
|
|
|
2017-11-20 15:46:23 +01:00
|
|
|
send_trailers(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
|
|
|
|
Stream=#stream{id=StreamID}, Trailers) ->
|
|
|
|
{HeaderBlock, EncodeState} = headers_encode(Trailers, EncodeState0),
|
|
|
|
Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
|
|
|
|
{State#state{encode_state=EncodeState}, Stream#stream{local=fin}}.
|
|
|
|
|
2017-08-21 16:55:30 +02:00
|
|
|
queue_data(Stream=#stream{local_buffer=Q0, local_buffer_size=Size0}, IsFin, Data, In) ->
|
2017-05-19 20:18:00 +02:00
|
|
|
DataSize = case Data of
|
|
|
|
{sendfile, _, Bytes, _} -> Bytes;
|
|
|
|
Iolist -> iolist_size(Iolist)
|
|
|
|
end,
|
2017-08-21 16:55:30 +02:00
|
|
|
Q = queue:In({IsFin, DataSize, Data}, Q0),
|
2017-05-19 20:18:00 +02:00
|
|
|
Stream#stream{local_buffer=Q, local_buffer_size=Size0 + DataSize}.
|
|
|
|
|
2017-11-29 14:54:47 +01:00
|
|
|
%% The set-cookie header is special; we can only send one cookie per header.
|
|
|
|
headers_encode(Headers0=#{<<"set-cookie">> := SetCookies}, EncodeState) ->
|
|
|
|
Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
|
|
|
|
Headers = Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies],
|
|
|
|
cow_hpack:encode(Headers, EncodeState);
|
|
|
|
headers_encode(Headers0, EncodeState) ->
|
|
|
|
Headers = maps:to_list(Headers0),
|
|
|
|
cow_hpack:encode(Headers, EncodeState).
|
|
|
|
|
2017-01-02 18:27:03 +01:00
|
|
|
-spec terminate(#state{}, _) -> no_return().
|
2017-02-25 20:05:31 +01:00
|
|
|
terminate(undefined, Reason) ->
|
|
|
|
exit({shutdown, Reason});
|
2017-11-29 17:49:42 +01:00
|
|
|
terminate(#state{socket=Socket, transport=Transport, parse_state={preface, _, _}}, Reason) ->
|
|
|
|
Transport:close(Socket),
|
|
|
|
exit({shutdown, Reason});
|
2017-02-25 20:05:31 +01:00
|
|
|
terminate(#state{socket=Socket, transport=Transport, client_streamid=LastStreamID,
|
2015-06-11 17:04:21 +02:00
|
|
|
streams=Streams, children=Children}, Reason) ->
|
2017-02-25 20:05:31 +01:00
|
|
|
%% @todo We might want to optionally send the Reason value
|
|
|
|
%% as debug data in the GOAWAY frame here. Perhaps more.
|
|
|
|
Transport:send(Socket, cow_http2:goaway(LastStreamID, terminate_reason(Reason), <<>>)),
|
2017-08-08 16:59:33 +02:00
|
|
|
terminate_all_streams(Streams, Reason),
|
|
|
|
cowboy_children:terminate(Children),
|
2015-06-11 17:04:21 +02:00
|
|
|
Transport:close(Socket),
|
|
|
|
exit({shutdown, Reason}).
|
|
|
|
|
2017-02-25 20:05:31 +01:00
|
|
|
terminate_reason({connection_error, Reason, _}) -> Reason;
|
|
|
|
terminate_reason({stop, _, _}) -> no_error;
|
|
|
|
terminate_reason({socket_error, _, _}) -> internal_error;
|
|
|
|
terminate_reason({internal_error, _, _}) -> internal_error.
|
|
|
|
|
2017-08-08 16:59:33 +02:00
|
|
|
terminate_all_streams([], _) ->
|
2015-06-11 17:04:21 +02:00
|
|
|
ok;
|
2017-05-31 13:20:12 +02:00
|
|
|
%% This stream was already terminated and is now just flushing the data out. Skip it.
|
2017-08-08 16:59:33 +02:00
|
|
|
terminate_all_streams([#stream{state=flush}|Tail], Reason) ->
|
|
|
|
terminate_all_streams(Tail, Reason);
|
|
|
|
terminate_all_streams([#stream{id=StreamID, state=StreamState}|Tail], Reason) ->
|
2017-01-16 14:22:43 +01:00
|
|
|
stream_call_terminate(StreamID, Reason, StreamState),
|
2017-08-08 16:59:33 +02:00
|
|
|
terminate_all_streams(Tail, Reason).
|
2015-06-11 17:04:21 +02:00
|
|
|
|
|
|
|
%% Stream functions.
|
|
|
|
|
2017-11-29 14:54:47 +01:00
|
|
|
stream_decode_init(State=#state{decode_state=DecodeState0}, StreamID, IsFin, HeaderBlock) ->
|
|
|
|
try cow_hpack:decode(HeaderBlock, DecodeState0) of
|
|
|
|
{Headers, DecodeState} ->
|
|
|
|
stream_pseudo_headers_init(State#state{decode_state=DecodeState},
|
|
|
|
StreamID, IsFin, Headers)
|
2015-06-11 17:04:21 +02:00
|
|
|
catch _:_ ->
|
2017-07-26 17:31:12 +02:00
|
|
|
terminate(State, {connection_error, compression_error,
|
2015-06-11 17:04:21 +02:00
|
|
|
'Error while trying to decode HPACK-encoded header block. (RFC7540 4.3)'})
|
|
|
|
end.
|
|
|
|
|
2017-11-29 14:54:47 +01:00
|
|
|
stream_pseudo_headers_init(State, StreamID, IsFin, Headers0) ->
|
|
|
|
case pseudo_headers(Headers0, #{}) of
|
|
|
|
%% @todo Add clause for CONNECT requests (no scheme/path).
|
2017-12-06 10:54:23 +01:00
|
|
|
{ok, PseudoHeaders=#{method := <<"CONNECT">>}, _} ->
|
2017-12-13 12:40:00 +01:00
|
|
|
stream_early_error(State, StreamID, IsFin, 501, PseudoHeaders,
|
2017-12-06 00:30:59 +01:00
|
|
|
'The CONNECT method is currently not implemented. (RFC7231 4.3.6)');
|
2017-12-06 10:54:23 +01:00
|
|
|
{ok, PseudoHeaders=#{method := <<"TRACE">>}, _} ->
|
2017-12-13 12:40:00 +01:00
|
|
|
stream_early_error(State, StreamID, IsFin, 501, PseudoHeaders,
|
2017-12-06 10:54:23 +01:00
|
|
|
'The TRACE method is currently not implemented. (RFC7231 4.3.8)');
|
2017-11-29 14:54:47 +01:00
|
|
|
{ok, PseudoHeaders=#{method := _, scheme := _, authority := _, path := _}, Headers} ->
|
|
|
|
stream_regular_headers_init(State, StreamID, IsFin, Headers, PseudoHeaders);
|
|
|
|
{ok, _, _} ->
|
|
|
|
stream_malformed(State, StreamID,
|
|
|
|
'A required pseudo-header was not found. (RFC7540 8.1.2.3)');
|
|
|
|
{error, HumanReadable} ->
|
|
|
|
stream_malformed(State, StreamID, HumanReadable)
|
|
|
|
end.
|
|
|
|
|
|
|
|
pseudo_headers([{<<":method">>, _}|_], #{method := _}) ->
|
|
|
|
{error, 'Multiple :method pseudo-headers were found. (RFC7540 8.1.2.3)'};
|
|
|
|
pseudo_headers([{<<":method">>, Method}|Tail], PseudoHeaders) ->
|
|
|
|
pseudo_headers(Tail, PseudoHeaders#{method => Method});
|
|
|
|
pseudo_headers([{<<":scheme">>, _}|_], #{scheme := _}) ->
|
|
|
|
{error, 'Multiple :scheme pseudo-headers were found. (RFC7540 8.1.2.3)'};
|
|
|
|
pseudo_headers([{<<":scheme">>, Scheme}|Tail], PseudoHeaders) ->
|
|
|
|
pseudo_headers(Tail, PseudoHeaders#{scheme => Scheme});
|
|
|
|
pseudo_headers([{<<":authority">>, _}|_], #{authority := _}) ->
|
|
|
|
{error, 'Multiple :authority pseudo-headers were found. (RFC7540 8.1.2.3)'};
|
|
|
|
pseudo_headers([{<<":authority">>, Authority}|Tail], PseudoHeaders) ->
|
|
|
|
%% @todo Probably parse the authority here.
|
|
|
|
pseudo_headers(Tail, PseudoHeaders#{authority => Authority});
|
|
|
|
pseudo_headers([{<<":path">>, _}|_], #{path := _}) ->
|
|
|
|
{error, 'Multiple :path pseudo-headers were found. (RFC7540 8.1.2.3)'};
|
|
|
|
pseudo_headers([{<<":path">>, Path}|Tail], PseudoHeaders) ->
|
|
|
|
%% @todo Probably parse the path here.
|
|
|
|
pseudo_headers(Tail, PseudoHeaders#{path => Path});
|
|
|
|
pseudo_headers([{<<":", _/bits>>, _}|_], _) ->
|
|
|
|
{error, 'An unknown or invalid pseudo-header was found. (RFC7540 8.1.2.1)'};
|
|
|
|
pseudo_headers(Headers, PseudoHeaders) ->
|
|
|
|
{ok, PseudoHeaders, Headers}.
|
|
|
|
|
|
|
|
stream_regular_headers_init(State, StreamID, IsFin, Headers, PseudoHeaders) ->
|
|
|
|
case regular_headers(Headers) of
|
|
|
|
ok ->
|
|
|
|
stream_req_init(State, StreamID, IsFin,
|
|
|
|
headers_to_map(Headers, #{}), PseudoHeaders);
|
|
|
|
{error, HumanReadable} ->
|
|
|
|
stream_malformed(State, StreamID, HumanReadable)
|
|
|
|
end.
|
|
|
|
|
|
|
|
regular_headers([{<<":", _/bits>>, _}|_]) ->
|
|
|
|
{error, 'Pseudo-headers were found after regular headers. (RFC7540 8.1.2.1)'};
|
|
|
|
regular_headers([{<<"connection">>, _}|_]) ->
|
|
|
|
{error, 'The connection header is not allowed. (RFC7540 8.1.2.2)'};
|
|
|
|
regular_headers([{<<"keep-alive">>, _}|_]) ->
|
|
|
|
{error, 'The keep-alive header is not allowed. (RFC7540 8.1.2.2)'};
|
|
|
|
regular_headers([{<<"proxy-authenticate">>, _}|_]) ->
|
|
|
|
{error, 'The proxy-authenticate header is not allowed. (RFC7540 8.1.2.2)'};
|
|
|
|
regular_headers([{<<"proxy-authorization">>, _}|_]) ->
|
|
|
|
{error, 'The proxy-authorization header is not allowed. (RFC7540 8.1.2.2)'};
|
|
|
|
regular_headers([{<<"transfer-encoding">>, _}|_]) ->
|
|
|
|
{error, 'The transfer-encoding header is not allowed. (RFC7540 8.1.2.2)'};
|
|
|
|
regular_headers([{<<"upgrade">>, _}|_]) ->
|
|
|
|
{error, 'The upgrade header is not allowed. (RFC7540 8.1.2.2)'};
|
|
|
|
regular_headers([{<<"te">>, Value}|_]) when Value =/= <<"trailers">> ->
|
|
|
|
{error, 'The te header with a value other than "trailers" is not allowed. (RFC7540 8.1.2.2)'};
|
|
|
|
regular_headers([{Name, _}|Tail]) ->
|
|
|
|
case cowboy_bstr:to_lower(Name) of
|
|
|
|
Name -> regular_headers(Tail);
|
|
|
|
_ -> {error, 'Header names must be lowercase. (RFC7540 8.1.2)'}
|
|
|
|
end;
|
|
|
|
regular_headers([]) ->
|
|
|
|
ok.
|
|
|
|
|
|
|
|
%% This function is necessary to properly handle duplicate headers
|
|
|
|
%% and the special-case cookie header.
|
|
|
|
headers_to_map([], Acc) ->
|
|
|
|
Acc;
|
|
|
|
headers_to_map([{Name, Value}|Tail], Acc0) ->
|
|
|
|
Acc = case Acc0 of
|
|
|
|
%% The cookie header does not use proper HTTP header lists.
|
|
|
|
#{Name := Value0} when Name =:= <<"cookie">> -> Acc0#{Name => << Value0/binary, "; ", Value/binary >>};
|
|
|
|
#{Name := Value0} -> Acc0#{Name => << Value0/binary, ", ", Value/binary >>};
|
|
|
|
_ -> Acc0#{Name => Value}
|
|
|
|
end,
|
|
|
|
headers_to_map(Tail, Acc).
|
|
|
|
|
2018-02-28 16:18:29 +01:00
|
|
|
stream_req_init(State, StreamID, IsFin, Headers, PseudoHeaders) ->
|
|
|
|
case Headers of
|
2017-07-26 17:31:12 +02:00
|
|
|
_ when IsFin =:= fin ->
|
2018-02-28 16:18:29 +01:00
|
|
|
stream_req_init(State, StreamID, IsFin, Headers, PseudoHeaders, 0);
|
2017-07-26 17:31:12 +02:00
|
|
|
#{<<"content-length">> := <<"0">>} ->
|
2018-02-28 16:18:29 +01:00
|
|
|
stream_req_init(State, StreamID, IsFin, Headers, PseudoHeaders, 0);
|
2017-07-26 17:31:12 +02:00
|
|
|
#{<<"content-length">> := BinLength} ->
|
|
|
|
try
|
2018-02-28 16:18:29 +01:00
|
|
|
stream_req_init(State, StreamID, IsFin, Headers, PseudoHeaders,
|
|
|
|
cow_http_hd:parse_content_length(BinLength))
|
2017-07-26 17:31:12 +02:00
|
|
|
catch _:_ ->
|
2018-02-28 16:18:29 +01:00
|
|
|
stream_malformed(State, StreamID,
|
|
|
|
'The content-length header is invalid. (RFC7230 3.3.2)')
|
2017-07-26 17:31:12 +02:00
|
|
|
end;
|
|
|
|
_ ->
|
2018-02-28 16:18:29 +01:00
|
|
|
stream_req_init(State, StreamID, IsFin, Headers, PseudoHeaders, undefined)
|
|
|
|
end.
|
|
|
|
|
|
|
|
stream_req_init(State=#state{ref=Ref, peer=Peer, sock=Sock, cert=Cert},
|
|
|
|
StreamID, IsFin, Headers, #{method := Method, scheme := Scheme,
|
|
|
|
authority := Authority, path := PathWithQs}, BodyLength) ->
|
2017-11-29 14:54:47 +01:00
|
|
|
try cow_http_hd:parse_host(Authority) of
|
|
|
|
{Host, Port} ->
|
|
|
|
try cow_http:parse_fullpath(PathWithQs) of
|
|
|
|
{<<>>, _} ->
|
|
|
|
stream_malformed(State, StreamID,
|
|
|
|
'The path component must not be empty. (RFC7540 8.1.2.3)');
|
|
|
|
{Path, Qs} ->
|
|
|
|
Req = #{
|
|
|
|
ref => Ref,
|
|
|
|
pid => self(),
|
|
|
|
streamid => StreamID,
|
|
|
|
peer => Peer,
|
|
|
|
sock => Sock,
|
|
|
|
cert => Cert,
|
|
|
|
method => Method,
|
|
|
|
scheme => Scheme,
|
|
|
|
host => Host,
|
|
|
|
port => Port,
|
|
|
|
path => Path,
|
|
|
|
qs => Qs,
|
|
|
|
version => 'HTTP/2',
|
|
|
|
headers => Headers,
|
|
|
|
has_body => IsFin =:= nofin,
|
|
|
|
body_length => BodyLength
|
|
|
|
},
|
|
|
|
stream_handler_init(State, StreamID, IsFin, idle, Req)
|
|
|
|
catch _:_ ->
|
|
|
|
stream_malformed(State, StreamID,
|
|
|
|
'The :path pseudo-header is invalid. (RFC7540 8.1.2.3)')
|
|
|
|
end
|
|
|
|
catch _:_ ->
|
|
|
|
stream_malformed(State, StreamID,
|
|
|
|
'The :authority pseudo-header is invalid. (RFC7540 8.1.2.3)')
|
|
|
|
end.
|
|
|
|
|
|
|
|
stream_malformed(State=#state{socket=Socket, transport=Transport}, StreamID, _) ->
|
|
|
|
Transport:send(Socket, cow_http2:rst_stream(StreamID, protocol_error)),
|
|
|
|
State.
|
2017-07-26 17:31:12 +02:00
|
|
|
|
2017-12-13 12:40:00 +01:00
|
|
|
stream_early_error(State0=#state{ref=Ref, opts=Opts, peer=Peer,
|
|
|
|
local_settings=#{initial_window_size := RemoteWindow},
|
|
|
|
remote_settings=#{initial_window_size := LocalWindow},
|
|
|
|
streams=Streams}, StreamID, IsFin, StatusCode0,
|
|
|
|
#{method := Method}, HumanReadable) ->
|
2017-12-06 00:30:59 +01:00
|
|
|
%% We automatically terminate the stream but it is not an error
|
|
|
|
%% per se (at least not in the first implementation).
|
|
|
|
Reason = {stream_error, no_error, HumanReadable},
|
|
|
|
%% The partial Req is minimal for now. We only have one case
|
|
|
|
%% where it can be called (when a method is completely disabled).
|
|
|
|
PartialReq = #{
|
|
|
|
ref => Ref,
|
|
|
|
peer => Peer,
|
|
|
|
method => Method
|
|
|
|
},
|
|
|
|
Resp = {response, StatusCode0, RespHeaders0=#{<<"content-length">> => <<"0">>}, <<>>},
|
|
|
|
%% We need a stream to talk to the send_* functions.
|
2017-12-13 12:40:00 +01:00
|
|
|
Stream0 = #stream{id=StreamID, state=flush, method=Method,
|
|
|
|
remote=IsFin, local=idle,
|
|
|
|
local_window=LocalWindow, remote_window=RemoteWindow},
|
2017-12-06 00:30:59 +01:00
|
|
|
try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts) of
|
|
|
|
{response, StatusCode, RespHeaders, RespBody} ->
|
|
|
|
case send_response(State0, Stream0, StatusCode, RespHeaders, RespBody) of
|
|
|
|
{State, #stream{local=fin}} ->
|
|
|
|
State;
|
|
|
|
{State, Stream} ->
|
|
|
|
State#state{streams=[Stream|Streams]}
|
|
|
|
end
|
|
|
|
catch Class:Exception ->
|
|
|
|
cowboy_stream:report_error(early_error,
|
|
|
|
[StreamID, Reason, PartialReq, Resp, Opts],
|
|
|
|
Class, Exception, erlang:get_stacktrace()),
|
|
|
|
%% We still need to send an error response, so send what we initially
|
|
|
|
%% wanted to send. It's better than nothing.
|
|
|
|
send_headers(State0, Stream0, StatusCode0, RespHeaders0, fin)
|
|
|
|
end.
|
|
|
|
|
2017-05-19 20:18:00 +02:00
|
|
|
stream_handler_init(State=#state{opts=Opts,
|
|
|
|
local_settings=#{initial_window_size := RemoteWindow},
|
|
|
|
remote_settings=#{initial_window_size := LocalWindow}},
|
2017-12-04 18:21:10 +01:00
|
|
|
StreamID, RemoteIsFin, LocalIsFin,
|
|
|
|
Req=#{method := Method, headers := Headers}) ->
|
2017-01-16 14:22:43 +01:00
|
|
|
try cowboy_stream:init(StreamID, Req, Opts) of
|
2016-03-12 18:25:35 +01:00
|
|
|
{Commands, StreamState} ->
|
2017-02-25 20:05:31 +01:00
|
|
|
commands(State#state{client_streamid=StreamID},
|
2017-04-18 14:06:34 +02:00
|
|
|
#stream{id=StreamID, state=StreamState,
|
2017-12-04 18:21:10 +01:00
|
|
|
method=Method, remote=RemoteIsFin, local=LocalIsFin,
|
2017-11-15 14:58:49 +01:00
|
|
|
local_window=LocalWindow, remote_window=RemoteWindow,
|
|
|
|
te=maps:get(<<"te">>, Headers, undefined)},
|
2017-05-19 20:18:00 +02:00
|
|
|
Commands)
|
2017-09-21 12:53:21 +02:00
|
|
|
catch Class:Exception ->
|
|
|
|
cowboy_stream:report_error(init,
|
|
|
|
[StreamID, Req, Opts],
|
|
|
|
Class, Exception, erlang:get_stacktrace()),
|
|
|
|
stream_reset(State, StreamID, {internal_error, {Class, Exception},
|
2017-09-27 14:17:27 +02:00
|
|
|
'Unhandled exception in cowboy_stream:init/3.'})
|
2016-03-12 18:25:35 +01:00
|
|
|
end.
|
|
|
|
|
2017-10-23 14:49:33 +01:00
|
|
|
%% @todo Don't send an RST_STREAM if one was already sent.
|
|
|
|
stream_reset(State=#state{socket=Socket, transport=Transport}, StreamID, StreamError) ->
|
|
|
|
Reason = case StreamError of
|
|
|
|
{internal_error, _, _} -> internal_error;
|
|
|
|
{stream_error, Reason0, _} -> Reason0
|
|
|
|
end,
|
2015-06-11 17:04:21 +02:00
|
|
|
Transport:send(Socket, cow_http2:rst_stream(StreamID, Reason)),
|
2017-10-23 14:49:33 +01:00
|
|
|
stream_terminate(stream_linger(State, StreamID), StreamID, StreamError).
|
2015-06-11 17:04:21 +02:00
|
|
|
|
2017-10-23 14:49:33 +01:00
|
|
|
%% We only keep up to 100 streams in this state. @todo Make it configurable?
|
|
|
|
stream_linger(State=#state{lingering_streams=Lingering0}, StreamID) ->
|
|
|
|
Lingering = [StreamID|lists:sublist(Lingering0, 100 - 1)],
|
|
|
|
State#state{lingering_streams=Lingering}.
|
|
|
|
|
2017-11-01 15:33:10 +00:00
|
|
|
stream_terminate(State0=#state{streams=Streams0, children=Children0}, StreamID, Reason) ->
|
2015-06-11 17:04:21 +02:00
|
|
|
case lists:keytake(StreamID, #stream.id, Streams0) of
|
2017-04-18 16:07:01 +02:00
|
|
|
%% When the stream terminates normally (without sending RST_STREAM)
|
|
|
|
%% and no response was sent, we need to send a proper response back to the client.
|
2017-10-23 14:49:33 +01:00
|
|
|
{value, Stream=#stream{local=idle}, Streams} when Reason =:= normal ->
|
|
|
|
State1 = #state{streams=Streams1} = info(State0, StreamID, {response, 204, #{}, <<>>}),
|
|
|
|
State = maybe_skip_body(State1, Stream, Reason),
|
2017-10-21 13:09:20 +01:00
|
|
|
#stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams1),
|
2017-01-16 14:22:43 +01:00
|
|
|
stream_call_terminate(StreamID, Reason, StreamState),
|
2017-08-08 16:59:33 +02:00
|
|
|
Children = cowboy_children:shutdown(Children0, StreamID),
|
2017-10-23 14:49:33 +01:00
|
|
|
State#state{streams=Streams, children=Children};
|
2017-04-18 16:07:01 +02:00
|
|
|
%% When a response was sent but not terminated, we need to close the stream.
|
2017-11-01 15:33:10 +00:00
|
|
|
{value, Stream=#stream{local=nofin, local_buffer_size=0}, Streams}
|
2017-05-19 20:18:00 +02:00
|
|
|
when Reason =:= normal ->
|
2017-11-01 15:33:10 +00:00
|
|
|
State1 = #state{streams=Streams1} = info(State0, StreamID, {data, fin, <<>>}),
|
|
|
|
State = maybe_skip_body(State1, Stream, Reason),
|
|
|
|
#stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams1),
|
2017-01-16 14:22:43 +01:00
|
|
|
stream_call_terminate(StreamID, Reason, StreamState),
|
2017-08-08 16:59:33 +02:00
|
|
|
Children = cowboy_children:shutdown(Children0, StreamID),
|
2016-06-13 16:00:17 +02:00
|
|
|
State#state{streams=Streams, children=Children};
|
2017-05-19 20:18:00 +02:00
|
|
|
%% Unless there is still data in the buffer. We can however reset
|
|
|
|
%% a few fields and set a special local state to avoid confusion.
|
2017-10-23 14:49:33 +01:00
|
|
|
%%
|
|
|
|
%% We do not reset the stream in this case (to skip the body)
|
|
|
|
%% because we are still sending data via the buffer. We will
|
|
|
|
%% reset the stream if necessary once the buffer is empty.
|
2017-05-19 20:18:00 +02:00
|
|
|
{value, Stream=#stream{state=StreamState, local=nofin}, Streams} ->
|
|
|
|
stream_call_terminate(StreamID, Reason, StreamState),
|
2017-08-08 16:59:33 +02:00
|
|
|
Children = cowboy_children:shutdown(Children0, StreamID),
|
2017-10-23 14:49:33 +01:00
|
|
|
State0#state{streams=[Stream#stream{state=flush, local=flush}|Streams],
|
2017-05-19 20:18:00 +02:00
|
|
|
children=Children};
|
2017-11-27 13:42:04 +01:00
|
|
|
%% Otherwise we sent or received an RST_STREAM and/or the stream is already closed.
|
2017-10-23 14:49:33 +01:00
|
|
|
{value, Stream=#stream{state=StreamState}, Streams} ->
|
|
|
|
State = maybe_skip_body(State0, Stream, Reason),
|
2017-01-16 14:22:43 +01:00
|
|
|
stream_call_terminate(StreamID, Reason, StreamState),
|
2017-08-08 16:59:33 +02:00
|
|
|
Children = cowboy_children:shutdown(Children0, StreamID),
|
2015-06-11 17:04:21 +02:00
|
|
|
State#state{streams=Streams, children=Children};
|
2017-09-27 14:17:27 +02:00
|
|
|
%% The stream doesn't exist. This can occur for various reasons.
|
|
|
|
%% It can happen before the stream has been created, or because
|
|
|
|
%% the cowboy_stream:init call failed, in which case doing nothing
|
|
|
|
%% is correct.
|
2015-06-11 17:04:21 +02:00
|
|
|
false ->
|
2017-10-23 14:49:33 +01:00
|
|
|
State0
|
2015-06-11 17:04:21 +02:00
|
|
|
end.
|
|
|
|
|
2017-10-23 14:49:33 +01:00
|
|
|
%% When the stream stops normally without reading the request
|
|
|
|
%% body fully we need to tell the client to stop sending it.
|
|
|
|
%% We do this by sending an RST_STREAM with reason NO_ERROR. (RFC7540 8.1.0)
|
|
|
|
maybe_skip_body(State=#state{socket=Socket, transport=Transport},
|
|
|
|
#stream{id=StreamID, remote=nofin}, normal) ->
|
|
|
|
Transport:send(Socket, cow_http2:rst_stream(StreamID, no_error)),
|
|
|
|
stream_linger(State, StreamID);
|
|
|
|
maybe_skip_body(State, _, _) ->
|
|
|
|
State.
|
|
|
|
|
2017-01-16 14:22:43 +01:00
|
|
|
stream_call_terminate(StreamID, Reason, StreamState) ->
|
2015-06-11 17:04:21 +02:00
|
|
|
try
|
2017-01-16 14:22:43 +01:00
|
|
|
cowboy_stream:terminate(StreamID, Reason, StreamState)
|
2017-09-21 12:53:21 +02:00
|
|
|
catch Class:Exception ->
|
|
|
|
cowboy_stream:report_error(terminate,
|
|
|
|
[StreamID, Reason, StreamState],
|
|
|
|
Class, Exception, erlang:get_stacktrace())
|
2015-06-11 17:04:21 +02:00
|
|
|
end.
|
|
|
|
|
|
|
|
%% System callbacks.
|
|
|
|
|
2017-01-02 18:27:03 +01:00
|
|
|
-spec system_continue(_, _, {#state{}, binary()}) -> ok.
|
2015-06-11 17:04:21 +02:00
|
|
|
system_continue(_, _, {State, Buffer}) ->
|
|
|
|
loop(State, Buffer).
|
|
|
|
|
2017-08-08 16:59:33 +02:00
|
|
|
-spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return().
|
|
|
|
system_terminate(Reason, _, _, {State, _}) ->
|
2018-03-13 11:19:13 +01:00
|
|
|
%% @todo We should exit gracefully, if possible.
|
2017-08-08 16:59:33 +02:00
|
|
|
terminate(State, Reason).
|
2015-06-11 17:04:21 +02:00
|
|
|
|
|
|
|
-spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
|
|
|
|
system_code_change(Misc, _, _, _) ->
|
|
|
|
{ok, Misc}.
|