cowboy_http2.erl 37 KB

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