cowboy_http2.erl 33 KB

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