cowboy_http2.erl 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. -ifdef(OTP_RELEASE).
  16. -compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}).
  17. -endif.
  18. -export([init/5]).
  19. -export([init/9]).
  20. -export([init/11]).
  21. -export([system_continue/3]).
  22. -export([system_terminate/4]).
  23. -export([system_code_change/4]).
  24. -type opts() :: #{
  25. connection_type => worker | supervisor,
  26. enable_connect_protocol => boolean(),
  27. env => cowboy_middleware:env(),
  28. inactivity_timeout => timeout(),
  29. initial_connection_window_size => 65535..16#7fffffff,
  30. initial_stream_window_size => 0..16#7fffffff,
  31. logger => module(),
  32. max_concurrent_streams => non_neg_integer() | infinity,
  33. max_decode_table_size => non_neg_integer(),
  34. max_encode_table_size => non_neg_integer(),
  35. max_frame_size_received => 16384..16777215,
  36. max_frame_size_sent => 16384..16777215 | infinity,
  37. middlewares => [module()],
  38. preface_timeout => timeout(),
  39. settings_timeout => timeout(),
  40. shutdown_timeout => timeout(),
  41. stream_handlers => [module()]
  42. }.
  43. -export_type([opts/0]).
  44. -record(state, {
  45. parent = undefined :: pid(),
  46. ref :: ranch:ref(),
  47. socket = undefined :: inet:socket(),
  48. transport :: module(),
  49. opts = #{} :: opts(),
  50. %% Remote address and port for the connection.
  51. peer = undefined :: {inet:ip_address(), inet:port_number()},
  52. %% Local address and port for the connection.
  53. sock = undefined :: {inet:ip_address(), inet:port_number()},
  54. %% Client certificate (TLS only).
  55. cert :: undefined | binary(),
  56. %% HTTP/2 state machine.
  57. http2_init :: sequence | settings | upgrade | complete,
  58. http2_machine :: cow_http2_machine:http2_machine(),
  59. %% Currently active HTTP/2 streams. Streams may be initiated either
  60. %% by the client or by the server through PUSH_PROMISE frames.
  61. streams = #{} :: #{cow_http2:streamid() => {running | stopping, {module, any()}}},
  62. %% Streams can spawn zero or more children which are then managed
  63. %% by this module if operating as a supervisor.
  64. children = cowboy_children:init() :: cowboy_children:children()
  65. }).
  66. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts()) -> ok.
  67. init(Parent, Ref, Socket, Transport, Opts) ->
  68. Peer0 = Transport:peername(Socket),
  69. Sock0 = Transport:sockname(Socket),
  70. Cert1 = case Transport:name() of
  71. ssl ->
  72. case ssl:peercert(Socket) of
  73. {error, no_peercert} ->
  74. {ok, undefined};
  75. Cert0 ->
  76. Cert0
  77. end;
  78. _ ->
  79. {ok, undefined}
  80. end,
  81. case {Peer0, Sock0, Cert1} of
  82. {{ok, Peer}, {ok, Sock}, {ok, Cert}} ->
  83. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, <<>>);
  84. {{error, Reason}, _, _} ->
  85. terminate(undefined, {socket_error, Reason,
  86. 'A socket error occurred when retrieving the peer name.'});
  87. {_, {error, Reason}, _} ->
  88. terminate(undefined, {socket_error, Reason,
  89. 'A socket error occurred when retrieving the sock name.'});
  90. {_, _, {error, Reason}} ->
  91. terminate(undefined, {socket_error, Reason,
  92. 'A socket error occurred when retrieving the client TLS certificate.'})
  93. end.
  94. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  95. {inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()},
  96. binary() | undefined, binary()) -> ok.
  97. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, Buffer) ->
  98. {ok, Preface, HTTP2Machine} = cow_http2_machine:init(server, Opts),
  99. State = #state{parent=Parent, ref=Ref, socket=Socket,
  100. transport=Transport, opts=Opts, peer=Peer, sock=Sock, cert=Cert,
  101. http2_init=sequence, http2_machine=HTTP2Machine},
  102. Transport:send(Socket, Preface),
  103. case Buffer of
  104. <<>> -> before_loop(State, Buffer);
  105. _ -> parse(State, Buffer)
  106. end.
  107. %% @todo Add an argument for the request body.
  108. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(),
  109. {inet:ip_address(), inet:port_number()}, {inet:ip_address(), inet:port_number()},
  110. binary() | undefined, binary(), map() | undefined, cowboy_req:req()) -> ok.
  111. init(Parent, Ref, Socket, Transport, Opts, Peer, Sock, Cert, Buffer,
  112. _Settings, Req=#{method := Method}) ->
  113. {ok, Preface, HTTP2Machine0} = cow_http2_machine:init(server, Opts),
  114. {ok, StreamID, HTTP2Machine}
  115. = cow_http2_machine:init_upgrade_stream(Method, HTTP2Machine0),
  116. State0 = #state{parent=Parent, ref=Ref, socket=Socket,
  117. transport=Transport, opts=Opts, peer=Peer, sock=Sock, cert=Cert,
  118. http2_init=upgrade, http2_machine=HTTP2Machine},
  119. State1 = headers_frame(State0#state{
  120. http2_machine=HTTP2Machine}, StreamID, Req),
  121. %% We assume that the upgrade will be applied. A stream handler
  122. %% must not prevent the normal operations of the server.
  123. State2 = info(State1, 1, {switch_protocol, #{
  124. <<"connection">> => <<"Upgrade">>,
  125. <<"upgrade">> => <<"h2c">>
  126. }, ?MODULE, undefined}), %% @todo undefined or #{}?
  127. State = State2#state{http2_init=sequence},
  128. Transport:send(Socket, Preface),
  129. case Buffer of
  130. <<>> -> before_loop(State, Buffer);
  131. _ -> parse(State, Buffer)
  132. end.
  133. %% @todo Add the timeout for last time since we heard of connection.
  134. before_loop(State, Buffer) ->
  135. loop(State, Buffer).
  136. loop(State=#state{parent=Parent, socket=Socket, transport=Transport,
  137. opts=Opts, children=Children}, Buffer) ->
  138. Transport:setopts(Socket, [{active, once}]),
  139. {OK, Closed, Error} = Transport:messages(),
  140. InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000),
  141. receive
  142. %% Socket messages.
  143. {OK, Socket, Data} ->
  144. parse(State, << Buffer/binary, Data/binary >>);
  145. {Closed, Socket} ->
  146. terminate(State, {socket_error, closed, 'The socket has been closed.'});
  147. {Error, Socket, Reason} ->
  148. terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'});
  149. %% System messages.
  150. {'EXIT', Parent, Reason} ->
  151. terminate(State, {stop, {exit, Reason}, 'Parent process terminated.'});
  152. {system, From, Request} ->
  153. sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer});
  154. %% Timeouts.
  155. {timeout, Ref, {shutdown, Pid}} ->
  156. cowboy_children:shutdown_timeout(Children, Ref, Pid),
  157. loop(State, Buffer);
  158. {timeout, TRef, {cow_http2_machine, Name}} ->
  159. loop(timeout(State, Name, TRef), Buffer);
  160. %% Messages pertaining to a stream.
  161. {{Pid, StreamID}, Msg} when Pid =:= self() ->
  162. loop(info(State, StreamID, Msg), Buffer);
  163. %% Exit signal from children.
  164. Msg = {'EXIT', Pid, _} ->
  165. loop(down(State, Pid, Msg), Buffer);
  166. %% Calls from supervisor module.
  167. {'$gen_call', From, Call} ->
  168. cowboy_children:handle_supervisor_call(Call, From, Children, ?MODULE),
  169. loop(State, Buffer);
  170. Msg ->
  171. cowboy:log(warning, "Received stray message ~p.", [Msg], Opts),
  172. loop(State, Buffer)
  173. after InactivityTimeout ->
  174. terminate(State, {internal_error, timeout, 'No message or data received before timeout.'})
  175. end.
  176. %% HTTP/2 protocol parsing.
  177. parse(State=#state{http2_init=sequence}, Data) ->
  178. case cow_http2:parse_sequence(Data) of
  179. {ok, Rest} ->
  180. parse(State#state{http2_init=settings}, Rest);
  181. more ->
  182. before_loop(State, Data);
  183. Error = {connection_error, _, _} ->
  184. terminate(State, Error)
  185. end;
  186. parse(State=#state{http2_machine=HTTP2Machine}, Data) ->
  187. MaxFrameSize = cow_http2_machine:get_local_setting(max_frame_size, HTTP2Machine),
  188. case cow_http2:parse(Data, MaxFrameSize) of
  189. {ok, Frame, Rest} ->
  190. parse(frame(State, Frame), Rest);
  191. {ignore, Rest} ->
  192. parse(ignored_frame(State), Rest);
  193. {stream_error, StreamID, Reason, Human, Rest} ->
  194. parse(stream_reset(State, StreamID, {stream_error, Reason, Human}), Rest);
  195. Error = {connection_error, _, _} ->
  196. terminate(State, Error);
  197. more ->
  198. before_loop(State, Data)
  199. end.
  200. %% Frames received.
  201. frame(State=#state{http2_machine=HTTP2Machine0}, Frame) ->
  202. case cow_http2_machine:frame(Frame, HTTP2Machine0) of
  203. {ok, HTTP2Machine} ->
  204. maybe_ack(State#state{http2_machine=HTTP2Machine}, Frame);
  205. {ok, {data, StreamID, IsFin, Data}, HTTP2Machine} ->
  206. data_frame(State#state{http2_machine=HTTP2Machine}, StreamID, IsFin, Data);
  207. {ok, {headers, StreamID, IsFin, Headers, PseudoHeaders, BodyLen}, HTTP2Machine} ->
  208. headers_frame(State#state{http2_machine=HTTP2Machine},
  209. StreamID, IsFin, Headers, PseudoHeaders, BodyLen);
  210. {ok, {trailers, _StreamID, _Trailers}, HTTP2Machine} ->
  211. %% @todo Propagate trailers.
  212. State#state{http2_machine=HTTP2Machine};
  213. {ok, {rst_stream, StreamID, Reason}, HTTP2Machine} ->
  214. rst_stream_frame(State#state{http2_machine=HTTP2Machine}, StreamID, Reason);
  215. {ok, Frame={goaway, _StreamID, _Reason, _Data}, HTTP2Machine} ->
  216. terminate(State#state{http2_machine=HTTP2Machine},
  217. {stop, Frame, 'Client is going away.'});
  218. {send, SendData, HTTP2Machine} ->
  219. send_data(maybe_ack(State#state{http2_machine=HTTP2Machine}, Frame), SendData);
  220. {error, {stream_error, StreamID, Reason, Human}, HTTP2Machine} ->
  221. stream_reset(State#state{http2_machine=HTTP2Machine},
  222. StreamID, {stream_error, Reason, Human});
  223. {error, Error={connection_error, _, _}, HTTP2Machine} ->
  224. terminate(State#state{http2_machine=HTTP2Machine}, Error)
  225. end.
  226. %% We use this opportunity to mark the HTTP/2 initialization
  227. %% as complete if we were still waiting for a SETTINGS frame.
  228. maybe_ack(State=#state{http2_init=settings}, Frame) ->
  229. maybe_ack(State#state{http2_init=complete}, Frame);
  230. maybe_ack(State=#state{socket=Socket, transport=Transport}, Frame) ->
  231. case Frame of
  232. {settings, _} -> Transport:send(Socket, cow_http2:settings_ack());
  233. {ping, Opaque} -> Transport:send(Socket, cow_http2:ping_ack(Opaque));
  234. _ -> ok
  235. end,
  236. State.
  237. data_frame(State=#state{opts=Opts, streams=Streams}, StreamID, IsFin, Data) ->
  238. case Streams of
  239. #{StreamID := {running, StreamState0}} ->
  240. try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
  241. {Commands, StreamState} ->
  242. commands(State#state{streams=Streams#{StreamID => {running, StreamState}}},
  243. StreamID, Commands)
  244. catch Class:Exception ->
  245. cowboy:log(cowboy_stream:make_error_log(data,
  246. [StreamID, IsFin, Data, StreamState0],
  247. Class, Exception, erlang:get_stacktrace()), Opts),
  248. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  249. 'Unhandled exception in cowboy_stream:data/4.'})
  250. end;
  251. %% We ignore DATA frames for streams that are stopping.
  252. #{} ->
  253. State
  254. end.
  255. headers_frame(State, StreamID, IsFin, Headers,
  256. PseudoHeaders=#{method := <<"CONNECT">>}, _)
  257. when map_size(PseudoHeaders) =:= 2 ->
  258. early_error(State, StreamID, IsFin, Headers, PseudoHeaders, 501,
  259. 'The CONNECT method is currently not implemented. (RFC7231 4.3.6)');
  260. headers_frame(State, StreamID, IsFin, Headers,
  261. PseudoHeaders=#{method := <<"TRACE">>}, _) ->
  262. early_error(State, StreamID, IsFin, Headers, PseudoHeaders, 501,
  263. 'The TRACE method is currently not implemented. (RFC7231 4.3.8)');
  264. headers_frame(State=#state{ref=Ref, peer=Peer, sock=Sock, cert=Cert},
  265. StreamID, IsFin, Headers, PseudoHeaders=#{method := Method, scheme := Scheme,
  266. authority := Authority, path := PathWithQs}, BodyLen) ->
  267. try cow_http_hd:parse_host(Authority) of
  268. {Host, Port0} ->
  269. Port = ensure_port(Scheme, Port0),
  270. try cow_http:parse_fullpath(PathWithQs) of
  271. {<<>>, _} ->
  272. malformed_request(State, StreamID,
  273. 'The path component must not be empty. (RFC7540 8.1.2.3)');
  274. {Path, Qs} ->
  275. Req0 = #{
  276. ref => Ref,
  277. pid => self(),
  278. streamid => StreamID,
  279. peer => Peer,
  280. sock => Sock,
  281. cert => Cert,
  282. method => Method,
  283. scheme => Scheme,
  284. host => Host,
  285. port => Port,
  286. path => Path,
  287. qs => Qs,
  288. version => 'HTTP/2',
  289. headers => headers_to_map(Headers, #{}),
  290. has_body => IsFin =:= nofin,
  291. body_length => BodyLen
  292. },
  293. %% We add the protocol information for extended CONNECTs.
  294. Req = case PseudoHeaders of
  295. #{protocol := Protocol} ->
  296. Req0#{protocol => Protocol};
  297. _ ->
  298. Req0
  299. end,
  300. headers_frame(State, StreamID, Req)
  301. catch _:_ ->
  302. malformed_request(State, StreamID,
  303. 'The :path pseudo-header is invalid. (RFC7540 8.1.2.3)')
  304. end
  305. catch _:_ ->
  306. malformed_request(State, StreamID,
  307. 'The :authority pseudo-header is invalid. (RFC7540 8.1.2.3)')
  308. end.
  309. ensure_port(<<"http">>, undefined) -> 80;
  310. ensure_port(<<"https">>, undefined) -> 443;
  311. ensure_port(_, Port) -> Port.
  312. %% This function is necessary to properly handle duplicate headers
  313. %% and the special-case cookie header.
  314. headers_to_map([], Acc) ->
  315. Acc;
  316. headers_to_map([{Name, Value}|Tail], Acc0) ->
  317. Acc = case Acc0 of
  318. %% The cookie header does not use proper HTTP header lists.
  319. #{Name := Value0} when Name =:= <<"cookie">> ->
  320. Acc0#{Name => << Value0/binary, "; ", Value/binary >>};
  321. #{Name := Value0} ->
  322. Acc0#{Name => << Value0/binary, ", ", Value/binary >>};
  323. _ ->
  324. Acc0#{Name => Value}
  325. end,
  326. headers_to_map(Tail, Acc).
  327. %% @todo Probably not a very useful function, just use stream_reset.
  328. malformed_request(State=#state{socket=Socket, transport=Transport,
  329. http2_machine=HTTP2Machine0}, StreamID, _) ->
  330. Transport:send(Socket, cow_http2:rst_stream(StreamID, protocol_error)),
  331. {ok, HTTP2Machine} = cow_http2_machine:reset_stream(StreamID, HTTP2Machine0),
  332. State#state{http2_machine=HTTP2Machine}.
  333. headers_frame(State=#state{opts=Opts, streams=Streams}, StreamID, Req) ->
  334. try cowboy_stream:init(StreamID, Req, Opts) of
  335. {Commands, StreamState} ->
  336. commands(State#state{
  337. streams=Streams#{StreamID => {running, StreamState}}},
  338. StreamID, Commands)
  339. catch Class:Exception ->
  340. cowboy:log(cowboy_stream:make_error_log(init,
  341. [StreamID, Req, Opts],
  342. Class, Exception, erlang:get_stacktrace()), Opts),
  343. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  344. 'Unhandled exception in cowboy_stream:init/3.'})
  345. end.
  346. early_error(State0=#state{ref=Ref, opts=Opts, peer=Peer},
  347. StreamID, _IsFin, _Headers, #{method := Method},
  348. StatusCode0, HumanReadable) ->
  349. %% We automatically terminate the stream but it is not an error
  350. %% per se (at least not in the first implementation).
  351. Reason = {stream_error, no_error, HumanReadable},
  352. %% The partial Req is minimal for now. We only have one case
  353. %% where it can be called (when a method is completely disabled).
  354. %% @todo Fill in the other elements.
  355. PartialReq = #{
  356. ref => Ref,
  357. peer => Peer,
  358. method => Method
  359. },
  360. Resp = {response, StatusCode0, RespHeaders0=#{<<"content-length">> => <<"0">>}, <<>>},
  361. try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts) of
  362. {response, StatusCode, RespHeaders, RespBody} ->
  363. send_response(State0, StreamID, StatusCode, RespHeaders, RespBody)
  364. catch Class:Exception ->
  365. cowboy:log(cowboy_stream:make_error_log(early_error,
  366. [StreamID, Reason, PartialReq, Resp, Opts],
  367. Class, Exception, erlang:get_stacktrace()), Opts),
  368. %% We still need to send an error response, so send what we initially
  369. %% wanted to send. It's better than nothing.
  370. send_headers(State0, StreamID, fin, StatusCode0, RespHeaders0)
  371. end.
  372. rst_stream_frame(State=#state{streams=Streams0, children=Children0}, StreamID, Reason) ->
  373. case maps:take(StreamID, Streams0) of
  374. {{_, StreamState}, Streams} ->
  375. stream_call_terminate(StreamID, Reason, StreamState, State),
  376. Children = cowboy_children:shutdown(Children0, StreamID),
  377. State#state{streams=Streams, children=Children};
  378. error ->
  379. State
  380. end.
  381. ignored_frame(State=#state{http2_machine=HTTP2Machine0}) ->
  382. case cow_http2_machine:ignored_frame(HTTP2Machine0) of
  383. {ok, HTTP2Machine} ->
  384. State#state{http2_machine=HTTP2Machine};
  385. {error, Error={connection_error, _, _}, HTTP2Machine} ->
  386. terminate(State#state{http2_machine=HTTP2Machine}, Error)
  387. end.
  388. %% HTTP/2 timeouts.
  389. timeout(State=#state{http2_machine=HTTP2Machine0}, Name, TRef) ->
  390. case cow_http2_machine:timeout(Name, TRef, HTTP2Machine0) of
  391. {ok, HTTP2Machine} ->
  392. State#state{http2_machine=HTTP2Machine};
  393. {error, Error={connection_error, _, _}, HTTP2Machine} ->
  394. terminate(State#state{http2_machine=HTTP2Machine}, Error)
  395. end.
  396. %% Erlang messages.
  397. down(State=#state{opts=Opts, children=Children0}, Pid, Msg) ->
  398. case cowboy_children:down(Children0, Pid) of
  399. %% The stream was terminated already.
  400. {ok, undefined, Children} ->
  401. State#state{children=Children};
  402. %% The stream is still running.
  403. {ok, StreamID, Children} ->
  404. info(State#state{children=Children}, StreamID, Msg);
  405. %% The process was unknown.
  406. error ->
  407. cowboy:log(warning, "Received EXIT signal ~p for unknown process ~p.~n",
  408. [Msg, Pid], Opts),
  409. State
  410. end.
  411. info(State=#state{opts=Opts, streams=Streams}, StreamID, Msg) ->
  412. case Streams of
  413. #{StreamID := {IsRunning, StreamState0}} ->
  414. try cowboy_stream:info(StreamID, Msg, StreamState0) of
  415. {Commands, StreamState} ->
  416. commands(State#state{streams=Streams#{StreamID => {IsRunning, StreamState}}},
  417. StreamID, Commands)
  418. catch Class:Exception ->
  419. cowboy:log(cowboy_stream:make_error_log(info,
  420. [StreamID, Msg, StreamState0],
  421. Class, Exception, erlang:get_stacktrace()), Opts),
  422. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  423. 'Unhandled exception in cowboy_stream:info/3.'})
  424. end;
  425. _ ->
  426. cowboy:log(warning, "Received message ~p for unknown or terminated stream ~p.",
  427. [Msg, StreamID], Opts),
  428. State
  429. end.
  430. %% Stream handler commands.
  431. %%
  432. %% @todo Kill the stream if it tries to send a response, headers,
  433. %% data or push promise when the stream is closed or half-closed.
  434. commands(State, _, []) ->
  435. State;
  436. %% Error responses are sent only if a response wasn't sent already.
  437. commands(State=#state{http2_machine=HTTP2Machine}, StreamID,
  438. [{error_response, StatusCode, Headers, Body}|Tail]) ->
  439. case cow_http2_machine:get_stream_local_state(StreamID, HTTP2Machine) of
  440. {ok, idle, _} ->
  441. commands(State, StreamID, [{response, StatusCode, Headers, Body}|Tail]);
  442. _ ->
  443. commands(State, StreamID, Tail)
  444. end;
  445. %% Send an informational response.
  446. commands(State0, StreamID, [{inform, StatusCode, Headers}|Tail]) ->
  447. State = send_headers(State0, StreamID, idle, StatusCode, Headers),
  448. commands(State, StreamID, Tail);
  449. %% Send response headers.
  450. commands(State0, StreamID, [{response, StatusCode, Headers, Body}|Tail]) ->
  451. State = send_response(State0, StreamID, StatusCode, Headers, Body),
  452. commands(State, StreamID, Tail);
  453. %% Send response headers.
  454. commands(State0, StreamID, [{headers, StatusCode, Headers}|Tail]) ->
  455. State = send_headers(State0, StreamID, nofin, StatusCode, Headers),
  456. commands(State, StreamID, Tail);
  457. %% Send a response body chunk.
  458. commands(State0, StreamID, [{data, IsFin, Data}|Tail]) ->
  459. State = maybe_send_data(State0, StreamID, IsFin, Data),
  460. commands(State, StreamID, Tail);
  461. %% Send trailers.
  462. commands(State0, StreamID, [{trailers, Trailers}|Tail]) ->
  463. State = maybe_send_data(State0, StreamID, fin, {trailers, maps:to_list(Trailers)}),
  464. commands(State, StreamID, Tail);
  465. %% Send a file.
  466. %% @todo Add the sendfile command.
  467. %commands(State0, Stream0=#stream{local=nofin},
  468. % [{sendfile, IsFin, Offset, Bytes, Path}|Tail]) ->
  469. % {State, Stream} = maybe_send_data(State0, Stream0, IsFin, {sendfile, Offset, Bytes, Path}),
  470. % commands(State, Stream, Tail);
  471. %% Send a push promise.
  472. %%
  473. %% @todo Responses sent as a result of a push_promise request
  474. %% must not send push_promise frames themselves.
  475. commands(State0=#state{socket=Socket, transport=Transport, http2_machine=HTTP2Machine0},
  476. StreamID, [{push, Method, Scheme, Host, Port, Path, Qs, Headers0}|Tail]) ->
  477. Authority = case {Scheme, Port} of
  478. {<<"http">>, 80} -> Host;
  479. {<<"https">>, 443} -> Host;
  480. _ -> iolist_to_binary([Host, $:, integer_to_binary(Port)])
  481. end,
  482. PathWithQs = iolist_to_binary(case Qs of
  483. <<>> -> Path;
  484. _ -> [Path, $?, Qs]
  485. end),
  486. PseudoHeaders = #{
  487. method => Method,
  488. scheme => Scheme,
  489. authority => Authority,
  490. path => PathWithQs
  491. },
  492. %% We need to make sure the header value is binary before we can
  493. %% create the Req object, as it expects them to be flat.
  494. Headers = maps:to_list(maps:map(fun(_, V) -> iolist_to_binary(V) end, Headers0)),
  495. State = case cow_http2_machine:prepare_push_promise(StreamID, HTTP2Machine0,
  496. PseudoHeaders, Headers) of
  497. {ok, PromisedStreamID, HeaderBlock, HTTP2Machine} ->
  498. Transport:send(Socket, cow_http2:push_promise(
  499. StreamID, PromisedStreamID, HeaderBlock)),
  500. headers_frame(State0#state{http2_machine=HTTP2Machine},
  501. PromisedStreamID, fin, Headers, PseudoHeaders, 0);
  502. {error, no_push} ->
  503. State0
  504. end,
  505. commands(State, StreamID, Tail);
  506. commands(State=#state{socket=Socket, transport=Transport, http2_machine=HTTP2Machine0},
  507. StreamID, [{flow, Size}|Tail]) ->
  508. Transport:send(Socket, [
  509. cow_http2:window_update(Size),
  510. cow_http2:window_update(StreamID, Size)
  511. ]),
  512. HTTP2Machine1 = cow_http2_machine:update_window(Size, HTTP2Machine0),
  513. HTTP2Machine = cow_http2_machine:update_window(StreamID, Size, HTTP2Machine1),
  514. commands(State#state{http2_machine=HTTP2Machine}, StreamID, Tail);
  515. %% Supervise a child process.
  516. commands(State=#state{children=Children}, StreamID, [{spawn, Pid, Shutdown}|Tail]) ->
  517. commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)},
  518. StreamID, Tail);
  519. %% Error handling.
  520. commands(State, StreamID, [Error = {internal_error, _, _}|_Tail]) ->
  521. %% @todo Do we want to run the commands after an internal_error?
  522. %% @todo Do we even allow commands after?
  523. %% @todo Only reset when the stream still exists.
  524. stream_reset(State, StreamID, Error);
  525. %% Upgrade to HTTP/2. This is triggered by cowboy_http2 itself.
  526. commands(State=#state{socket=Socket, transport=Transport, http2_init=upgrade},
  527. StreamID, [{switch_protocol, Headers, ?MODULE, _}|Tail]) ->
  528. %% @todo This 101 response needs to be passed through stream handlers.
  529. Transport:send(Socket, cow_http:response(101, 'HTTP/1.1', maps:to_list(Headers))),
  530. commands(State, StreamID, Tail);
  531. %% Use a different protocol within the stream (CONNECT :protocol).
  532. %% @todo Make sure we error out when the feature is disabled.
  533. commands(State0, StreamID, [{switch_protocol, Headers, _Mod, _ModState}|Tail]) ->
  534. State = info(State0, StreamID, {headers, 200, Headers}),
  535. commands(State, StreamID, Tail);
  536. commands(State, StreamID, [stop|_Tail]) ->
  537. %% @todo Do we want to run the commands after a stop?
  538. %% @todo Do we even allow commands after?
  539. stop_stream(State, StreamID);
  540. %% Log event.
  541. commands(State=#state{opts=Opts}, StreamID, [Log={log, _, _, _}|Tail]) ->
  542. cowboy:log(Log, Opts),
  543. commands(State, StreamID, Tail).
  544. %% Send the response, trailers or data.
  545. send_response(State0, StreamID, StatusCode, Headers, Body) ->
  546. Size = case Body of
  547. {sendfile, _, Bytes, _} -> Bytes;
  548. _ -> iolist_size(Body)
  549. end,
  550. case Size of
  551. 0 ->
  552. State = send_headers(State0, StreamID, fin, StatusCode, Headers),
  553. maybe_terminate_stream(State, StreamID, fin);
  554. _ ->
  555. State = send_headers(State0, StreamID, nofin, StatusCode, Headers),
  556. maybe_send_data(State, StreamID, fin, Body)
  557. end.
  558. send_headers(State=#state{socket=Socket, transport=Transport,
  559. http2_machine=HTTP2Machine0}, StreamID, IsFin0, StatusCode, Headers) ->
  560. {ok, IsFin, HeaderBlock, HTTP2Machine}
  561. = cow_http2_machine:prepare_headers(StreamID, HTTP2Machine0, IsFin0,
  562. #{status => cow_http:status_to_integer(StatusCode)},
  563. headers_to_list(Headers)),
  564. Transport:send(Socket, cow_http2:headers(StreamID, IsFin, HeaderBlock)),
  565. State#state{http2_machine=HTTP2Machine}.
  566. %% The set-cookie header is special; we can only send one cookie per header.
  567. headers_to_list(Headers0=#{<<"set-cookie">> := SetCookies}) ->
  568. Headers = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  569. Headers ++ [{<<"set-cookie">>, Value} || Value <- SetCookies];
  570. headers_to_list(Headers) ->
  571. maps:to_list(Headers).
  572. maybe_send_data(State=#state{http2_machine=HTTP2Machine0}, StreamID, IsFin, Data0) ->
  573. Data = case is_tuple(Data0) of
  574. false -> {data, Data0};
  575. true -> Data0
  576. end,
  577. case cow_http2_machine:send_or_queue_data(StreamID, HTTP2Machine0, IsFin, Data) of
  578. {ok, HTTP2Machine} ->
  579. State#state{http2_machine=HTTP2Machine};
  580. {send, SendData, HTTP2Machine} ->
  581. send_data(State#state{http2_machine=HTTP2Machine}, SendData)
  582. end.
  583. send_data(State, []) ->
  584. State;
  585. send_data(State0, [{StreamID, IsFin, SendData}|Tail]) ->
  586. State = send_data(State0, StreamID, IsFin, SendData),
  587. send_data(State, Tail).
  588. send_data(State0, StreamID, IsFin, [Data]) ->
  589. State = send_data_frame(State0, StreamID, IsFin, Data),
  590. maybe_terminate_stream(State, StreamID, IsFin);
  591. send_data(State0, StreamID, IsFin, [Data|Tail]) ->
  592. State = send_data_frame(State0, StreamID, nofin, Data),
  593. send_data(State, StreamID, IsFin, Tail).
  594. send_data_frame(State=#state{socket=Socket, transport=Transport},
  595. StreamID, IsFin, {data, Data}) ->
  596. Transport:send(Socket, cow_http2:data(StreamID, IsFin, Data)),
  597. State;
  598. send_data_frame(State=#state{socket=Socket, transport=Transport},
  599. StreamID, IsFin, {sendfile, Offset, Bytes, Path}) ->
  600. Transport:send(Socket, cow_http2:data_header(StreamID, IsFin, Bytes)),
  601. Transport:sendfile(Socket, Path, Offset, Bytes),
  602. State;
  603. %% The stream is terminated in cow_http2_machine:prepare_trailers.
  604. send_data_frame(State=#state{socket=Socket, transport=Transport,
  605. http2_machine=HTTP2Machine0}, StreamID, nofin, {trailers, Trailers}) ->
  606. {ok, HeaderBlock, HTTP2Machine}
  607. = cow_http2_machine:prepare_trailers(StreamID, HTTP2Machine0, Trailers),
  608. Transport:send(Socket, cow_http2:headers(StreamID, fin, HeaderBlock)),
  609. State#state{http2_machine=HTTP2Machine}.
  610. %% Terminate a stream or the connection.
  611. -spec terminate(#state{}, _) -> no_return().
  612. terminate(undefined, Reason) ->
  613. exit({shutdown, Reason});
  614. terminate(State=#state{socket=Socket, transport=Transport, http2_init=complete,
  615. http2_machine=HTTP2Machine, streams=Streams, children=Children}, Reason) ->
  616. %% @todo We might want to optionally send the Reason value
  617. %% as debug data in the GOAWAY frame here. Perhaps more.
  618. Transport:send(Socket, cow_http2:goaway(
  619. cow_http2_machine:get_last_streamid(HTTP2Machine),
  620. terminate_reason(Reason), <<>>)),
  621. terminate_all_streams(State, maps:to_list(Streams), Reason),
  622. cowboy_children:terminate(Children),
  623. Transport:close(Socket),
  624. exit({shutdown, Reason});
  625. terminate(#state{socket=Socket, transport=Transport}, Reason) ->
  626. Transport:close(Socket),
  627. exit({shutdown, Reason}).
  628. terminate_reason({connection_error, Reason, _}) -> Reason;
  629. terminate_reason({stop, _, _}) -> no_error;
  630. terminate_reason({socket_error, _, _}) -> internal_error;
  631. terminate_reason({internal_error, _, _}) -> internal_error.
  632. terminate_all_streams(_, [], _) ->
  633. ok;
  634. terminate_all_streams(State, [{StreamID, {_, StreamState}}|Tail], Reason) ->
  635. stream_call_terminate(StreamID, Reason, StreamState, State),
  636. terminate_all_streams(State, Tail, Reason).
  637. %% @todo Don't send an RST_STREAM if one was already sent.
  638. %% @todo Maybe rename reset_stream.
  639. stream_reset(State=#state{socket=Socket, transport=Transport,
  640. http2_machine=HTTP2Machine0}, StreamID, Error) ->
  641. Reason = case Error of
  642. {internal_error, _, _} -> internal_error;
  643. {stream_error, Reason0, _} -> Reason0
  644. end,
  645. Transport:send(Socket, cow_http2:rst_stream(StreamID, Reason)),
  646. case cow_http2_machine:reset_stream(StreamID, HTTP2Machine0) of
  647. {ok, HTTP2Machine} ->
  648. terminate_stream(State#state{http2_machine=HTTP2Machine}, StreamID, Error);
  649. {error, not_found} ->
  650. terminate_stream(State, StreamID, Error)
  651. end.
  652. stop_stream(State=#state{http2_machine=HTTP2Machine}, StreamID) ->
  653. case cow_http2_machine:get_stream_local_state(StreamID, HTTP2Machine) of
  654. %% When the stream terminates normally (without sending RST_STREAM)
  655. %% and no response was sent, we need to send a proper response back to the client.
  656. %% We delay the termination of the stream until the response is fully sent.
  657. {ok, idle, _} ->
  658. info(stopping(State, StreamID), StreamID, {response, 204, #{}, <<>>});
  659. %% When a response was sent but not terminated, we need to close the stream.
  660. %% We delay the termination of the stream until the response is fully sent.
  661. {ok, nofin, fin} ->
  662. stopping(State, StreamID);
  663. %% We only send a final DATA frame if there isn't one queued yet.
  664. {ok, nofin, _} ->
  665. info(stopping(State, StreamID), StreamID, {data, fin, <<>>});
  666. %% When a response was sent fully we can terminate the stream,
  667. %% regardless of the stream being in half-closed or closed state.
  668. _ ->
  669. terminate_stream(State, StreamID)
  670. end.
  671. stopping(State=#state{streams=Streams}, StreamID) ->
  672. #{StreamID := {_, StreamState}} = Streams,
  673. State#state{streams=Streams#{StreamID => {stopping, StreamState}}}.
  674. %% If we finished sending data and the stream is stopping, terminate it.
  675. maybe_terminate_stream(State=#state{streams=Streams}, StreamID, fin) ->
  676. case Streams of
  677. #{StreamID := {stopping, _}} ->
  678. terminate_stream(State, StreamID);
  679. _ ->
  680. State
  681. end;
  682. maybe_terminate_stream(State, _, _) ->
  683. State.
  684. %% When the stream stops normally without reading the request
  685. %% body fully we need to tell the client to stop sending it.
  686. %% We do this by sending an RST_STREAM with reason NO_ERROR. (RFC7540 8.1.0)
  687. terminate_stream(State0=#state{socket=Socket, transport=Transport,
  688. http2_machine=HTTP2Machine0}, StreamID) ->
  689. State = case cow_http2_machine:get_stream_local_state(StreamID, HTTP2Machine0) of
  690. {ok, fin, _} ->
  691. Transport:send(Socket, cow_http2:rst_stream(StreamID, no_error)),
  692. {ok, HTTP2Machine} = cow_http2_machine:reset_stream(StreamID, HTTP2Machine0),
  693. State0#state{http2_machine=HTTP2Machine};
  694. {error, closed} ->
  695. State0
  696. end,
  697. terminate_stream(State, StreamID, normal).
  698. terminate_stream(State=#state{streams=Streams0, children=Children0}, StreamID, Reason) ->
  699. case maps:take(StreamID, Streams0) of
  700. {{_, StreamState}, Streams} ->
  701. stream_call_terminate(StreamID, Reason, StreamState, State),
  702. Children = cowboy_children:shutdown(Children0, StreamID),
  703. State#state{streams=Streams, children=Children};
  704. error ->
  705. State
  706. end.
  707. %% @todo Maybe put State first.
  708. stream_call_terminate(StreamID, Reason, StreamState, #state{opts=Opts}) ->
  709. try
  710. cowboy_stream:terminate(StreamID, Reason, StreamState)
  711. catch Class:Exception ->
  712. cowboy:log(cowboy_stream:make_error_log(terminate,
  713. [StreamID, Reason, StreamState],
  714. Class, Exception, erlang:get_stacktrace()), Opts)
  715. end.
  716. %% System callbacks.
  717. -spec system_continue(_, _, {#state{}, binary()}) -> ok.
  718. system_continue(_, _, {State, Buffer}) ->
  719. loop(State, Buffer).
  720. -spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return().
  721. system_terminate(Reason, _, _, {State, _}) ->
  722. terminate(State, {stop, {exit, Reason}, 'sys:terminate/2,3 was called.'}).
  723. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  724. system_code_change(Misc, _, _, _) ->
  725. {ok, Misc}.