cowboy_http2.erl 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  1. %% Copyright (c) 2015-2017, Loïc Hoguin <essen@ninenines.eu>
  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. -module(cowboy_http2).
  15. -export([init/5]).
  16. -export([init/9]).
  17. -export([init/11]).
  18. -export([system_continue/3]).
  19. -export([system_terminate/4]).
  20. -export([system_code_change/4]).
  21. -type opts() :: #{
  22. connection_type => worker | supervisor,
  23. env => cowboy_middleware:env(),
  24. inactivity_timeout => timeout(),
  25. middlewares => [module()],
  26. preface_timeout => timeout(),
  27. shutdown_timeout => timeout(),
  28. stream_handlers => [module()]
  29. }.
  30. -export_type([opts/0]).
  31. -record(stream, {
  32. id = undefined :: cowboy_stream:streamid(),
  33. %% Stream handlers and their state.
  34. state = undefined :: {module(), any()} | flush,
  35. %% Whether we finished sending data.
  36. local = idle :: idle | upgrade | cowboy_stream:fin() | flush,
  37. %% Local flow control window (how much we can send).
  38. local_window :: integer(),
  39. %% Buffered data waiting for the flow control window to increase.
  40. local_buffer = queue:new() :: queue:queue(
  41. {cowboy_stream:fin(), non_neg_integer(), iolist()
  42. | {sendfile, non_neg_integer(), pos_integer(), file:name_all()}}),
  43. local_buffer_size = 0 :: non_neg_integer(),
  44. local_trailers = undefined :: undefined | cowboy:http_headers(),
  45. %% Whether we finished receiving data.
  46. remote = nofin :: cowboy_stream:fin(),
  47. %% Remote flow control window (how much we accept to receive).
  48. remote_window :: integer(),
  49. %% Unparsed te header. Used to know if we can send trailers.
  50. te :: undefined | binary()
  51. }).
  52. -type stream() :: #stream{}.
  53. -record(state, {
  54. parent = undefined :: pid(),
  55. ref :: ranch:ref(),
  56. socket = undefined :: inet:socket(),
  57. transport :: module(),
  58. opts = #{} :: opts(),
  59. %% Remote address and port for the connection.
  60. peer = undefined :: {inet:ip_address(), inet:port_number()},
  61. %% Local address and port for the connection.
  62. sock = undefined :: {inet:ip_address(), inet:port_number()},
  63. %% Client certificate (TLS only).
  64. cert :: undefined | binary(),
  65. %% Settings are separate for each endpoint. In addition, settings
  66. %% must be acknowledged before they can be expected to be applied.
  67. %%
  68. %% @todo Since the ack is required, we must timeout if we don't receive it.
  69. %% @todo I haven't put as much thought as I should have on this,
  70. %% the final settings handling will be very different.
  71. local_settings = #{
  72. % header_table_size => 4096,
  73. % enable_push => false, %% We are the server. Push is never enabled.
  74. % max_concurrent_streams => infinity,
  75. initial_window_size => 65535,
  76. max_frame_size => 16384
  77. % max_header_list_size => infinity
  78. } :: map(),
  79. %% @todo We need a TimerRef to do SETTINGS_TIMEOUT errors.
  80. %% We need to be careful there. It's well possible that we send
  81. %% two SETTINGS frames before we receive a SETTINGS ack.
  82. next_settings = #{} :: undefined | map(), %% @todo perhaps set to undefined by default
  83. remote_settings = #{
  84. initial_window_size => 65535
  85. } :: map(),
  86. %% Connection-wide flow control window.
  87. local_window = 65535 :: integer(), %% How much we can send.
  88. remote_window = 65535 :: integer(), %% How much we accept to receive.
  89. %% Stream identifiers.
  90. client_streamid = 0 :: non_neg_integer(),
  91. server_streamid = 2 :: pos_integer(),
  92. %% Currently active HTTP/2 streams. Streams may be initiated either
  93. %% by the client or by the server through PUSH_PROMISE frames.
  94. streams = [] :: [stream()],
  95. %% HTTP/2 streams that have been reset recently. We are expected
  96. %% to keep receiving additional frames after sending an RST_STREAM.
  97. lingering_streams = [] :: [cowboy_stream:streamid()],
  98. %% Streams can spawn zero or more children which are then managed
  99. %% by this module if operating as a supervisor.
  100. children = cowboy_children:init() :: cowboy_children:children(),
  101. %% The client starts by sending a sequence of bytes as a preface,
  102. %% followed by a potentially empty SETTINGS frame. Then the connection
  103. %% is established and continues normally. An exception is when a HEADERS
  104. %% frame is sent followed by CONTINUATION frames: no other frame can be
  105. %% sent in between.
  106. parse_state = undefined :: {preface, sequence, reference()}
  107. | {preface, settings, reference()}
  108. | normal
  109. | {continuation, cowboy_stream:streamid(), cowboy_stream:fin(), binary()},
  110. %% HPACK decoding and encoding state.
  111. decode_state = cow_hpack:init() :: cow_hpack:state(),
  112. encode_state = cow_hpack:init() :: cow_hpack:state()
  113. }).
  114. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts()) -> ok.
  115. init(Parent, Ref, Socket, Transport, Opts) ->
  116. Peer0 = Transport:peername(Socket),
  117. Sock0 = Transport:sockname(Socket),
  118. Cert1 = case Transport:name() of
  119. ssl ->
  120. case ssl:peercert(Socket) of
  121. {error, no_peercert} ->
  122. {ok, undefined};
  123. Cert0 ->
  124. Cert0
  125. end;
  126. _ ->
  127. {ok, undefined}
  128. end,
  129. case {Peer0, Sock0, Cert1} of
  130. {{ok, Peer}, {ok, Sock}, {ok, Cert}} ->
  131. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, <<>>);
  132. {{error, Reason}, _, _} ->
  133. terminate(undefined, {socket_error, Reason,
  134. 'A socket error occurred when retrieving the peer name.'});
  135. {_, {error, Reason}, _} ->
  136. terminate(undefined, {socket_error, Reason,
  137. 'A socket error occurred when retrieving the sock name.'});
  138. {_, _, {error, Reason}} ->
  139. terminate(undefined, {socket_error, Reason,
  140. 'A socket error occurred when retrieving the client TLS certificate.'})
  141. end.
  142. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  143. {inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()},
  144. binary() | undefined, binary()) -> ok.
  145. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, Buffer) ->
  146. State = #state{parent=Parent, ref=Ref, socket=Socket,
  147. transport=Transport, opts=Opts, peer=Peer, sock=Sock, cert=Cert,
  148. parse_state={preface, sequence, preface_timeout(Opts)}},
  149. preface(State),
  150. case Buffer of
  151. <<>> -> before_loop(State, Buffer);
  152. _ -> parse(State, Buffer)
  153. end.
  154. %% @todo Add an argument for the request body.
  155. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  156. {inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()},
  157. binary() | undefined, binary(), map() | undefined, cowboy_req:req()) -> ok.
  158. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, Buffer, _Settings, Req) ->
  159. State0 = #state{parent=Parent, ref=Ref, socket=Socket,
  160. transport=Transport, opts=Opts, peer=Peer, sock=Sock, cert=Cert,
  161. parse_state={preface, sequence, preface_timeout(Opts)}},
  162. %% @todo Apply settings.
  163. %% StreamID from HTTP/1.1 Upgrade requests is always 1.
  164. %% The stream is always in the half-closed (remote) state.
  165. State1 = stream_handler_init(State0, 1, fin, upgrade, Req),
  166. %% We assume that the upgrade will be applied. A stream handler
  167. %% must not prevent the normal operations of the server.
  168. State = info(State1, 1, {switch_protocol, #{
  169. <<"connection">> => <<"Upgrade">>,
  170. <<"upgrade">> => <<"h2c">>
  171. }, ?MODULE, undefined}), %% @todo undefined or #{}?
  172. preface(State),
  173. case Buffer of
  174. <<>> -> before_loop(State, Buffer);
  175. _ -> parse(State, Buffer)
  176. end.
  177. preface(#state{socket=Socket, transport=Transport, next_settings=Settings}) ->
  178. %% We send next_settings and use defaults until we get a ack.
  179. ok = Transport:send(Socket, cow_http2:settings(Settings)).
  180. preface_timeout(Opts) ->
  181. PrefaceTimeout = maps:get(preface_timeout, Opts, 5000),
  182. erlang:start_timer(PrefaceTimeout, self(), preface_timeout).
  183. %% @todo Add the timeout for last time since we heard of connection.
  184. before_loop(State, Buffer) ->
  185. loop(State, Buffer).
  186. loop(State=#state{parent=Parent, socket=Socket, transport=Transport,
  187. opts=Opts, children=Children, parse_state=PS}, Buffer) ->
  188. Transport:setopts(Socket, [{active, once}]),
  189. {OK, Closed, Error} = Transport:messages(),
  190. InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000),
  191. receive
  192. %% Socket messages.
  193. {OK, Socket, Data} ->
  194. parse(State, << Buffer/binary, Data/binary >>);
  195. {Closed, Socket} ->
  196. terminate(State, {socket_error, closed, 'The socket has been closed.'});
  197. {Error, Socket, Reason} ->
  198. terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'});
  199. %% System messages.
  200. {'EXIT', Parent, Reason} ->
  201. exit(Reason);
  202. {system, From, Request} ->
  203. sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer});
  204. %% Timeouts.
  205. {timeout, Ref, {shutdown, Pid}} ->
  206. cowboy_children:shutdown_timeout(Children, Ref, Pid),
  207. loop(State, Buffer);
  208. {timeout, TRef, preface_timeout} ->
  209. case PS of
  210. {preface, _, TRef} ->
  211. terminate(State, {connection_error, protocol_error,
  212. 'The preface was not received in a reasonable amount of time.'});
  213. _ ->
  214. loop(State, Buffer)
  215. end;
  216. %% Messages pertaining to a stream.
  217. {{Pid, StreamID}, Msg} when Pid =:= self() ->
  218. loop(info(State, StreamID, Msg), Buffer);
  219. %% Exit signal from children.
  220. Msg = {'EXIT', Pid, _} ->
  221. loop(down(State, Pid, Msg), Buffer);
  222. %% Calls from supervisor module.
  223. {'$gen_call', {From, Tag}, which_children} ->
  224. From ! {Tag, cowboy_children:which_children(Children, ?MODULE)},
  225. loop(State, Buffer);
  226. {'$gen_call', {From, Tag}, count_children} ->
  227. From ! {Tag, cowboy_children:count_children(Children)},
  228. loop(State, Buffer);
  229. {'$gen_call', {From, Tag}, _} ->
  230. From ! {Tag, {error, ?MODULE}},
  231. loop(State, Buffer);
  232. Msg ->
  233. error_logger:error_msg("Received stray message ~p.", [Msg]),
  234. loop(State, Buffer)
  235. after InactivityTimeout ->
  236. terminate(State, {internal_error, timeout, 'No message or data received before timeout.'})
  237. end.
  238. parse(State=#state{socket=Socket, transport=Transport, parse_state={preface, sequence, TRef}}, Data) ->
  239. case Data of
  240. << "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n", Rest/bits >> ->
  241. parse(State#state{parse_state={preface, settings, TRef}}, Rest);
  242. _ when byte_size(Data) >= 24 ->
  243. Transport:close(Socket),
  244. exit({shutdown, {connection_error, protocol_error,
  245. 'The connection preface was invalid. (RFC7540 3.5)'}});
  246. _ ->
  247. Len = byte_size(Data),
  248. << Preface:Len/binary, _/bits >> = <<"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n">>,
  249. case Data of
  250. Preface ->
  251. %% @todo OK we should have a timeout when waiting for the preface.
  252. before_loop(State, Data);
  253. _ ->
  254. Transport:close(Socket),
  255. exit({shutdown, {connection_error, protocol_error,
  256. 'The connection preface was invalid. (RFC7540 3.5)'}})
  257. end
  258. end;
  259. %% @todo Perhaps instead of just more we can have {more, Len} to avoid all the checks.
  260. parse(State=#state{local_settings=#{max_frame_size := MaxFrameSize},
  261. parse_state=ParseState}, Data) ->
  262. case cow_http2:parse(Data, MaxFrameSize) of
  263. {ok, Frame, Rest} ->
  264. case ParseState of
  265. normal ->
  266. parse(frame(State, Frame), Rest);
  267. {preface, settings, TRef} ->
  268. parse_settings_preface(State, Frame, Rest, TRef);
  269. {continuation, _, _, _} ->
  270. parse(continuation_frame(State, Frame), Rest)
  271. end;
  272. {ignore, Rest} ->
  273. parse(State, Rest);
  274. {stream_error, StreamID, Reason, Human, Rest} ->
  275. parse(stream_reset(State, StreamID, {stream_error, Reason, Human}), Rest);
  276. Error = {connection_error, _, _} ->
  277. terminate(State, Error);
  278. more ->
  279. before_loop(State, Data)
  280. end.
  281. parse_settings_preface(State, Frame={settings, _}, Rest, TRef) ->
  282. _ = erlang:cancel_timer(TRef, [{async, true}, {info, false}]),
  283. parse(frame(State#state{parse_state=normal}, Frame), Rest);
  284. parse_settings_preface(State, _, _, _) ->
  285. terminate(State, {connection_error, protocol_error,
  286. 'The preface sequence must be followed by a SETTINGS frame. (RFC7540 3.5)'}).
  287. %% @todo When we get a 'fin' we need to check if the stream had a 'fin' sent back
  288. %% and terminate the stream if this is the end of it.
  289. %% DATA frame.
  290. frame(State=#state{client_streamid=LastStreamID}, {data, StreamID, _, _})
  291. when StreamID > LastStreamID ->
  292. terminate(State, {connection_error, protocol_error,
  293. 'DATA frame received on a stream in idle state. (RFC7540 5.1)'});
  294. frame(State0=#state{remote_window=ConnWindow, streams=Streams, lingering_streams=Lingering},
  295. {data, StreamID, IsFin, Data}) ->
  296. DataLen = byte_size(Data),
  297. State = State0#state{remote_window=ConnWindow - DataLen},
  298. case lists:keyfind(StreamID, #stream.id, Streams) of
  299. Stream = #stream{state=flush, remote=nofin, remote_window=StreamWindow} ->
  300. after_commands(State, Stream#stream{remote=IsFin, remote_window=StreamWindow - DataLen});
  301. Stream = #stream{state=StreamState0, remote=nofin, remote_window=StreamWindow} ->
  302. try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
  303. {Commands, StreamState} ->
  304. commands(State, Stream#stream{state=StreamState, remote=IsFin,
  305. remote_window=StreamWindow - DataLen}, Commands)
  306. catch Class:Exception ->
  307. cowboy_stream:report_error(data,
  308. [StreamID, IsFin, Data, StreamState0],
  309. Class, Exception, erlang:get_stacktrace()),
  310. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  311. 'Unhandled exception in cowboy_stream:data/4.'})
  312. end;
  313. #stream{remote=fin} ->
  314. stream_reset(State, StreamID, {stream_error, stream_closed,
  315. 'DATA frame received for a half-closed (remote) stream. (RFC7540 5.1)'});
  316. false ->
  317. %% After we send an RST_STREAM frame and terminate a stream,
  318. %% the client still might be sending us some more frames
  319. %% until it can process this RST_STREAM. We therefore ignore
  320. %% DATA frames received for such lingering streams.
  321. case lists:member(StreamID, Lingering) of
  322. true ->
  323. State0;
  324. false ->
  325. terminate(State, {connection_error, stream_closed,
  326. 'DATA frame received for a closed stream. (RFC7540 5.1)'})
  327. end
  328. end;
  329. %% HEADERS frame with invalid even-numbered streamid.
  330. frame(State, {headers, StreamID, _, _, _}) when StreamID rem 2 =:= 0 ->
  331. terminate(State, {connection_error, protocol_error,
  332. 'HEADERS frame received with even-numbered streamid. (RFC7540 5.1.1)'});
  333. %% HEADERS frame received on (half-)closed stream.
  334. frame(State=#state{client_streamid=LastStreamID}, {headers, StreamID, _, _, _})
  335. when StreamID =< LastStreamID ->
  336. stream_reset(State, StreamID, {stream_error, stream_closed,
  337. 'HEADERS frame received on a stream in closed or half-closed state. (RFC7540 5.1)'});
  338. %% Single HEADERS frame headers block.
  339. frame(State, {headers, StreamID, IsFin, head_fin, HeaderBlock}) ->
  340. %% @todo We probably need to validate StreamID here and in 4 next clauses.
  341. stream_decode_init(State, StreamID, IsFin, HeaderBlock);
  342. %% HEADERS frame starting a headers block. Enter continuation mode.
  343. frame(State, {headers, StreamID, IsFin, head_nofin, HeaderBlockFragment}) ->
  344. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
  345. %% Single HEADERS frame headers block with priority.
  346. frame(State, {headers, StreamID, IsFin, head_fin,
  347. _IsExclusive, _DepStreamID, _Weight, HeaderBlock}) ->
  348. %% @todo Handle priority.
  349. stream_decode_init(State, StreamID, IsFin, HeaderBlock);
  350. %% HEADERS frame starting a headers block. Enter continuation mode.
  351. frame(State, {headers, StreamID, IsFin, head_nofin,
  352. _IsExclusive, _DepStreamID, _Weight, HeaderBlockFragment}) ->
  353. %% @todo Handle priority.
  354. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
  355. %% PRIORITY frame.
  356. frame(State, {priority, _StreamID, _IsExclusive, _DepStreamID, _Weight}) ->
  357. %% @todo Validate StreamID?
  358. %% @todo Handle priority.
  359. State;
  360. %% RST_STREAM frame.
  361. frame(State=#state{client_streamid=LastStreamID}, {rst_stream, StreamID, _})
  362. when StreamID > LastStreamID ->
  363. terminate(State, {connection_error, protocol_error,
  364. 'RST_STREAM frame received on a stream in idle state. (RFC7540 5.1)'});
  365. frame(State, {rst_stream, StreamID, Reason}) ->
  366. stream_terminate(State, StreamID, {stream_error, Reason, 'Stream reset requested by client.'});
  367. %% SETTINGS frame.
  368. frame(State=#state{socket=Socket, transport=Transport, remote_settings=Settings0},
  369. {settings, Settings}) ->
  370. Transport:send(Socket, cow_http2:settings_ack()),
  371. State#state{remote_settings=maps:merge(Settings0, Settings)};
  372. %% Ack for a previously sent SETTINGS frame.
  373. frame(State=#state{next_settings=_NextSettings}, settings_ack) ->
  374. %% @todo Apply SETTINGS that require synchronization.
  375. State;
  376. %% Unexpected PUSH_PROMISE frame.
  377. frame(State, {push_promise, _, _, _, _}) ->
  378. terminate(State, {connection_error, protocol_error,
  379. 'PUSH_PROMISE frames MUST only be sent on a peer-initiated stream. (RFC7540 6.6)'});
  380. %% PING frame.
  381. frame(State=#state{socket=Socket, transport=Transport}, {ping, Opaque}) ->
  382. Transport:send(Socket, cow_http2:ping_ack(Opaque)),
  383. State;
  384. %% Ack for a previously sent PING frame.
  385. %%
  386. %% @todo Might want to check contents but probably a waste of time.
  387. frame(State, {ping_ack, _Opaque}) ->
  388. State;
  389. %% GOAWAY frame.
  390. frame(State, Frame={goaway, _, _, _}) ->
  391. terminate(State, {stop, Frame, 'Client is going away.'});
  392. %% Connection-wide WINDOW_UPDATE frame.
  393. frame(State=#state{local_window=ConnWindow}, {window_update, Increment}) ->
  394. send_data(State#state{local_window=ConnWindow + Increment});
  395. %% Stream-specific WINDOW_UPDATE frame.
  396. frame(State=#state{client_streamid=LastStreamID}, {window_update, StreamID, _})
  397. when StreamID > LastStreamID ->
  398. terminate(State, {connection_error, protocol_error,
  399. 'WINDOW_UPDATE frame received on a stream in idle state. (RFC7540 5.1)'});
  400. frame(State0=#state{streams=Streams0}, {window_update, StreamID, Increment}) ->
  401. case lists:keyfind(StreamID, #stream.id, Streams0) of
  402. Stream0 = #stream{local_window=StreamWindow} ->
  403. {State, Stream} = send_data(State0,
  404. Stream0#stream{local_window=StreamWindow + Increment}),
  405. Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
  406. State#state{streams=Streams};
  407. %% @todo We must reject WINDOW_UPDATE frames on RST_STREAM closed streams.
  408. false ->
  409. %% WINDOW_UPDATE frames may be received for a short period of time
  410. %% after a stream is closed. They must be ignored.
  411. State0
  412. end;
  413. %% Unexpected CONTINUATION frame.
  414. frame(State, {continuation, _, _, _}) ->
  415. terminate(State, {connection_error, protocol_error,
  416. 'CONTINUATION frames MUST be preceded by a HEADERS frame. (RFC7540 6.10)'}).
  417. continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
  418. {continuation, StreamID, head_fin, HeaderBlockFragment1}) ->
  419. stream_decode_init(State#state{parse_state=normal}, StreamID, IsFin,
  420. << HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>);
  421. continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
  422. {continuation, StreamID, head_nofin, HeaderBlockFragment1}) ->
  423. State#state{parse_state={continuation, StreamID, IsFin,
  424. << HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>}};
  425. continuation_frame(State, _) ->
  426. terminate(State, {connection_error, protocol_error,
  427. 'An invalid frame was received while expecting a CONTINUATION frame. (RFC7540 6.2)'}).
  428. down(State=#state{children=Children0}, Pid, Msg) ->
  429. case cowboy_children:down(Children0, Pid) of
  430. %% The stream was terminated already.
  431. {ok, undefined, Children} ->
  432. State#state{children=Children};
  433. %% The stream is still running.
  434. {ok, StreamID, Children} ->
  435. info(State#state{children=Children}, StreamID, Msg);
  436. %% The process was unknown.
  437. error ->
  438. error_logger:error_msg("Received EXIT signal ~p for unknown process ~p.~n", [Msg, Pid]),
  439. State
  440. end.
  441. info(State=#state{streams=Streams}, StreamID, Msg) ->
  442. case lists:keyfind(StreamID, #stream.id, Streams) of
  443. #stream{state=flush} ->
  444. error_logger:error_msg("Received message ~p for terminated stream ~p.", [Msg, StreamID]),
  445. State;
  446. Stream = #stream{state=StreamState0} ->
  447. try cowboy_stream:info(StreamID, Msg, StreamState0) of
  448. {Commands, StreamState} ->
  449. commands(State, Stream#stream{state=StreamState}, Commands)
  450. catch Class:Exception ->
  451. cowboy_stream:report_error(info,
  452. [StreamID, Msg, StreamState0],
  453. Class, Exception, erlang:get_stacktrace()),
  454. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  455. 'Unhandled exception in cowboy_stream:info/3.'})
  456. end;
  457. false ->
  458. error_logger:error_msg("Received message ~p for unknown stream ~p.", [Msg, StreamID]),
  459. State
  460. end.
  461. commands(State, Stream, []) ->
  462. after_commands(State, Stream);
  463. %% Error responses are sent only if a response wasn't sent already.
  464. commands(State, Stream=#stream{local=idle}, [{error_response, StatusCode, Headers, Body}|Tail]) ->
  465. commands(State, Stream, [{response, StatusCode, Headers, Body}|Tail]);
  466. commands(State, Stream, [{error_response, _, _, _}|Tail]) ->
  467. commands(State, Stream, Tail);
  468. %% Send an informational response.
  469. commands(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  470. Stream=#stream{id=StreamID, local=idle}, [{inform, StatusCode, Headers0}|Tail]) ->
  471. Headers = Headers0#{<<":status">> => status(StatusCode)},
  472. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  473. Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
  474. commands(State#state{encode_state=EncodeState}, Stream, Tail);
  475. %% Send response headers.
  476. %%
  477. %% @todo Kill the stream if it sent a response when one has already been sent.
  478. %% @todo Keep IsFin in the state.
  479. %% @todo Same two things above apply to DATA, possibly promise too.
  480. commands(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  481. Stream=#stream{id=StreamID, local=idle}, [{response, StatusCode, Headers0, Body}|Tail]) ->
  482. Headers = Headers0#{<<":status">> => status(StatusCode)},
  483. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  484. case Body of
  485. <<>> ->
  486. Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
  487. commands(State#state{encode_state=EncodeState}, Stream#stream{local=fin}, Tail);
  488. {sendfile, O, B, P} ->
  489. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  490. commands(State#state{encode_state=EncodeState}, Stream#stream{local=nofin},
  491. [{sendfile, fin, O, B, P}|Tail]);
  492. _ ->
  493. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  494. {State1, Stream1} = send_data(State, Stream#stream{local=nofin}, fin, Body),
  495. commands(State1#state{encode_state=EncodeState}, Stream1, Tail)
  496. end;
  497. %% @todo response when local!=idle
  498. %% Send response headers.
  499. commands(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  500. Stream=#stream{id=StreamID, local=idle}, [{headers, StatusCode, Headers0}|Tail]) ->
  501. Headers = Headers0#{<<":status">> => status(StatusCode)},
  502. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  503. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  504. commands(State#state{encode_state=EncodeState}, Stream#stream{local=nofin}, Tail);
  505. %% @todo headers when local!=idle
  506. %% Send a response body chunk.
  507. commands(State0, Stream0=#stream{local=nofin}, [{data, IsFin, Data}|Tail]) ->
  508. {State, Stream} = send_data(State0, Stream0, IsFin, Data),
  509. commands(State, Stream, Tail);
  510. %% @todo data when local!=nofin
  511. %% Send trailers.
  512. commands(State0, Stream0=#stream{local=nofin, te=TE0}, [{trailers, Trailers}|Tail]) ->
  513. %% We only accept TE headers containing exactly "trailers" (RFC7540 8.1.2.1).
  514. TE = try cow_http_hd:parse_te(TE0) of
  515. {trailers, []} -> trailers;
  516. _ -> no_trailers
  517. catch _:_ ->
  518. %% If we can't parse the TE header, assume we can't send trailers.
  519. no_trailers
  520. end,
  521. {State, Stream} = case TE of
  522. trailers ->
  523. send_data(State0, Stream0, fin, {trailers, Trailers});
  524. no_trailers ->
  525. send_data(State0, Stream0, fin, <<>>)
  526. end,
  527. commands(State, Stream, Tail);
  528. %% Send a file.
  529. commands(State0, Stream0=#stream{local=nofin},
  530. [{sendfile, IsFin, Offset, Bytes, Path}|Tail]) ->
  531. {State, Stream} = send_data(State0, Stream0, IsFin, {sendfile, Offset, Bytes, Path}),
  532. commands(State, Stream, Tail);
  533. %% @todo sendfile when local!=nofin
  534. %% Send a push promise.
  535. %%
  536. %% @todo We need to keep track of what promises we made so that we don't
  537. %% end up with an infinite loop of promises.
  538. commands(State0=#state{socket=Socket, transport=Transport, server_streamid=PromisedStreamID,
  539. encode_state=EncodeState0}, Stream=#stream{id=StreamID},
  540. [{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) ->
  541. Authority = case {Scheme, Port} of
  542. {<<"http">>, 80} -> Host;
  543. {<<"https">>, 443} -> Host;
  544. _ -> iolist_to_binary([Host, $:, integer_to_binary(Port)])
  545. end,
  546. PathWithQs = case Qs of
  547. <<>> -> Path;
  548. _ -> [Path, $?, Qs]
  549. end,
  550. %% We need to make sure the header value is binary before we can
  551. %% pass it to stream_req_init, as it expects them to be flat.
  552. Headers1 = maps:map(fun(_, V) -> iolist_to_binary(V) end, Headers0),
  553. Headers = Headers1#{
  554. <<":method">> => Method,
  555. <<":scheme">> => Scheme,
  556. <<":authority">> => Authority,
  557. <<":path">> => iolist_to_binary(PathWithQs)},
  558. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  559. Transport:send(Socket, cow_http2:push_promise(StreamID, PromisedStreamID, HeaderBlock)),
  560. State = stream_req_init(State0#state{server_streamid=PromisedStreamID + 2,
  561. encode_state=EncodeState}, PromisedStreamID, fin, Headers),
  562. commands(State, Stream, Tail);
  563. commands(State=#state{socket=Socket, transport=Transport, remote_window=ConnWindow},
  564. Stream=#stream{id=StreamID, remote_window=StreamWindow},
  565. [{flow, Size}|Tail]) ->
  566. Transport:send(Socket, [
  567. cow_http2:window_update(Size),
  568. cow_http2:window_update(StreamID, Size)
  569. ]),
  570. commands(State#state{remote_window=ConnWindow + Size},
  571. Stream#stream{remote_window=StreamWindow + Size}, Tail);
  572. %% Supervise a child process.
  573. commands(State=#state{children=Children}, Stream=#stream{id=StreamID},
  574. [{spawn, Pid, Shutdown}|Tail]) ->
  575. commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)},
  576. Stream, Tail);
  577. %% Error handling.
  578. commands(State, Stream=#stream{id=StreamID}, [Error = {internal_error, _, _}|_Tail]) ->
  579. %% @todo Do we want to run the commands after an internal_error?
  580. %% @todo Do we even allow commands after?
  581. %% @todo Only reset when the stream still exists.
  582. stream_reset(after_commands(State, Stream), StreamID, Error);
  583. %% Upgrade to HTTP/2. This is triggered by cowboy_http2 itself.
  584. commands(State=#state{socket=Socket, transport=Transport},
  585. Stream=#stream{local=upgrade}, [{switch_protocol, Headers, ?MODULE, _}|Tail]) ->
  586. Transport:send(Socket, cow_http:response(101, 'HTTP/1.1', maps:to_list(Headers))),
  587. commands(State, Stream#stream{local=idle}, Tail);
  588. %% HTTP/2 has no support for the Upgrade mechanism.
  589. commands(State, Stream, [{switch_protocol, _Headers, _Mod, _ModState}|Tail]) ->
  590. %% @todo This is an error. Not sure what to do here yet.
  591. commands(State, Stream, Tail);
  592. commands(State, Stream=#stream{id=StreamID}, [stop|_Tail]) ->
  593. %% @todo Do we want to run the commands after a stop?
  594. %% @todo Do we even allow commands after?
  595. stream_terminate(after_commands(State, Stream), StreamID, normal).
  596. after_commands(State=#state{streams=Streams0}, Stream=#stream{id=StreamID}) ->
  597. Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
  598. State#state{streams=Streams}.
  599. status(Status) when is_integer(Status) ->
  600. integer_to_binary(Status);
  601. status(<< H, T, U, _/bits >>) when H >= $1, H =< $9, T >= $0, T =< $9, U >= $0, U =< $9 ->
  602. << H, T, U >>.
  603. %% @todo Should we ever want to implement the PRIORITY mechanism,
  604. %% this would be the place to do it. Right now, we just go over
  605. %% all streams and send what we can until either everything is
  606. %% sent or we run out of space in the window.
  607. send_data(State=#state{streams=Streams}) ->
  608. resume_streams(State, Streams, []).
  609. resume_streams(State, [], Acc) ->
  610. State#state{streams=lists:reverse(Acc)};
  611. %% While technically we should never get < 0 here, let's be on the safe side.
  612. resume_streams(State=#state{local_window=ConnWindow}, Streams, Acc)
  613. when ConnWindow =< 0 ->
  614. State#state{streams=lists:reverse(Acc, Streams)};
  615. %% We rely on send_data/2 to do all the necessary checks about the stream.
  616. resume_streams(State0, [Stream0|Tail], Acc) ->
  617. {State1, Stream} = send_data(State0, Stream0),
  618. case Stream of
  619. %% We are done flushing, remove the stream.
  620. %% Maybe skip the request body if it was not fully read.
  621. #stream{state=flush, local=fin} ->
  622. State = maybe_skip_body(State1, Stream, normal),
  623. resume_streams(State, Tail, Acc);
  624. %% Keep the stream. Either the stream handler is still running,
  625. %% or we are not finished flushing.
  626. _ ->
  627. resume_streams(State1, Tail, [Stream|Acc])
  628. end.
  629. send_data(State, Stream=#stream{local=Local, local_buffer_size=0, local_trailers=Trailers})
  630. when (Trailers =/= undefined) andalso ((Local =:= idle) orelse (Local =:= nofin)) ->
  631. send_trailers(State, Stream#stream{local_trailers=undefined}, Trailers);
  632. %% @todo We might want to print an error if local=fin.
  633. %%
  634. %% @todo It's possible that the stream terminates. We must remove it.
  635. send_data(State=#state{local_window=ConnWindow},
  636. Stream=#stream{local=IsFin, local_window=StreamWindow, local_buffer_size=BufferSize})
  637. when ConnWindow =< 0; IsFin =:= fin; StreamWindow =< 0; BufferSize =:= 0 ->
  638. {State, Stream};
  639. send_data(State0, Stream0=#stream{local_buffer=Q0, local_buffer_size=BufferSize}) ->
  640. %% We know there is an item in the queue.
  641. {{value, {IsFin, DataSize, Data}}, Q} = queue:out(Q0),
  642. {State, Stream} = send_data(State0,
  643. Stream0#stream{local_buffer=Q, local_buffer_size=BufferSize - DataSize},
  644. IsFin, Data, in_r),
  645. send_data(State, Stream).
  646. send_data(State, Stream, IsFin, Data) ->
  647. send_data(State, Stream, IsFin, Data, in).
  648. %% We can send trailers immediately if the queue is empty, otherwise we queue.
  649. %% We always send trailer frames even if the window is empty.
  650. send_data(State, Stream=#stream{local_buffer_size=0}, fin, {trailers, Trailers}, _) ->
  651. send_trailers(State, Stream, Trailers);
  652. send_data(State, Stream, fin, {trailers, Trailers}, _) ->
  653. {State, Stream#stream{local_trailers=Trailers}};
  654. %% Send data immediately if we can, buffer otherwise.
  655. %% @todo We might want to print an error if local=fin.
  656. send_data(State=#state{local_window=ConnWindow},
  657. Stream=#stream{local_window=StreamWindow}, IsFin, Data, In)
  658. when ConnWindow =< 0; StreamWindow =< 0 ->
  659. {State, queue_data(Stream, IsFin, Data, In)};
  660. send_data(State=#state{socket=Socket, transport=Transport, local_window=ConnWindow},
  661. Stream=#stream{id=StreamID, local_window=StreamWindow}, IsFin, Data, In) ->
  662. MaxFrameSize = 16384, %% @todo Use the real SETTINGS_MAX_FRAME_SIZE set by the client.
  663. MaxSendSize = min(min(ConnWindow, StreamWindow), MaxFrameSize),
  664. case Data of
  665. {sendfile, Offset, Bytes, Path} when Bytes =< MaxSendSize ->
  666. Transport:send(Socket, cow_http2:data_header(StreamID, IsFin, Bytes)),
  667. Transport:sendfile(Socket, Path, Offset, Bytes),
  668. {State#state{local_window=ConnWindow - Bytes},
  669. Stream#stream{local=IsFin, local_window=StreamWindow - Bytes}};
  670. {sendfile, Offset, Bytes, Path} ->
  671. Transport:send(Socket, cow_http2:data_header(StreamID, nofin, MaxSendSize)),
  672. Transport:sendfile(Socket, Path, Offset, MaxSendSize),
  673. send_data(State#state{local_window=ConnWindow - MaxSendSize},
  674. Stream#stream{local_window=StreamWindow - MaxSendSize},
  675. IsFin, {sendfile, Offset + MaxSendSize, Bytes - MaxSendSize, Path}, In);
  676. Iolist0 ->
  677. IolistSize = iolist_size(Iolist0),
  678. if
  679. IolistSize =< MaxSendSize ->
  680. Transport:send(Socket, cow_http2:data(StreamID, IsFin, Iolist0)),
  681. {State#state{local_window=ConnWindow - IolistSize},
  682. Stream#stream{local=IsFin, local_window=StreamWindow - IolistSize}};
  683. true ->
  684. {Iolist, More} = cowboy_iolists:split(MaxSendSize, Iolist0),
  685. Transport:send(Socket, cow_http2:data(StreamID, nofin, Iolist)),
  686. send_data(State#state{local_window=ConnWindow - MaxSendSize},
  687. Stream#stream{local_window=StreamWindow - MaxSendSize},
  688. IsFin, More, In)
  689. end
  690. end.
  691. send_trailers(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  692. Stream=#stream{id=StreamID}, Trailers) ->
  693. {HeaderBlock, EncodeState} = headers_encode(Trailers, EncodeState0),
  694. Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
  695. {State#state{encode_state=EncodeState}, Stream#stream{local=fin}}.
  696. queue_data(Stream=#stream{local_buffer=Q0, local_buffer_size=Size0}, IsFin, Data, In) ->
  697. DataSize = case Data of
  698. {sendfile, _, Bytes, _} -> Bytes;
  699. Iolist -> iolist_size(Iolist)
  700. end,
  701. Q = queue:In({IsFin, DataSize, Data}, Q0),
  702. Stream#stream{local_buffer=Q, local_buffer_size=Size0 + DataSize}.
  703. -spec terminate(#state{}, _) -> no_return().
  704. terminate(undefined, Reason) ->
  705. exit({shutdown, Reason});
  706. terminate(#state{socket=Socket, transport=Transport, client_streamid=LastStreamID,
  707. streams=Streams, children=Children}, Reason) ->
  708. %% @todo We might want to optionally send the Reason value
  709. %% as debug data in the GOAWAY frame here. Perhaps more.
  710. Transport:send(Socket, cow_http2:goaway(LastStreamID, terminate_reason(Reason), <<>>)),
  711. terminate_all_streams(Streams, Reason),
  712. cowboy_children:terminate(Children),
  713. Transport:close(Socket),
  714. exit({shutdown, Reason}).
  715. terminate_reason({connection_error, Reason, _}) -> Reason;
  716. terminate_reason({stop, _, _}) -> no_error;
  717. terminate_reason({socket_error, _, _}) -> internal_error;
  718. terminate_reason({internal_error, _, _}) -> internal_error.
  719. terminate_all_streams([], _) ->
  720. ok;
  721. %% This stream was already terminated and is now just flushing the data out. Skip it.
  722. terminate_all_streams([#stream{state=flush}|Tail], Reason) ->
  723. terminate_all_streams(Tail, Reason);
  724. terminate_all_streams([#stream{id=StreamID, state=StreamState}|Tail], Reason) ->
  725. stream_call_terminate(StreamID, Reason, StreamState),
  726. terminate_all_streams(Tail, Reason).
  727. %% Stream functions.
  728. stream_decode_init(State=#state{socket=Socket, transport=Transport,
  729. decode_state=DecodeState0}, StreamID, IsFin, HeaderBlock) ->
  730. %% @todo Add clause for CONNECT requests (no scheme/path).
  731. try headers_decode(HeaderBlock, DecodeState0) of
  732. {Headers=#{<<":method">> := _, <<":scheme">> := _,
  733. <<":authority">> := _, <<":path">> := _}, DecodeState} ->
  734. stream_req_init(State#state{decode_state=DecodeState}, StreamID, IsFin, Headers);
  735. {_, DecodeState} ->
  736. Transport:send(Socket, cow_http2:rst_stream(StreamID, protocol_error)),
  737. State#state{decode_state=DecodeState}
  738. catch _:_ ->
  739. terminate(State, {connection_error, compression_error,
  740. 'Error while trying to decode HPACK-encoded header block. (RFC7540 4.3)'})
  741. end.
  742. stream_req_init(State=#state{ref=Ref, peer=Peer, sock=Sock, cert=Cert},
  743. StreamID, IsFin, Headers0=#{
  744. <<":method">> := Method, <<":scheme">> := Scheme,
  745. <<":authority">> := Authority, <<":path">> := PathWithQs}) ->
  746. Headers = maps:without([<<":method">>, <<":scheme">>, <<":authority">>, <<":path">>], Headers0),
  747. BodyLength = case Headers of
  748. _ when IsFin =:= fin ->
  749. 0;
  750. #{<<"content-length">> := <<"0">>} ->
  751. 0;
  752. #{<<"content-length">> := BinLength} ->
  753. try
  754. cow_http_hd:parse_content_length(BinLength)
  755. catch _:_ ->
  756. terminate(State, {stream_error, StreamID, protocol_error,
  757. 'The content-length header is invalid. (RFC7230 3.3.2)'})
  758. end;
  759. _ ->
  760. undefined
  761. end,
  762. %% @todo If this fails to parse we want to gracefully handle the crash.
  763. {Host, Port} = cow_http_hd:parse_host(Authority),
  764. {Path, Qs} = cow_http:parse_fullpath(PathWithQs),
  765. Req = #{
  766. ref => Ref,
  767. pid => self(),
  768. streamid => StreamID,
  769. peer => Peer,
  770. sock => Sock,
  771. cert => Cert,
  772. method => Method,
  773. scheme => Scheme,
  774. host => Host,
  775. port => Port,
  776. path => Path,
  777. qs => Qs,
  778. version => 'HTTP/2',
  779. headers => Headers,
  780. has_body => IsFin =:= nofin,
  781. body_length => BodyLength
  782. },
  783. stream_handler_init(State, StreamID, IsFin, idle, Req).
  784. stream_handler_init(State=#state{opts=Opts,
  785. local_settings=#{initial_window_size := RemoteWindow},
  786. remote_settings=#{initial_window_size := LocalWindow}},
  787. StreamID, RemoteIsFin, LocalIsFin, Req=#{headers := Headers}) ->
  788. try cowboy_stream:init(StreamID, Req, Opts) of
  789. {Commands, StreamState} ->
  790. commands(State#state{client_streamid=StreamID},
  791. #stream{id=StreamID, state=StreamState,
  792. remote=RemoteIsFin, local=LocalIsFin,
  793. local_window=LocalWindow, remote_window=RemoteWindow,
  794. te=maps:get(<<"te">>, Headers, undefined)},
  795. Commands)
  796. catch Class:Exception ->
  797. cowboy_stream:report_error(init,
  798. [StreamID, Req, Opts],
  799. Class, Exception, erlang:get_stacktrace()),
  800. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  801. 'Unhandled exception in cowboy_stream:init/3.'})
  802. end.
  803. %% @todo Don't send an RST_STREAM if one was already sent.
  804. stream_reset(State=#state{socket=Socket, transport=Transport}, StreamID, StreamError) ->
  805. Reason = case StreamError of
  806. {internal_error, _, _} -> internal_error;
  807. {stream_error, Reason0, _} -> Reason0
  808. end,
  809. Transport:send(Socket, cow_http2:rst_stream(StreamID, Reason)),
  810. stream_terminate(stream_linger(State, StreamID), StreamID, StreamError).
  811. %% We only keep up to 100 streams in this state. @todo Make it configurable?
  812. stream_linger(State=#state{lingering_streams=Lingering0}, StreamID) ->
  813. Lingering = [StreamID|lists:sublist(Lingering0, 100 - 1)],
  814. State#state{lingering_streams=Lingering}.
  815. stream_terminate(State0=#state{streams=Streams0, children=Children0}, StreamID, Reason) ->
  816. case lists:keytake(StreamID, #stream.id, Streams0) of
  817. %% When the stream terminates normally (without sending RST_STREAM)
  818. %% and no response was sent, we need to send a proper response back to the client.
  819. {value, Stream=#stream{local=idle}, Streams} when Reason =:= normal ->
  820. State1 = #state{streams=Streams1} = info(State0, StreamID, {response, 204, #{}, <<>>}),
  821. State = maybe_skip_body(State1, Stream, Reason),
  822. #stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams1),
  823. stream_call_terminate(StreamID, Reason, StreamState),
  824. Children = cowboy_children:shutdown(Children0, StreamID),
  825. State#state{streams=Streams, children=Children};
  826. %% When a response was sent but not terminated, we need to close the stream.
  827. {value, Stream=#stream{local=nofin, local_buffer_size=0}, Streams}
  828. when Reason =:= normal ->
  829. State1 = #state{streams=Streams1} = info(State0, StreamID, {data, fin, <<>>}),
  830. State = maybe_skip_body(State1, Stream, Reason),
  831. #stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams1),
  832. stream_call_terminate(StreamID, Reason, StreamState),
  833. Children = cowboy_children:shutdown(Children0, StreamID),
  834. State#state{streams=Streams, children=Children};
  835. %% Unless there is still data in the buffer. We can however reset
  836. %% a few fields and set a special local state to avoid confusion.
  837. %%
  838. %% We do not reset the stream in this case (to skip the body)
  839. %% because we are still sending data via the buffer. We will
  840. %% reset the stream if necessary once the buffer is empty.
  841. {value, Stream=#stream{state=StreamState, local=nofin}, Streams} ->
  842. stream_call_terminate(StreamID, Reason, StreamState),
  843. Children = cowboy_children:shutdown(Children0, StreamID),
  844. State0#state{streams=[Stream#stream{state=flush, local=flush}|Streams],
  845. children=Children};
  846. %% Otherwise we sent an RST_STREAM and/or the stream is already closed.
  847. {value, Stream=#stream{state=StreamState}, Streams} ->
  848. State = maybe_skip_body(State0, Stream, Reason),
  849. stream_call_terminate(StreamID, Reason, StreamState),
  850. Children = cowboy_children:shutdown(Children0, StreamID),
  851. State#state{streams=Streams, children=Children};
  852. %% The stream doesn't exist. This can occur for various reasons.
  853. %% It can happen before the stream has been created, or because
  854. %% the cowboy_stream:init call failed, in which case doing nothing
  855. %% is correct.
  856. false ->
  857. State0
  858. end.
  859. %% When the stream stops normally without reading the request
  860. %% body fully we need to tell the client to stop sending it.
  861. %% We do this by sending an RST_STREAM with reason NO_ERROR. (RFC7540 8.1.0)
  862. maybe_skip_body(State=#state{socket=Socket, transport=Transport},
  863. #stream{id=StreamID, remote=nofin}, normal) ->
  864. Transport:send(Socket, cow_http2:rst_stream(StreamID, no_error)),
  865. stream_linger(State, StreamID);
  866. maybe_skip_body(State, _, _) ->
  867. State.
  868. stream_call_terminate(StreamID, Reason, StreamState) ->
  869. try
  870. cowboy_stream:terminate(StreamID, Reason, StreamState)
  871. catch Class:Exception ->
  872. cowboy_stream:report_error(terminate,
  873. [StreamID, Reason, StreamState],
  874. Class, Exception, erlang:get_stacktrace())
  875. end.
  876. %% Headers encode/decode.
  877. headers_decode(HeaderBlock, DecodeState0) ->
  878. {Headers, DecodeState} = cow_hpack:decode(HeaderBlock, DecodeState0),
  879. {headers_to_map(Headers, #{}), DecodeState}.
  880. %% This function is necessary to properly handle duplicate headers
  881. %% and the special-case cookie header.
  882. headers_to_map([], Acc) ->
  883. Acc;
  884. headers_to_map([{Name, Value}|Tail], Acc0) ->
  885. Acc = case Acc0 of
  886. %% The cookie header does not use proper HTTP header lists.
  887. #{Name := Value0} when Name =:= <<"cookie">> -> Acc0#{Name => << Value0/binary, "; ", Value/binary >>};
  888. #{Name := Value0} -> Acc0#{Name => << Value0/binary, ", ", Value/binary >>};
  889. _ -> Acc0#{Name => Value}
  890. end,
  891. headers_to_map(Tail, Acc).
  892. %% The set-cookie header is special; we can only send one cookie per header.
  893. headers_encode(Headers0=#{<<"set-cookie">> := SetCookies}, EncodeState) ->
  894. Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  895. Headers = Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies],
  896. cow_hpack:encode(Headers, EncodeState);
  897. headers_encode(Headers0, EncodeState) ->
  898. Headers = maps:to_list(Headers0),
  899. cow_hpack:encode(Headers, EncodeState).
  900. %% System callbacks.
  901. -spec system_continue(_, _, {#state{}, binary()}) -> ok.
  902. system_continue(_, _, {State, Buffer}) ->
  903. loop(State, Buffer).
  904. -spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return().
  905. system_terminate(Reason, _, _, {State, _}) ->
  906. terminate(State, Reason).
  907. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  908. system_code_change(Misc, _, _, _) ->
  909. {ok, Misc}.