cowboy_http2.erl 31 KB

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