cowboy_http2.erl 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391
  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. -ifdef(OTP_RELEASE).
  16. -compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}).
  17. -endif.
  18. -export([init/5]).
  19. -export([init/9]).
  20. -export([init/11]).
  21. -export([system_continue/3]).
  22. -export([system_terminate/4]).
  23. -export([system_code_change/4]).
  24. -type opts() :: #{
  25. connection_type => worker | supervisor,
  26. enable_connect_protocol => boolean(),
  27. env => cowboy_middleware:env(),
  28. inactivity_timeout => timeout(),
  29. initial_connection_window_size => 65535..16#7fffffff,
  30. initial_stream_window_size => 0..16#7fffffff,
  31. logger => module(),
  32. max_concurrent_streams => non_neg_integer() | infinity,
  33. max_decode_table_size => non_neg_integer(),
  34. max_encode_table_size => non_neg_integer(),
  35. max_frame_size_received => 16384..16777215,
  36. max_frame_size_sent => 16384..16777215 | infinity,
  37. middlewares => [module()],
  38. preface_timeout => timeout(),
  39. settings_timeout => timeout(),
  40. shutdown_timeout => timeout(),
  41. stream_handlers => [module()]
  42. }.
  43. -export_type([opts/0]).
  44. -record(stream, {
  45. id = undefined :: cowboy_stream:streamid(),
  46. %% Stream handlers and their state.
  47. state = undefined :: {module(), any()} | flush,
  48. %% Request method.
  49. method = undefined :: binary(),
  50. %% Whether we finished sending data.
  51. local = idle :: idle | upgrade | cowboy_stream:fin() | flush,
  52. %% Local flow control window (how much we can send).
  53. local_window :: integer(),
  54. %% Buffered data waiting for the flow control window to increase.
  55. local_buffer = queue:new() :: queue:queue(
  56. {cowboy_stream:fin(), non_neg_integer(), iolist()
  57. | {sendfile, non_neg_integer(), pos_integer(), file:name_all()}}),
  58. local_buffer_size = 0 :: non_neg_integer(),
  59. local_trailers = undefined :: undefined | cowboy:http_headers(),
  60. %% Whether we finished receiving data.
  61. remote = nofin :: cowboy_stream:fin(),
  62. %% Remote flow control window (how much we accept to receive).
  63. remote_window :: integer(),
  64. %% Size expected and read from the request body.
  65. remote_expected_size = undefined :: undefined | non_neg_integer(),
  66. remote_read_size = 0 :: non_neg_integer(),
  67. %% Unparsed te header. Used to know if we can send trailers.
  68. te :: undefined | binary()
  69. }).
  70. -type stream() :: #stream{}.
  71. -record(state, {
  72. parent = undefined :: pid(),
  73. ref :: ranch:ref(),
  74. socket = undefined :: inet:socket(),
  75. transport :: module(),
  76. opts = #{} :: opts(),
  77. %% Remote address and port for the connection.
  78. peer = undefined :: {inet:ip_address(), inet:port_number()},
  79. %% Local address and port for the connection.
  80. sock = undefined :: {inet:ip_address(), inet:port_number()},
  81. %% Client certificate (TLS only).
  82. cert :: undefined | binary(),
  83. %% Settings are separate for each endpoint. In addition, settings
  84. %% must be acknowledged before they can be expected to be applied.
  85. local_settings = #{
  86. % header_table_size => 4096,
  87. % enable_push => false, %% We are the server. Push is never enabled for clients.
  88. % max_concurrent_streams => infinity,
  89. initial_window_size => 65535,
  90. max_frame_size => 16384
  91. % max_header_list_size => infinity
  92. } :: map(),
  93. next_settings = undefined :: undefined | map(),
  94. next_settings_timer = undefined :: undefined | reference(),
  95. remote_settings = #{
  96. initial_window_size => 65535
  97. } :: map(),
  98. %% Connection-wide flow control window.
  99. local_window = 65535 :: integer(), %% How much we can send.
  100. remote_window = 65535 :: integer(), %% How much we accept to receive.
  101. %% Stream identifiers.
  102. client_streamid = 0 :: non_neg_integer(),
  103. server_streamid = 2 :: pos_integer(),
  104. %% Currently active HTTP/2 streams. Streams may be initiated either
  105. %% by the client or by the server through PUSH_PROMISE frames.
  106. streams = [] :: [stream()],
  107. %% HTTP/2 streams that have been reset recently by the server.
  108. %% We are expected to keep receiving additional frames after
  109. %% sending an RST_STREAM.
  110. lingering_streams = [] :: [cowboy_stream:streamid()],
  111. %% HTTP/2 streams that have been reset recently by the client.
  112. %% We keep a few of these around in order to reject subsequent
  113. %% frames on these streams.
  114. rst_lingering_streams = [] :: [cowboy_stream:streamid()],
  115. %% Streams can spawn zero or more children which are then managed
  116. %% by this module if operating as a supervisor.
  117. children = cowboy_children:init() :: cowboy_children:children(),
  118. %% The client starts by sending a sequence of bytes as a preface,
  119. %% followed by a potentially empty SETTINGS frame. Then the connection
  120. %% is established and continues normally. An exception is when a HEADERS
  121. %% frame is sent followed by CONTINUATION frames: no other frame can be
  122. %% sent in between.
  123. parse_state = undefined :: {preface, sequence, undefined | reference()}
  124. | {preface, settings, reference()}
  125. | normal
  126. | {continuation, cowboy_stream:streamid(), cowboy_stream:fin(), binary()},
  127. %% HPACK decoding and encoding state.
  128. decode_state = cow_hpack:init() :: cow_hpack:state(),
  129. encode_state = cow_hpack:init() :: cow_hpack:state()
  130. }).
  131. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts()) -> ok.
  132. init(Parent, Ref, Socket, Transport, Opts) ->
  133. Peer0 = Transport:peername(Socket),
  134. Sock0 = Transport:sockname(Socket),
  135. Cert1 = case Transport:name() of
  136. ssl ->
  137. case ssl:peercert(Socket) of
  138. {error, no_peercert} ->
  139. {ok, undefined};
  140. Cert0 ->
  141. Cert0
  142. end;
  143. _ ->
  144. {ok, undefined}
  145. end,
  146. case {Peer0, Sock0, Cert1} of
  147. {{ok, Peer}, {ok, Sock}, {ok, Cert}} ->
  148. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, <<>>);
  149. {{error, Reason}, _, _} ->
  150. terminate(undefined, {socket_error, Reason,
  151. 'A socket error occurred when retrieving the peer name.'});
  152. {_, {error, Reason}, _} ->
  153. terminate(undefined, {socket_error, Reason,
  154. 'A socket error occurred when retrieving the sock name.'});
  155. {_, _, {error, Reason}} ->
  156. terminate(undefined, {socket_error, Reason,
  157. 'A socket error occurred when retrieving the client TLS certificate.'})
  158. end.
  159. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  160. {inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()},
  161. binary() | undefined, binary()) -> ok.
  162. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, Buffer) ->
  163. State0 = #state{parent=Parent, ref=Ref, socket=Socket,
  164. transport=Transport, opts=Opts, peer=Peer, sock=Sock, cert=Cert,
  165. remote_window=maps:get(initial_connection_window_size, Opts, 65535),
  166. parse_state={preface, sequence, preface_timeout(Opts)}},
  167. State = settings_init(State0, Opts),
  168. preface(State),
  169. case Buffer of
  170. <<>> -> before_loop(State, Buffer);
  171. _ -> parse(State, Buffer)
  172. end.
  173. %% @todo Add an argument for the request body.
  174. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  175. {inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()},
  176. binary() | undefined, binary(), map() | undefined, cowboy_req:req()) -> ok.
  177. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, Buffer, _Settings, Req) ->
  178. State0 = #state{parent=Parent, ref=Ref, socket=Socket,
  179. transport=Transport, opts=Opts, peer=Peer, sock=Sock, cert=Cert,
  180. remote_window=maps:get(initial_connection_window_size, Opts, 65535),
  181. parse_state={preface, sequence, preface_timeout(Opts)}},
  182. %% @todo Apply settings.
  183. %% StreamID from HTTP/1.1 Upgrade requests is always 1.
  184. %% The stream is always in the half-closed (remote) state.
  185. State1 = stream_handler_init(State0, 1, fin, upgrade, Req),
  186. %% We assume that the upgrade will be applied. A stream handler
  187. %% must not prevent the normal operations of the server.
  188. State2 = info(State1, 1, {switch_protocol, #{
  189. <<"connection">> => <<"Upgrade">>,
  190. <<"upgrade">> => <<"h2c">>
  191. }, ?MODULE, undefined}), %% @todo undefined or #{}?
  192. State = settings_init(State2, Opts),
  193. preface(State),
  194. case Buffer of
  195. <<>> -> before_loop(State, Buffer);
  196. _ -> parse(State, Buffer)
  197. end.
  198. settings_init(State, Opts) ->
  199. S0 = setting_from_opt(#{}, Opts, max_decode_table_size,
  200. header_table_size, 4096),
  201. S1 = setting_from_opt(S0, Opts, max_concurrent_streams,
  202. max_concurrent_streams, infinity),
  203. S2 = setting_from_opt(S1, Opts, initial_stream_window_size,
  204. initial_window_size, 65535),
  205. S3 = setting_from_opt(S2, Opts, max_frame_size_received,
  206. max_frame_size, 16384),
  207. %% @todo max_header_list_size
  208. Settings = setting_from_opt(S3, Opts, enable_connect_protocol,
  209. enable_connect_protocol, false),
  210. %% Start a timer if necessary. The timer will trigger only
  211. %% if no SETTINGS ack was received in time.
  212. TRef = case maps:get(settings_timeout, Opts, 5000) of
  213. infinity -> undefined;
  214. SettingsTimeout -> erlang:start_timer(SettingsTimeout, self(), settings_timeout)
  215. end,
  216. State#state{next_settings=Settings, next_settings_timer=TRef}.
  217. setting_from_opt(Settings, Opts, OptName, SettingName, Default) ->
  218. case maps:get(OptName, Opts, Default) of
  219. Default -> Settings;
  220. Value -> Settings#{SettingName => Value}
  221. end.
  222. %% We send next_settings and use defaults until we get an ack.
  223. %%
  224. %% We also send a WINDOW_UPDATE frame for the connection when
  225. %% the user specified an initial_connection_window_size.
  226. preface(#state{socket=Socket, transport=Transport, opts=Opts, next_settings=Settings}) ->
  227. MaybeWindowUpdate = case maps:get(initial_connection_window_size, Opts, 65535) of
  228. 65535 -> <<>>;
  229. Size -> cow_http2:window_update(Size - 65535)
  230. end,
  231. Transport:send(Socket, [cow_http2:settings(Settings), MaybeWindowUpdate]).
  232. preface_timeout(Opts) ->
  233. case maps:get(preface_timeout, Opts, 5000) of
  234. infinity -> undefined;
  235. PrefaceTimeout -> erlang:start_timer(PrefaceTimeout, self(), preface_timeout)
  236. end.
  237. %% @todo Add the timeout for last time since we heard of connection.
  238. before_loop(State, Buffer) ->
  239. loop(State, Buffer).
  240. loop(State=#state{parent=Parent, socket=Socket, transport=Transport,
  241. opts=Opts, children=Children, next_settings_timer=SettingsTRef,
  242. parse_state=PS}, Buffer) ->
  243. Transport:setopts(Socket, [{active, once}]),
  244. {OK, Closed, Error} = Transport:messages(),
  245. InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000),
  246. receive
  247. %% Socket messages.
  248. {OK, Socket, Data} ->
  249. parse(State, << Buffer/binary, Data/binary >>);
  250. {Closed, Socket} ->
  251. terminate(State, {socket_error, closed, 'The socket has been closed.'});
  252. {Error, Socket, Reason} ->
  253. terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'});
  254. %% System messages.
  255. {'EXIT', Parent, Reason} ->
  256. %% @todo We should exit gracefully.
  257. exit(Reason);
  258. {system, From, Request} ->
  259. sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer});
  260. %% Timeouts.
  261. {timeout, Ref, {shutdown, Pid}} ->
  262. cowboy_children:shutdown_timeout(Children, Ref, Pid),
  263. loop(State, Buffer);
  264. {timeout, TRef, preface_timeout} ->
  265. case PS of
  266. {preface, _, TRef} ->
  267. terminate(State, {connection_error, protocol_error,
  268. 'The preface was not received in a reasonable amount of time.'});
  269. _ ->
  270. loop(State, Buffer)
  271. end;
  272. {timeout, SettingsTRef, settings_timeout} ->
  273. terminate(State, {connection_error, settings_timeout,
  274. 'The SETTINGS ack was not received within the configured time. (RFC7540 6.5.3)'});
  275. %% Messages pertaining to a stream.
  276. {{Pid, StreamID}, Msg} when Pid =:= self() ->
  277. loop(info(State, StreamID, Msg), Buffer);
  278. %% Exit signal from children.
  279. Msg = {'EXIT', Pid, _} ->
  280. loop(down(State, Pid, Msg), Buffer);
  281. %% Calls from supervisor module.
  282. {'$gen_call', From, Call} ->
  283. cowboy_children:handle_supervisor_call(Call, From, Children, ?MODULE),
  284. loop(State, Buffer);
  285. Msg ->
  286. cowboy:log(warning, "Received stray message ~p.", [Msg], Opts),
  287. loop(State, Buffer)
  288. after InactivityTimeout ->
  289. terminate(State, {internal_error, timeout, 'No message or data received before timeout.'})
  290. end.
  291. parse(State=#state{socket=Socket, transport=Transport, parse_state={preface, sequence, TRef}}, Data) ->
  292. case Data of
  293. << "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n", Rest/bits >> ->
  294. parse(State#state{parse_state={preface, settings, TRef}}, Rest);
  295. _ when byte_size(Data) >= 24 ->
  296. Transport:close(Socket),
  297. exit({shutdown, {connection_error, protocol_error,
  298. 'The connection preface was invalid. (RFC7540 3.5)'}});
  299. _ ->
  300. Len = byte_size(Data),
  301. << Preface:Len/binary, _/bits >> = <<"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n">>,
  302. case Data of
  303. Preface ->
  304. before_loop(State, Data);
  305. _ ->
  306. Transport:close(Socket),
  307. exit({shutdown, {connection_error, protocol_error,
  308. 'The connection preface was invalid. (RFC7540 3.5)'}})
  309. end
  310. end;
  311. %% @todo Perhaps instead of just more we can have {more, Len} to avoid all the checks.
  312. parse(State=#state{local_settings=#{max_frame_size := MaxFrameSize},
  313. parse_state=ParseState}, Data) ->
  314. case cow_http2:parse(Data, MaxFrameSize) of
  315. {ok, Frame, Rest} ->
  316. case ParseState of
  317. normal ->
  318. parse(frame(State, Frame), Rest);
  319. {preface, settings, TRef} ->
  320. parse_settings_preface(State, Frame, Rest, TRef);
  321. {continuation, _, _, _} ->
  322. parse(continuation_frame(State, Frame), Rest)
  323. end;
  324. {ignore, _} when element(1, ParseState) =:= continuation ->
  325. terminate(State, {connection_error, protocol_error,
  326. 'An invalid frame was received in the middle of a header block. (RFC7540 6.2)'});
  327. {ignore, Rest} ->
  328. parse(State, Rest);
  329. {stream_error, StreamID, Reason, Human, Rest} ->
  330. parse(stream_reset(State, StreamID, {stream_error, Reason, Human}), Rest);
  331. Error = {connection_error, _, _} ->
  332. terminate(State, Error);
  333. more ->
  334. before_loop(State, Data)
  335. end.
  336. parse_settings_preface(State, Frame={settings, _}, Rest, TRef) ->
  337. ok = case TRef of
  338. undefined -> ok;
  339. _ -> erlang:cancel_timer(TRef, [{async, true}, {info, false}])
  340. end,
  341. parse(frame(State#state{parse_state=normal}, Frame), Rest);
  342. parse_settings_preface(State, _, _, _) ->
  343. terminate(State, {connection_error, protocol_error,
  344. 'The preface sequence must be followed by a SETTINGS frame. (RFC7540 3.5)'}).
  345. %% @todo When we get a 'fin' we need to check if the stream had a 'fin' sent back
  346. %% and terminate the stream if this is the end of it.
  347. %% DATA frame.
  348. frame(State=#state{client_streamid=LastStreamID}, {data, StreamID, _, _})
  349. when StreamID > LastStreamID ->
  350. terminate(State, {connection_error, protocol_error,
  351. 'DATA frame received on a stream in idle state. (RFC7540 5.1)'});
  352. frame(State=#state{remote_window=ConnWindow}, {data, _, _, Data})
  353. when byte_size(Data) > ConnWindow ->
  354. terminate(State, {connection_error, flow_control_error,
  355. 'DATA frame overflowed the connection flow control window. (RFC7540 6.9, RFC7540 6.9.1)'});
  356. frame(State0=#state{remote_window=ConnWindow, streams=Streams, lingering_streams=Lingering},
  357. {data, StreamID, IsFin, Data}) ->
  358. DataLen = byte_size(Data),
  359. State = State0#state{remote_window=ConnWindow - DataLen},
  360. case lists:keyfind(StreamID, #stream.id, Streams) of
  361. #stream{remote_window=StreamWindow} when StreamWindow < DataLen ->
  362. stream_reset(State, StreamID, {stream_error, flow_control_error,
  363. 'DATA frame overflowed the stream flow control window. (RFC7540 6.9, RFC7540 6.9.1)'});
  364. Stream = #stream{remote=nofin} ->
  365. data_frame(State, Stream, IsFin, DataLen, Data);
  366. #stream{remote=fin} ->
  367. stream_reset(State, StreamID, {stream_error, stream_closed,
  368. 'DATA frame received for a half-closed (remote) stream. (RFC7540 5.1)'});
  369. false ->
  370. %% After we send an RST_STREAM frame and terminate a stream,
  371. %% the client still might be sending us some more frames
  372. %% until it can process this RST_STREAM. We therefore ignore
  373. %% DATA frames received for such lingering streams.
  374. case lists:member(StreamID, Lingering) of
  375. true ->
  376. State0;
  377. false ->
  378. terminate(State, {connection_error, stream_closed,
  379. 'DATA frame received for a closed stream. (RFC7540 5.1)'})
  380. end
  381. end;
  382. %% HEADERS frame with invalid even-numbered streamid.
  383. frame(State, {headers, StreamID, _, _, _}) when StreamID rem 2 =:= 0 ->
  384. terminate(State, {connection_error, protocol_error,
  385. 'HEADERS frame received with even-numbered streamid. (RFC7540 5.1.1)'});
  386. %% Either a HEADERS frame received on (half-)closed stream,
  387. %% or a HEADERS frame containing the trailers.
  388. frame(State=#state{client_streamid=LastStreamID, streams=Streams},
  389. {headers, StreamID, IsFin, IsHeadFin, HeaderBlockOrFragment})
  390. when StreamID =< LastStreamID ->
  391. case lists:keyfind(StreamID, #stream.id, Streams) of
  392. Stream = #stream{remote=nofin} when IsFin =:= fin ->
  393. case IsHeadFin of
  394. head_fin ->
  395. stream_decode_trailers(State, Stream, HeaderBlockOrFragment);
  396. head_nofin ->
  397. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockOrFragment}}
  398. end;
  399. %% We always close the connection here to avoid having to decode
  400. %% the headers to not waste resources on non-compliant clients.
  401. #stream{remote=nofin} when IsFin =:= nofin ->
  402. terminate(State, {connection_error, protocol_error,
  403. 'Trailing HEADERS frame received without the END_STREAM flag set. (RFC7540 8.1, RFC7540 8.1.2.6)'});
  404. _ ->
  405. terminate(State, {connection_error, stream_closed,
  406. 'HEADERS frame received on a stream in closed or half-closed state. (RFC7540 5.1)'})
  407. end;
  408. %% Single HEADERS frame headers block.
  409. frame(State, {headers, StreamID, IsFin, head_fin, HeaderBlock}) ->
  410. stream_decode_init(State, StreamID, IsFin, HeaderBlock);
  411. %% HEADERS frame starting a headers block. Enter continuation mode.
  412. frame(State, {headers, StreamID, IsFin, head_nofin, HeaderBlockFragment}) ->
  413. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
  414. %% Single HEADERS frame headers block with priority.
  415. frame(State, {headers, StreamID, IsFin, head_fin,
  416. _IsExclusive, _DepStreamID, _Weight, HeaderBlock}) ->
  417. %% @todo Handle priority.
  418. stream_decode_init(State, StreamID, IsFin, HeaderBlock);
  419. %% HEADERS frame starting a headers block. Enter continuation mode.
  420. frame(State, {headers, StreamID, IsFin, head_nofin,
  421. _IsExclusive, _DepStreamID, _Weight, HeaderBlockFragment}) ->
  422. %% @todo Handle priority.
  423. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
  424. %% PRIORITY frame.
  425. frame(State, {priority, _StreamID, _IsExclusive, _DepStreamID, _Weight}) ->
  426. %% @todo Handle priority.
  427. State;
  428. %% RST_STREAM frame.
  429. frame(State=#state{client_streamid=LastStreamID}, {rst_stream, StreamID, _})
  430. when StreamID > LastStreamID ->
  431. terminate(State, {connection_error, protocol_error,
  432. 'RST_STREAM frame received on a stream in idle state. (RFC7540 5.1)'});
  433. frame(State, {rst_stream, StreamID, Reason}) ->
  434. stream_terminate(stream_rst_linger(State, StreamID), StreamID,
  435. {stream_error, Reason, 'Stream reset requested by client.'});
  436. %% SETTINGS frame.
  437. frame(State0=#state{socket=Socket, transport=Transport, opts=Opts,
  438. remote_settings=Settings0}, {settings, Settings}) ->
  439. Transport:send(Socket, cow_http2:settings_ack()),
  440. State1 = State0#state{remote_settings=maps:merge(Settings0, Settings)},
  441. maps:fold(fun
  442. (header_table_size, NewSize, State=#state{encode_state=EncodeState0}) ->
  443. MaxSize = maps:get(max_encode_table_size, Opts, 4096),
  444. EncodeState = cow_hpack:set_max_size(min(NewSize, MaxSize), EncodeState0),
  445. State#state{encode_state=EncodeState};
  446. (initial_window_size, NewWindowSize, State) ->
  447. OldWindowSize = maps:get(initial_window_size, Settings0, 65535),
  448. update_streams_local_window(State, NewWindowSize - OldWindowSize);
  449. (_, _, State) ->
  450. State
  451. end, State1, Settings);
  452. %% Ack for a previously sent SETTINGS frame.
  453. frame(State0=#state{local_settings=Local0, next_settings=NextSettings,
  454. next_settings_timer=TRef}, settings_ack) ->
  455. ok = case TRef of
  456. undefined -> ok;
  457. _ -> erlang:cancel_timer(TRef, [{async, true}, {info, false}])
  458. end,
  459. Local = maps:merge(Local0, NextSettings),
  460. State1 = State0#state{local_settings=Local, next_settings=#{},
  461. next_settings_timer=undefined},
  462. maps:fold(fun
  463. (header_table_size, MaxSize, State=#state{decode_state=DecodeState0}) ->
  464. DecodeState = cow_hpack:set_max_size(MaxSize, DecodeState0),
  465. State#state{decode_state=DecodeState};
  466. (initial_window_size, NewWindowSize, State) ->
  467. OldWindowSize = maps:get(initial_window_size, Local0, 65535),
  468. update_streams_remote_window(State, NewWindowSize - OldWindowSize);
  469. (_, _, State) ->
  470. State
  471. end, State1, NextSettings);
  472. %% Unexpected PUSH_PROMISE frame.
  473. frame(State, {push_promise, _, _, _, _}) ->
  474. terminate(State, {connection_error, protocol_error,
  475. 'PUSH_PROMISE frames MUST only be sent on a peer-initiated stream. (RFC7540 6.6)'});
  476. %% PING frame.
  477. frame(State=#state{socket=Socket, transport=Transport}, {ping, Opaque}) ->
  478. Transport:send(Socket, cow_http2:ping_ack(Opaque)),
  479. State;
  480. %% Ack for a previously sent PING frame.
  481. %%
  482. %% @todo Might want to check contents but probably a waste of time.
  483. frame(State, {ping_ack, _Opaque}) ->
  484. State;
  485. %% GOAWAY frame.
  486. frame(State, Frame={goaway, _, _, _}) ->
  487. terminate(State, {stop, Frame, 'Client is going away.'});
  488. %% Connection-wide WINDOW_UPDATE frame.
  489. frame(State=#state{local_window=ConnWindow}, {window_update, Increment})
  490. when ConnWindow + Increment > 16#7fffffff ->
  491. terminate(State, {connection_error, flow_control_error,
  492. 'The flow control window must not be greater than 2^31-1. (RFC7540 6.9.1)'});
  493. frame(State=#state{local_window=ConnWindow}, {window_update, Increment}) ->
  494. send_data(State#state{local_window=ConnWindow + Increment});
  495. %% Stream-specific WINDOW_UPDATE frame.
  496. frame(State=#state{client_streamid=LastStreamID}, {window_update, StreamID, _})
  497. when StreamID > LastStreamID ->
  498. terminate(State, {connection_error, protocol_error,
  499. 'WINDOW_UPDATE frame received on a stream in idle state. (RFC7540 5.1)'});
  500. frame(State0=#state{streams=Streams0, rst_lingering_streams=RstLingering},
  501. {window_update, StreamID, Increment}) ->
  502. case lists:keyfind(StreamID, #stream.id, Streams0) of
  503. #stream{local_window=StreamWindow} when StreamWindow + Increment > 16#7fffffff ->
  504. stream_reset(State0, StreamID, {stream_error, flow_control_error,
  505. 'The flow control window must not be greater than 2^31-1. (RFC7540 6.9.1)'});
  506. Stream0 = #stream{local_window=StreamWindow} ->
  507. {State, Stream} = send_data(State0,
  508. Stream0#stream{local_window=StreamWindow + Increment}),
  509. Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
  510. State#state{streams=Streams};
  511. false ->
  512. %% WINDOW_UPDATE frames may be received for a short period of time
  513. %% after a stream is closed. They must be ignored.
  514. case lists:member(StreamID, RstLingering) of
  515. false -> State0;
  516. true -> stream_closed(State0, StreamID, {stream_error, stream_closed,
  517. 'WINDOW_UPDATE frame received after the stream was reset. (RFC7540 5.1)'})
  518. end
  519. end;
  520. %% Unexpected CONTINUATION frame.
  521. frame(State, {continuation, _, _, _}) ->
  522. terminate(State, {connection_error, protocol_error,
  523. 'CONTINUATION frames MUST be preceded by a HEADERS frame. (RFC7540 6.10)'}).
  524. data_frame(State, Stream0=#stream{id=StreamID, remote_window=StreamWindow,
  525. remote_read_size=StreamRead}, IsFin, DataLen, Data) ->
  526. Stream = Stream0#stream{remote=IsFin,
  527. remote_window=StreamWindow - DataLen,
  528. remote_read_size=StreamRead + DataLen},
  529. case is_body_size_valid(Stream) of
  530. true ->
  531. data_frame(State, Stream, IsFin, Data);
  532. false ->
  533. stream_reset(after_commands(State, Stream), StreamID, {stream_error, protocol_error,
  534. 'The total size of DATA frames is different than the content-length. (RFC7540 8.1.2.6)'})
  535. end.
  536. %% We ignore DATA frames for streams that are flushing out data.
  537. data_frame(State, Stream=#stream{state=flush}, _, _) ->
  538. after_commands(State, Stream);
  539. data_frame(State=#state{opts=Opts}, Stream=#stream{id=StreamID, state=StreamState0},
  540. IsFin, Data) ->
  541. try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
  542. {Commands, StreamState} ->
  543. commands(State, Stream#stream{state=StreamState}, Commands)
  544. catch Class:Exception ->
  545. cowboy:log(cowboy_stream:make_error_log(data,
  546. [StreamID, IsFin, Data, StreamState0],
  547. Class, Exception, erlang:get_stacktrace()), Opts),
  548. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  549. 'Unhandled exception in cowboy_stream:data/4.'})
  550. end.
  551. %% It's always valid when no content-length header was specified.
  552. is_body_size_valid(#stream{remote_expected_size=undefined}) ->
  553. true;
  554. %% We didn't finish reading the body but the size is already larger than expected.
  555. is_body_size_valid(#stream{remote=nofin, remote_expected_size=Expected,
  556. remote_read_size=Read}) when Read > Expected ->
  557. false;
  558. is_body_size_valid(#stream{remote=nofin}) ->
  559. true;
  560. is_body_size_valid(#stream{remote=fin, remote_expected_size=Expected,
  561. remote_read_size=Expected}) ->
  562. true;
  563. %% We finished reading the body and the size read is not the one expected.
  564. is_body_size_valid(_) ->
  565. false.
  566. continuation_frame(State=#state{client_streamid=LastStreamID, streams=Streams,
  567. parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
  568. {continuation, StreamID, head_fin, HeaderBlockFragment1}) ->
  569. HeaderBlock = << HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>,
  570. case StreamID > LastStreamID of
  571. true -> %% New stream.
  572. stream_decode_init(State#state{parse_state=normal}, StreamID, IsFin, HeaderBlock);
  573. false -> %% Trailers.
  574. Stream = lists:keyfind(StreamID, #stream.id, Streams),
  575. stream_decode_trailers(State, Stream, HeaderBlock)
  576. end;
  577. continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
  578. {continuation, StreamID, head_nofin, HeaderBlockFragment1}) ->
  579. State#state{parse_state={continuation, StreamID, IsFin,
  580. << HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>}};
  581. continuation_frame(State, _) ->
  582. terminate(State, {connection_error, protocol_error,
  583. 'An invalid frame was received in the middle of a header block. (RFC7540 6.2)'}).
  584. down(State=#state{opts=Opts, children=Children0}, Pid, Msg) ->
  585. case cowboy_children:down(Children0, Pid) of
  586. %% The stream was terminated already.
  587. {ok, undefined, Children} ->
  588. State#state{children=Children};
  589. %% The stream is still running.
  590. {ok, StreamID, Children} ->
  591. info(State#state{children=Children}, StreamID, Msg);
  592. %% The process was unknown.
  593. error ->
  594. cowboy:log(warning, "Received EXIT signal ~p for unknown process ~p.~n",
  595. [Msg, Pid], Opts),
  596. State
  597. end.
  598. info(State=#state{opts=Opts, client_streamid=LastStreamID, streams=Streams}, StreamID, Msg) ->
  599. case lists:keyfind(StreamID, #stream.id, Streams) of
  600. #stream{state=flush} ->
  601. cowboy:log(warning, "Received message ~p for terminated stream ~p.",
  602. [Msg, StreamID], Opts),
  603. State;
  604. Stream = #stream{state=StreamState0} ->
  605. try cowboy_stream:info(StreamID, Msg, StreamState0) of
  606. {Commands, StreamState} ->
  607. commands(State, Stream#stream{state=StreamState}, Commands)
  608. catch Class:Exception ->
  609. cowboy:log(cowboy_stream:make_error_log(info,
  610. [StreamID, Msg, StreamState0],
  611. Class, Exception, erlang:get_stacktrace()), Opts),
  612. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  613. 'Unhandled exception in cowboy_stream:info/3.'})
  614. end;
  615. false when StreamID =< LastStreamID ->
  616. %% Streams that were reset by the client or streams that are
  617. %% in the lingering state may still have Erlang messages going
  618. %% around. In these cases we do not want to log anything.
  619. State;
  620. false ->
  621. cowboy:log(warning, "Received message ~p for unknown stream ~p.",
  622. [Msg, StreamID], Opts),
  623. State
  624. end.
  625. %% @todo Kill the stream if it tries to send a response, headers,
  626. %% data or push promise when the stream is closed or half-closed.
  627. commands(State, Stream, []) ->
  628. after_commands(State, Stream);
  629. %% Error responses are sent only if a response wasn't sent already.
  630. commands(State, Stream=#stream{local=idle}, [{error_response, StatusCode, Headers, Body}|Tail]) ->
  631. commands(State, Stream, [{response, StatusCode, Headers, Body}|Tail]);
  632. commands(State, Stream, [{error_response, _, _, _}|Tail]) ->
  633. commands(State, Stream, Tail);
  634. %% Send an informational response.
  635. commands(State0, Stream=#stream{local=idle}, [{inform, StatusCode, Headers}|Tail]) ->
  636. State = send_headers(State0, Stream, StatusCode, Headers, nofin),
  637. commands(State, Stream, Tail);
  638. %% Send response headers.
  639. commands(State0, Stream0=#stream{local=idle},
  640. [{response, StatusCode, Headers, Body}|Tail]) ->
  641. {State, Stream} = send_response(State0, Stream0, StatusCode, Headers, Body),
  642. commands(State, Stream, Tail);
  643. %% Send response headers.
  644. commands(State0, Stream=#stream{method=Method, local=idle},
  645. [{headers, StatusCode, Headers}|Tail]) ->
  646. IsFin = case Method of
  647. <<"HEAD">> -> fin;
  648. _ -> nofin
  649. end,
  650. State = send_headers(State0, Stream, StatusCode, Headers, IsFin),
  651. commands(State, Stream#stream{local=IsFin}, Tail);
  652. %% Send a response body chunk.
  653. commands(State0, Stream0=#stream{local=nofin}, [{data, IsFin, Data}|Tail]) ->
  654. {State, Stream} = send_data(State0, Stream0, IsFin, Data),
  655. commands(State, Stream, Tail);
  656. %% Send trailers.
  657. commands(State0, Stream0=#stream{local=nofin, te=TE0}, [{trailers, Trailers}|Tail]) ->
  658. %% We only accept TE headers containing exactly "trailers" (RFC7540 8.1.2.1).
  659. TE = try cow_http_hd:parse_te(TE0) of
  660. {trailers, []} -> trailers;
  661. _ -> no_trailers
  662. catch _:_ ->
  663. %% If we can't parse the TE header, assume we can't send trailers.
  664. no_trailers
  665. end,
  666. {State, Stream} = case TE of
  667. trailers ->
  668. send_data(State0, Stream0, fin, {trailers, Trailers});
  669. no_trailers ->
  670. send_data(State0, Stream0, fin, <<>>)
  671. end,
  672. commands(State, Stream, Tail);
  673. %% Send a file.
  674. %% @todo Add the sendfile command.
  675. %commands(State0, Stream0=#stream{local=nofin},
  676. % [{sendfile, IsFin, Offset, Bytes, Path}|Tail]) ->
  677. % {State, Stream} = send_data(State0, Stream0, IsFin, {sendfile, Offset, Bytes, Path}),
  678. % commands(State, Stream, Tail);
  679. %% Push promises are not sent to clients who disabled them.
  680. commands(State=#state{remote_settings=#{enable_push := false}}, Stream,
  681. [{push, _, _, _, _, _, _, _}|Tail]) ->
  682. commands(State, Stream, Tail);
  683. %% Send a push promise.
  684. %%
  685. %% @todo We need to keep track of what promises we made so that we don't
  686. %% end up with an infinite loop of promises.
  687. commands(State0=#state{socket=Socket, transport=Transport, server_streamid=PromisedStreamID,
  688. encode_state=EncodeState0}, Stream=#stream{id=StreamID},
  689. [{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) ->
  690. Authority = case {Scheme, Port} of
  691. {<<"http">>, 80} -> Host;
  692. {<<"https">>, 443} -> Host;
  693. _ -> iolist_to_binary([Host, $:, integer_to_binary(Port)])
  694. end,
  695. PathWithQs = iolist_to_binary(case Qs of
  696. <<>> -> Path;
  697. _ -> [Path, $?, Qs]
  698. end),
  699. %% We need to make sure the header value is binary before we can
  700. %% pass it to stream_req_init, as it expects them to be flat.
  701. Headers1 = maps:map(fun(_, V) -> iolist_to_binary(V) end, Headers0),
  702. Headers = Headers1#{
  703. <<":method">> => Method,
  704. <<":scheme">> => Scheme,
  705. <<":authority">> => Authority,
  706. <<":path">> => PathWithQs},
  707. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  708. Transport:send(Socket, cow_http2:push_promise(StreamID, PromisedStreamID, HeaderBlock)),
  709. State = stream_req_init(State0#state{server_streamid=PromisedStreamID + 2,
  710. encode_state=EncodeState}, PromisedStreamID, fin, Headers1, #{
  711. method => Method,
  712. scheme => Scheme,
  713. authority => Authority,
  714. path => PathWithQs
  715. }),
  716. commands(State, Stream, Tail);
  717. commands(State=#state{socket=Socket, transport=Transport, remote_window=ConnWindow},
  718. Stream=#stream{id=StreamID, remote_window=StreamWindow},
  719. [{flow, Size}|Tail]) ->
  720. Transport:send(Socket, [
  721. cow_http2:window_update(Size),
  722. cow_http2:window_update(StreamID, Size)
  723. ]),
  724. commands(State#state{remote_window=ConnWindow + Size},
  725. Stream#stream{remote_window=StreamWindow + Size}, Tail);
  726. %% Supervise a child process.
  727. commands(State=#state{children=Children}, Stream=#stream{id=StreamID},
  728. [{spawn, Pid, Shutdown}|Tail]) ->
  729. commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)},
  730. Stream, Tail);
  731. %% Error handling.
  732. commands(State, Stream=#stream{id=StreamID}, [Error = {internal_error, _, _}|_Tail]) ->
  733. %% @todo Do we want to run the commands after an internal_error?
  734. %% @todo Do we even allow commands after?
  735. %% @todo Only reset when the stream still exists.
  736. stream_reset(after_commands(State, Stream), StreamID, Error);
  737. %% Upgrade to HTTP/2. This is triggered by cowboy_http2 itself.
  738. commands(State=#state{socket=Socket, transport=Transport},
  739. Stream=#stream{local=upgrade}, [{switch_protocol, Headers, ?MODULE, _}|Tail]) ->
  740. Transport:send(Socket, cow_http:response(101, 'HTTP/1.1', maps:to_list(Headers))),
  741. commands(State, Stream#stream{local=idle}, Tail);
  742. %% Use a different protocol within the stream (CONNECT :protocol).
  743. %% @todo Make sure we error out when the feature is disabled.
  744. commands(State0, #stream{id=StreamID}, [{switch_protocol, Headers, _Mod, _ModState}|Tail]) ->
  745. State = #state{streams=Streams} = info(State0, StreamID, {headers, 200, Headers}),
  746. Stream = lists:keyfind(StreamID, #stream.id, Streams),
  747. commands(State, Stream, Tail);
  748. commands(State, Stream=#stream{id=StreamID}, [stop|_Tail]) ->
  749. %% @todo Do we want to run the commands after a stop?
  750. %% @todo Do we even allow commands after?
  751. stream_terminate(after_commands(State, Stream), StreamID, normal);
  752. %% Log event.
  753. commands(State=#state{opts=Opts}, StreamID, [Log={log, _, _, _}|Tail]) ->
  754. cowboy:log(Log, Opts),
  755. commands(State, StreamID, Tail).
  756. after_commands(State=#state{streams=Streams0}, Stream=#stream{id=StreamID}) ->
  757. Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
  758. State#state{streams=Streams}.
  759. send_response(State0, Stream=#stream{method=Method}, StatusCode, Headers0, Body) ->
  760. if
  761. Method =:= <<"HEAD">>; Body =:= <<>> ->
  762. State = send_headers(State0, Stream, StatusCode, Headers0, fin),
  763. {State, Stream#stream{local=fin}};
  764. true ->
  765. State = send_headers(State0, Stream, StatusCode, Headers0, nofin),
  766. %% send_data works with both sendfile and iolists.
  767. send_data(State, Stream#stream{local=nofin}, fin, Body)
  768. end.
  769. send_headers(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  770. #stream{id=StreamID}, StatusCode, Headers0, IsFin) ->
  771. Headers = Headers0#{<<":status">> => status(StatusCode)},
  772. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  773. Transport:send(Socket, cow_http2:headers(StreamID, IsFin, HeaderBlock)),
  774. State#state{encode_state=EncodeState}.
  775. status(Status) when is_integer(Status) ->
  776. integer_to_binary(Status);
  777. status(<< H, T, U, _/bits >>) when H >= $1, H =< $9, T >= $0, T =< $9, U >= $0, U =< $9 ->
  778. << H, T, U >>.
  779. %% @todo Should we ever want to implement the PRIORITY mechanism,
  780. %% this would be the place to do it. Right now, we just go over
  781. %% all streams and send what we can until either everything is
  782. %% sent or we run out of space in the window.
  783. send_data(State=#state{streams=Streams}) ->
  784. resume_streams(State, Streams, []).
  785. %% When SETTINGS_INITIAL_WINDOW_SIZE changes we need to update
  786. %% the local stream windows for all active streams and perhaps
  787. %% resume sending data.
  788. update_streams_local_window(State=#state{streams=Streams0}, Increment) ->
  789. Streams = [
  790. S#stream{local_window=StreamWindow + Increment}
  791. || S=#stream{local_window=StreamWindow} <- Streams0],
  792. resume_streams(State, Streams, []).
  793. %% When we receive an ack to a SETTINGS frame we sent we need to update
  794. %% the remote stream windows for all active streams.
  795. update_streams_remote_window(State=#state{streams=Streams0}, Increment) ->
  796. Streams = [
  797. S#stream{remote_window=StreamWindow + Increment}
  798. || S=#stream{remote_window=StreamWindow} <- Streams0],
  799. State#state{streams=Streams}.
  800. resume_streams(State, [], Acc) ->
  801. State#state{streams=lists:reverse(Acc)};
  802. %% While technically we should never get < 0 here, let's be on the safe side.
  803. resume_streams(State=#state{local_window=ConnWindow}, Streams, Acc)
  804. when ConnWindow =< 0 ->
  805. State#state{streams=lists:reverse(Acc, Streams)};
  806. %% We rely on send_data/2 to do all the necessary checks about the stream.
  807. resume_streams(State0, [Stream0|Tail], Acc) ->
  808. {State1, Stream} = send_data(State0, Stream0),
  809. case Stream of
  810. %% We are done flushing, remove the stream.
  811. %% Maybe skip the request body if it was not fully read.
  812. #stream{state=flush, local=fin} ->
  813. State = maybe_skip_body(State1, Stream, normal),
  814. resume_streams(State, Tail, Acc);
  815. %% Keep the stream. Either the stream handler is still running,
  816. %% or we are not finished flushing.
  817. _ ->
  818. resume_streams(State1, Tail, [Stream|Acc])
  819. end.
  820. send_data(State, Stream=#stream{local=Local, local_buffer_size=0, local_trailers=Trailers})
  821. when (Trailers =/= undefined) andalso ((Local =:= idle) orelse (Local =:= nofin)) ->
  822. send_trailers(State, Stream#stream{local_trailers=undefined}, Trailers);
  823. %% @todo It's possible that the stream terminates. We must remove it.
  824. send_data(State=#state{local_window=ConnWindow},
  825. Stream=#stream{local=IsFin, local_window=StreamWindow, local_buffer_size=BufferSize})
  826. when ConnWindow =< 0; IsFin =:= fin; StreamWindow =< 0; BufferSize =:= 0 ->
  827. {State, Stream};
  828. send_data(State0, Stream0=#stream{local_buffer=Q0, local_buffer_size=BufferSize}) ->
  829. %% We know there is an item in the queue.
  830. {{value, {IsFin, DataSize, Data}}, Q} = queue:out(Q0),
  831. {State, Stream} = send_data(State0,
  832. Stream0#stream{local_buffer=Q, local_buffer_size=BufferSize - DataSize},
  833. IsFin, Data, in_r),
  834. send_data(State, Stream).
  835. send_data(State, Stream, IsFin, Data) ->
  836. send_data(State, Stream, IsFin, Data, in).
  837. %% We can send trailers immediately if the queue is empty, otherwise we queue.
  838. %% We always send trailer frames even if the window is empty.
  839. send_data(State, Stream=#stream{local_buffer_size=0}, fin, {trailers, Trailers}, _) ->
  840. send_trailers(State, Stream, Trailers);
  841. send_data(State, Stream, fin, {trailers, Trailers}, _) ->
  842. {State, Stream#stream{local_trailers=Trailers}};
  843. %% Send data immediately if we can, buffer otherwise.
  844. send_data(State=#state{local_window=ConnWindow},
  845. Stream=#stream{local_window=StreamWindow}, IsFin, Data, In)
  846. when ConnWindow =< 0; StreamWindow =< 0 ->
  847. {State, queue_data(Stream, IsFin, Data, In)};
  848. send_data(State=#state{socket=Socket, transport=Transport, opts=Opts,
  849. remote_settings=RemoteSettings, local_window=ConnWindow},
  850. Stream=#stream{id=StreamID, local_window=StreamWindow}, IsFin, Data, In) ->
  851. RemoteMaxFrameSize = maps:get(max_frame_size, RemoteSettings, 16384),
  852. ConfiguredMaxFrameSize = maps:get(max_frame_size_sent, Opts, infinity),
  853. MaxSendSize = min(
  854. min(ConnWindow, StreamWindow),
  855. min(RemoteMaxFrameSize, ConfiguredMaxFrameSize)
  856. ),
  857. case Data of
  858. {sendfile, Offset, Bytes, Path} when Bytes =< MaxSendSize ->
  859. Transport:send(Socket, cow_http2:data_header(StreamID, IsFin, Bytes)),
  860. Transport:sendfile(Socket, Path, Offset, Bytes),
  861. {State#state{local_window=ConnWindow - Bytes},
  862. Stream#stream{local=IsFin, local_window=StreamWindow - Bytes}};
  863. {sendfile, Offset, Bytes, Path} ->
  864. Transport:send(Socket, cow_http2:data_header(StreamID, nofin, MaxSendSize)),
  865. Transport:sendfile(Socket, Path, Offset, MaxSendSize),
  866. send_data(State#state{local_window=ConnWindow - MaxSendSize},
  867. Stream#stream{local_window=StreamWindow - MaxSendSize},
  868. IsFin, {sendfile, Offset + MaxSendSize, Bytes - MaxSendSize, Path}, In);
  869. Iolist0 ->
  870. IolistSize = iolist_size(Iolist0),
  871. if
  872. IolistSize =< MaxSendSize ->
  873. Transport:send(Socket, cow_http2:data(StreamID, IsFin, Iolist0)),
  874. {State#state{local_window=ConnWindow - IolistSize},
  875. Stream#stream{local=IsFin, local_window=StreamWindow - IolistSize}};
  876. true ->
  877. {Iolist, More} = cow_iolists:split(MaxSendSize, Iolist0),
  878. Transport:send(Socket, cow_http2:data(StreamID, nofin, Iolist)),
  879. send_data(State#state{local_window=ConnWindow - MaxSendSize},
  880. Stream#stream{local_window=StreamWindow - MaxSendSize},
  881. IsFin, More, In)
  882. end
  883. end.
  884. send_trailers(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  885. Stream=#stream{id=StreamID}, Trailers) ->
  886. {HeaderBlock, EncodeState} = headers_encode(Trailers, EncodeState0),
  887. Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
  888. {State#state{encode_state=EncodeState}, Stream#stream{local=fin}}.
  889. queue_data(Stream=#stream{local_buffer=Q0, local_buffer_size=Size0}, IsFin, Data, In) ->
  890. DataSize = case Data of
  891. {sendfile, _, Bytes, _} -> Bytes;
  892. Iolist -> iolist_size(Iolist)
  893. end,
  894. Q = queue:In({IsFin, DataSize, Data}, Q0),
  895. Stream#stream{local_buffer=Q, local_buffer_size=Size0 + DataSize}.
  896. %% The set-cookie header is special; we can only send one cookie per header.
  897. headers_encode(Headers0=#{<<"set-cookie">> := SetCookies}, EncodeState) ->
  898. Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  899. Headers = Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies],
  900. cow_hpack:encode(Headers, EncodeState);
  901. headers_encode(Headers0, EncodeState) ->
  902. Headers = maps:to_list(Headers0),
  903. cow_hpack:encode(Headers, EncodeState).
  904. -spec terminate(#state{}, _) -> no_return().
  905. terminate(undefined, Reason) ->
  906. exit({shutdown, Reason});
  907. terminate(#state{socket=Socket, transport=Transport, parse_state={preface, _, _}}, Reason) ->
  908. Transport:close(Socket),
  909. exit({shutdown, Reason});
  910. terminate(State=#state{socket=Socket, transport=Transport, client_streamid=LastStreamID,
  911. streams=Streams, children=Children}, Reason) ->
  912. %% @todo We might want to optionally send the Reason value
  913. %% as debug data in the GOAWAY frame here. Perhaps more.
  914. Transport:send(Socket, cow_http2:goaway(LastStreamID, terminate_reason(Reason), <<>>)),
  915. terminate_all_streams(State, Streams, Reason),
  916. cowboy_children:terminate(Children),
  917. Transport:close(Socket),
  918. exit({shutdown, Reason}).
  919. terminate_reason({connection_error, Reason, _}) -> Reason;
  920. terminate_reason({stop, _, _}) -> no_error;
  921. terminate_reason({socket_error, _, _}) -> internal_error;
  922. terminate_reason({internal_error, _, _}) -> internal_error.
  923. terminate_all_streams(_, [], _) ->
  924. ok;
  925. %% This stream was already terminated and is now just flushing the data out. Skip it.
  926. terminate_all_streams(State, [#stream{state=flush}|Tail], Reason) ->
  927. terminate_all_streams(State, Tail, Reason);
  928. terminate_all_streams(State, [#stream{id=StreamID, state=StreamState}|Tail], Reason) ->
  929. stream_call_terminate(StreamID, Reason, StreamState, State),
  930. terminate_all_streams(State, Tail, Reason).
  931. %% Stream functions.
  932. stream_decode_init(State=#state{decode_state=DecodeState0}, StreamID, IsFin, HeaderBlock) ->
  933. try cow_hpack:decode(HeaderBlock, DecodeState0) of
  934. {Headers, DecodeState} ->
  935. stream_enforce_concurrency_limit(State#state{decode_state=DecodeState},
  936. StreamID, IsFin, Headers)
  937. catch _:_ ->
  938. terminate(State, {connection_error, compression_error,
  939. 'Error while trying to decode HPACK-encoded header block. (RFC7540 4.3)'})
  940. end.
  941. stream_enforce_concurrency_limit(State=#state{opts=Opts, streams=Streams},
  942. StreamID, IsFin, Headers) ->
  943. MaxConcurrentStreams = maps:get(max_concurrent_streams, Opts, infinity),
  944. case length(Streams) < MaxConcurrentStreams of
  945. true ->
  946. stream_pseudo_headers_init(State, StreamID, IsFin, Headers);
  947. false ->
  948. stream_refused(State, StreamID,
  949. 'Maximum number of concurrent streams has been reached. (RFC7540 5.1.2)')
  950. end.
  951. stream_pseudo_headers_init(State=#state{local_settings=LocalSettings},
  952. StreamID, IsFin, Headers0) ->
  953. IsExtendedConnectEnabled = maps:get(enable_connect_protocol, LocalSettings, false),
  954. case pseudo_headers(Headers0, #{}) of
  955. {ok, PseudoHeaders=#{method := <<"CONNECT">>, scheme := _,
  956. authority := _, path := _, protocol := _}, Headers}
  957. when IsExtendedConnectEnabled ->
  958. stream_regular_headers_init(State, StreamID, IsFin, Headers, PseudoHeaders);
  959. {ok, #{method := <<"CONNECT">>, scheme := _,
  960. authority := _, path := _}, _}
  961. when IsExtendedConnectEnabled ->
  962. stream_malformed(State, StreamID,
  963. 'The :protocol pseudo-header MUST be sent with an extended CONNECT. (draft_h2_websockets 4)');
  964. {ok, #{protocol := _}, _} ->
  965. stream_malformed(State, StreamID,
  966. 'The :protocol pseudo-header is only defined for the extended CONNECT. (draft_h2_websockets 4)');
  967. %% @todo Add clause for CONNECT requests (no scheme/path).
  968. {ok, PseudoHeaders=#{method := <<"CONNECT">>}, _} ->
  969. stream_early_error(State, StreamID, IsFin, 501, PseudoHeaders,
  970. 'The CONNECT method is currently not implemented. (RFC7231 4.3.6)');
  971. {ok, PseudoHeaders=#{method := <<"TRACE">>}, _} ->
  972. stream_early_error(State, StreamID, IsFin, 501, PseudoHeaders,
  973. 'The TRACE method is currently not implemented. (RFC7231 4.3.8)');
  974. {ok, PseudoHeaders=#{method := _, scheme := _, authority := _, path := _}, Headers} ->
  975. stream_regular_headers_init(State, StreamID, IsFin, Headers, PseudoHeaders);
  976. {ok, _, _} ->
  977. stream_malformed(State, StreamID,
  978. 'A required pseudo-header was not found. (RFC7540 8.1.2.3)');
  979. {error, HumanReadable} ->
  980. stream_malformed(State, StreamID, HumanReadable)
  981. end.
  982. pseudo_headers([{<<":method">>, _}|_], #{method := _}) ->
  983. {error, 'Multiple :method pseudo-headers were found. (RFC7540 8.1.2.3)'};
  984. pseudo_headers([{<<":method">>, Method}|Tail], PseudoHeaders) ->
  985. pseudo_headers(Tail, PseudoHeaders#{method => Method});
  986. pseudo_headers([{<<":scheme">>, _}|_], #{scheme := _}) ->
  987. {error, 'Multiple :scheme pseudo-headers were found. (RFC7540 8.1.2.3)'};
  988. pseudo_headers([{<<":scheme">>, Scheme}|Tail], PseudoHeaders) ->
  989. pseudo_headers(Tail, PseudoHeaders#{scheme => Scheme});
  990. pseudo_headers([{<<":authority">>, _}|_], #{authority := _}) ->
  991. {error, 'Multiple :authority pseudo-headers were found. (RFC7540 8.1.2.3)'};
  992. pseudo_headers([{<<":authority">>, Authority}|Tail], PseudoHeaders) ->
  993. pseudo_headers(Tail, PseudoHeaders#{authority => Authority});
  994. pseudo_headers([{<<":path">>, _}|_], #{path := _}) ->
  995. {error, 'Multiple :path pseudo-headers were found. (RFC7540 8.1.2.3)'};
  996. pseudo_headers([{<<":path">>, Path}|Tail], PseudoHeaders) ->
  997. pseudo_headers(Tail, PseudoHeaders#{path => Path});
  998. pseudo_headers([{<<":protocol">>, _}|_], #{protocol := _}) ->
  999. {error, 'Multiple :protocol pseudo-headers were found. (RFC7540 8.1.2.3)'};
  1000. pseudo_headers([{<<":protocol">>, Protocol}|Tail], PseudoHeaders) ->
  1001. pseudo_headers(Tail, PseudoHeaders#{protocol => Protocol});
  1002. pseudo_headers([{<<":", _/bits>>, _}|_], _) ->
  1003. {error, 'An unknown or invalid pseudo-header was found. (RFC7540 8.1.2.1)'};
  1004. pseudo_headers(Headers, PseudoHeaders) ->
  1005. {ok, PseudoHeaders, Headers}.
  1006. stream_regular_headers_init(State, StreamID, IsFin, Headers, PseudoHeaders) ->
  1007. case regular_headers(Headers) of
  1008. ok ->
  1009. stream_req_init(State, StreamID, IsFin,
  1010. headers_to_map(Headers, #{}), PseudoHeaders);
  1011. {error, HumanReadable} ->
  1012. stream_malformed(State, StreamID, HumanReadable)
  1013. end.
  1014. regular_headers([{<<":", _/bits>>, _}|_]) ->
  1015. {error, 'Pseudo-headers were found after regular headers. (RFC7540 8.1.2.1)'};
  1016. regular_headers([{<<"connection">>, _}|_]) ->
  1017. {error, 'The connection header is not allowed. (RFC7540 8.1.2.2)'};
  1018. regular_headers([{<<"keep-alive">>, _}|_]) ->
  1019. {error, 'The keep-alive header is not allowed. (RFC7540 8.1.2.2)'};
  1020. regular_headers([{<<"proxy-authenticate">>, _}|_]) ->
  1021. {error, 'The proxy-authenticate header is not allowed. (RFC7540 8.1.2.2)'};
  1022. regular_headers([{<<"proxy-authorization">>, _}|_]) ->
  1023. {error, 'The proxy-authorization header is not allowed. (RFC7540 8.1.2.2)'};
  1024. regular_headers([{<<"transfer-encoding">>, _}|_]) ->
  1025. {error, 'The transfer-encoding header is not allowed. (RFC7540 8.1.2.2)'};
  1026. regular_headers([{<<"upgrade">>, _}|_]) ->
  1027. {error, 'The upgrade header is not allowed. (RFC7540 8.1.2.2)'};
  1028. regular_headers([{<<"te">>, Value}|_]) when Value =/= <<"trailers">> ->
  1029. {error, 'The te header with a value other than "trailers" is not allowed. (RFC7540 8.1.2.2)'};
  1030. regular_headers([{Name, _}|Tail]) ->
  1031. case cowboy_bstr:to_lower(Name) of
  1032. Name -> regular_headers(Tail);
  1033. _ -> {error, 'Header names must be lowercase. (RFC7540 8.1.2)'}
  1034. end;
  1035. regular_headers([]) ->
  1036. ok.
  1037. %% This function is necessary to properly handle duplicate headers
  1038. %% and the special-case cookie header.
  1039. headers_to_map([], Acc) ->
  1040. Acc;
  1041. headers_to_map([{Name, Value}|Tail], Acc0) ->
  1042. Acc = case Acc0 of
  1043. %% The cookie header does not use proper HTTP header lists.
  1044. #{Name := Value0} when Name =:= <<"cookie">> -> Acc0#{Name => << Value0/binary, "; ", Value/binary >>};
  1045. #{Name := Value0} -> Acc0#{Name => << Value0/binary, ", ", Value/binary >>};
  1046. _ -> Acc0#{Name => Value}
  1047. end,
  1048. headers_to_map(Tail, Acc).
  1049. stream_req_init(State, StreamID, IsFin, Headers, PseudoHeaders) ->
  1050. case Headers of
  1051. #{<<"content-length">> := BinLength} when BinLength =/= <<"0">>, IsFin =:= fin ->
  1052. stream_malformed(State, StreamID,
  1053. 'HEADERS frame with the END_STREAM flag contains a non-zero content-length. (RFC7540 8.1.2.6)');
  1054. _ when IsFin =:= fin ->
  1055. stream_req_init(State, StreamID, IsFin, Headers, PseudoHeaders, 0);
  1056. #{<<"content-length">> := <<"0">>} ->
  1057. stream_req_init(State, StreamID, IsFin, Headers, PseudoHeaders, 0);
  1058. #{<<"content-length">> := BinLength} ->
  1059. try
  1060. stream_req_init(State, StreamID, IsFin, Headers, PseudoHeaders,
  1061. cow_http_hd:parse_content_length(BinLength))
  1062. catch _:_ ->
  1063. stream_malformed(State, StreamID,
  1064. 'The content-length header is invalid. (RFC7230 3.3.2)')
  1065. end;
  1066. _ ->
  1067. stream_req_init(State, StreamID, IsFin, Headers, PseudoHeaders, undefined)
  1068. end.
  1069. stream_req_init(State=#state{ref=Ref, peer=Peer, sock=Sock, cert=Cert},
  1070. StreamID, IsFin, Headers, PseudoHeaders=#{method := Method, scheme := Scheme,
  1071. authority := Authority, path := PathWithQs}, BodyLength) ->
  1072. try cow_http_hd:parse_host(Authority) of
  1073. {Host, Port0} ->
  1074. Port = ensure_port(Scheme, Port0),
  1075. try cow_http:parse_fullpath(PathWithQs) of
  1076. {<<>>, _} ->
  1077. stream_malformed(State, StreamID,
  1078. 'The path component must not be empty. (RFC7540 8.1.2.3)');
  1079. {Path, Qs} ->
  1080. Req0 = #{
  1081. ref => Ref,
  1082. pid => self(),
  1083. streamid => StreamID,
  1084. peer => Peer,
  1085. sock => Sock,
  1086. cert => Cert,
  1087. method => Method,
  1088. scheme => Scheme,
  1089. host => Host,
  1090. port => Port,
  1091. path => Path,
  1092. qs => Qs,
  1093. version => 'HTTP/2',
  1094. headers => Headers,
  1095. has_body => IsFin =:= nofin,
  1096. body_length => BodyLength
  1097. },
  1098. %% We add the protocol information for extended CONNECTs.
  1099. Req = case PseudoHeaders of
  1100. #{protocol := Protocol} ->
  1101. Req0#{protocol => Protocol};
  1102. _ ->
  1103. Req0
  1104. end,
  1105. stream_handler_init(State, StreamID, IsFin, idle, Req)
  1106. catch _:_ ->
  1107. stream_malformed(State, StreamID,
  1108. 'The :path pseudo-header is invalid. (RFC7540 8.1.2.3)')
  1109. end
  1110. catch _:_ ->
  1111. stream_malformed(State, StreamID,
  1112. 'The :authority pseudo-header is invalid. (RFC7540 8.1.2.3)')
  1113. end.
  1114. ensure_port(<<"http">>, undefined) -> 80;
  1115. ensure_port(<<"https">>, undefined) -> 443;
  1116. ensure_port(_, Port) -> Port.
  1117. stream_closed(State=#state{socket=Socket, transport=Transport}, StreamID, _) ->
  1118. Transport:send(Socket, cow_http2:rst_stream(StreamID, stream_closed)),
  1119. State.
  1120. stream_malformed(State=#state{socket=Socket, transport=Transport}, StreamID, _) ->
  1121. Transport:send(Socket, cow_http2:rst_stream(StreamID, protocol_error)),
  1122. State.
  1123. stream_refused(State=#state{socket=Socket, transport=Transport}, StreamID, _) ->
  1124. Transport:send(Socket, cow_http2:rst_stream(StreamID, refused_stream)),
  1125. State.
  1126. stream_early_error(State0=#state{ref=Ref, opts=Opts, peer=Peer,
  1127. local_settings=#{initial_window_size := RemoteWindow},
  1128. remote_settings=#{initial_window_size := LocalWindow},
  1129. streams=Streams}, StreamID, IsFin, StatusCode0,
  1130. #{method := Method}, HumanReadable) ->
  1131. %% We automatically terminate the stream but it is not an error
  1132. %% per se (at least not in the first implementation).
  1133. Reason = {stream_error, no_error, HumanReadable},
  1134. %% The partial Req is minimal for now. We only have one case
  1135. %% where it can be called (when a method is completely disabled).
  1136. PartialReq = #{
  1137. ref => Ref,
  1138. peer => Peer,
  1139. method => Method
  1140. },
  1141. Resp = {response, StatusCode0, RespHeaders0=#{<<"content-length">> => <<"0">>}, <<>>},
  1142. %% We need a stream to talk to the send_* functions.
  1143. Stream0 = #stream{id=StreamID, state=flush, method=Method,
  1144. remote=IsFin, local=idle,
  1145. local_window=LocalWindow, remote_window=RemoteWindow},
  1146. try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts) of
  1147. {response, StatusCode, RespHeaders, RespBody} ->
  1148. case send_response(State0, Stream0, StatusCode, RespHeaders, RespBody) of
  1149. {State, #stream{local=fin}} ->
  1150. State;
  1151. {State, Stream} ->
  1152. State#state{streams=[Stream|Streams]}
  1153. end
  1154. catch Class:Exception ->
  1155. cowboy:log(cowboy_stream:make_error_log(early_error,
  1156. [StreamID, Reason, PartialReq, Resp, Opts],
  1157. Class, Exception, erlang:get_stacktrace()), Opts),
  1158. %% We still need to send an error response, so send what we initially
  1159. %% wanted to send. It's better than nothing.
  1160. send_headers(State0, Stream0, StatusCode0, RespHeaders0, fin)
  1161. end.
  1162. stream_handler_init(State=#state{opts=Opts,
  1163. local_settings=#{initial_window_size := RemoteWindow},
  1164. remote_settings=#{initial_window_size := LocalWindow}},
  1165. StreamID, RemoteIsFin, LocalIsFin,
  1166. Req=#{method := Method, headers := Headers, body_length := BodyLength}) ->
  1167. try cowboy_stream:init(StreamID, Req, Opts) of
  1168. {Commands, StreamState} ->
  1169. commands(State#state{client_streamid=StreamID},
  1170. #stream{id=StreamID, state=StreamState,
  1171. method=Method, remote=RemoteIsFin, local=LocalIsFin,
  1172. local_window=LocalWindow, remote_window=RemoteWindow,
  1173. remote_expected_size=BodyLength,
  1174. te=maps:get(<<"te">>, Headers, undefined)},
  1175. Commands)
  1176. catch Class:Exception ->
  1177. cowboy:log(cowboy_stream:make_error_log(init,
  1178. [StreamID, Req, Opts],
  1179. Class, Exception, erlang:get_stacktrace()), Opts),
  1180. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  1181. 'Unhandled exception in cowboy_stream:init/3.'})
  1182. end.
  1183. stream_decode_trailers(State=#state{decode_state=DecodeState0}, Stream, HeaderBlock) ->
  1184. try cow_hpack:decode(HeaderBlock, DecodeState0) of
  1185. {Headers, DecodeState} ->
  1186. stream_trailers_is_body_size_valid(State#state{decode_state=DecodeState},
  1187. Stream#stream{remote=fin}, Headers)
  1188. catch _:_ ->
  1189. terminate(State, {connection_error, compression_error,
  1190. 'Error while trying to decode HPACK-encoded header block. (RFC7540 4.3)'})
  1191. end.
  1192. stream_trailers_is_body_size_valid(State, Stream=#stream{id=StreamID}, Headers) ->
  1193. case is_body_size_valid(Stream) of
  1194. true ->
  1195. stream_reject_pseudo_headers_in_trailers(State, Stream, Headers);
  1196. false ->
  1197. stream_reset(after_commands(State, Stream), StreamID, {stream_error, protocol_error,
  1198. 'The total size of DATA frames is different than the content-length. (RFC7540 8.1.2.6)'})
  1199. end.
  1200. stream_reject_pseudo_headers_in_trailers(State, Stream=#stream{id=StreamID}, Headers) ->
  1201. case has_pseudo_header(Headers) of
  1202. false ->
  1203. %% @todo There's probably a number of regular headers forbidden too.
  1204. %% @todo Propagate trailers.
  1205. after_commands(State, Stream);
  1206. true ->
  1207. stream_reset(after_commands(State, Stream), StreamID, {stream_error, protocol_error,
  1208. 'Trailer header blocks must not contain pseudo-headers. (RFC7540 8.1.2.1)'})
  1209. end.
  1210. has_pseudo_header([]) ->
  1211. false;
  1212. has_pseudo_header([{<<":", _/bits>>, _}|_]) ->
  1213. true;
  1214. has_pseudo_header([_|Tail]) ->
  1215. has_pseudo_header(Tail).
  1216. %% @todo Don't send an RST_STREAM if one was already sent.
  1217. stream_reset(State=#state{socket=Socket, transport=Transport}, StreamID, StreamError) ->
  1218. Reason = case StreamError of
  1219. {internal_error, _, _} -> internal_error;
  1220. {stream_error, Reason0, _} -> Reason0
  1221. end,
  1222. Transport:send(Socket, cow_http2:rst_stream(StreamID, Reason)),
  1223. stream_terminate(stream_linger(State, StreamID), StreamID, StreamError).
  1224. %% We only keep up to 100 streams in this state. @todo Make it configurable?
  1225. stream_linger(State=#state{lingering_streams=Lingering0}, StreamID) ->
  1226. Lingering = [StreamID|lists:sublist(Lingering0, 100 - 1)],
  1227. State#state{lingering_streams=Lingering}.
  1228. %% We only keep up to 10 streams in this state. @todo Make it configurable?
  1229. stream_rst_linger(State=#state{rst_lingering_streams=Lingering0}, StreamID) ->
  1230. Lingering = [StreamID|lists:sublist(Lingering0, 10 - 1)],
  1231. State#state{rst_lingering_streams=Lingering}.
  1232. stream_terminate(State0=#state{streams=Streams0, children=Children0}, StreamID, Reason) ->
  1233. case lists:keytake(StreamID, #stream.id, Streams0) of
  1234. %% When the stream terminates normally (without sending RST_STREAM)
  1235. %% and no response was sent, we need to send a proper response back to the client.
  1236. {value, Stream=#stream{local=idle}, Streams} when Reason =:= normal ->
  1237. State1 = #state{streams=Streams1} = info(State0, StreamID, {response, 204, #{}, <<>>}),
  1238. State = maybe_skip_body(State1, Stream, Reason),
  1239. #stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams1),
  1240. stream_call_terminate(StreamID, Reason, StreamState, State),
  1241. Children = cowboy_children:shutdown(Children0, StreamID),
  1242. State#state{streams=Streams, children=Children};
  1243. %% When a response was sent but not terminated, we need to close the stream.
  1244. {value, Stream=#stream{local=nofin, local_buffer_size=0}, Streams}
  1245. when Reason =:= normal ->
  1246. State1 = #state{streams=Streams1} = info(State0, StreamID, {data, fin, <<>>}),
  1247. State = maybe_skip_body(State1, Stream, Reason),
  1248. #stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams1),
  1249. stream_call_terminate(StreamID, Reason, StreamState, State),
  1250. Children = cowboy_children:shutdown(Children0, StreamID),
  1251. State#state{streams=Streams, children=Children};
  1252. %% Unless there is still data in the buffer. We can however reset
  1253. %% a few fields and set a special local state to avoid confusion.
  1254. %%
  1255. %% We do not reset the stream in this case (to skip the body)
  1256. %% because we are still sending data via the buffer. We will
  1257. %% reset the stream if necessary once the buffer is empty.
  1258. {value, Stream=#stream{state=StreamState, local=nofin}, Streams} ->
  1259. stream_call_terminate(StreamID, Reason, StreamState, State0),
  1260. Children = cowboy_children:shutdown(Children0, StreamID),
  1261. State0#state{streams=[Stream#stream{state=flush, local=flush}|Streams],
  1262. children=Children};
  1263. %% Otherwise we sent or received an RST_STREAM and/or the stream is already closed.
  1264. {value, Stream=#stream{state=StreamState}, Streams} ->
  1265. State = maybe_skip_body(State0, Stream, Reason),
  1266. stream_call_terminate(StreamID, Reason, StreamState, State),
  1267. Children = cowboy_children:shutdown(Children0, StreamID),
  1268. State#state{streams=Streams, children=Children};
  1269. %% The stream doesn't exist. This can occur for various reasons.
  1270. %% It can happen before the stream has been created, or because
  1271. %% the cowboy_stream:init call failed, in which case doing nothing
  1272. %% is correct.
  1273. false ->
  1274. State0
  1275. end.
  1276. %% When the stream stops normally without reading the request
  1277. %% body fully we need to tell the client to stop sending it.
  1278. %% We do this by sending an RST_STREAM with reason NO_ERROR. (RFC7540 8.1.0)
  1279. maybe_skip_body(State=#state{socket=Socket, transport=Transport},
  1280. #stream{id=StreamID, remote=nofin}, normal) ->
  1281. Transport:send(Socket, cow_http2:rst_stream(StreamID, no_error)),
  1282. stream_linger(State, StreamID);
  1283. maybe_skip_body(State, _, _) ->
  1284. State.
  1285. stream_call_terminate(StreamID, Reason, StreamState, #state{opts=Opts}) ->
  1286. try
  1287. cowboy_stream:terminate(StreamID, Reason, StreamState)
  1288. catch Class:Exception ->
  1289. cowboy:log(cowboy_stream:make_error_log(terminate,
  1290. [StreamID, Reason, StreamState],
  1291. Class, Exception, erlang:get_stacktrace()), Opts)
  1292. end.
  1293. %% System callbacks.
  1294. -spec system_continue(_, _, {#state{}, binary()}) -> ok.
  1295. system_continue(_, _, {State, Buffer}) ->
  1296. loop(State, Buffer).
  1297. -spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return().
  1298. system_terminate(Reason, _, _, {State, _}) ->
  1299. %% @todo We should exit gracefully, if possible.
  1300. terminate(State, Reason).
  1301. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  1302. system_code_change(Misc, _, _, _) ->
  1303. {ok, Misc}.