cowboy_http2.erl 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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. -record(stream, {
  22. id = undefined :: cowboy_stream:streamid(),
  23. %% Stream handlers and their state.
  24. state = undefined :: {module(), any()},
  25. %% Whether we finished sending data.
  26. local = idle :: idle | cowboy_stream:fin(),
  27. %% Whether we finished receiving data.
  28. remote = nofin :: cowboy_stream:fin(),
  29. %% Request body length.
  30. body_length = 0 :: non_neg_integer()
  31. }).
  32. -type stream() :: #stream{}.
  33. -record(state, {
  34. parent = undefined :: pid(),
  35. ref :: ranch:ref(),
  36. socket = undefined :: inet:socket(),
  37. transport :: module(),
  38. opts = #{} :: map(),
  39. %% Remote address and port for the connection.
  40. peer = undefined :: {inet:ip_address(), inet:port_number()},
  41. %% Settings are separate for each endpoint. In addition, settings
  42. %% must be acknowledged before they can be expected to be applied.
  43. %%
  44. %% @todo Since the ack is required, we must timeout if we don't receive it.
  45. %% @todo I haven't put as much thought as I should have on this,
  46. %% the final settings handling will be very different.
  47. local_settings = #{} :: map(),
  48. %% @todo We need a TimerRef to do SETTINGS_TIMEOUT errors.
  49. %% We need to be careful there. It's well possible that we send
  50. %% two SETTINGS frames before we receive a SETTINGS ack.
  51. next_settings = #{} :: undefined | map(), %% @todo perhaps set to undefined by default
  52. remote_settings = #{} :: map(),
  53. %% Stream identifiers.
  54. server_streamid = 2 :: pos_integer(),
  55. %% @todo last known good streamid
  56. %% Currently active HTTP/2 streams. Streams may be initiated either
  57. %% by the client or by the server through PUSH_PROMISE frames.
  58. streams = [] :: [stream()],
  59. %% Streams can spawn zero or more children which are then managed
  60. %% by this module if operating as a supervisor.
  61. children = [] :: [{pid(), cowboy_stream:streamid()}],
  62. %% The client starts by sending a sequence of bytes as a preface,
  63. %% followed by a potentially empty SETTINGS frame. Then the connection
  64. %% is established and continues normally. An exception is when a HEADERS
  65. %% frame is sent followed by CONTINUATION frames: no other frame can be
  66. %% sent in between.
  67. parse_state = undefined :: {preface, sequence, reference()}
  68. | {preface, settings, reference()}
  69. | normal
  70. | {continuation, cowboy_stream:streamid(), cowboy_stream:fin(), binary()},
  71. %% HPACK decoding and encoding state.
  72. decode_state = cow_hpack:init() :: cow_hpack:state(),
  73. encode_state = cow_hpack:init() :: cow_hpack:state()
  74. }).
  75. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts()) -> ok.
  76. init(Parent, Ref, Socket, Transport, Opts) ->
  77. case Transport:peername(Socket) of
  78. {ok, Peer} ->
  79. init(Parent, Ref, Socket, Transport, Opts, Peer, <<>>);
  80. {error, Reason} ->
  81. %% Couldn't read the peer address; connection is gone.
  82. terminate(undefined, {socket_error, Reason, 'An error has occurred on the socket.'})
  83. end.
  84. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  85. {inet:ip_address(), inet:port_number()}, binary()) -> ok.
  86. init(Parent, Ref, Socket, Transport, Opts, Peer, Buffer) ->
  87. State = #state{parent=Parent, ref=Ref, socket=Socket,
  88. transport=Transport, opts=Opts, peer=Peer,
  89. parse_state={preface, sequence, preface_timeout(Opts)}},
  90. preface(State),
  91. case Buffer of
  92. <<>> -> before_loop(State, Buffer);
  93. _ -> parse(State, Buffer)
  94. end.
  95. %% @todo Add an argument for the request body.
  96. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  97. {inet:ip_address(), inet:port_number()}, binary(), map() | undefined, cowboy_req:req()) -> ok.
  98. init(Parent, Ref, Socket, Transport, Opts, Peer, Buffer, _Settings, Req) ->
  99. State0 = #state{parent=Parent, ref=Ref, socket=Socket,
  100. transport=Transport, opts=Opts, peer=Peer,
  101. parse_state={preface, sequence, preface_timeout(Opts)}},
  102. preface(State0),
  103. %% @todo Apply settings.
  104. %% StreamID from HTTP/1.1 Upgrade requests is always 1.
  105. %% The stream is always in the half-closed (remote) state.
  106. State = stream_handler_init(State0, 1, fin, Req),
  107. case Buffer of
  108. <<>> -> before_loop(State, Buffer);
  109. _ -> parse(State, Buffer)
  110. end.
  111. preface(#state{socket=Socket, transport=Transport, next_settings=Settings}) ->
  112. %% We send next_settings and use defaults until we get a ack.
  113. ok = Transport:send(Socket, cow_http2:settings(Settings)).
  114. preface_timeout(Opts) ->
  115. PrefaceTimeout = maps:get(preface_timeout, Opts, 5000),
  116. erlang:start_timer(PrefaceTimeout, self(), preface_timeout).
  117. %% @todo Add the timeout for last time since we heard of connection.
  118. before_loop(State, Buffer) ->
  119. loop(State, Buffer).
  120. loop(State=#state{parent=Parent, socket=Socket, transport=Transport,
  121. children=Children, parse_state=PS}, Buffer) ->
  122. Transport:setopts(Socket, [{active, once}]),
  123. {OK, Closed, Error} = Transport:messages(),
  124. receive
  125. %% Socket messages.
  126. {OK, Socket, Data} ->
  127. parse(State, << Buffer/binary, Data/binary >>);
  128. {Closed, Socket} ->
  129. terminate(State, {socket_error, closed, 'The socket has been closed.'});
  130. {Error, Socket, Reason} ->
  131. terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'});
  132. %% System messages.
  133. {'EXIT', Parent, Reason} ->
  134. exit(Reason);
  135. {system, From, Request} ->
  136. sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer});
  137. {timeout, TRef, preface_timeout} ->
  138. case PS of
  139. {preface, _, TRef} ->
  140. terminate(State, {connection_error, protocol_error,
  141. 'The preface was not received in a reasonable amount of time.'});
  142. _ ->
  143. loop(State, Buffer)
  144. end;
  145. %% Messages pertaining to a stream.
  146. {{Pid, StreamID}, Msg} when Pid =:= self() ->
  147. loop(info(State, StreamID, Msg), Buffer);
  148. %% Exit signal from children.
  149. Msg = {'EXIT', Pid, _} ->
  150. loop(down(State, Pid, Msg), Buffer);
  151. %% Calls from supervisor module.
  152. {'$gen_call', {From, Tag}, which_children} ->
  153. Workers = [{?MODULE, Pid, worker, [?MODULE]} || {Pid, _} <- Children],
  154. From ! {Tag, Workers},
  155. loop(State, Buffer);
  156. {'$gen_call', {From, Tag}, count_children} ->
  157. NbChildren = length(Children),
  158. Counts = [{specs, 1}, {active, NbChildren},
  159. {supervisors, 0}, {workers, NbChildren}],
  160. From ! {Tag, Counts},
  161. loop(State, Buffer);
  162. {'$gen_call', {From, Tag}, _} ->
  163. From ! {Tag, {error, ?MODULE}},
  164. loop(State, Buffer);
  165. Msg ->
  166. error_logger:error_msg("Received stray message ~p.", [Msg]),
  167. loop(State, Buffer)
  168. %% @todo Configurable timeout.
  169. after 60000 ->
  170. terminate(State, {internal_error, timeout, 'No message or data received before timeout.'})
  171. end.
  172. parse(State=#state{socket=Socket, transport=Transport, parse_state={preface, sequence, TRef}}, Data) ->
  173. case Data of
  174. << "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n", Rest/bits >> ->
  175. parse(State#state{parse_state={preface, settings, TRef}}, Rest);
  176. _ when byte_size(Data) >= 24 ->
  177. Transport:close(Socket),
  178. exit({shutdown, {connection_error, protocol_error,
  179. 'The connection preface was invalid. (RFC7540 3.5)'}});
  180. _ ->
  181. Len = byte_size(Data),
  182. << Preface:Len/binary, _/bits >> = <<"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n">>,
  183. case Data of
  184. Preface ->
  185. %% @todo OK we should have a timeout when waiting for the preface.
  186. before_loop(State, Data);
  187. _ ->
  188. Transport:close(Socket),
  189. exit({shutdown, {connection_error, protocol_error,
  190. 'The connection preface was invalid. (RFC7540 3.5)'}})
  191. end
  192. end;
  193. %% @todo Perhaps instead of just more we can have {more, Len} to avoid all the checks.
  194. parse(State=#state{parse_state=ParseState}, Data) ->
  195. case cow_http2:parse(Data) of
  196. {ok, Frame, Rest} ->
  197. case ParseState of
  198. normal ->
  199. parse(frame(State, Frame), Rest);
  200. {preface, settings, TRef} ->
  201. parse_settings_preface(State, Frame, Rest, TRef);
  202. {continuation, _, _, _} ->
  203. parse(continuation_frame(State, Frame), Rest)
  204. end;
  205. {stream_error, StreamID, Reason, Human, Rest} ->
  206. parse(stream_reset(State, StreamID, {stream_error, Reason, Human}), Rest);
  207. Error = {connection_error, _, _} ->
  208. terminate(State, Error);
  209. more ->
  210. before_loop(State, Data)
  211. end.
  212. parse_settings_preface(State, Frame={settings, _}, Rest, TRef) ->
  213. _ = erlang:cancel_timer(TRef, [{async, true}, {info, false}]),
  214. parse(frame(State#state{parse_state=normal}, Frame), Rest);
  215. parse_settings_preface(State, _, _, _) ->
  216. terminate(State, {connection_error, protocol_error,
  217. 'The preface sequence must be followed by a SETTINGS frame. (RFC7540 3.5)'}).
  218. %% @todo When we get a 'fin' we need to check if the stream had a 'fin' sent back
  219. %% and terminate the stream if this is the end of it.
  220. %% DATA frame.
  221. frame(State=#state{streams=Streams}, {data, StreamID, IsFin0, Data}) ->
  222. case lists:keyfind(StreamID, #stream.id, Streams) of
  223. Stream = #stream{state=StreamState0, remote=nofin, body_length=Len0} ->
  224. Len = Len0 + byte_size(Data),
  225. IsFin = case IsFin0 of
  226. fin -> {fin, Len};
  227. nofin -> nofin
  228. end,
  229. try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
  230. {Commands, StreamState} ->
  231. commands(State, Stream#stream{state=StreamState, body_length=Len}, Commands)
  232. catch Class:Reason ->
  233. error_logger:error_msg("Exception occurred in "
  234. "cowboy_stream:data(~p, ~p, ~p, ~p) with reason ~p:~p.",
  235. [StreamID, IsFin0, Data, StreamState0, Class, Reason]),
  236. stream_reset(State, StreamID, {internal_error, {Class, Reason},
  237. 'Exception occurred in cowboy_stream:data/4.'})
  238. end;
  239. _ ->
  240. stream_reset(State, StreamID, {stream_error, stream_closed,
  241. 'DATA frame received for a closed or non-existent stream. (RFC7540 6.1)'})
  242. end;
  243. %% Single HEADERS frame headers block.
  244. frame(State, {headers, StreamID, IsFin, head_fin, HeaderBlock}) ->
  245. %% @todo We probably need to validate StreamID here and in 4 next clauses.
  246. stream_init(State, StreamID, IsFin, HeaderBlock);
  247. %% HEADERS frame starting a headers block. Enter continuation mode.
  248. frame(State, {headers, StreamID, IsFin, head_nofin, HeaderBlockFragment}) ->
  249. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
  250. %% Single HEADERS frame headers block with priority.
  251. frame(State, {headers, StreamID, IsFin, head_fin,
  252. _IsExclusive, _DepStreamID, _Weight, HeaderBlock}) ->
  253. %% @todo Handle priority.
  254. stream_init(State, StreamID, IsFin, HeaderBlock);
  255. %% HEADERS frame starting a headers block. Enter continuation mode.
  256. frame(State, {headers, StreamID, IsFin, head_nofin,
  257. _IsExclusive, _DepStreamID, _Weight, HeaderBlockFragment}) ->
  258. %% @todo Handle priority.
  259. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
  260. %% PRIORITY frame.
  261. frame(State, {priority, _StreamID, _IsExclusive, _DepStreamID, _Weight}) ->
  262. %% @todo Validate StreamID?
  263. %% @todo Handle priority.
  264. State;
  265. %% RST_STREAM frame.
  266. frame(State, {rst_stream, StreamID, Reason}) ->
  267. stream_reset(State, StreamID, {stream_error, Reason, 'Stream reset requested by client.'});
  268. %% SETTINGS frame.
  269. frame(State=#state{socket=Socket, transport=Transport}, {settings, _Settings}) ->
  270. %% @todo Apply SETTINGS.
  271. Transport:send(Socket, cow_http2:settings_ack()),
  272. State;
  273. %% Ack for a previously sent SETTINGS frame.
  274. frame(State=#state{next_settings=_NextSettings}, settings_ack) ->
  275. %% @todo Apply SETTINGS that require synchronization.
  276. State;
  277. %% Unexpected PUSH_PROMISE frame.
  278. frame(State, {push_promise, _, _, _, _}) ->
  279. terminate(State, {connection_error, protocol_error,
  280. 'PUSH_PROMISE frames MUST only be sent on a peer-initiated stream. (RFC7540 6.6)'});
  281. %% PING frame.
  282. frame(State=#state{socket=Socket, transport=Transport}, {ping, Opaque}) ->
  283. Transport:send(Socket, cow_http2:ping_ack(Opaque)),
  284. State;
  285. %% Ack for a previously sent PING frame.
  286. %%
  287. %% @todo Might want to check contents but probably a waste of time.
  288. frame(State, {ping_ack, _Opaque}) ->
  289. State;
  290. %% GOAWAY frame.
  291. frame(State, Frame={goaway, _, _, _}) ->
  292. terminate(State, {stop, Frame, 'Client is going away.'});
  293. %% Connection-wide WINDOW_UPDATE frame.
  294. frame(State, {window_update, _Increment}) ->
  295. %% @todo control flow
  296. State;
  297. %% Stream-specific WINDOW_UPDATE frame.
  298. frame(State, {window_update, _StreamID, _Increment}) ->
  299. %% @todo stream-specific control flow
  300. State;
  301. %% Unexpected CONTINUATION frame.
  302. frame(State, {continuation, _, _, _}) ->
  303. terminate(State, {connection_error, protocol_error,
  304. 'CONTINUATION frames MUST be preceded by a HEADERS frame. (RFC7540 6.10)'}).
  305. continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
  306. {continuation, StreamID, head_fin, HeaderBlockFragment1}) ->
  307. stream_init(State#state{parse_state=normal}, StreamID, IsFin,
  308. << HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>);
  309. continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
  310. {continuation, StreamID, head_nofin, HeaderBlockFragment1}) ->
  311. State#state{parse_state={continuation, StreamID, IsFin,
  312. << HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>}};
  313. continuation_frame(State, _) ->
  314. terminate(State, {connection_error, protocol_error,
  315. 'An invalid frame was received while expecting a CONTINUATION frame. (RFC7540 6.2)'}).
  316. down(State=#state{children=Children0}, Pid, Msg) ->
  317. case lists:keytake(Pid, 1, Children0) of
  318. {value, {_, StreamID}, Children} ->
  319. info(State#state{children=Children}, StreamID, Msg);
  320. false ->
  321. error_logger:error_msg("Received EXIT signal ~p for unknown process ~p.", [Msg, Pid]),
  322. State
  323. end.
  324. info(State=#state{streams=Streams}, StreamID, Msg) ->
  325. case lists:keyfind(StreamID, #stream.id, Streams) of
  326. Stream = #stream{state=StreamState0} ->
  327. try cowboy_stream:info(StreamID, Msg, StreamState0) of
  328. {Commands, StreamState} ->
  329. commands(State, Stream#stream{state=StreamState}, Commands)
  330. catch Class:Reason ->
  331. error_logger:error_msg("Exception occurred in "
  332. "cowboy_stream:info(~p, ~p, ~p) with reason ~p:~p.",
  333. [StreamID, Msg, StreamState0, Class, Reason]),
  334. stream_reset(State, StreamID, {internal_error, {Class, Reason},
  335. 'Exception occurred in cowboy_stream:info/3.'})
  336. end;
  337. false ->
  338. error_logger:error_msg("Received message ~p for unknown stream ~p.", [Msg, StreamID]),
  339. State
  340. end.
  341. commands(State, Stream, []) ->
  342. after_commands(State, Stream);
  343. %% Error responses are sent only if a response wasn't sent already.
  344. commands(State, Stream=#stream{local=idle}, [{error_response, StatusCode, Headers, Body}|Tail]) ->
  345. commands(State, Stream, [{response, StatusCode, Headers, Body}|Tail]);
  346. commands(State, Stream, [{error_response, _, _, _}|Tail]) ->
  347. commands(State, Stream, Tail);
  348. %% Send response headers.
  349. %%
  350. %% @todo Kill the stream if it sent a response when one has already been sent.
  351. %% @todo Keep IsFin in the state.
  352. %% @todo Same two things above apply to DATA, possibly promise too.
  353. commands(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  354. Stream=#stream{id=StreamID, local=idle}, [{response, StatusCode, Headers0, Body}|Tail]) ->
  355. Headers = Headers0#{<<":status">> => status(StatusCode)},
  356. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  357. case Body of
  358. <<>> ->
  359. Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
  360. commands(State#state{encode_state=EncodeState}, Stream#stream{local=fin}, Tail);
  361. {sendfile, O, B, P} ->
  362. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  363. commands(State#state{encode_state=EncodeState}, Stream#stream{local=nofin},
  364. [{sendfile, fin, O, B, P}|Tail]);
  365. _ ->
  366. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  367. %% @todo 16384 is the default SETTINGS_MAX_FRAME_SIZE.
  368. %% Use the length set by the server instead, if any.
  369. %% @todo Would be better if we didn't have to convert to binary.
  370. send_data(Socket, Transport, StreamID, fin, iolist_to_binary(Body), 16384),
  371. commands(State#state{encode_state=EncodeState}, Stream#stream{local=fin}, Tail)
  372. end;
  373. %% @todo response when local!=idle
  374. %% Send response headers and initiate chunked encoding.
  375. commands(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  376. Stream=#stream{id=StreamID, local=idle}, [{headers, StatusCode, Headers0}|Tail]) ->
  377. Headers = Headers0#{<<":status">> => status(StatusCode)},
  378. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  379. Transport:send(Socket, cow_http2:headers(StreamID, nofin, HeaderBlock)),
  380. commands(State#state{encode_state=EncodeState}, Stream#stream{local=nofin}, Tail);
  381. %% @todo headers when local!=idle
  382. %% Send a response body chunk.
  383. %%
  384. %% @todo WINDOW_UPDATE stuff require us to buffer some data.
  385. %%
  386. %% When the body is sent using sendfile, the current solution is not
  387. %% very good. The body could be too large, blocking the connection.
  388. %% Also sendfile technically only works over TCP, so it's not that
  389. %% useful for HTTP/2. At the very least the sendfile call should be
  390. %% split into multiple calls and flow control should be used to make
  391. %% sure we only send as fast as the client can receive and don't block
  392. %% anything.
  393. commands(State=#state{socket=Socket, transport=Transport}, Stream=#stream{id=StreamID, local=nofin},
  394. [{data, IsFin, Data}|Tail]) ->
  395. Transport:send(Socket, cow_http2:data(StreamID, IsFin, Data)),
  396. commands(State, Stream#stream{local=IsFin}, Tail);
  397. %% @todo data when local!=nofin
  398. %% Send a file.
  399. %%
  400. %% @todo This implementation is terrible. A good implementation would
  401. %% need to check that Bytes is exact (or we need to document that we
  402. %% trust it to be exact), and would need to send the file asynchronously
  403. %% in many data frames. Perhaps a sendfile call should result in a
  404. %% process being created specifically for this purpose. Or perhaps
  405. %% the protocol should be "dumb" and the stream handler be the one
  406. %% to ensure the file is sent in chunks (which would require a better
  407. %% flow control at the stream handler level). One thing for sure, the
  408. %% implementation necessarily varies between HTTP/1.1 and HTTP/2.
  409. commands(State=#state{socket=Socket, transport=Transport}, Stream=#stream{id=StreamID, local=nofin},
  410. [{sendfile, IsFin, Offset, Bytes, Path}|Tail]) ->
  411. %% @todo We currently have a naive implementation without a
  412. %% scheduler to prioritize frames that need to be sent.
  413. %% A future update will need to queue such data frames
  414. %% and only send them when there is nothing currently
  415. %% being sent. We would probably also benefit from doing
  416. %% asynchronous sends.
  417. sendfile(Socket, Transport, StreamID, IsFin, Offset, Bytes, Path, 16384),
  418. commands(State, Stream#stream{local=IsFin}, Tail);
  419. %% @todo sendfile when local!=nofin
  420. %% Send a push promise.
  421. %%
  422. %% @todo We need to keep track of what promises we made so that we don't
  423. %% end up with an infinite loop of promises.
  424. commands(State0=#state{socket=Socket, transport=Transport, server_streamid=PromisedStreamID,
  425. encode_state=EncodeState0}, Stream=#stream{id=StreamID},
  426. [{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) ->
  427. Authority = case {Scheme, Port} of
  428. {<<"http">>, 80} -> Host;
  429. {<<"https">>, 443} -> Host;
  430. _ -> [Host, $:, integer_to_binary(Port)]
  431. end,
  432. PathWithQs = case Qs of
  433. <<>> -> Path;
  434. _ -> [Path, $?, Qs]
  435. end,
  436. Headers = Headers0#{<<":method">> => Method,
  437. <<":scheme">> => Scheme,
  438. <<":authority">> => Authority,
  439. <<":path">> => PathWithQs},
  440. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  441. Transport:send(Socket, cow_http2:push_promise(StreamID, PromisedStreamID, HeaderBlock)),
  442. %% @todo iolist_to_binary(HeaderBlock) isn't optimal. Need a shortcut.
  443. State = stream_init(State0#state{server_streamid=PromisedStreamID + 2, encode_state=EncodeState},
  444. PromisedStreamID, fin, iolist_to_binary(HeaderBlock)),
  445. commands(State, Stream, Tail);
  446. %% @todo Update the flow control state.
  447. commands(State, Stream, [{flow, _Size}|Tail]) ->
  448. commands(State, Stream, Tail);
  449. %% Supervise a child process.
  450. commands(State=#state{children=Children}, Stream=#stream{id=StreamID},
  451. [{spawn, Pid, _Shutdown}|Tail]) -> %% @todo Shutdown
  452. commands(State#state{children=[{Pid, StreamID}|Children]}, Stream, Tail);
  453. %% Error handling.
  454. commands(State, Stream=#stream{id=StreamID}, [Error = {internal_error, _, _}|_Tail]) ->
  455. %% @todo Do we want to run the commands after an internal_error?
  456. %% @todo Do we even allow commands after?
  457. %% @todo Only reset when the stream still exists.
  458. stream_reset(after_commands(State, Stream), StreamID, Error);
  459. %% @todo HTTP/2 has no support for the Upgrade mechanism.
  460. commands(State, Stream, [{switch_protocol, _Headers, _Mod, _ModState}|Tail]) ->
  461. %% @todo This is an error. Not sure what to do here yet.
  462. commands(State, Stream, Tail);
  463. commands(State, Stream=#stream{id=StreamID}, [stop|_Tail]) ->
  464. %% @todo Do we want to run the commands after a stop?
  465. %% @todo Do we even allow commands after?
  466. stream_terminate(after_commands(State, Stream), StreamID, normal).
  467. after_commands(State=#state{streams=Streams0}, Stream=#stream{id=StreamID}) ->
  468. Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
  469. State#state{streams=Streams}.
  470. status(Status) when is_integer(Status) ->
  471. integer_to_binary(Status);
  472. status(<< H, T, U, _/bits >>) when H >= $1, H =< $9, T >= $0, T =< $9, U >= $0, U =< $9 ->
  473. << H, T, U >>.
  474. %% This same function is found in gun_http2.
  475. send_data(Socket, Transport, StreamID, IsFin, Data, Length) ->
  476. if
  477. Length < byte_size(Data) ->
  478. << Payload:Length/binary, Rest/bits >> = Data,
  479. Transport:send(Socket, cow_http2:data(StreamID, nofin, Payload)),
  480. send_data(Socket, Transport, StreamID, IsFin, Rest, Length);
  481. true ->
  482. Transport:send(Socket, cow_http2:data(StreamID, IsFin, Data))
  483. end.
  484. %% @todo This is currently awfully slow. But at least it's correct.
  485. sendfile(Socket, Transport, StreamID, IsFin, Offset, Bytes, Path, Length) ->
  486. if
  487. Length < Bytes ->
  488. Transport:send(Socket, cow_http2:data_header(StreamID, nofin, Length)),
  489. Transport:sendfile(Socket, Path, Offset, Length),
  490. sendfile(Socket, Transport, StreamID, IsFin,
  491. Offset + Length, Bytes - Length, Path, Length);
  492. true ->
  493. Transport:send(Socket, cow_http2:data_header(StreamID, IsFin, Bytes)),
  494. Transport:sendfile(Socket, Path, Offset, Bytes)
  495. end.
  496. -spec terminate(#state{}, _) -> no_return().
  497. terminate(#state{socket=Socket, transport=Transport,
  498. streams=Streams, children=Children}, Reason) ->
  499. %% @todo Send GOAWAY frame; need to keep track of last good stream id; how?
  500. terminate_all_streams(Streams, Reason, Children),
  501. Transport:close(Socket),
  502. exit({shutdown, Reason}).
  503. terminate_all_streams([], _, []) ->
  504. ok;
  505. terminate_all_streams([#stream{id=StreamID, state=StreamState}|Tail], Reason, Children0) ->
  506. stream_call_terminate(StreamID, Reason, StreamState),
  507. Children = stream_terminate_children(Children0, StreamID, []),
  508. terminate_all_streams(Tail, Reason, Children).
  509. %% Stream functions.
  510. stream_init(State0=#state{ref=Ref, socket=Socket, transport=Transport, peer=Peer, decode_state=DecodeState0},
  511. StreamID, IsFin, HeaderBlock) ->
  512. %% @todo Add clause for CONNECT requests (no scheme/path).
  513. try headers_decode(HeaderBlock, DecodeState0) of
  514. {Headers0=#{
  515. <<":method">> := Method,
  516. <<":scheme">> := Scheme,
  517. <<":authority">> := Authority,
  518. <<":path">> := PathWithQs}, DecodeState} ->
  519. State = State0#state{decode_state=DecodeState},
  520. Headers = maps:without([<<":method">>, <<":scheme">>, <<":authority">>, <<":path">>], Headers0),
  521. BodyLength = case Headers of
  522. _ when IsFin =:= fin ->
  523. 0;
  524. #{<<"content-length">> := <<"0">>} ->
  525. 0;
  526. #{<<"content-length">> := BinLength} ->
  527. Length = try
  528. cow_http_hd:parse_content_length(BinLength)
  529. catch _:_ ->
  530. terminate(State0, {stream_error, StreamID, protocol_error,
  531. 'The content-length header is invalid. (RFC7230 3.3.2)'})
  532. %% @todo Err should terminate here...
  533. end,
  534. Length;
  535. _ ->
  536. undefined
  537. end,
  538. {Host, Port} = cow_http_hd:parse_host(Authority),
  539. {Path, Qs} = cow_http:parse_fullpath(PathWithQs),
  540. Req = #{
  541. ref => Ref,
  542. pid => self(),
  543. streamid => StreamID,
  544. peer => Peer,
  545. method => Method,
  546. scheme => Scheme,
  547. host => Host,
  548. port => Port,
  549. path => Path,
  550. qs => Qs,
  551. version => 'HTTP/2',
  552. headers => Headers,
  553. has_body => IsFin =:= nofin,
  554. body_length => BodyLength
  555. },
  556. stream_handler_init(State, StreamID, IsFin, Req);
  557. {_, DecodeState} ->
  558. Transport:send(Socket, cow_http2:rst_stream(StreamID, protocol_error)),
  559. State0#state{decode_state=DecodeState}
  560. catch _:_ ->
  561. terminate(State0, {connection_error, compression_error,
  562. 'Error while trying to decode HPACK-encoded header block. (RFC7540 4.3)'})
  563. end.
  564. stream_handler_init(State=#state{opts=Opts}, StreamID, IsFin, Req) ->
  565. try cowboy_stream:init(StreamID, Req, Opts) of
  566. {Commands, StreamState} ->
  567. commands(State, #stream{id=StreamID, state=StreamState, remote=IsFin}, Commands)
  568. catch Class:Reason ->
  569. error_logger:error_msg("Exception occurred in "
  570. "cowboy_stream:init(~p, ~p, ~p) with reason ~p:~p.",
  571. [StreamID, IsFin, Req, Class, Reason]),
  572. stream_reset(State, StreamID, {internal_error, {Class, Reason},
  573. 'Exception occurred in cowboy_stream:init/3.'})
  574. end.
  575. %% @todo We might need to keep track of which stream has been reset so we don't send lots of them.
  576. stream_reset(State=#state{socket=Socket, transport=Transport}, StreamID,
  577. StreamError={internal_error, _, _}) ->
  578. Transport:send(Socket, cow_http2:rst_stream(StreamID, internal_error)),
  579. stream_terminate(State, StreamID, StreamError);
  580. stream_reset(State=#state{socket=Socket, transport=Transport}, StreamID,
  581. StreamError={stream_error, Reason, _}) ->
  582. Transport:send(Socket, cow_http2:rst_stream(StreamID, Reason)),
  583. stream_terminate(State, StreamID, StreamError).
  584. stream_terminate(State=#state{socket=Socket, transport=Transport,
  585. streams=Streams0, children=Children0, encode_state=EncodeState0}, StreamID, Reason) ->
  586. case lists:keytake(StreamID, #stream.id, Streams0) of
  587. {value, #stream{state=StreamState, local=idle}, Streams} when Reason =:= normal ->
  588. Headers = #{<<":status">> => <<"204">>},
  589. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  590. Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
  591. stream_call_terminate(StreamID, Reason, StreamState),
  592. Children = stream_terminate_children(Children0, StreamID, []),
  593. State#state{streams=Streams, children=Children, encode_state=EncodeState};
  594. {value, #stream{state=StreamState, local=nofin}, Streams} when Reason =:= normal ->
  595. Transport:send(Socket, cow_http2:data(StreamID, fin, <<>>)),
  596. stream_call_terminate(StreamID, Reason, StreamState),
  597. Children = stream_terminate_children(Children0, StreamID, []),
  598. State#state{streams=Streams, children=Children};
  599. {value, #stream{state=StreamState}, Streams} ->
  600. stream_call_terminate(StreamID, Reason, StreamState),
  601. Children = stream_terminate_children(Children0, StreamID, []),
  602. State#state{streams=Streams, children=Children};
  603. false ->
  604. %% @todo Unknown stream. Not sure what to do here. Check again once all
  605. %% terminate calls have been written.
  606. State
  607. end.
  608. stream_call_terminate(StreamID, Reason, StreamState) ->
  609. try
  610. cowboy_stream:terminate(StreamID, Reason, StreamState)
  611. catch Class:Reason ->
  612. error_logger:error_msg("Exception occurred in "
  613. "cowboy_stream:terminate(~p, ~p, ~p) with reason ~p:~p.",
  614. [StreamID, Reason, StreamState, Class, Reason])
  615. end.
  616. stream_terminate_children([], _, Acc) ->
  617. Acc;
  618. stream_terminate_children([{Pid, StreamID}|Tail], StreamID, Acc) ->
  619. exit(Pid, kill),
  620. stream_terminate_children(Tail, StreamID, Acc);
  621. stream_terminate_children([Child|Tail], StreamID, Acc) ->
  622. stream_terminate_children(Tail, StreamID, [Child|Acc]).
  623. %% Headers encode/decode.
  624. headers_decode(HeaderBlock, DecodeState0) ->
  625. {Headers, DecodeState} = cow_hpack:decode(HeaderBlock, DecodeState0),
  626. {headers_to_map(Headers, #{}), DecodeState}.
  627. %% This function is necessary to properly handle duplicate headers
  628. %% and the special-case cookie header.
  629. headers_to_map([], Acc) ->
  630. Acc;
  631. headers_to_map([{Name, Value}|Tail], Acc0) ->
  632. Acc = case Acc0 of
  633. %% The cookie header does not use proper HTTP header lists.
  634. #{Name := Value0} when Name =:= <<"cookie">> -> Acc0#{Name => << Value0/binary, "; ", Value/binary >>};
  635. #{Name := Value0} -> Acc0#{Name => << Value0/binary, ", ", Value/binary >>};
  636. _ -> Acc0#{Name => Value}
  637. end,
  638. headers_to_map(Tail, Acc).
  639. %% The set-cookie header is special; we can only send one cookie per header.
  640. headers_encode(Headers0=#{<<"set-cookie">> := SetCookies}, EncodeState) ->
  641. Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  642. Headers = Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies],
  643. cow_hpack:encode(Headers, EncodeState);
  644. headers_encode(Headers0, EncodeState) ->
  645. Headers = maps:to_list(Headers0),
  646. cow_hpack:encode(Headers, EncodeState).
  647. %% System callbacks.
  648. -spec system_continue(_, _, {#state{}, binary()}) -> ok.
  649. system_continue(_, _, {State, Buffer}) ->
  650. loop(State, Buffer).
  651. -spec system_terminate(any(), _, _, _) -> no_return().
  652. system_terminate(Reason, _, _, _) ->
  653. exit(Reason).
  654. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  655. system_code_change(Misc, _, _, _) ->
  656. {ok, Misc}.