cowboy_http2.erl 36 KB

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