cowboy_http2.erl 24 KB

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