cowboy_http2.erl 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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/9]).
  17. -export([init/11]).
  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. %% Request method.
  36. method = undefined :: binary(),
  37. %% Whether we finished sending data.
  38. local = idle :: idle | upgrade | cowboy_stream:fin() | flush,
  39. %% Local flow control window (how much we can send).
  40. local_window :: integer(),
  41. %% Buffered data waiting for the flow control window to increase.
  42. local_buffer = queue:new() :: queue:queue(
  43. {cowboy_stream:fin(), non_neg_integer(), iolist()
  44. | {sendfile, non_neg_integer(), pos_integer(), file:name_all()}}),
  45. local_buffer_size = 0 :: non_neg_integer(),
  46. local_trailers = undefined :: undefined | cowboy:http_headers(),
  47. %% Whether we finished receiving data.
  48. remote = nofin :: cowboy_stream:fin(),
  49. %% Remote flow control window (how much we accept to receive).
  50. remote_window :: integer(),
  51. %% Unparsed te header. Used to know if we can send trailers.
  52. te :: undefined | binary()
  53. }).
  54. -type stream() :: #stream{}.
  55. -record(state, {
  56. parent = undefined :: pid(),
  57. ref :: ranch:ref(),
  58. socket = undefined :: inet:socket(),
  59. transport :: module(),
  60. opts = #{} :: opts(),
  61. %% Remote address and port for the connection.
  62. peer = undefined :: {inet:ip_address(), inet:port_number()},
  63. %% Local address and port for the connection.
  64. sock = undefined :: {inet:ip_address(), inet:port_number()},
  65. %% Client certificate (TLS only).
  66. cert :: undefined | binary(),
  67. %% Settings are separate for each endpoint. In addition, settings
  68. %% must be acknowledged before they can be expected to be applied.
  69. %%
  70. %% @todo Since the ack is required, we must timeout if we don't receive it.
  71. %% @todo I haven't put as much thought as I should have on this,
  72. %% the final settings handling will be very different.
  73. local_settings = #{
  74. % header_table_size => 4096,
  75. % enable_push => false, %% We are the server. Push is never enabled.
  76. % max_concurrent_streams => infinity,
  77. initial_window_size => 65535,
  78. max_frame_size => 16384
  79. % max_header_list_size => infinity
  80. } :: map(),
  81. %% @todo We need a TimerRef to do SETTINGS_TIMEOUT errors.
  82. %% We need to be careful there. It's well possible that we send
  83. %% two SETTINGS frames before we receive a SETTINGS ack.
  84. next_settings = #{} :: undefined | map(), %% @todo perhaps set to undefined by default
  85. remote_settings = #{
  86. initial_window_size => 65535
  87. } :: map(),
  88. %% Connection-wide flow control window.
  89. local_window = 65535 :: integer(), %% How much we can send.
  90. remote_window = 65535 :: integer(), %% How much we accept to receive.
  91. %% Stream identifiers.
  92. client_streamid = 0 :: non_neg_integer(),
  93. server_streamid = 2 :: pos_integer(),
  94. %% Currently active HTTP/2 streams. Streams may be initiated either
  95. %% by the client or by the server through PUSH_PROMISE frames.
  96. streams = [] :: [stream()],
  97. %% HTTP/2 streams that have been reset recently. We are expected
  98. %% to keep receiving additional frames after sending an RST_STREAM.
  99. lingering_streams = [] :: [cowboy_stream:streamid()],
  100. %% Streams can spawn zero or more children which are then managed
  101. %% by this module if operating as a supervisor.
  102. children = cowboy_children:init() :: cowboy_children:children(),
  103. %% The client starts by sending a sequence of bytes as a preface,
  104. %% followed by a potentially empty SETTINGS frame. Then the connection
  105. %% is established and continues normally. An exception is when a HEADERS
  106. %% frame is sent followed by CONTINUATION frames: no other frame can be
  107. %% sent in between.
  108. parse_state = undefined :: {preface, sequence, reference()}
  109. | {preface, settings, reference()}
  110. | normal
  111. | {continuation, cowboy_stream:streamid(), cowboy_stream:fin(), binary()},
  112. %% HPACK decoding and encoding state.
  113. decode_state = cow_hpack:init() :: cow_hpack:state(),
  114. encode_state = cow_hpack:init() :: cow_hpack:state()
  115. }).
  116. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts()) -> ok.
  117. init(Parent, Ref, Socket, Transport, Opts) ->
  118. Peer0 = Transport:peername(Socket),
  119. Sock0 = Transport:sockname(Socket),
  120. Cert1 = case Transport:name() of
  121. ssl ->
  122. case ssl:peercert(Socket) of
  123. {error, no_peercert} ->
  124. {ok, undefined};
  125. Cert0 ->
  126. Cert0
  127. end;
  128. _ ->
  129. {ok, undefined}
  130. end,
  131. case {Peer0, Sock0, Cert1} of
  132. {{ok, Peer}, {ok, Sock}, {ok, Cert}} ->
  133. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, <<>>);
  134. {{error, Reason}, _, _} ->
  135. terminate(undefined, {socket_error, Reason,
  136. 'A socket error occurred when retrieving the peer name.'});
  137. {_, {error, Reason}, _} ->
  138. terminate(undefined, {socket_error, Reason,
  139. 'A socket error occurred when retrieving the sock name.'});
  140. {_, _, {error, Reason}} ->
  141. terminate(undefined, {socket_error, Reason,
  142. 'A socket error occurred when retrieving the client TLS certificate.'})
  143. end.
  144. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  145. {inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()},
  146. binary() | undefined, binary()) -> ok.
  147. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, Buffer) ->
  148. State = #state{parent=Parent, ref=Ref, socket=Socket,
  149. transport=Transport, opts=Opts, peer=Peer, sock=Sock, cert=Cert,
  150. parse_state={preface, sequence, preface_timeout(Opts)}},
  151. preface(State),
  152. case Buffer of
  153. <<>> -> before_loop(State, Buffer);
  154. _ -> parse(State, Buffer)
  155. end.
  156. %% @todo Add an argument for the request body.
  157. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  158. {inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()},
  159. binary() | undefined, binary(), map() | undefined, cowboy_req:req()) -> ok.
  160. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, Buffer, _Settings, Req) ->
  161. State0 = #state{parent=Parent, ref=Ref, socket=Socket,
  162. transport=Transport, opts=Opts, peer=Peer, sock=Sock, cert=Cert,
  163. parse_state={preface, sequence, preface_timeout(Opts)}},
  164. %% @todo Apply settings.
  165. %% StreamID from HTTP/1.1 Upgrade requests is always 1.
  166. %% The stream is always in the half-closed (remote) state.
  167. State1 = stream_handler_init(State0, 1, fin, upgrade, Req),
  168. %% We assume that the upgrade will be applied. A stream handler
  169. %% must not prevent the normal operations of the server.
  170. State = info(State1, 1, {switch_protocol, #{
  171. <<"connection">> => <<"Upgrade">>,
  172. <<"upgrade">> => <<"h2c">>
  173. }, ?MODULE, undefined}), %% @todo undefined or #{}?
  174. preface(State),
  175. case Buffer of
  176. <<>> -> before_loop(State, Buffer);
  177. _ -> parse(State, Buffer)
  178. end.
  179. preface(#state{socket=Socket, transport=Transport, next_settings=Settings}) ->
  180. %% We send next_settings and use defaults until we get a ack.
  181. Transport:send(Socket, cow_http2:settings(Settings)).
  182. preface_timeout(Opts) ->
  183. PrefaceTimeout = maps:get(preface_timeout, Opts, 5000),
  184. erlang:start_timer(PrefaceTimeout, self(), preface_timeout).
  185. %% @todo Add the timeout for last time since we heard of connection.
  186. before_loop(State, Buffer) ->
  187. loop(State, Buffer).
  188. loop(State=#state{parent=Parent, socket=Socket, transport=Transport,
  189. opts=Opts, children=Children, parse_state=PS}, Buffer) ->
  190. Transport:setopts(Socket, [{active, once}]),
  191. {OK, Closed, Error} = Transport:messages(),
  192. InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000),
  193. receive
  194. %% Socket messages.
  195. {OK, Socket, Data} ->
  196. parse(State, << Buffer/binary, Data/binary >>);
  197. {Closed, Socket} ->
  198. terminate(State, {socket_error, closed, 'The socket has been closed.'});
  199. {Error, Socket, Reason} ->
  200. terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'});
  201. %% System messages.
  202. {'EXIT', Parent, Reason} ->
  203. exit(Reason);
  204. {system, From, Request} ->
  205. sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer});
  206. %% Timeouts.
  207. {timeout, Ref, {shutdown, Pid}} ->
  208. cowboy_children:shutdown_timeout(Children, Ref, Pid),
  209. loop(State, Buffer);
  210. {timeout, TRef, preface_timeout} ->
  211. case PS of
  212. {preface, _, TRef} ->
  213. terminate(State, {connection_error, protocol_error,
  214. 'The preface was not received in a reasonable amount of time.'});
  215. _ ->
  216. loop(State, Buffer)
  217. end;
  218. %% Messages pertaining to a stream.
  219. {{Pid, StreamID}, Msg} when Pid =:= self() ->
  220. loop(info(State, StreamID, Msg), Buffer);
  221. %% Exit signal from children.
  222. Msg = {'EXIT', Pid, _} ->
  223. loop(down(State, Pid, Msg), Buffer);
  224. %% Calls from supervisor module.
  225. {'$gen_call', {From, Tag}, which_children} ->
  226. From ! {Tag, cowboy_children:which_children(Children, ?MODULE)},
  227. loop(State, Buffer);
  228. {'$gen_call', {From, Tag}, count_children} ->
  229. From ! {Tag, cowboy_children:count_children(Children)},
  230. loop(State, Buffer);
  231. {'$gen_call', {From, Tag}, _} ->
  232. From ! {Tag, {error, ?MODULE}},
  233. loop(State, Buffer);
  234. Msg ->
  235. error_logger:error_msg("Received stray message ~p.", [Msg]),
  236. loop(State, Buffer)
  237. after InactivityTimeout ->
  238. terminate(State, {internal_error, timeout, 'No message or data received before timeout.'})
  239. end.
  240. parse(State=#state{socket=Socket, transport=Transport, parse_state={preface, sequence, TRef}}, Data) ->
  241. case Data of
  242. << "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n", Rest/bits >> ->
  243. parse(State#state{parse_state={preface, settings, TRef}}, Rest);
  244. _ when byte_size(Data) >= 24 ->
  245. Transport:close(Socket),
  246. exit({shutdown, {connection_error, protocol_error,
  247. 'The connection preface was invalid. (RFC7540 3.5)'}});
  248. _ ->
  249. Len = byte_size(Data),
  250. << Preface:Len/binary, _/bits >> = <<"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n">>,
  251. case Data of
  252. Preface ->
  253. before_loop(State, Data);
  254. _ ->
  255. Transport:close(Socket),
  256. exit({shutdown, {connection_error, protocol_error,
  257. 'The connection preface was invalid. (RFC7540 3.5)'}})
  258. end
  259. end;
  260. %% @todo Perhaps instead of just more we can have {more, Len} to avoid all the checks.
  261. parse(State=#state{local_settings=#{max_frame_size := MaxFrameSize},
  262. parse_state=ParseState}, Data) ->
  263. case cow_http2:parse(Data, MaxFrameSize) of
  264. {ok, Frame, Rest} ->
  265. case ParseState of
  266. normal ->
  267. parse(frame(State, Frame), Rest);
  268. {preface, settings, TRef} ->
  269. parse_settings_preface(State, Frame, Rest, TRef);
  270. {continuation, _, _, _} ->
  271. parse(continuation_frame(State, Frame), Rest)
  272. end;
  273. {ignore, _} when element(1, ParseState) =:= continuation ->
  274. terminate(State, {connection_error, protocol_error,
  275. 'An invalid frame was received in the middle of a header block. (RFC7540 6.2)'});
  276. {ignore, Rest} ->
  277. parse(State, Rest);
  278. {stream_error, StreamID, Reason, Human, Rest} ->
  279. parse(stream_reset(State, StreamID, {stream_error, Reason, Human}), Rest);
  280. Error = {connection_error, _, _} ->
  281. terminate(State, Error);
  282. more ->
  283. before_loop(State, Data)
  284. end.
  285. parse_settings_preface(State, Frame={settings, _}, Rest, TRef) ->
  286. _ = erlang:cancel_timer(TRef, [{async, true}, {info, false}]),
  287. parse(frame(State#state{parse_state=normal}, Frame), Rest);
  288. parse_settings_preface(State, _, _, _) ->
  289. terminate(State, {connection_error, protocol_error,
  290. 'The preface sequence must be followed by a SETTINGS frame. (RFC7540 3.5)'}).
  291. %% @todo When we get a 'fin' we need to check if the stream had a 'fin' sent back
  292. %% and terminate the stream if this is the end of it.
  293. %% DATA frame.
  294. frame(State=#state{client_streamid=LastStreamID}, {data, StreamID, _, _})
  295. when StreamID > LastStreamID ->
  296. terminate(State, {connection_error, protocol_error,
  297. 'DATA frame received on a stream in idle state. (RFC7540 5.1)'});
  298. frame(State0=#state{remote_window=ConnWindow, streams=Streams, lingering_streams=Lingering},
  299. {data, StreamID, IsFin, Data}) ->
  300. DataLen = byte_size(Data),
  301. State = State0#state{remote_window=ConnWindow - DataLen},
  302. case lists:keyfind(StreamID, #stream.id, Streams) of
  303. Stream = #stream{state=flush, remote=nofin, remote_window=StreamWindow} ->
  304. after_commands(State, Stream#stream{remote=IsFin, remote_window=StreamWindow - DataLen});
  305. Stream = #stream{state=StreamState0, remote=nofin, remote_window=StreamWindow} ->
  306. try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
  307. {Commands, StreamState} ->
  308. commands(State, Stream#stream{state=StreamState, remote=IsFin,
  309. remote_window=StreamWindow - DataLen}, Commands)
  310. catch Class:Exception ->
  311. cowboy_stream:report_error(data,
  312. [StreamID, IsFin, Data, StreamState0],
  313. Class, Exception, erlang:get_stacktrace()),
  314. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  315. 'Unhandled exception in cowboy_stream:data/4.'})
  316. end;
  317. #stream{remote=fin} ->
  318. stream_reset(State, StreamID, {stream_error, stream_closed,
  319. 'DATA frame received for a half-closed (remote) stream. (RFC7540 5.1)'});
  320. false ->
  321. %% After we send an RST_STREAM frame and terminate a stream,
  322. %% the client still might be sending us some more frames
  323. %% until it can process this RST_STREAM. We therefore ignore
  324. %% DATA frames received for such lingering streams.
  325. case lists:member(StreamID, Lingering) of
  326. true ->
  327. State0;
  328. false ->
  329. terminate(State, {connection_error, stream_closed,
  330. 'DATA frame received for a closed stream. (RFC7540 5.1)'})
  331. end
  332. end;
  333. %% HEADERS frame with invalid even-numbered streamid.
  334. frame(State, {headers, StreamID, _, _, _}) when StreamID rem 2 =:= 0 ->
  335. terminate(State, {connection_error, protocol_error,
  336. 'HEADERS frame received with even-numbered streamid. (RFC7540 5.1.1)'});
  337. %% HEADERS frame received on (half-)closed stream.
  338. %%
  339. %% We always close the connection here to avoid having to decode
  340. %% the headers to not waste resources on non-compliant clients.
  341. frame(State=#state{client_streamid=LastStreamID}, {headers, StreamID, _, _, _})
  342. when StreamID =< LastStreamID ->
  343. terminate(State, {connection_error, stream_closed,
  344. 'HEADERS frame received on a stream in closed or half-closed state. (RFC7540 5.1)'});
  345. %% Single HEADERS frame headers block.
  346. frame(State, {headers, StreamID, IsFin, head_fin, HeaderBlock}) ->
  347. %% @todo We probably need to validate StreamID here and in 4 next clauses.
  348. stream_decode_init(State, StreamID, IsFin, HeaderBlock);
  349. %% HEADERS frame starting a headers block. Enter continuation mode.
  350. frame(State, {headers, StreamID, IsFin, head_nofin, HeaderBlockFragment}) ->
  351. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
  352. %% Single HEADERS frame headers block with priority.
  353. frame(State, {headers, StreamID, IsFin, head_fin,
  354. _IsExclusive, _DepStreamID, _Weight, HeaderBlock}) ->
  355. %% @todo Handle priority.
  356. stream_decode_init(State, StreamID, IsFin, HeaderBlock);
  357. %% HEADERS frame starting a headers block. Enter continuation mode.
  358. frame(State, {headers, StreamID, IsFin, head_nofin,
  359. _IsExclusive, _DepStreamID, _Weight, HeaderBlockFragment}) ->
  360. %% @todo Handle priority.
  361. State#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment}};
  362. %% PRIORITY frame.
  363. frame(State, {priority, _StreamID, _IsExclusive, _DepStreamID, _Weight}) ->
  364. %% @todo Validate StreamID?
  365. %% @todo Handle priority.
  366. State;
  367. %% RST_STREAM frame.
  368. frame(State=#state{client_streamid=LastStreamID}, {rst_stream, StreamID, _})
  369. when StreamID > LastStreamID ->
  370. terminate(State, {connection_error, protocol_error,
  371. 'RST_STREAM frame received on a stream in idle state. (RFC7540 5.1)'});
  372. frame(State, {rst_stream, StreamID, Reason}) ->
  373. stream_terminate(State, StreamID, {stream_error, Reason, 'Stream reset requested by client.'});
  374. %% SETTINGS frame.
  375. frame(State0=#state{socket=Socket, transport=Transport, remote_settings=Settings0},
  376. {settings, Settings}) ->
  377. Transport:send(Socket, cow_http2:settings_ack()),
  378. State = State0#state{remote_settings=maps:merge(Settings0, Settings)},
  379. case Settings of
  380. #{initial_window_size := NewWindowSize} ->
  381. OldWindowSize = maps:get(initial_window_size, Settings0, 65535),
  382. update_stream_windows(State, NewWindowSize - OldWindowSize);
  383. _ ->
  384. State
  385. end;
  386. %% Ack for a previously sent SETTINGS frame.
  387. frame(State=#state{next_settings=_NextSettings}, settings_ack) ->
  388. %% @todo Apply SETTINGS that require synchronization.
  389. State;
  390. %% Unexpected PUSH_PROMISE frame.
  391. frame(State, {push_promise, _, _, _, _}) ->
  392. terminate(State, {connection_error, protocol_error,
  393. 'PUSH_PROMISE frames MUST only be sent on a peer-initiated stream. (RFC7540 6.6)'});
  394. %% PING frame.
  395. frame(State=#state{socket=Socket, transport=Transport}, {ping, Opaque}) ->
  396. Transport:send(Socket, cow_http2:ping_ack(Opaque)),
  397. State;
  398. %% Ack for a previously sent PING frame.
  399. %%
  400. %% @todo Might want to check contents but probably a waste of time.
  401. frame(State, {ping_ack, _Opaque}) ->
  402. State;
  403. %% GOAWAY frame.
  404. frame(State, Frame={goaway, _, _, _}) ->
  405. terminate(State, {stop, Frame, 'Client is going away.'});
  406. %% Connection-wide WINDOW_UPDATE frame.
  407. frame(State=#state{local_window=ConnWindow}, {window_update, Increment})
  408. when ConnWindow + Increment > 16#7fffffff ->
  409. terminate(State, {connection_error, flow_control_error,
  410. 'The flow control window must not be greater than 2^31-1. (RFC7540 6.9.1)'});
  411. frame(State=#state{local_window=ConnWindow}, {window_update, Increment}) ->
  412. send_data(State#state{local_window=ConnWindow + Increment});
  413. %% Stream-specific WINDOW_UPDATE frame.
  414. frame(State=#state{client_streamid=LastStreamID}, {window_update, StreamID, _})
  415. when StreamID > LastStreamID ->
  416. terminate(State, {connection_error, protocol_error,
  417. 'WINDOW_UPDATE frame received on a stream in idle state. (RFC7540 5.1)'});
  418. frame(State0=#state{streams=Streams0}, {window_update, StreamID, Increment}) ->
  419. case lists:keyfind(StreamID, #stream.id, Streams0) of
  420. #stream{local_window=StreamWindow} when StreamWindow + Increment > 16#7fffffff ->
  421. stream_reset(State0, StreamID, {stream_error, flow_control_error,
  422. 'The flow control window must not be greater than 2^31-1. (RFC7540 6.9.1)'});
  423. Stream0 = #stream{local_window=StreamWindow} ->
  424. {State, Stream} = send_data(State0,
  425. Stream0#stream{local_window=StreamWindow + Increment}),
  426. Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
  427. State#state{streams=Streams};
  428. %% @todo We must reject WINDOW_UPDATE frames on RST_STREAM closed streams.
  429. false ->
  430. %% WINDOW_UPDATE frames may be received for a short period of time
  431. %% after a stream is closed. They must be ignored.
  432. State0
  433. end;
  434. %% Unexpected CONTINUATION frame.
  435. frame(State, {continuation, _, _, _}) ->
  436. terminate(State, {connection_error, protocol_error,
  437. 'CONTINUATION frames MUST be preceded by a HEADERS frame. (RFC7540 6.10)'}).
  438. continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
  439. {continuation, StreamID, head_fin, HeaderBlockFragment1}) ->
  440. stream_decode_init(State#state{parse_state=normal}, StreamID, IsFin,
  441. << HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>);
  442. continuation_frame(State=#state{parse_state={continuation, StreamID, IsFin, HeaderBlockFragment0}},
  443. {continuation, StreamID, head_nofin, HeaderBlockFragment1}) ->
  444. State#state{parse_state={continuation, StreamID, IsFin,
  445. << HeaderBlockFragment0/binary, HeaderBlockFragment1/binary >>}};
  446. continuation_frame(State, _) ->
  447. terminate(State, {connection_error, protocol_error,
  448. 'An invalid frame was received in the middle of a header block. (RFC7540 6.2)'}).
  449. down(State=#state{children=Children0}, Pid, Msg) ->
  450. case cowboy_children:down(Children0, Pid) of
  451. %% The stream was terminated already.
  452. {ok, undefined, Children} ->
  453. State#state{children=Children};
  454. %% The stream is still running.
  455. {ok, StreamID, Children} ->
  456. info(State#state{children=Children}, StreamID, Msg);
  457. %% The process was unknown.
  458. error ->
  459. error_logger:error_msg("Received EXIT signal ~p for unknown process ~p.~n", [Msg, Pid]),
  460. State
  461. end.
  462. info(State=#state{client_streamid=LastStreamID, streams=Streams}, StreamID, Msg) ->
  463. case lists:keyfind(StreamID, #stream.id, Streams) of
  464. #stream{state=flush} ->
  465. error_logger:error_msg("Received message ~p for terminated stream ~p.", [Msg, StreamID]),
  466. State;
  467. Stream = #stream{state=StreamState0} ->
  468. try cowboy_stream:info(StreamID, Msg, StreamState0) of
  469. {Commands, StreamState} ->
  470. commands(State, Stream#stream{state=StreamState}, Commands)
  471. catch Class:Exception ->
  472. cowboy_stream:report_error(info,
  473. [StreamID, Msg, StreamState0],
  474. Class, Exception, erlang:get_stacktrace()),
  475. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  476. 'Unhandled exception in cowboy_stream:info/3.'})
  477. end;
  478. false when StreamID =< LastStreamID ->
  479. %% Streams that were reset by the client or streams that are
  480. %% in the lingering state may still have Erlang messages going
  481. %% around. In these cases we do not want to log anything.
  482. State;
  483. false ->
  484. error_logger:error_msg("Received message ~p for unknown stream ~p.",
  485. [Msg, StreamID]),
  486. State
  487. end.
  488. commands(State, Stream, []) ->
  489. after_commands(State, Stream);
  490. %% Error responses are sent only if a response wasn't sent already.
  491. commands(State, Stream=#stream{local=idle}, [{error_response, StatusCode, Headers, Body}|Tail]) ->
  492. commands(State, Stream, [{response, StatusCode, Headers, Body}|Tail]);
  493. commands(State, Stream, [{error_response, _, _, _}|Tail]) ->
  494. commands(State, Stream, Tail);
  495. %% Send an informational response.
  496. commands(State0, Stream=#stream{local=idle}, [{inform, StatusCode, Headers}|Tail]) ->
  497. State = send_headers(State0, Stream, StatusCode, Headers, fin),
  498. commands(State, Stream, Tail);
  499. %% Send response headers.
  500. %%
  501. %% @todo Kill the stream if it sent a response when one has already been sent.
  502. %% @todo Keep IsFin in the state.
  503. %% @todo Same two things above apply to DATA, possibly promise too.
  504. commands(State0, Stream0=#stream{local=idle},
  505. [{response, StatusCode, Headers, Body}|Tail]) ->
  506. {State, Stream} = send_response(State0, Stream0, StatusCode, Headers, Body),
  507. commands(State, Stream, Tail);
  508. %% @todo response when local!=idle
  509. %% Send response headers.
  510. commands(State0, Stream=#stream{method=Method, local=idle},
  511. [{headers, StatusCode, Headers}|Tail]) ->
  512. IsFin = case Method of
  513. <<"HEAD">> -> fin;
  514. _ -> nofin
  515. end,
  516. State = send_headers(State0, Stream, StatusCode, Headers, IsFin),
  517. commands(State, Stream#stream{local=IsFin}, Tail);
  518. %% @todo headers when local!=idle
  519. %% Send a response body chunk.
  520. commands(State0, Stream0=#stream{local=nofin}, [{data, IsFin, Data}|Tail]) ->
  521. {State, Stream} = send_data(State0, Stream0, IsFin, Data),
  522. commands(State, Stream, Tail);
  523. %% @todo data when local!=nofin
  524. %% Send trailers.
  525. commands(State0, Stream0=#stream{local=nofin, te=TE0}, [{trailers, Trailers}|Tail]) ->
  526. %% We only accept TE headers containing exactly "trailers" (RFC7540 8.1.2.1).
  527. TE = try cow_http_hd:parse_te(TE0) of
  528. {trailers, []} -> trailers;
  529. _ -> no_trailers
  530. catch _:_ ->
  531. %% If we can't parse the TE header, assume we can't send trailers.
  532. no_trailers
  533. end,
  534. {State, Stream} = case TE of
  535. trailers ->
  536. send_data(State0, Stream0, fin, {trailers, Trailers});
  537. no_trailers ->
  538. send_data(State0, Stream0, fin, <<>>)
  539. end,
  540. commands(State, Stream, Tail);
  541. %% Send a file.
  542. %% @todo Add the sendfile command.
  543. %commands(State0, Stream0=#stream{local=nofin},
  544. % [{sendfile, IsFin, Offset, Bytes, Path}|Tail]) ->
  545. % {State, Stream} = send_data(State0, Stream0, IsFin, {sendfile, Offset, Bytes, Path}),
  546. % commands(State, Stream, Tail);
  547. %% @todo sendfile when local!=nofin
  548. %% Send a push promise.
  549. %%
  550. %% @todo We need to keep track of what promises we made so that we don't
  551. %% end up with an infinite loop of promises.
  552. commands(State0=#state{socket=Socket, transport=Transport, server_streamid=PromisedStreamID,
  553. encode_state=EncodeState0}, Stream=#stream{id=StreamID},
  554. [{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) ->
  555. Authority = case {Scheme, Port} of
  556. {<<"http">>, 80} -> Host;
  557. {<<"https">>, 443} -> Host;
  558. _ -> iolist_to_binary([Host, $:, integer_to_binary(Port)])
  559. end,
  560. PathWithQs = iolist_to_binary(case Qs of
  561. <<>> -> Path;
  562. _ -> [Path, $?, Qs]
  563. end),
  564. %% We need to make sure the header value is binary before we can
  565. %% pass it to stream_req_init, as it expects them to be flat.
  566. Headers1 = maps:map(fun(_, V) -> iolist_to_binary(V) end, Headers0),
  567. Headers = Headers1#{
  568. <<":method">> => Method,
  569. <<":scheme">> => Scheme,
  570. <<":authority">> => Authority,
  571. <<":path">> => PathWithQs},
  572. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  573. Transport:send(Socket, cow_http2:push_promise(StreamID, PromisedStreamID, HeaderBlock)),
  574. State = stream_req_init(State0#state{server_streamid=PromisedStreamID + 2,
  575. encode_state=EncodeState}, PromisedStreamID, fin, Headers1, #{
  576. method => Method,
  577. scheme => Scheme,
  578. authority => Authority,
  579. path => PathWithQs
  580. }),
  581. commands(State, Stream, Tail);
  582. commands(State=#state{socket=Socket, transport=Transport, remote_window=ConnWindow},
  583. Stream=#stream{id=StreamID, remote_window=StreamWindow},
  584. [{flow, Size}|Tail]) ->
  585. Transport:send(Socket, [
  586. cow_http2:window_update(Size),
  587. cow_http2:window_update(StreamID, Size)
  588. ]),
  589. commands(State#state{remote_window=ConnWindow + Size},
  590. Stream#stream{remote_window=StreamWindow + Size}, Tail);
  591. %% Supervise a child process.
  592. commands(State=#state{children=Children}, Stream=#stream{id=StreamID},
  593. [{spawn, Pid, Shutdown}|Tail]) ->
  594. commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)},
  595. Stream, Tail);
  596. %% Error handling.
  597. commands(State, Stream=#stream{id=StreamID}, [Error = {internal_error, _, _}|_Tail]) ->
  598. %% @todo Do we want to run the commands after an internal_error?
  599. %% @todo Do we even allow commands after?
  600. %% @todo Only reset when the stream still exists.
  601. stream_reset(after_commands(State, Stream), StreamID, Error);
  602. %% Upgrade to HTTP/2. This is triggered by cowboy_http2 itself.
  603. commands(State=#state{socket=Socket, transport=Transport},
  604. Stream=#stream{local=upgrade}, [{switch_protocol, Headers, ?MODULE, _}|Tail]) ->
  605. Transport:send(Socket, cow_http:response(101, 'HTTP/1.1', maps:to_list(Headers))),
  606. commands(State, Stream#stream{local=idle}, Tail);
  607. %% HTTP/2 has no support for the Upgrade mechanism.
  608. commands(State, Stream, [{switch_protocol, _Headers, _Mod, _ModState}|Tail]) ->
  609. %% @todo This is an error. Not sure what to do here yet.
  610. commands(State, Stream, Tail);
  611. commands(State, Stream=#stream{id=StreamID}, [stop|_Tail]) ->
  612. %% @todo Do we want to run the commands after a stop?
  613. %% @todo Do we even allow commands after?
  614. stream_terminate(after_commands(State, Stream), StreamID, normal).
  615. after_commands(State=#state{streams=Streams0}, Stream=#stream{id=StreamID}) ->
  616. Streams = lists:keystore(StreamID, #stream.id, Streams0, Stream),
  617. State#state{streams=Streams}.
  618. send_response(State0, Stream=#stream{method=Method}, StatusCode, Headers0, Body) ->
  619. if
  620. Method =:= <<"HEAD">>; Body =:= <<>> ->
  621. State = send_headers(State0, Stream, StatusCode, Headers0, fin),
  622. {State, Stream#stream{local=fin}};
  623. true ->
  624. State = send_headers(State0, Stream, StatusCode, Headers0, nofin),
  625. %% send_data works with both sendfile and iolists.
  626. send_data(State, Stream#stream{local=nofin}, fin, Body)
  627. end.
  628. send_headers(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  629. #stream{id=StreamID}, StatusCode, Headers0, IsFin) ->
  630. Headers = Headers0#{<<":status">> => status(StatusCode)},
  631. {HeaderBlock, EncodeState} = headers_encode(Headers, EncodeState0),
  632. Transport:send(Socket, cow_http2:headers(StreamID, IsFin, HeaderBlock)),
  633. State#state{encode_state=EncodeState}.
  634. status(Status) when is_integer(Status) ->
  635. integer_to_binary(Status);
  636. status(<< H, T, U, _/bits >>) when H >= $1, H =< $9, T >= $0, T =< $9, U >= $0, U =< $9 ->
  637. << H, T, U >>.
  638. %% @todo Should we ever want to implement the PRIORITY mechanism,
  639. %% this would be the place to do it. Right now, we just go over
  640. %% all streams and send what we can until either everything is
  641. %% sent or we run out of space in the window.
  642. send_data(State=#state{streams=Streams}) ->
  643. resume_streams(State, Streams, []).
  644. %% When SETTINGS_INITIAL_WINDOW_SIZE changes we need to update
  645. %% the stream windows for all active streams and perhaps resume
  646. %% sending data.
  647. update_stream_windows(State=#state{streams=Streams0}, Increment) ->
  648. Streams = [
  649. S#stream{local_window=StreamWindow + Increment}
  650. || S=#stream{local_window=StreamWindow} <- Streams0],
  651. resume_streams(State, Streams, []).
  652. resume_streams(State, [], Acc) ->
  653. State#state{streams=lists:reverse(Acc)};
  654. %% While technically we should never get < 0 here, let's be on the safe side.
  655. resume_streams(State=#state{local_window=ConnWindow}, Streams, Acc)
  656. when ConnWindow =< 0 ->
  657. State#state{streams=lists:reverse(Acc, Streams)};
  658. %% We rely on send_data/2 to do all the necessary checks about the stream.
  659. resume_streams(State0, [Stream0|Tail], Acc) ->
  660. {State1, Stream} = send_data(State0, Stream0),
  661. case Stream of
  662. %% We are done flushing, remove the stream.
  663. %% Maybe skip the request body if it was not fully read.
  664. #stream{state=flush, local=fin} ->
  665. State = maybe_skip_body(State1, Stream, normal),
  666. resume_streams(State, Tail, Acc);
  667. %% Keep the stream. Either the stream handler is still running,
  668. %% or we are not finished flushing.
  669. _ ->
  670. resume_streams(State1, Tail, [Stream|Acc])
  671. end.
  672. send_data(State, Stream=#stream{local=Local, local_buffer_size=0, local_trailers=Trailers})
  673. when (Trailers =/= undefined) andalso ((Local =:= idle) orelse (Local =:= nofin)) ->
  674. send_trailers(State, Stream#stream{local_trailers=undefined}, Trailers);
  675. %% @todo We might want to print an error if local=fin.
  676. %%
  677. %% @todo It's possible that the stream terminates. We must remove it.
  678. send_data(State=#state{local_window=ConnWindow},
  679. Stream=#stream{local=IsFin, local_window=StreamWindow, local_buffer_size=BufferSize})
  680. when ConnWindow =< 0; IsFin =:= fin; StreamWindow =< 0; BufferSize =:= 0 ->
  681. {State, Stream};
  682. send_data(State0, Stream0=#stream{local_buffer=Q0, local_buffer_size=BufferSize}) ->
  683. %% We know there is an item in the queue.
  684. {{value, {IsFin, DataSize, Data}}, Q} = queue:out(Q0),
  685. {State, Stream} = send_data(State0,
  686. Stream0#stream{local_buffer=Q, local_buffer_size=BufferSize - DataSize},
  687. IsFin, Data, in_r),
  688. send_data(State, Stream).
  689. send_data(State, Stream, IsFin, Data) ->
  690. send_data(State, Stream, IsFin, Data, in).
  691. %% We can send trailers immediately if the queue is empty, otherwise we queue.
  692. %% We always send trailer frames even if the window is empty.
  693. send_data(State, Stream=#stream{local_buffer_size=0}, fin, {trailers, Trailers}, _) ->
  694. send_trailers(State, Stream, Trailers);
  695. send_data(State, Stream, fin, {trailers, Trailers}, _) ->
  696. {State, Stream#stream{local_trailers=Trailers}};
  697. %% Send data immediately if we can, buffer otherwise.
  698. %% @todo We might want to print an error if local=fin.
  699. send_data(State=#state{local_window=ConnWindow},
  700. Stream=#stream{local_window=StreamWindow}, IsFin, Data, In)
  701. when ConnWindow =< 0; StreamWindow =< 0 ->
  702. {State, queue_data(Stream, IsFin, Data, In)};
  703. send_data(State=#state{socket=Socket, transport=Transport, local_window=ConnWindow},
  704. Stream=#stream{id=StreamID, local_window=StreamWindow}, IsFin, Data, In) ->
  705. MaxFrameSize = 16384, %% @todo Use the real SETTINGS_MAX_FRAME_SIZE set by the client.
  706. MaxSendSize = min(min(ConnWindow, StreamWindow), MaxFrameSize),
  707. case Data of
  708. {sendfile, Offset, Bytes, Path} when Bytes =< MaxSendSize ->
  709. Transport:send(Socket, cow_http2:data_header(StreamID, IsFin, Bytes)),
  710. Transport:sendfile(Socket, Path, Offset, Bytes),
  711. {State#state{local_window=ConnWindow - Bytes},
  712. Stream#stream{local=IsFin, local_window=StreamWindow - Bytes}};
  713. {sendfile, Offset, Bytes, Path} ->
  714. Transport:send(Socket, cow_http2:data_header(StreamID, nofin, MaxSendSize)),
  715. Transport:sendfile(Socket, Path, Offset, MaxSendSize),
  716. send_data(State#state{local_window=ConnWindow - MaxSendSize},
  717. Stream#stream{local_window=StreamWindow - MaxSendSize},
  718. IsFin, {sendfile, Offset + MaxSendSize, Bytes - MaxSendSize, Path}, In);
  719. Iolist0 ->
  720. IolistSize = iolist_size(Iolist0),
  721. if
  722. IolistSize =< MaxSendSize ->
  723. Transport:send(Socket, cow_http2:data(StreamID, IsFin, Iolist0)),
  724. {State#state{local_window=ConnWindow - IolistSize},
  725. Stream#stream{local=IsFin, local_window=StreamWindow - IolistSize}};
  726. true ->
  727. {Iolist, More} = cowboy_iolists:split(MaxSendSize, Iolist0),
  728. Transport:send(Socket, cow_http2:data(StreamID, nofin, Iolist)),
  729. send_data(State#state{local_window=ConnWindow - MaxSendSize},
  730. Stream#stream{local_window=StreamWindow - MaxSendSize},
  731. IsFin, More, In)
  732. end
  733. end.
  734. send_trailers(State=#state{socket=Socket, transport=Transport, encode_state=EncodeState0},
  735. Stream=#stream{id=StreamID}, Trailers) ->
  736. {HeaderBlock, EncodeState} = headers_encode(Trailers, EncodeState0),
  737. Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
  738. {State#state{encode_state=EncodeState}, Stream#stream{local=fin}}.
  739. queue_data(Stream=#stream{local_buffer=Q0, local_buffer_size=Size0}, IsFin, Data, In) ->
  740. DataSize = case Data of
  741. {sendfile, _, Bytes, _} -> Bytes;
  742. Iolist -> iolist_size(Iolist)
  743. end,
  744. Q = queue:In({IsFin, DataSize, Data}, Q0),
  745. Stream#stream{local_buffer=Q, local_buffer_size=Size0 + DataSize}.
  746. %% The set-cookie header is special; we can only send one cookie per header.
  747. headers_encode(Headers0=#{<<"set-cookie">> := SetCookies}, EncodeState) ->
  748. Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  749. Headers = Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies],
  750. cow_hpack:encode(Headers, EncodeState);
  751. headers_encode(Headers0, EncodeState) ->
  752. Headers = maps:to_list(Headers0),
  753. cow_hpack:encode(Headers, EncodeState).
  754. -spec terminate(#state{}, _) -> no_return().
  755. terminate(undefined, Reason) ->
  756. exit({shutdown, Reason});
  757. terminate(#state{socket=Socket, transport=Transport, parse_state={preface, _, _}}, Reason) ->
  758. Transport:close(Socket),
  759. exit({shutdown, Reason});
  760. terminate(#state{socket=Socket, transport=Transport, client_streamid=LastStreamID,
  761. streams=Streams, children=Children}, Reason) ->
  762. %% @todo We might want to optionally send the Reason value
  763. %% as debug data in the GOAWAY frame here. Perhaps more.
  764. Transport:send(Socket, cow_http2:goaway(LastStreamID, terminate_reason(Reason), <<>>)),
  765. terminate_all_streams(Streams, Reason),
  766. cowboy_children:terminate(Children),
  767. Transport:close(Socket),
  768. exit({shutdown, Reason}).
  769. terminate_reason({connection_error, Reason, _}) -> Reason;
  770. terminate_reason({stop, _, _}) -> no_error;
  771. terminate_reason({socket_error, _, _}) -> internal_error;
  772. terminate_reason({internal_error, _, _}) -> internal_error.
  773. terminate_all_streams([], _) ->
  774. ok;
  775. %% This stream was already terminated and is now just flushing the data out. Skip it.
  776. terminate_all_streams([#stream{state=flush}|Tail], Reason) ->
  777. terminate_all_streams(Tail, Reason);
  778. terminate_all_streams([#stream{id=StreamID, state=StreamState}|Tail], Reason) ->
  779. stream_call_terminate(StreamID, Reason, StreamState),
  780. terminate_all_streams(Tail, Reason).
  781. %% Stream functions.
  782. stream_decode_init(State=#state{decode_state=DecodeState0}, StreamID, IsFin, HeaderBlock) ->
  783. try cow_hpack:decode(HeaderBlock, DecodeState0) of
  784. {Headers, DecodeState} ->
  785. stream_pseudo_headers_init(State#state{decode_state=DecodeState},
  786. StreamID, IsFin, Headers)
  787. catch _:_ ->
  788. terminate(State, {connection_error, compression_error,
  789. 'Error while trying to decode HPACK-encoded header block. (RFC7540 4.3)'})
  790. end.
  791. stream_pseudo_headers_init(State, StreamID, IsFin, Headers0) ->
  792. case pseudo_headers(Headers0, #{}) of
  793. %% @todo Add clause for CONNECT requests (no scheme/path).
  794. {ok, PseudoHeaders=#{method := <<"CONNECT">>}, _} ->
  795. stream_early_error(State, StreamID, IsFin, 501, PseudoHeaders,
  796. 'The CONNECT method is currently not implemented. (RFC7231 4.3.6)');
  797. {ok, PseudoHeaders=#{method := <<"TRACE">>}, _} ->
  798. stream_early_error(State, StreamID, IsFin, 501, PseudoHeaders,
  799. 'The TRACE method is currently not implemented. (RFC7231 4.3.8)');
  800. {ok, PseudoHeaders=#{method := _, scheme := _, authority := _, path := _}, Headers} ->
  801. stream_regular_headers_init(State, StreamID, IsFin, Headers, PseudoHeaders);
  802. {ok, _, _} ->
  803. stream_malformed(State, StreamID,
  804. 'A required pseudo-header was not found. (RFC7540 8.1.2.3)');
  805. {error, HumanReadable} ->
  806. stream_malformed(State, StreamID, HumanReadable)
  807. end.
  808. pseudo_headers([{<<":method">>, _}|_], #{method := _}) ->
  809. {error, 'Multiple :method pseudo-headers were found. (RFC7540 8.1.2.3)'};
  810. pseudo_headers([{<<":method">>, Method}|Tail], PseudoHeaders) ->
  811. pseudo_headers(Tail, PseudoHeaders#{method => Method});
  812. pseudo_headers([{<<":scheme">>, _}|_], #{scheme := _}) ->
  813. {error, 'Multiple :scheme pseudo-headers were found. (RFC7540 8.1.2.3)'};
  814. pseudo_headers([{<<":scheme">>, Scheme}|Tail], PseudoHeaders) ->
  815. pseudo_headers(Tail, PseudoHeaders#{scheme => Scheme});
  816. pseudo_headers([{<<":authority">>, _}|_], #{authority := _}) ->
  817. {error, 'Multiple :authority pseudo-headers were found. (RFC7540 8.1.2.3)'};
  818. pseudo_headers([{<<":authority">>, Authority}|Tail], PseudoHeaders) ->
  819. %% @todo Probably parse the authority here.
  820. pseudo_headers(Tail, PseudoHeaders#{authority => Authority});
  821. pseudo_headers([{<<":path">>, _}|_], #{path := _}) ->
  822. {error, 'Multiple :path pseudo-headers were found. (RFC7540 8.1.2.3)'};
  823. pseudo_headers([{<<":path">>, Path}|Tail], PseudoHeaders) ->
  824. %% @todo Probably parse the path here.
  825. pseudo_headers(Tail, PseudoHeaders#{path => Path});
  826. pseudo_headers([{<<":", _/bits>>, _}|_], _) ->
  827. {error, 'An unknown or invalid pseudo-header was found. (RFC7540 8.1.2.1)'};
  828. pseudo_headers(Headers, PseudoHeaders) ->
  829. {ok, PseudoHeaders, Headers}.
  830. stream_regular_headers_init(State, StreamID, IsFin, Headers, PseudoHeaders) ->
  831. case regular_headers(Headers) of
  832. ok ->
  833. stream_req_init(State, StreamID, IsFin,
  834. headers_to_map(Headers, #{}), PseudoHeaders);
  835. {error, HumanReadable} ->
  836. stream_malformed(State, StreamID, HumanReadable)
  837. end.
  838. regular_headers([{<<":", _/bits>>, _}|_]) ->
  839. {error, 'Pseudo-headers were found after regular headers. (RFC7540 8.1.2.1)'};
  840. regular_headers([{<<"connection">>, _}|_]) ->
  841. {error, 'The connection header is not allowed. (RFC7540 8.1.2.2)'};
  842. regular_headers([{<<"keep-alive">>, _}|_]) ->
  843. {error, 'The keep-alive header is not allowed. (RFC7540 8.1.2.2)'};
  844. regular_headers([{<<"proxy-authenticate">>, _}|_]) ->
  845. {error, 'The proxy-authenticate header is not allowed. (RFC7540 8.1.2.2)'};
  846. regular_headers([{<<"proxy-authorization">>, _}|_]) ->
  847. {error, 'The proxy-authorization header is not allowed. (RFC7540 8.1.2.2)'};
  848. regular_headers([{<<"transfer-encoding">>, _}|_]) ->
  849. {error, 'The transfer-encoding header is not allowed. (RFC7540 8.1.2.2)'};
  850. regular_headers([{<<"upgrade">>, _}|_]) ->
  851. {error, 'The upgrade header is not allowed. (RFC7540 8.1.2.2)'};
  852. regular_headers([{<<"te">>, Value}|_]) when Value =/= <<"trailers">> ->
  853. {error, 'The te header with a value other than "trailers" is not allowed. (RFC7540 8.1.2.2)'};
  854. regular_headers([{Name, _}|Tail]) ->
  855. case cowboy_bstr:to_lower(Name) of
  856. Name -> regular_headers(Tail);
  857. _ -> {error, 'Header names must be lowercase. (RFC7540 8.1.2)'}
  858. end;
  859. regular_headers([]) ->
  860. ok.
  861. %% This function is necessary to properly handle duplicate headers
  862. %% and the special-case cookie header.
  863. headers_to_map([], Acc) ->
  864. Acc;
  865. headers_to_map([{Name, Value}|Tail], Acc0) ->
  866. Acc = case Acc0 of
  867. %% The cookie header does not use proper HTTP header lists.
  868. #{Name := Value0} when Name =:= <<"cookie">> -> Acc0#{Name => << Value0/binary, "; ", Value/binary >>};
  869. #{Name := Value0} -> Acc0#{Name => << Value0/binary, ", ", Value/binary >>};
  870. _ -> Acc0#{Name => Value}
  871. end,
  872. headers_to_map(Tail, Acc).
  873. stream_req_init(State=#state{ref=Ref, peer=Peer, sock=Sock, cert=Cert},
  874. StreamID, IsFin, Headers, #{method := Method, scheme := Scheme,
  875. authority := Authority, path := PathWithQs}) ->
  876. BodyLength = case Headers of
  877. _ when IsFin =:= fin ->
  878. 0;
  879. #{<<"content-length">> := <<"0">>} ->
  880. 0;
  881. #{<<"content-length">> := BinLength} ->
  882. try
  883. cow_http_hd:parse_content_length(BinLength)
  884. catch _:_ ->
  885. terminate(State, {stream_error, StreamID, protocol_error,
  886. 'The content-length header is invalid. (RFC7230 3.3.2)'})
  887. end;
  888. _ ->
  889. undefined
  890. end,
  891. try cow_http_hd:parse_host(Authority) of
  892. {Host, Port} ->
  893. try cow_http:parse_fullpath(PathWithQs) of
  894. {<<>>, _} ->
  895. stream_malformed(State, StreamID,
  896. 'The path component must not be empty. (RFC7540 8.1.2.3)');
  897. {Path, Qs} ->
  898. Req = #{
  899. ref => Ref,
  900. pid => self(),
  901. streamid => StreamID,
  902. peer => Peer,
  903. sock => Sock,
  904. cert => Cert,
  905. method => Method,
  906. scheme => Scheme,
  907. host => Host,
  908. port => Port,
  909. path => Path,
  910. qs => Qs,
  911. version => 'HTTP/2',
  912. headers => Headers,
  913. has_body => IsFin =:= nofin,
  914. body_length => BodyLength
  915. },
  916. stream_handler_init(State, StreamID, IsFin, idle, Req)
  917. catch _:_ ->
  918. stream_malformed(State, StreamID,
  919. 'The :path pseudo-header is invalid. (RFC7540 8.1.2.3)')
  920. end
  921. catch _:_ ->
  922. stream_malformed(State, StreamID,
  923. 'The :authority pseudo-header is invalid. (RFC7540 8.1.2.3)')
  924. end.
  925. stream_malformed(State=#state{socket=Socket, transport=Transport}, StreamID, _) ->
  926. Transport:send(Socket, cow_http2:rst_stream(StreamID, protocol_error)),
  927. State.
  928. stream_early_error(State0=#state{ref=Ref, opts=Opts, peer=Peer,
  929. local_settings=#{initial_window_size := RemoteWindow},
  930. remote_settings=#{initial_window_size := LocalWindow},
  931. streams=Streams}, StreamID, IsFin, StatusCode0,
  932. #{method := Method}, HumanReadable) ->
  933. %% We automatically terminate the stream but it is not an error
  934. %% per se (at least not in the first implementation).
  935. Reason = {stream_error, no_error, HumanReadable},
  936. %% The partial Req is minimal for now. We only have one case
  937. %% where it can be called (when a method is completely disabled).
  938. PartialReq = #{
  939. ref => Ref,
  940. peer => Peer,
  941. method => Method
  942. },
  943. Resp = {response, StatusCode0, RespHeaders0=#{<<"content-length">> => <<"0">>}, <<>>},
  944. %% We need a stream to talk to the send_* functions.
  945. Stream0 = #stream{id=StreamID, state=flush, method=Method,
  946. remote=IsFin, local=idle,
  947. local_window=LocalWindow, remote_window=RemoteWindow},
  948. try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts) of
  949. {response, StatusCode, RespHeaders, RespBody} ->
  950. case send_response(State0, Stream0, StatusCode, RespHeaders, RespBody) of
  951. {State, #stream{local=fin}} ->
  952. State;
  953. {State, Stream} ->
  954. State#state{streams=[Stream|Streams]}
  955. end
  956. catch Class:Exception ->
  957. cowboy_stream:report_error(early_error,
  958. [StreamID, Reason, PartialReq, Resp, Opts],
  959. Class, Exception, erlang:get_stacktrace()),
  960. %% We still need to send an error response, so send what we initially
  961. %% wanted to send. It's better than nothing.
  962. send_headers(State0, Stream0, StatusCode0, RespHeaders0, fin)
  963. end.
  964. stream_handler_init(State=#state{opts=Opts,
  965. local_settings=#{initial_window_size := RemoteWindow},
  966. remote_settings=#{initial_window_size := LocalWindow}},
  967. StreamID, RemoteIsFin, LocalIsFin,
  968. Req=#{method := Method, headers := Headers}) ->
  969. try cowboy_stream:init(StreamID, Req, Opts) of
  970. {Commands, StreamState} ->
  971. commands(State#state{client_streamid=StreamID},
  972. #stream{id=StreamID, state=StreamState,
  973. method=Method, remote=RemoteIsFin, local=LocalIsFin,
  974. local_window=LocalWindow, remote_window=RemoteWindow,
  975. te=maps:get(<<"te">>, Headers, undefined)},
  976. Commands)
  977. catch Class:Exception ->
  978. cowboy_stream:report_error(init,
  979. [StreamID, Req, Opts],
  980. Class, Exception, erlang:get_stacktrace()),
  981. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  982. 'Unhandled exception in cowboy_stream:init/3.'})
  983. end.
  984. %% @todo Don't send an RST_STREAM if one was already sent.
  985. stream_reset(State=#state{socket=Socket, transport=Transport}, StreamID, StreamError) ->
  986. Reason = case StreamError of
  987. {internal_error, _, _} -> internal_error;
  988. {stream_error, Reason0, _} -> Reason0
  989. end,
  990. Transport:send(Socket, cow_http2:rst_stream(StreamID, Reason)),
  991. stream_terminate(stream_linger(State, StreamID), StreamID, StreamError).
  992. %% We only keep up to 100 streams in this state. @todo Make it configurable?
  993. stream_linger(State=#state{lingering_streams=Lingering0}, StreamID) ->
  994. Lingering = [StreamID|lists:sublist(Lingering0, 100 - 1)],
  995. State#state{lingering_streams=Lingering}.
  996. stream_terminate(State0=#state{streams=Streams0, children=Children0}, StreamID, Reason) ->
  997. case lists:keytake(StreamID, #stream.id, Streams0) of
  998. %% When the stream terminates normally (without sending RST_STREAM)
  999. %% and no response was sent, we need to send a proper response back to the client.
  1000. {value, Stream=#stream{local=idle}, Streams} when Reason =:= normal ->
  1001. State1 = #state{streams=Streams1} = info(State0, StreamID, {response, 204, #{}, <<>>}),
  1002. State = maybe_skip_body(State1, Stream, Reason),
  1003. #stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams1),
  1004. stream_call_terminate(StreamID, Reason, StreamState),
  1005. Children = cowboy_children:shutdown(Children0, StreamID),
  1006. State#state{streams=Streams, children=Children};
  1007. %% When a response was sent but not terminated, we need to close the stream.
  1008. {value, Stream=#stream{local=nofin, local_buffer_size=0}, Streams}
  1009. when Reason =:= normal ->
  1010. State1 = #state{streams=Streams1} = info(State0, StreamID, {data, fin, <<>>}),
  1011. State = maybe_skip_body(State1, Stream, Reason),
  1012. #stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams1),
  1013. stream_call_terminate(StreamID, Reason, StreamState),
  1014. Children = cowboy_children:shutdown(Children0, StreamID),
  1015. State#state{streams=Streams, children=Children};
  1016. %% Unless there is still data in the buffer. We can however reset
  1017. %% a few fields and set a special local state to avoid confusion.
  1018. %%
  1019. %% We do not reset the stream in this case (to skip the body)
  1020. %% because we are still sending data via the buffer. We will
  1021. %% reset the stream if necessary once the buffer is empty.
  1022. {value, Stream=#stream{state=StreamState, local=nofin}, Streams} ->
  1023. stream_call_terminate(StreamID, Reason, StreamState),
  1024. Children = cowboy_children:shutdown(Children0, StreamID),
  1025. State0#state{streams=[Stream#stream{state=flush, local=flush}|Streams],
  1026. children=Children};
  1027. %% Otherwise we sent or received an RST_STREAM and/or the stream is already closed.
  1028. {value, Stream=#stream{state=StreamState}, Streams} ->
  1029. State = maybe_skip_body(State0, Stream, Reason),
  1030. stream_call_terminate(StreamID, Reason, StreamState),
  1031. Children = cowboy_children:shutdown(Children0, StreamID),
  1032. State#state{streams=Streams, children=Children};
  1033. %% The stream doesn't exist. This can occur for various reasons.
  1034. %% It can happen before the stream has been created, or because
  1035. %% the cowboy_stream:init call failed, in which case doing nothing
  1036. %% is correct.
  1037. false ->
  1038. State0
  1039. end.
  1040. %% When the stream stops normally without reading the request
  1041. %% body fully we need to tell the client to stop sending it.
  1042. %% We do this by sending an RST_STREAM with reason NO_ERROR. (RFC7540 8.1.0)
  1043. maybe_skip_body(State=#state{socket=Socket, transport=Transport},
  1044. #stream{id=StreamID, remote=nofin}, normal) ->
  1045. Transport:send(Socket, cow_http2:rst_stream(StreamID, no_error)),
  1046. stream_linger(State, StreamID);
  1047. maybe_skip_body(State, _, _) ->
  1048. State.
  1049. stream_call_terminate(StreamID, Reason, StreamState) ->
  1050. try
  1051. cowboy_stream:terminate(StreamID, Reason, StreamState)
  1052. catch Class:Exception ->
  1053. cowboy_stream:report_error(terminate,
  1054. [StreamID, Reason, StreamState],
  1055. Class, Exception, erlang:get_stacktrace())
  1056. end.
  1057. %% System callbacks.
  1058. -spec system_continue(_, _, {#state{}, binary()}) -> ok.
  1059. system_continue(_, _, {State, Buffer}) ->
  1060. loop(State, Buffer).
  1061. -spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return().
  1062. system_terminate(Reason, _, _, {State, _}) ->
  1063. terminate(State, Reason).
  1064. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  1065. system_code_change(Misc, _, _, _) ->
  1066. {ok, Misc}.