cowboy_http.erl 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442
  1. %% Copyright (c) 2016-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_http).
  15. -ifdef(OTP_RELEASE).
  16. -compile({nowarn_deprecated_function, [{erlang, get_stacktrace, 0}]}).
  17. -endif.
  18. -export([init/6]).
  19. -export([system_continue/3]).
  20. -export([system_terminate/4]).
  21. -export([system_code_change/4]).
  22. -type opts() :: #{
  23. chunked => boolean(),
  24. compress_buffering => boolean(),
  25. compress_threshold => non_neg_integer(),
  26. connection_type => worker | supervisor,
  27. env => cowboy_middleware:env(),
  28. http10_keepalive => boolean(),
  29. idle_timeout => timeout(),
  30. inactivity_timeout => timeout(),
  31. linger_timeout => timeout(),
  32. logger => module(),
  33. max_authority_length => non_neg_integer(),
  34. max_empty_lines => non_neg_integer(),
  35. max_header_name_length => non_neg_integer(),
  36. max_header_value_length => non_neg_integer(),
  37. max_headers => non_neg_integer(),
  38. max_keepalive => non_neg_integer(),
  39. max_method_length => non_neg_integer(),
  40. max_request_line_length => non_neg_integer(),
  41. metrics_callback => cowboy_metrics_h:metrics_callback(),
  42. middlewares => [module()],
  43. proxy_header => boolean(),
  44. request_timeout => timeout(),
  45. sendfile => boolean(),
  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(ps_request_line, {
  55. empty_lines = 0 :: non_neg_integer()
  56. }).
  57. -record(ps_header, {
  58. method = undefined :: binary(),
  59. authority = undefined :: binary() | undefined,
  60. path = undefined :: binary(),
  61. qs = undefined :: binary(),
  62. version = undefined :: cowboy:http_version(),
  63. headers = undefined :: cowboy:http_headers() | undefined,
  64. name = undefined :: binary() | undefined
  65. }).
  66. %% @todo We need a state where we wait for the stream process to ask for the body
  67. %% and do not attempt to read from the socket while in that state (we should read
  68. %% up to a certain length, and then wait, basically implementing flow control but
  69. %% by not reading from the socket when the window is empty).
  70. -record(ps_body, {
  71. length :: non_neg_integer() | undefined,
  72. received = 0 :: non_neg_integer(),
  73. %% @todo flow
  74. transfer_decode_fun :: fun(), %% @todo better type
  75. transfer_decode_state :: any() %% @todo better type
  76. }).
  77. -record(stream, {
  78. id = undefined :: cowboy_stream:streamid(),
  79. %% Stream handlers and their state.
  80. state = undefined :: {module(), any()},
  81. %% Request method.
  82. method = undefined :: binary(),
  83. %% Client HTTP version for this stream.
  84. version = undefined :: cowboy:http_version(),
  85. %% Unparsed te header. Used to know if we can send trailers.
  86. te :: undefined | binary(),
  87. %% Expected body size.
  88. local_expected_size = undefined :: undefined | non_neg_integer(),
  89. %% Sent body size.
  90. local_sent_size = 0 :: non_neg_integer(),
  91. %% Commands queued.
  92. queue = [] :: cowboy_stream:commands()
  93. }).
  94. -type stream() :: #stream{}.
  95. -record(state, {
  96. parent :: pid(),
  97. ref :: ranch:ref(),
  98. socket :: inet:socket(),
  99. transport :: module(),
  100. proxy_header :: undefined | ranch_proxy_header:proxy_info(),
  101. opts = #{} :: cowboy:opts(),
  102. %% Some options may be overriden for the current stream.
  103. overriden_opts = #{} :: cowboy:opts(),
  104. %% Remote address and port for the connection.
  105. peer = undefined :: {inet:ip_address(), inet:port_number()},
  106. %% Local address and port for the connection.
  107. sock = undefined :: {inet:ip_address(), inet:port_number()},
  108. %% Client certificate (TLS only).
  109. cert :: undefined | binary(),
  110. timer = undefined :: undefined | reference(),
  111. %% Identifier for the stream currently being read (or waiting to be received).
  112. in_streamid = 1 :: pos_integer(),
  113. %% Parsing state for the current stream or stream-to-be.
  114. in_state = #ps_request_line{} :: #ps_request_line{} | #ps_header{} | #ps_body{},
  115. %% Identifier for the stream currently being written.
  116. %% Note that out_streamid =< in_streamid.
  117. out_streamid = 1 :: pos_integer(),
  118. %% Whether we finished writing data for the current stream.
  119. out_state = wait :: wait | chunked | streaming | done,
  120. %% The connection will be closed after this stream.
  121. last_streamid = undefined :: pos_integer(),
  122. %% Currently active HTTP/1.1 streams.
  123. streams = [] :: [stream()],
  124. %% Children processes created by streams.
  125. children = cowboy_children:init() :: cowboy_children:children()
  126. }).
  127. -include_lib("cowlib/include/cow_inline.hrl").
  128. -include_lib("cowlib/include/cow_parse.hrl").
  129. -spec init(pid(), ranch:ref(), inet:socket(), module(),
  130. ranch_proxy_header:proxy_info(), cowboy:opts()) -> ok.
  131. init(Parent, Ref, Socket, Transport, ProxyHeader, Opts) ->
  132. Peer0 = Transport:peername(Socket),
  133. Sock0 = Transport:sockname(Socket),
  134. Cert1 = case Transport:name() of
  135. ssl ->
  136. case ssl:peercert(Socket) of
  137. {error, no_peercert} ->
  138. {ok, undefined};
  139. Cert0 ->
  140. Cert0
  141. end;
  142. _ ->
  143. {ok, undefined}
  144. end,
  145. case {Peer0, Sock0, Cert1} of
  146. {{ok, Peer}, {ok, Sock}, {ok, Cert}} ->
  147. LastStreamID = maps:get(max_keepalive, Opts, 100),
  148. before_loop(set_timeout(#state{
  149. parent=Parent, ref=Ref, socket=Socket,
  150. transport=Transport, proxy_header=ProxyHeader, opts=Opts,
  151. peer=Peer, sock=Sock, cert=Cert,
  152. last_streamid=LastStreamID}), <<>>);
  153. {{error, Reason}, _, _} ->
  154. terminate(undefined, {socket_error, Reason,
  155. 'A socket error occurred when retrieving the peer name.'});
  156. {_, {error, Reason}, _} ->
  157. terminate(undefined, {socket_error, Reason,
  158. 'A socket error occurred when retrieving the sock name.'});
  159. {_, _, {error, Reason}} ->
  160. terminate(undefined, {socket_error, Reason,
  161. 'A socket error occurred when retrieving the client TLS certificate.'})
  162. end.
  163. before_loop(State=#state{socket=Socket, transport=Transport}, Buffer) ->
  164. %% @todo disable this when we get to the body, until the stream asks for it?
  165. %% Perhaps have a threshold for how much we're willing to read before waiting.
  166. Transport:setopts(Socket, [{active, once}]),
  167. loop(State, Buffer).
  168. loop(State=#state{parent=Parent, socket=Socket, transport=Transport, opts=Opts,
  169. timer=TimerRef, children=Children, in_streamid=InStreamID,
  170. last_streamid=LastStreamID, streams=Streams}, Buffer) ->
  171. {OK, Closed, Error} = Transport:messages(),
  172. InactivityTimeout = maps:get(inactivity_timeout, Opts, 300000),
  173. receive
  174. %% Discard data coming in after the last request
  175. %% we want to process was received fully.
  176. {OK, Socket, _} when InStreamID > LastStreamID ->
  177. before_loop(State, Buffer);
  178. %% Socket messages.
  179. {OK, Socket, Data} ->
  180. %% Only reset the timeout if it is idle_timeout (active streams).
  181. State1 = case Streams of
  182. [] -> State;
  183. _ -> set_timeout(State)
  184. end,
  185. parse(<< Buffer/binary, Data/binary >>, State1);
  186. {Closed, Socket} ->
  187. terminate(State, {socket_error, closed, 'The socket has been closed.'});
  188. {Error, Socket, Reason} ->
  189. terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'});
  190. %% Timeouts.
  191. {timeout, Ref, {shutdown, Pid}} ->
  192. cowboy_children:shutdown_timeout(Children, Ref, Pid),
  193. loop(State, Buffer);
  194. {timeout, TimerRef, Reason} ->
  195. timeout(State, Reason);
  196. {timeout, _, _} ->
  197. loop(State, Buffer);
  198. %% System messages.
  199. {'EXIT', Parent, Reason} ->
  200. terminate(State, {stop, {exit, Reason}, 'Parent process terminated.'});
  201. {system, From, Request} ->
  202. sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer});
  203. %% Messages pertaining to a stream.
  204. {{Pid, StreamID}, Msg} when Pid =:= self() ->
  205. loop(info(State, StreamID, Msg), Buffer);
  206. %% Exit signal from children.
  207. Msg = {'EXIT', Pid, _} ->
  208. loop(down(State, Pid, Msg), Buffer);
  209. %% Calls from supervisor module.
  210. {'$gen_call', From, Call} ->
  211. cowboy_children:handle_supervisor_call(Call, From, Children, ?MODULE),
  212. loop(State, Buffer);
  213. %% Unknown messages.
  214. Msg ->
  215. cowboy:log(warning, "Received stray message ~p.~n", [Msg], Opts),
  216. loop(State, Buffer)
  217. after InactivityTimeout ->
  218. terminate(State, {internal_error, timeout, 'No message or data received before timeout.'})
  219. end.
  220. %% We set request_timeout when there are no active streams,
  221. %% and idle_timeout otherwise.
  222. set_timeout(State0=#state{opts=Opts, overriden_opts=Override, streams=Streams}) ->
  223. State = cancel_timeout(State0),
  224. {Name, Default} = case Streams of
  225. [] -> {request_timeout, 5000};
  226. _ -> {idle_timeout, 60000}
  227. end,
  228. Timeout = case Override of
  229. %% The timeout may have been overriden for the current stream.
  230. #{Name := Timeout0} -> Timeout0;
  231. _ -> maps:get(Name, Opts, Default)
  232. end,
  233. TimerRef = case Timeout of
  234. infinity -> undefined;
  235. Timeout -> erlang:start_timer(Timeout, self(), Name)
  236. end,
  237. State#state{timer=TimerRef}.
  238. cancel_timeout(State=#state{timer=TimerRef}) ->
  239. ok = case TimerRef of
  240. undefined -> ok;
  241. _ -> erlang:cancel_timer(TimerRef, [{async, true}, {info, false}])
  242. end,
  243. State#state{timer=undefined}.
  244. -spec timeout(_, _) -> no_return().
  245. timeout(State=#state{in_state=#ps_request_line{}}, request_timeout) ->
  246. terminate(State, {connection_error, timeout,
  247. 'No request-line received before timeout.'});
  248. timeout(State=#state{in_state=#ps_header{}}, request_timeout) ->
  249. error_terminate(408, State, {connection_error, timeout,
  250. 'Request headers not received before timeout.'});
  251. timeout(State, idle_timeout) ->
  252. terminate(State, {connection_error, timeout,
  253. 'Connection idle longer than configuration allows.'}).
  254. parse(<<>>, State) ->
  255. before_loop(State, <<>>);
  256. %% Do not process requests that come in after the last request
  257. %% and discard the buffer if any to save memory.
  258. parse(_, State=#state{in_streamid=InStreamID, in_state=#ps_request_line{},
  259. last_streamid=LastStreamID}) when InStreamID > LastStreamID ->
  260. before_loop(State, <<>>);
  261. parse(Buffer, State=#state{in_state=#ps_request_line{empty_lines=EmptyLines}}) ->
  262. after_parse(parse_request(Buffer, State, EmptyLines));
  263. parse(Buffer, State=#state{in_state=PS=#ps_header{headers=Headers, name=undefined}}) ->
  264. after_parse(parse_header(Buffer,
  265. State#state{in_state=PS#ps_header{headers=undefined}},
  266. Headers));
  267. parse(Buffer, State=#state{in_state=PS=#ps_header{headers=Headers, name=Name}}) ->
  268. after_parse(parse_hd_before_value(Buffer,
  269. State#state{in_state=PS#ps_header{headers=undefined, name=undefined}},
  270. Headers, Name));
  271. parse(Buffer, State=#state{in_state=#ps_body{}}) ->
  272. %% @todo We do not want to get the body automatically if the request doesn't ask for it.
  273. %% We may want to get bodies that are below a threshold without waiting, and buffer them
  274. %% until the request asks, though.
  275. after_parse(parse_body(Buffer, State)).
  276. after_parse({request, Req=#{streamid := StreamID, method := Method,
  277. headers := Headers, version := Version},
  278. State0=#state{opts=Opts, streams=Streams0}, Buffer}) ->
  279. try cowboy_stream:init(StreamID, Req, Opts) of
  280. {Commands, StreamState} ->
  281. TE = maps:get(<<"te">>, Headers, undefined),
  282. Streams = [#stream{id=StreamID, state=StreamState,
  283. method=Method, version=Version, te=TE}|Streams0],
  284. State1 = case maybe_req_close(State0, Headers, Version) of
  285. close -> State0#state{streams=Streams, last_streamid=StreamID};
  286. keepalive -> State0#state{streams=Streams}
  287. end,
  288. State = set_timeout(State1),
  289. parse(Buffer, commands(State, StreamID, Commands))
  290. catch Class:Exception ->
  291. cowboy:log(cowboy_stream:make_error_log(init,
  292. [StreamID, Req, Opts],
  293. Class, Exception, erlang:get_stacktrace()), Opts),
  294. early_error(500, State0, {internal_error, {Class, Exception},
  295. 'Unhandled exception in cowboy_stream:init/3.'}, Req),
  296. parse(Buffer, State0)
  297. end;
  298. %% Streams are sequential so the body is always about the last stream created
  299. %% unless that stream has terminated.
  300. after_parse({data, StreamID, IsFin, Data, State=#state{opts=Opts,
  301. streams=Streams0=[Stream=#stream{id=StreamID, state=StreamState0}|_]}, Buffer}) ->
  302. try cowboy_stream:data(StreamID, IsFin, Data, StreamState0) of
  303. {Commands, StreamState} ->
  304. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  305. Stream#stream{state=StreamState}),
  306. parse(Buffer, commands(State#state{streams=Streams}, StreamID, Commands))
  307. catch Class:Exception ->
  308. cowboy:log(cowboy_stream:make_error_log(data,
  309. [StreamID, IsFin, Data, StreamState0],
  310. Class, Exception, erlang:get_stacktrace()), Opts),
  311. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  312. 'Unhandled exception in cowboy_stream:data/4.'})
  313. end;
  314. %% No corresponding stream. We must skip the body of the previous request
  315. %% in order to process the next one.
  316. after_parse({data, _, _, _, State, Buffer}) ->
  317. before_loop(State, Buffer);
  318. after_parse({more, State, Buffer}) ->
  319. before_loop(State, Buffer).
  320. %% Request-line.
  321. -spec parse_request(Buffer, State, non_neg_integer())
  322. -> {request, cowboy_req:req(), State, Buffer}
  323. | {data, cowboy_stream:streamid(), cowboy_stream:fin(), binary(), State, Buffer}
  324. | {more, State, Buffer}
  325. when Buffer::binary(), State::#state{}.
  326. %% Empty lines must be using \r\n.
  327. parse_request(<< $\n, _/bits >>, State, _) ->
  328. error_terminate(400, State, {connection_error, protocol_error,
  329. 'Empty lines between requests must use the CRLF line terminator. (RFC7230 3.5)'});
  330. parse_request(<< $\s, _/bits >>, State, _) ->
  331. error_terminate(400, State, {connection_error, protocol_error,
  332. 'The request-line must not begin with a space. (RFC7230 3.1.1, RFC7230 3.5)'});
  333. %% We limit the length of the Request-line to MaxLength to avoid endlessly
  334. %% reading from the socket and eventually crashing.
  335. parse_request(Buffer, State=#state{opts=Opts, in_streamid=InStreamID}, EmptyLines) ->
  336. MaxLength = maps:get(max_request_line_length, Opts, 8000),
  337. MaxEmptyLines = maps:get(max_empty_lines, Opts, 5),
  338. case match_eol(Buffer, 0) of
  339. nomatch when byte_size(Buffer) > MaxLength ->
  340. error_terminate(414, State, {connection_error, limit_reached,
  341. 'The request-line length is larger than configuration allows. (RFC7230 3.1.1)'});
  342. nomatch ->
  343. {more, State#state{in_state=#ps_request_line{empty_lines=EmptyLines}}, Buffer};
  344. 1 when EmptyLines =:= MaxEmptyLines ->
  345. error_terminate(400, State, {connection_error, limit_reached,
  346. 'More empty lines were received than configuration allows. (RFC7230 3.5)'});
  347. 1 ->
  348. << _:16, Rest/bits >> = Buffer,
  349. parse_request(Rest, State, EmptyLines + 1);
  350. _ ->
  351. case Buffer of
  352. %% @todo * is only for server-wide OPTIONS request (RFC7230 5.3.4); tests
  353. << "OPTIONS * ", Rest/bits >> ->
  354. parse_version(Rest, State, <<"OPTIONS">>, undefined, <<"*">>, <<>>);
  355. <<"CONNECT ", _/bits>> ->
  356. error_terminate(501, State, {connection_error, no_error,
  357. 'The CONNECT method is currently not implemented. (RFC7231 4.3.6)'});
  358. <<"TRACE ", _/bits>> ->
  359. error_terminate(501, State, {connection_error, no_error,
  360. 'The TRACE method is currently not implemented. (RFC7231 4.3.8)'});
  361. %% Accept direct HTTP/2 only at the beginning of the connection.
  362. << "PRI * HTTP/2.0\r\n", _/bits >> when InStreamID =:= 1 ->
  363. %% @todo Might be worth throwing to get a clean stacktrace.
  364. http2_upgrade(State, Buffer);
  365. _ ->
  366. parse_method(Buffer, State, <<>>,
  367. maps:get(max_method_length, Opts, 32))
  368. end
  369. end.
  370. match_eol(<< $\n, _/bits >>, N) ->
  371. N;
  372. match_eol(<< _, Rest/bits >>, N) ->
  373. match_eol(Rest, N + 1);
  374. match_eol(_, _) ->
  375. nomatch.
  376. parse_method(_, State, _, 0) ->
  377. error_terminate(501, State, {connection_error, limit_reached,
  378. 'The method name is longer than configuration allows. (RFC7230 3.1.1)'});
  379. parse_method(<< C, Rest/bits >>, State, SoFar, Remaining) ->
  380. case C of
  381. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  382. 'The method name must not be followed with a line break. (RFC7230 3.1.1)'});
  383. $\s -> parse_uri(Rest, State, SoFar);
  384. _ when ?IS_TOKEN(C) -> parse_method(Rest, State, << SoFar/binary, C >>, Remaining - 1);
  385. _ -> error_terminate(400, State, {connection_error, protocol_error,
  386. 'The method name must contain only valid token characters. (RFC7230 3.1.1)'})
  387. end.
  388. parse_uri(<< H, T, T, P, "://", Rest/bits >>, State, Method)
  389. when H =:= $h orelse H =:= $H, T =:= $t orelse T =:= $T;
  390. P =:= $p orelse P =:= $P ->
  391. parse_uri_authority(Rest, State, Method);
  392. parse_uri(<< H, T, T, P, S, "://", Rest/bits >>, State, Method)
  393. when H =:= $h orelse H =:= $H, T =:= $t orelse T =:= $T;
  394. P =:= $p orelse P =:= $P; S =:= $s orelse S =:= $S ->
  395. parse_uri_authority(Rest, State, Method);
  396. parse_uri(<< $/, Rest/bits >>, State, Method) ->
  397. parse_uri_path(Rest, State, Method, undefined, <<$/>>);
  398. parse_uri(_, State, _) ->
  399. error_terminate(400, State, {connection_error, protocol_error,
  400. 'Invalid request-line or request-target. (RFC7230 3.1.1, RFC7230 5.3)'}).
  401. %% @todo We probably want to apply max_authority_length also
  402. %% to the host header and to document this option. It might
  403. %% also be useful for HTTP/2 requests.
  404. parse_uri_authority(Rest, State=#state{opts=Opts}, Method) ->
  405. parse_uri_authority(Rest, State, Method, <<>>,
  406. maps:get(max_authority_length, Opts, 255)).
  407. parse_uri_authority(_, State, _, _, 0) ->
  408. error_terminate(414, State, {connection_error, limit_reached,
  409. 'The authority component of the absolute URI is longer than configuration allows. (RFC7230 2.7.1)'});
  410. parse_uri_authority(<<C, Rest/bits>>, State, Method, SoFar, Remaining) ->
  411. case C of
  412. $\r ->
  413. error_terminate(400, State, {connection_error, protocol_error,
  414. 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'});
  415. $@ ->
  416. error_terminate(400, State, {connection_error, protocol_error,
  417. 'Absolute URIs must not include a userinfo component. (RFC7230 2.7.1)'});
  418. C when SoFar =:= <<>> andalso
  419. ((C =:= $/) orelse (C =:= $\s) orelse (C =:= $?) orelse (C =:= $#)) ->
  420. error_terminate(400, State, {connection_error, protocol_error,
  421. 'Absolute URIs must include a non-empty host component. (RFC7230 2.7.1)'});
  422. $: when SoFar =:= <<>> ->
  423. error_terminate(400, State, {connection_error, protocol_error,
  424. 'Absolute URIs must include a non-empty host component. (RFC7230 2.7.1)'});
  425. $/ -> parse_uri_path(Rest, State, Method, SoFar, <<"/">>);
  426. $\s -> parse_version(Rest, State, Method, SoFar, <<"/">>, <<>>);
  427. $? -> parse_uri_query(Rest, State, Method, SoFar, <<"/">>, <<>>);
  428. $# -> skip_uri_fragment(Rest, State, Method, SoFar, <<"/">>, <<>>);
  429. C -> parse_uri_authority(Rest, State, Method, <<SoFar/binary, C>>, Remaining - 1)
  430. end.
  431. parse_uri_path(<<C, Rest/bits>>, State, Method, Authority, SoFar) ->
  432. case C of
  433. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  434. 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'});
  435. $\s -> parse_version(Rest, State, Method, Authority, SoFar, <<>>);
  436. $? -> parse_uri_query(Rest, State, Method, Authority, SoFar, <<>>);
  437. $# -> skip_uri_fragment(Rest, State, Method, Authority, SoFar, <<>>);
  438. _ -> parse_uri_path(Rest, State, Method, Authority, <<SoFar/binary, C>>)
  439. end.
  440. parse_uri_query(<<C, Rest/bits>>, State, M, A, P, SoFar) ->
  441. case C of
  442. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  443. 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'});
  444. $\s -> parse_version(Rest, State, M, A, P, SoFar);
  445. $# -> skip_uri_fragment(Rest, State, M, A, P, SoFar);
  446. _ -> parse_uri_query(Rest, State, M, A, P, <<SoFar/binary, C>>)
  447. end.
  448. skip_uri_fragment(<<C, Rest/bits>>, State, M, A, P, Q) ->
  449. case C of
  450. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  451. 'The request-target must not be followed by a line break. (RFC7230 3.1.1)'});
  452. $\s -> parse_version(Rest, State, M, A, P, Q);
  453. _ -> skip_uri_fragment(Rest, State, M, A, P, Q)
  454. end.
  455. parse_version(<< "HTTP/1.1\r\n", Rest/bits >>, State, M, A, P, Q) ->
  456. before_parse_headers(Rest, State, M, A, P, Q, 'HTTP/1.1');
  457. parse_version(<< "HTTP/1.0\r\n", Rest/bits >>, State, M, A, P, Q) ->
  458. before_parse_headers(Rest, State, M, A, P, Q, 'HTTP/1.0');
  459. parse_version(<< "HTTP/1.", _, C, _/bits >>, State, _, _, _, _) when C =:= $\s; C =:= $\t ->
  460. error_terminate(400, State, {connection_error, protocol_error,
  461. 'Whitespace is not allowed after the HTTP version. (RFC7230 3.1.1)'});
  462. parse_version(<< C, _/bits >>, State, _, _, _, _) when C =:= $\s; C =:= $\t ->
  463. error_terminate(400, State, {connection_error, protocol_error,
  464. 'The separator between request target and version must be a single SP. (RFC7230 3.1.1)'});
  465. parse_version(_, State, _, _, _, _) ->
  466. error_terminate(505, State, {connection_error, protocol_error,
  467. 'Unsupported HTTP version. (RFC7230 2.6)'}).
  468. before_parse_headers(Rest, State, M, A, P, Q, V) ->
  469. parse_header(Rest, State#state{in_state=#ps_header{
  470. method=M, authority=A, path=P, qs=Q, version=V}}, #{}).
  471. %% Headers.
  472. %% We need two or more bytes in the buffer to continue.
  473. parse_header(Rest, State=#state{in_state=PS}, Headers) when byte_size(Rest) < 2 ->
  474. {more, State#state{in_state=PS#ps_header{headers=Headers}}, Rest};
  475. parse_header(<< $\r, $\n, Rest/bits >>, S, Headers) ->
  476. request(Rest, S, Headers);
  477. parse_header(Buffer, State=#state{opts=Opts, in_state=PS}, Headers) ->
  478. MaxHeaders = maps:get(max_headers, Opts, 100),
  479. NumHeaders = maps:size(Headers),
  480. if
  481. NumHeaders >= MaxHeaders ->
  482. error_terminate(431, State#state{in_state=PS#ps_header{headers=Headers}},
  483. {connection_error, limit_reached,
  484. 'The number of headers is larger than configuration allows. (RFC7230 3.2.5, RFC6585 5)'});
  485. true ->
  486. parse_header_colon(Buffer, State, Headers)
  487. end.
  488. parse_header_colon(Buffer, State=#state{opts=Opts, in_state=PS}, Headers) ->
  489. MaxLength = maps:get(max_header_name_length, Opts, 64),
  490. case match_colon(Buffer, 0) of
  491. nomatch when byte_size(Buffer) > MaxLength ->
  492. error_terminate(431, State#state{in_state=PS#ps_header{headers=Headers}},
  493. {connection_error, limit_reached,
  494. 'A header name is larger than configuration allows. (RFC7230 3.2.5, RFC6585 5)'});
  495. nomatch ->
  496. {more, State#state{in_state=PS#ps_header{headers=Headers}}, Buffer};
  497. _ ->
  498. parse_hd_name(Buffer, State, Headers, <<>>)
  499. end.
  500. match_colon(<< $:, _/bits >>, N) ->
  501. N;
  502. match_colon(<< _, Rest/bits >>, N) ->
  503. match_colon(Rest, N + 1);
  504. match_colon(_, _) ->
  505. nomatch.
  506. parse_hd_name(<< $:, Rest/bits >>, State, H, SoFar) ->
  507. parse_hd_before_value(Rest, State, H, SoFar);
  508. parse_hd_name(<< C, _/bits >>, State=#state{in_state=PS}, H, <<>>) when ?IS_WS(C) ->
  509. error_terminate(400, State#state{in_state=PS#ps_header{headers=H}},
  510. {connection_error, protocol_error,
  511. 'Whitespace is not allowed before the header name. (RFC7230 3.2)'});
  512. parse_hd_name(<< C, _/bits >>, State=#state{in_state=PS}, H, _) when ?IS_WS(C) ->
  513. error_terminate(400, State#state{in_state=PS#ps_header{headers=H}},
  514. {connection_error, protocol_error,
  515. 'Whitespace is not allowed between the header name and the colon. (RFC7230 3.2.4)'});
  516. parse_hd_name(<< C, Rest/bits >>, State, H, SoFar) ->
  517. ?LOWER(parse_hd_name, Rest, State, H, SoFar).
  518. parse_hd_before_value(<< $\s, Rest/bits >>, S, H, N) ->
  519. parse_hd_before_value(Rest, S, H, N);
  520. parse_hd_before_value(<< $\t, Rest/bits >>, S, H, N) ->
  521. parse_hd_before_value(Rest, S, H, N);
  522. parse_hd_before_value(Buffer, State=#state{opts=Opts, in_state=PS}, H, N) ->
  523. MaxLength = maps:get(max_header_value_length, Opts, 4096),
  524. case match_eol(Buffer, 0) of
  525. nomatch when byte_size(Buffer) > MaxLength ->
  526. error_terminate(431, State#state{in_state=PS#ps_header{headers=H}},
  527. {connection_error, limit_reached,
  528. 'A header value is larger than configuration allows. (RFC7230 3.2.5, RFC6585 5)'});
  529. nomatch ->
  530. {more, State#state{in_state=PS#ps_header{headers=H, name=N}}, Buffer};
  531. _ ->
  532. parse_hd_value(Buffer, State, H, N, <<>>)
  533. end.
  534. parse_hd_value(<< $\r, $\n, Rest/bits >>, S, Headers0, Name, SoFar) ->
  535. Value = clean_value_ws_end(SoFar, byte_size(SoFar) - 1),
  536. Headers = case maps:get(Name, Headers0, undefined) of
  537. undefined -> Headers0#{Name => Value};
  538. %% The cookie header does not use proper HTTP header lists.
  539. Value0 when Name =:= <<"cookie">> -> Headers0#{Name => << Value0/binary, "; ", Value/binary >>};
  540. Value0 -> Headers0#{Name => << Value0/binary, ", ", Value/binary >>}
  541. end,
  542. parse_header(Rest, S, Headers);
  543. parse_hd_value(<< C, Rest/bits >>, S, H, N, SoFar) ->
  544. parse_hd_value(Rest, S, H, N, << SoFar/binary, C >>).
  545. clean_value_ws_end(_, -1) ->
  546. <<>>;
  547. clean_value_ws_end(Value, N) ->
  548. case binary:at(Value, N) of
  549. $\s -> clean_value_ws_end(Value, N - 1);
  550. $\t -> clean_value_ws_end(Value, N - 1);
  551. _ ->
  552. S = N + 1,
  553. << Value2:S/binary, _/bits >> = Value,
  554. Value2
  555. end.
  556. -ifdef(TEST).
  557. clean_value_ws_end_test_() ->
  558. Tests = [
  559. {<<>>, <<>>},
  560. {<<" ">>, <<>>},
  561. {<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  562. "text/html;level=2;q=0.4, */*;q=0.5 \t \t ">>,
  563. <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  564. "text/html;level=2;q=0.4, */*;q=0.5">>}
  565. ],
  566. [{V, fun() -> R = clean_value_ws_end(V, byte_size(V) - 1) end} || {V, R} <- Tests].
  567. horse_clean_value_ws_end() ->
  568. horse:repeat(200000,
  569. clean_value_ws_end(
  570. <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  571. "text/html;level=2;q=0.4, */*;q=0.5 ">>,
  572. byte_size(<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  573. "text/html;level=2;q=0.4, */*;q=0.5 ">>) - 1)
  574. ).
  575. -endif.
  576. request(Buffer, State=#state{transport=Transport, in_streamid=StreamID,
  577. in_state=PS=#ps_header{authority=Authority, version=Version}}, Headers) ->
  578. case maps:get(<<"host">>, Headers, undefined) of
  579. undefined when Version =:= 'HTTP/1.1' ->
  580. %% @todo Might want to not close the connection on this and next one.
  581. error_terminate(400, State#state{in_state=PS#ps_header{headers=Headers}},
  582. {stream_error, StreamID, protocol_error,
  583. 'HTTP/1.1 requests must include a host header. (RFC7230 5.4)'});
  584. undefined ->
  585. request(Buffer, State, Headers, <<>>, default_port(Transport:secure()));
  586. %% @todo When CONNECT requests come in we need to ignore the RawHost
  587. %% and instead use the Authority as the source of host.
  588. RawHost when Authority =:= undefined; Authority =:= RawHost ->
  589. request_parse_host(Buffer, State, Headers, RawHost);
  590. %% RFC7230 does not explicitly ask us to reject requests
  591. %% that have a different authority component and host header.
  592. %% However it DOES ask clients to set them to the same value,
  593. %% so we enforce that.
  594. _ ->
  595. error_terminate(400, State#state{in_state=PS#ps_header{headers=Headers}},
  596. {stream_error, StreamID, protocol_error,
  597. 'The host header is different than the absolute-form authority component. (RFC7230 5.4)'})
  598. end.
  599. request_parse_host(Buffer, State=#state{transport=Transport,
  600. in_streamid=StreamID, in_state=PS}, Headers, RawHost) ->
  601. try cow_http_hd:parse_host(RawHost) of
  602. {Host, undefined} ->
  603. request(Buffer, State, Headers, Host, default_port(Transport:secure()));
  604. {Host, Port} when Port > 0, Port =< 65535 ->
  605. request(Buffer, State, Headers, Host, Port);
  606. _ ->
  607. error_terminate(400, State, {stream_error, StreamID, protocol_error,
  608. 'The port component of the absolute-form is not in the range 0..65535. (RFC7230 2.7.1)'})
  609. catch _:_ ->
  610. error_terminate(400, State#state{in_state=PS#ps_header{headers=Headers}},
  611. {stream_error, StreamID, protocol_error,
  612. 'The host header is invalid. (RFC7230 5.4)'})
  613. end.
  614. -spec default_port(boolean()) -> 80 | 443.
  615. default_port(true) -> 443;
  616. default_port(_) -> 80.
  617. %% End of request parsing.
  618. request(Buffer, State0=#state{ref=Ref, transport=Transport, peer=Peer, sock=Sock, cert=Cert,
  619. proxy_header=ProxyHeader, in_streamid=StreamID, in_state=
  620. PS=#ps_header{method=Method, path=Path, qs=Qs, version=Version}},
  621. Headers0, Host, Port) ->
  622. Scheme = case Transport:secure() of
  623. true -> <<"https">>;
  624. false -> <<"http">>
  625. end,
  626. {Headers, HasBody, BodyLength, TDecodeFun, TDecodeState} = case Headers0 of
  627. #{<<"transfer-encoding">> := TransferEncoding0} ->
  628. try cow_http_hd:parse_transfer_encoding(TransferEncoding0) of
  629. [<<"chunked">>] ->
  630. {maps:remove(<<"content-length">>, Headers0),
  631. true, undefined, fun cow_http_te:stream_chunked/2, {0, 0}};
  632. _ ->
  633. error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers0}},
  634. {stream_error, StreamID, protocol_error,
  635. 'Cowboy only supports transfer-encoding: chunked. (RFC7230 3.3.1)'})
  636. catch _:_ ->
  637. error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers0}},
  638. {stream_error, StreamID, protocol_error,
  639. 'The transfer-encoding header is invalid. (RFC7230 3.3.1)'})
  640. end;
  641. #{<<"content-length">> := <<"0">>} ->
  642. {Headers0, false, 0, undefined, undefined};
  643. #{<<"content-length">> := BinLength} ->
  644. Length = try
  645. cow_http_hd:parse_content_length(BinLength)
  646. catch _:_ ->
  647. error_terminate(400, State0#state{in_state=PS#ps_header{headers=Headers0}},
  648. {stream_error, StreamID, protocol_error,
  649. 'The content-length header is invalid. (RFC7230 3.3.2)'})
  650. end,
  651. {Headers0, true, Length, fun cow_http_te:stream_identity/2, {0, Length}};
  652. _ ->
  653. {Headers0, false, 0, undefined, undefined}
  654. end,
  655. Req0 = #{
  656. ref => Ref,
  657. pid => self(),
  658. streamid => StreamID,
  659. peer => Peer,
  660. sock => Sock,
  661. cert => Cert,
  662. method => Method,
  663. scheme => Scheme,
  664. host => Host,
  665. port => Port,
  666. path => Path,
  667. qs => Qs,
  668. version => Version,
  669. %% We are transparently taking care of transfer-encodings so
  670. %% the user code has no need to know about it.
  671. headers => maps:remove(<<"transfer-encoding">>, Headers),
  672. has_body => HasBody,
  673. body_length => BodyLength
  674. },
  675. %% We add the PROXY header information if any.
  676. Req = case ProxyHeader of
  677. undefined -> Req0;
  678. _ -> Req0#{proxy_header => ProxyHeader}
  679. end,
  680. case is_http2_upgrade(Headers, Version) of
  681. false ->
  682. State = case HasBody of
  683. true ->
  684. State0#state{in_state=#ps_body{
  685. length = BodyLength,
  686. transfer_decode_fun = TDecodeFun,
  687. transfer_decode_state = TDecodeState
  688. }};
  689. false ->
  690. State0#state{in_streamid=StreamID + 1, in_state=#ps_request_line{}}
  691. end,
  692. {request, Req, State, Buffer};
  693. {true, HTTP2Settings} ->
  694. %% We save the headers in case the upgrade will fail
  695. %% and we need to pass them to cowboy_stream:early_error.
  696. http2_upgrade(State0#state{in_state=PS#ps_header{headers=Headers}},
  697. Buffer, HTTP2Settings, Req)
  698. end.
  699. %% HTTP/2 upgrade.
  700. %% @todo We must not upgrade to h2c over a TLS connection.
  701. is_http2_upgrade(#{<<"connection">> := Conn, <<"upgrade">> := Upgrade,
  702. <<"http2-settings">> := HTTP2Settings}, 'HTTP/1.1') ->
  703. Conns = cow_http_hd:parse_connection(Conn),
  704. case {lists:member(<<"upgrade">>, Conns), lists:member(<<"http2-settings">>, Conns)} of
  705. {true, true} ->
  706. Protocols = cow_http_hd:parse_upgrade(Upgrade),
  707. case lists:member(<<"h2c">>, Protocols) of
  708. true ->
  709. {true, HTTP2Settings};
  710. false ->
  711. false
  712. end;
  713. _ ->
  714. false
  715. end;
  716. is_http2_upgrade(_, _) ->
  717. false.
  718. %% Prior knowledge upgrade, without an HTTP/1.1 request.
  719. http2_upgrade(State=#state{parent=Parent, ref=Ref, socket=Socket, transport=Transport,
  720. proxy_header=ProxyHeader, opts=Opts, peer=Peer, sock=Sock, cert=Cert}, Buffer) ->
  721. case Transport:secure() of
  722. false ->
  723. _ = cancel_timeout(State),
  724. cowboy_http2:init(Parent, Ref, Socket, Transport,
  725. ProxyHeader, Opts, Peer, Sock, Cert, Buffer);
  726. true ->
  727. error_terminate(400, State, {connection_error, protocol_error,
  728. 'Clients that support HTTP/2 over TLS MUST use ALPN. (RFC7540 3.4)'})
  729. end.
  730. %% Upgrade via an HTTP/1.1 request.
  731. http2_upgrade(State=#state{parent=Parent, ref=Ref, socket=Socket, transport=Transport,
  732. proxy_header=ProxyHeader, opts=Opts, peer=Peer, sock=Sock, cert=Cert},
  733. Buffer, HTTP2Settings, Req) ->
  734. %% @todo
  735. %% However if the client sent a body, we need to read the body in full
  736. %% and if we can't do that, return a 413 response. Some options are in order.
  737. %% Always half-closed stream coming from this side.
  738. try cow_http_hd:parse_http2_settings(HTTP2Settings) of
  739. Settings ->
  740. _ = cancel_timeout(State),
  741. cowboy_http2:init(Parent, Ref, Socket, Transport,
  742. ProxyHeader, Opts, Peer, Sock, Cert, Buffer, Settings, Req)
  743. catch _:_ ->
  744. error_terminate(400, State, {connection_error, protocol_error,
  745. 'The HTTP2-Settings header must contain a base64 SETTINGS payload. (RFC7540 3.2, RFC7540 3.2.1)'})
  746. end.
  747. %% Request body parsing.
  748. parse_body(Buffer, State=#state{in_streamid=StreamID, in_state=
  749. PS=#ps_body{received=Received, transfer_decode_fun=TDecode,
  750. transfer_decode_state=TState0}}) ->
  751. %% @todo Proper trailers.
  752. try TDecode(Buffer, TState0) of
  753. more ->
  754. %% @todo Asks for 0 or more bytes.
  755. {more, State, Buffer};
  756. {more, Data, TState} ->
  757. %% @todo Asks for 0 or more bytes.
  758. {data, StreamID, nofin, Data, State#state{in_state=
  759. PS#ps_body{received=Received + byte_size(Data),
  760. transfer_decode_state=TState}}, <<>>};
  761. {more, Data, _Length, TState} when is_integer(_Length) ->
  762. %% @todo Asks for Length more bytes.
  763. {data, StreamID, nofin, Data, State#state{in_state=
  764. PS#ps_body{received=Received + byte_size(Data),
  765. transfer_decode_state=TState}}, <<>>};
  766. {more, Data, Rest, TState} ->
  767. %% @todo Asks for 0 or more bytes.
  768. {data, StreamID, nofin, Data, State#state{in_state=
  769. PS#ps_body{received=Received + byte_size(Data),
  770. transfer_decode_state=TState}}, Rest};
  771. {done, _HasTrailers, Rest} ->
  772. {data, StreamID, fin, <<>>, set_timeout(
  773. State#state{in_streamid=StreamID + 1, in_state=#ps_request_line{}}), Rest};
  774. {done, Data, _HasTrailers, Rest} ->
  775. {data, StreamID, fin, Data, set_timeout(
  776. State#state{in_streamid=StreamID + 1, in_state=#ps_request_line{}}), Rest}
  777. catch _:_ ->
  778. Reason = {connection_error, protocol_error,
  779. 'Failure to decode the content. (RFC7230 4)'},
  780. terminate(stream_terminate(State, StreamID, Reason), Reason)
  781. end.
  782. %% Message handling.
  783. down(State=#state{opts=Opts, children=Children0}, Pid, Msg) ->
  784. case cowboy_children:down(Children0, Pid) of
  785. %% The stream was terminated already.
  786. {ok, undefined, Children} ->
  787. State#state{children=Children};
  788. %% The stream is still running.
  789. {ok, StreamID, Children} ->
  790. info(State#state{children=Children}, StreamID, Msg);
  791. %% The process was unknown.
  792. error ->
  793. cowboy:log(warning, "Received EXIT signal ~p for unknown process ~p.~n",
  794. [Msg, Pid], Opts),
  795. State
  796. end.
  797. info(State=#state{opts=Opts, streams=Streams0}, StreamID, Msg) ->
  798. case lists:keyfind(StreamID, #stream.id, Streams0) of
  799. Stream = #stream{state=StreamState0} ->
  800. try cowboy_stream:info(StreamID, Msg, StreamState0) of
  801. {Commands, StreamState} ->
  802. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  803. Stream#stream{state=StreamState}),
  804. commands(State#state{streams=Streams}, StreamID, Commands)
  805. catch Class:Exception ->
  806. cowboy:log(cowboy_stream:make_error_log(info,
  807. [StreamID, Msg, StreamState0],
  808. Class, Exception, erlang:get_stacktrace()), Opts),
  809. stream_reset(State, StreamID, {internal_error, {Class, Exception},
  810. 'Unhandled exception in cowboy_stream:info/3.'})
  811. end;
  812. false ->
  813. cowboy:log(warning, "Received message ~p for unknown stream ~p.~n",
  814. [Msg, StreamID], Opts),
  815. State
  816. end.
  817. %% Commands.
  818. commands(State, _, []) ->
  819. State;
  820. %% Supervise a child process.
  821. commands(State=#state{children=Children}, StreamID, [{spawn, Pid, Shutdown}|Tail]) ->
  822. commands(State#state{children=cowboy_children:up(Children, Pid, StreamID, Shutdown)},
  823. StreamID, Tail);
  824. %% Error handling.
  825. commands(State, StreamID, [Error = {internal_error, _, _}|Tail]) ->
  826. commands(stream_reset(State, StreamID, Error), StreamID, Tail);
  827. %% Commands for a stream currently inactive.
  828. commands(State=#state{out_streamid=Current, streams=Streams0}, StreamID, Commands)
  829. when Current =/= StreamID ->
  830. %% @todo We still want to handle some commands...
  831. Stream = #stream{queue=Queue} = lists:keyfind(StreamID, #stream.id, Streams0),
  832. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  833. Stream#stream{queue=Queue ++ Commands}),
  834. State#state{streams=Streams};
  835. %% Read the request body.
  836. commands(State, StreamID, [{flow, _Length}|Tail]) ->
  837. %% @todo We only read from socket if buffer is empty, otherwise
  838. %% we decode the buffer.
  839. %% @todo Set the body reading length to min(Length, BodyLength)
  840. commands(State, StreamID, Tail);
  841. %% Error responses are sent only if a response wasn't sent already.
  842. commands(State=#state{out_state=wait, out_streamid=StreamID}, StreamID,
  843. [{error_response, Status, Headers0, Body}|Tail]) ->
  844. %% We close the connection when the error response is 408, as it
  845. %% indicates a timeout and the RFC recommends that we stop here. (RFC7231 6.5.7)
  846. Headers = case Status of
  847. 408 -> Headers0#{<<"connection">> => <<"close">>};
  848. <<"408", _/bits>> -> Headers0#{<<"connection">> => <<"close">>};
  849. _ -> Headers0
  850. end,
  851. commands(State, StreamID, [{response, Status, Headers, Body}|Tail]);
  852. commands(State, StreamID, [{error_response, _, _, _}|Tail]) ->
  853. commands(State, StreamID, Tail);
  854. %% Send an informational response.
  855. commands(State=#state{socket=Socket, transport=Transport, out_state=wait, streams=Streams},
  856. StreamID, [{inform, StatusCode, Headers}|Tail]) ->
  857. %% @todo I'm pretty sure the last stream in the list is the one we want
  858. %% considering all others are queued.
  859. #stream{version=Version} = lists:keyfind(StreamID, #stream.id, Streams),
  860. _ = case Version of
  861. 'HTTP/1.1' ->
  862. Transport:send(Socket, cow_http:response(StatusCode, 'HTTP/1.1',
  863. headers_to_list(Headers)));
  864. %% Do not send informational responses to HTTP/1.0 clients. (RFC7231 6.2)
  865. 'HTTP/1.0' ->
  866. ok
  867. end,
  868. commands(State, StreamID, Tail);
  869. %% Send a full response.
  870. %%
  871. %% @todo Kill the stream if it sent a response when one has already been sent.
  872. %% @todo Keep IsFin in the state.
  873. %% @todo Same two things above apply to DATA, possibly promise too.
  874. commands(State0=#state{socket=Socket, transport=Transport, out_state=wait, streams=Streams}, StreamID,
  875. [{response, StatusCode, Headers0, Body}|Tail]) ->
  876. %% @todo I'm pretty sure the last stream in the list is the one we want
  877. %% considering all others are queued.
  878. #stream{version=Version} = lists:keyfind(StreamID, #stream.id, Streams),
  879. {State1, Headers} = connection(State0, Headers0, StreamID, Version),
  880. State = State1#state{out_state=done},
  881. %% @todo Ensure content-length is set.
  882. Response = cow_http:response(StatusCode, 'HTTP/1.1', headers_to_list(Headers)),
  883. case Body of
  884. {sendfile, _, _, _} ->
  885. Transport:send(Socket, Response),
  886. sendfile(State, Body);
  887. _ ->
  888. Transport:send(Socket, [Response, Body])
  889. end,
  890. commands(State, StreamID, Tail);
  891. %% Send response headers and initiate chunked encoding or streaming.
  892. commands(State0=#state{socket=Socket, transport=Transport,
  893. opts=Opts, overriden_opts=Override, streams=Streams0, out_state=OutState},
  894. StreamID, [{headers, StatusCode, Headers0}|Tail]) ->
  895. %% @todo Same as above (about the last stream in the list).
  896. Stream = #stream{version=Version} = lists:keyfind(StreamID, #stream.id, Streams0),
  897. Status = cow_http:status_to_integer(StatusCode),
  898. ContentLength = maps:get(<<"content-length">>, Headers0, undefined),
  899. %% Chunked transfer-encoding can be disabled on a per-request basis.
  900. Chunked = case Override of
  901. #{chunked := Chunked0} -> Chunked0;
  902. _ -> maps:get(chunked, Opts, true)
  903. end,
  904. {State1, Headers1} = case {Status, ContentLength, Version} of
  905. {204, _, 'HTTP/1.1'} ->
  906. {State0#state{out_state=done}, Headers0};
  907. {304, _, 'HTTP/1.1'} ->
  908. {State0#state{out_state=done}, Headers0};
  909. {_, undefined, 'HTTP/1.1'} when Chunked ->
  910. {State0#state{out_state=chunked}, Headers0#{<<"transfer-encoding">> => <<"chunked">>}};
  911. %% Close the connection after streaming without content-length
  912. %% to all HTTP/1.0 clients and to HTTP/1.1 clients when chunked is disabled.
  913. {_, undefined, _} ->
  914. {State0#state{out_state=streaming, last_streamid=StreamID}, Headers0};
  915. %% Stream the response body without chunked transfer-encoding.
  916. _ ->
  917. ExpectedSize = cow_http_hd:parse_content_length(ContentLength),
  918. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  919. Stream#stream{local_expected_size=ExpectedSize}),
  920. {State0#state{out_state=streaming, streams=Streams}, Headers0}
  921. end,
  922. Headers2 = case stream_te(OutState, Stream) of
  923. trailers -> Headers1;
  924. _ -> maps:remove(<<"trailer">>, Headers1)
  925. end,
  926. {State, Headers} = connection(State1, Headers2, StreamID, Version),
  927. Transport:send(Socket, cow_http:response(StatusCode, 'HTTP/1.1', headers_to_list(Headers))),
  928. commands(State, StreamID, Tail);
  929. %% Send a response body chunk.
  930. %% @todo We need to kill the stream if it tries to send data before headers.
  931. commands(State0=#state{socket=Socket, transport=Transport, streams=Streams0, out_state=OutState},
  932. StreamID, [{data, IsFin, Data}|Tail]) ->
  933. %% Do not send anything when the user asks to send an empty
  934. %% data frame, as that would break the protocol.
  935. Size = case Data of
  936. {sendfile, _, B, _} -> B;
  937. _ -> iolist_size(Data)
  938. end,
  939. %% Depending on the current state we may need to send nothing,
  940. %% the last chunk, chunked data with/without the last chunk,
  941. %% or just the data as-is.
  942. Stream = case lists:keyfind(StreamID, #stream.id, Streams0) of
  943. Stream0=#stream{method= <<"HEAD">>} ->
  944. Stream0;
  945. Stream0 when Size =:= 0, IsFin =:= fin, OutState =:= chunked ->
  946. Transport:send(Socket, <<"0\r\n\r\n">>),
  947. Stream0;
  948. Stream0 when Size =:= 0 ->
  949. Stream0;
  950. Stream0 when is_tuple(Data), OutState =:= chunked ->
  951. Transport:send(Socket, [integer_to_binary(Size, 16), <<"\r\n">>]),
  952. sendfile(State0, Data),
  953. Transport:send(Socket,
  954. case IsFin of
  955. fin -> <<"\r\n0\r\n\r\n">>;
  956. nofin -> <<"\r\n">>
  957. end),
  958. Stream0;
  959. Stream0 when OutState =:= chunked ->
  960. Transport:send(Socket, [
  961. integer_to_binary(Size, 16), <<"\r\n">>, Data,
  962. case IsFin of
  963. fin -> <<"\r\n0\r\n\r\n">>;
  964. nofin -> <<"\r\n">>
  965. end
  966. ]),
  967. Stream0;
  968. Stream0 when OutState =:= streaming ->
  969. #stream{local_sent_size=SentSize0, local_expected_size=ExpectedSize} = Stream0,
  970. SentSize = SentSize0 + Size,
  971. if
  972. %% ExpectedSize may be undefined, which is > any integer value.
  973. SentSize > ExpectedSize ->
  974. terminate(State0, response_body_too_large);
  975. is_tuple(Data) ->
  976. sendfile(State0, Data);
  977. true ->
  978. Transport:send(Socket, Data)
  979. end,
  980. Stream0#stream{local_sent_size=SentSize}
  981. end,
  982. State = case IsFin of
  983. fin -> State0#state{out_state=done};
  984. nofin -> State0
  985. end,
  986. Streams = lists:keyreplace(StreamID, #stream.id, Streams0, Stream),
  987. commands(State#state{streams=Streams}, StreamID, Tail);
  988. commands(State=#state{socket=Socket, transport=Transport, streams=Streams, out_state=OutState},
  989. StreamID, [{trailers, Trailers}|Tail]) ->
  990. case stream_te(OutState, lists:keyfind(StreamID, #stream.id, Streams)) of
  991. trailers ->
  992. Transport:send(Socket, [
  993. <<"0\r\n">>,
  994. cow_http:headers(maps:to_list(Trailers)),
  995. <<"\r\n">>
  996. ]);
  997. no_trailers ->
  998. Transport:send(Socket, <<"0\r\n\r\n">>);
  999. not_chunked ->
  1000. ok
  1001. end,
  1002. commands(State#state{out_state=done}, StreamID, Tail);
  1003. %% Protocol takeover.
  1004. commands(State0=#state{ref=Ref, parent=Parent, socket=Socket, transport=Transport,
  1005. out_state=OutState, opts=Opts, children=Children}, StreamID,
  1006. [{switch_protocol, Headers, Protocol, InitialState}|_Tail]) ->
  1007. %% @todo This should be the last stream running otherwise we need to wait before switching.
  1008. %% @todo If there's streams opened after this one, fail instead of 101.
  1009. State = cancel_timeout(State0),
  1010. %% Before we send the 101 response we need to stop receiving data
  1011. %% from the socket, otherwise the data might be receive before the
  1012. %% call to flush/0 and we end up inadvertently dropping a packet.
  1013. %%
  1014. %% @todo Handle cases where the request came with a body. We need
  1015. %% to process or skip the body before the upgrade can be completed.
  1016. Transport:setopts(Socket, [{active, false}]),
  1017. %% Send a 101 response if necessary, then terminate the stream.
  1018. #state{streams=Streams} = case OutState of
  1019. wait -> info(State, StreamID, {inform, 101, Headers});
  1020. _ -> State
  1021. end,
  1022. #stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams),
  1023. %% @todo We need to shutdown processes here first.
  1024. stream_call_terminate(StreamID, switch_protocol, StreamState, State),
  1025. %% Terminate children processes and flush any remaining messages from the mailbox.
  1026. cowboy_children:terminate(Children),
  1027. flush(Parent),
  1028. %% @todo This is no good because commands return a state normally and here it doesn't
  1029. %% we need to let this module go entirely. Perhaps it should be handled directly in
  1030. %% cowboy_clear/cowboy_tls?
  1031. Protocol:takeover(Parent, Ref, Socket, Transport, Opts, <<>>, InitialState);
  1032. %% Set options dynamically.
  1033. commands(State0=#state{overriden_opts=Opts},
  1034. StreamID, [{set_options, SetOpts}|Tail]) ->
  1035. State1 = case SetOpts of
  1036. #{idle_timeout := IdleTimeout} ->
  1037. set_timeout(State0#state{overriden_opts=Opts#{idle_timeout => IdleTimeout}});
  1038. _ ->
  1039. State0
  1040. end,
  1041. State = case SetOpts of
  1042. #{chunked := Chunked} ->
  1043. State1#state{overriden_opts=Opts#{chunked => Chunked}};
  1044. _ ->
  1045. State1
  1046. end,
  1047. commands(State, StreamID, Tail);
  1048. %% Stream shutdown.
  1049. commands(State, StreamID, [stop|Tail]) ->
  1050. %% @todo Do we want to run the commands after a stop?
  1051. %% @todo We currently wait for the stop command before we
  1052. %% continue with the next request/response. In theory, if
  1053. %% the request body was read fully and the response body
  1054. %% was sent fully we should be able to start working on
  1055. %% the next request concurrently. This can be done as a
  1056. %% future optimization.
  1057. maybe_terminate(State, StreamID, Tail);
  1058. %% Log event.
  1059. commands(State=#state{opts=Opts}, StreamID, [Log={log, _, _, _}|Tail]) ->
  1060. cowboy:log(Log, Opts),
  1061. commands(State, StreamID, Tail);
  1062. %% HTTP/1.1 does not support push; ignore.
  1063. commands(State, StreamID, [{push, _, _, _, _, _, _, _}|Tail]) ->
  1064. commands(State, StreamID, Tail).
  1065. %% The set-cookie header is special; we can only send one cookie per header.
  1066. headers_to_list(Headers0=#{<<"set-cookie">> := SetCookies}) ->
  1067. Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  1068. Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies];
  1069. headers_to_list(Headers) ->
  1070. maps:to_list(Headers).
  1071. %% We wrap the sendfile call into a try/catch because on OTP-20
  1072. %% and earlier a few different crashes could occur for sockets
  1073. %% that were closing or closed. For example a badarg in
  1074. %% erlang:port_get_data(#Port<...>) or a badmatch like
  1075. %% {{badmatch,{error,einval}},[{prim_file,sendfile,8,[]}...
  1076. %%
  1077. %% OTP-21 uses a NIF instead of a port so the implementation
  1078. %% and behavior has dramatically changed and it is unclear
  1079. %% whether it will be necessary in the future.
  1080. %%
  1081. %% This try/catch prevents some noisy logs to be written
  1082. %% when these errors occur.
  1083. sendfile(State=#state{socket=Socket, transport=Transport, opts=Opts},
  1084. {sendfile, Offset, Bytes, Path}) ->
  1085. try
  1086. %% When sendfile is disabled we explicitly use the fallback.
  1087. _ = case maps:get(sendfile, Opts, true) of
  1088. true -> Transport:sendfile(Socket, Path, Offset, Bytes);
  1089. false -> ranch_transport:sendfile(Transport, Socket, Path, Offset, Bytes, [])
  1090. end,
  1091. ok
  1092. catch _:_ ->
  1093. terminate(State, {socket_error, sendfile_crash,
  1094. 'An error occurred when using the sendfile function.'})
  1095. end.
  1096. %% Flush messages specific to cowboy_http before handing over the
  1097. %% connection to another protocol.
  1098. flush(Parent) ->
  1099. receive
  1100. {timeout, _, _} ->
  1101. flush(Parent);
  1102. {{Pid, _}, _} when Pid =:= self() ->
  1103. flush(Parent);
  1104. {'EXIT', Pid, _} when Pid =/= Parent ->
  1105. flush(Parent)
  1106. after 0 ->
  1107. ok
  1108. end.
  1109. %% @todo In these cases I'm not sure if we should continue processing commands.
  1110. maybe_terminate(State=#state{last_streamid=StreamID}, StreamID, _Tail) ->
  1111. terminate(stream_terminate(State, StreamID, normal), normal); %% @todo Reason ok?
  1112. maybe_terminate(State, StreamID, _Tail) ->
  1113. stream_terminate(State, StreamID, normal).
  1114. stream_reset(State, StreamID, StreamError={internal_error, _, _}) ->
  1115. %% @todo headers
  1116. %% @todo Don't send this if there are no streams left.
  1117. % Transport:send(Socket, cow_http:response(500, 'HTTP/1.1', [
  1118. % {<<"content-length">>, <<"0">>}
  1119. % ])),
  1120. %% @todo update IsFin local
  1121. % stream_terminate(State#state{out_state=done}, StreamID, StreamError).
  1122. stream_terminate(State, StreamID, StreamError).
  1123. stream_terminate(State0=#state{opts=Opts, in_streamid=InStreamID, in_state=InState,
  1124. out_streamid=OutStreamID, out_state=OutState, streams=Streams0,
  1125. children=Children0}, StreamID, Reason) ->
  1126. #stream{version=Version, local_expected_size=ExpectedSize, local_sent_size=SentSize}
  1127. = lists:keyfind(StreamID, #stream.id, Streams0),
  1128. State1 = #state{streams=Streams1} = case OutState of
  1129. wait when element(1, Reason) =:= internal_error ->
  1130. info(State0, StreamID, {response, 500, #{<<"content-length">> => <<"0">>}, <<>>});
  1131. wait when element(1, Reason) =:= connection_error ->
  1132. info(State0, StreamID, {response, 400, #{<<"content-length">> => <<"0">>}, <<>>});
  1133. wait ->
  1134. info(State0, StreamID, {response, 204, #{}, <<>>});
  1135. chunked when Version =:= 'HTTP/1.1' ->
  1136. info(State0, StreamID, {data, fin, <<>>});
  1137. streaming when ExpectedSize < SentSize ->
  1138. terminate(State0, response_body_too_small);
  1139. _ -> %% done or Version =:= 'HTTP/1.0'
  1140. State0
  1141. end,
  1142. %% Remove the stream from the state and reset the overriden options.
  1143. {value, #stream{state=StreamState}, Streams}
  1144. = lists:keytake(StreamID, #stream.id, Streams1),
  1145. State2 = State1#state{streams=Streams, overriden_opts=#{}},
  1146. %% Stop the stream.
  1147. stream_call_terminate(StreamID, Reason, StreamState, State2),
  1148. Children = cowboy_children:shutdown(Children0, StreamID),
  1149. %% We reset the timeout if there are no active streams anymore.
  1150. State = case Streams of
  1151. [] -> set_timeout(State2);
  1152. _ -> State2
  1153. end,
  1154. %% We want to drop the connection if the body was not read fully
  1155. %% and we don't know its length or more remains to be read than
  1156. %% configuration allows.
  1157. %% @todo Only do this if Current =:= StreamID.
  1158. MaxSkipBodyLength = maps:get(max_skip_body_length, Opts, 1000000),
  1159. case InState of
  1160. #ps_body{length=undefined}
  1161. when InStreamID =:= OutStreamID ->
  1162. terminate(State#state{streams=Streams, children=Children}, skip_body_unknown_length);
  1163. #ps_body{length=Len, received=Received}
  1164. when InStreamID =:= OutStreamID, Received + MaxSkipBodyLength < Len ->
  1165. terminate(State#state{streams=Streams, children=Children}, skip_body_too_large);
  1166. _ ->
  1167. %% Move on to the next stream.
  1168. NextOutStreamID = OutStreamID + 1,
  1169. case lists:keyfind(NextOutStreamID, #stream.id, Streams) of
  1170. false ->
  1171. %% @todo This is clearly wrong, if the stream is gone we need to check if
  1172. %% there used to be such a stream, and if there was to send an error.
  1173. State#state{out_streamid=NextOutStreamID, out_state=wait,
  1174. streams=Streams, children=Children};
  1175. #stream{queue=Commands} ->
  1176. %% @todo Remove queue from the stream.
  1177. commands(State#state{out_streamid=NextOutStreamID, out_state=wait,
  1178. streams=Streams, children=Children}, NextOutStreamID, Commands)
  1179. end
  1180. end.
  1181. stream_call_terminate(StreamID, Reason, StreamState, #state{opts=Opts}) ->
  1182. try
  1183. cowboy_stream:terminate(StreamID, Reason, StreamState)
  1184. catch Class:Exception ->
  1185. cowboy:log(cowboy_stream:make_error_log(terminate,
  1186. [StreamID, Reason, StreamState],
  1187. Class, Exception, erlang:get_stacktrace()), Opts)
  1188. end.
  1189. maybe_req_close(#state{opts=#{http10_keepalive := false}}, _, 'HTTP/1.0') ->
  1190. close;
  1191. maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.0') ->
  1192. Conns = cow_http_hd:parse_connection(Conn),
  1193. case lists:member(<<"keep-alive">>, Conns) of
  1194. true -> keepalive;
  1195. false -> close
  1196. end;
  1197. maybe_req_close(_, _, 'HTTP/1.0') ->
  1198. close;
  1199. maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.1') ->
  1200. case connection_hd_is_close(Conn) of
  1201. true -> close;
  1202. false -> keepalive
  1203. end;
  1204. maybe_req_close(_, _, _) ->
  1205. keepalive.
  1206. connection(State=#state{last_streamid=StreamID}, Headers=#{<<"connection">> := Conn}, StreamID, _) ->
  1207. case connection_hd_is_close(Conn) of
  1208. true -> {State, Headers};
  1209. %% @todo Here we need to remove keep-alive and add close, not just add close.
  1210. false -> {State, Headers#{<<"connection">> => [<<"close, ">>, Conn]}}
  1211. end;
  1212. connection(State=#state{last_streamid=StreamID}, Headers, StreamID, _) ->
  1213. {State, Headers#{<<"connection">> => <<"close">>}};
  1214. connection(State, Headers=#{<<"connection">> := Conn}, StreamID, _) ->
  1215. case connection_hd_is_close(Conn) of
  1216. true -> {State#state{last_streamid=StreamID}, Headers};
  1217. %% @todo Here we need to set keep-alive only if it wasn't set before.
  1218. false -> {State, Headers}
  1219. end;
  1220. connection(State, Headers, _, 'HTTP/1.0') ->
  1221. {State, Headers#{<<"connection">> => <<"keep-alive">>}};
  1222. connection(State, Headers, _, _) ->
  1223. {State, Headers}.
  1224. connection_hd_is_close(Conn) ->
  1225. Conns = cow_http_hd:parse_connection(iolist_to_binary(Conn)),
  1226. lists:member(<<"close">>, Conns).
  1227. stream_te(streaming, _) ->
  1228. not_chunked;
  1229. %% No TE header was sent.
  1230. stream_te(_, #stream{te=undefined}) ->
  1231. no_trailers;
  1232. stream_te(_, #stream{te=TE0}) ->
  1233. try cow_http_hd:parse_te(TE0) of
  1234. {TE1, _} -> TE1
  1235. catch _:_ ->
  1236. %% If we can't parse the TE header, assume we can't send trailers.
  1237. no_trailers
  1238. end.
  1239. %% This function is only called when an error occurs on a new stream.
  1240. -spec error_terminate(cowboy:http_status(), #state{}, _) -> no_return().
  1241. error_terminate(StatusCode, State=#state{ref=Ref, peer=Peer, in_state=StreamState}, Reason) ->
  1242. PartialReq = case StreamState of
  1243. #ps_request_line{} -> #{
  1244. ref => Ref,
  1245. peer => Peer
  1246. };
  1247. #ps_header{method=Method, path=Path, qs=Qs,
  1248. version=Version, headers=ReqHeaders} -> #{
  1249. ref => Ref,
  1250. peer => Peer,
  1251. method => Method,
  1252. path => Path,
  1253. qs => Qs,
  1254. version => Version,
  1255. headers => case ReqHeaders of
  1256. undefined -> #{};
  1257. _ -> ReqHeaders
  1258. end
  1259. }
  1260. end,
  1261. early_error(StatusCode, State, Reason, PartialReq, #{<<"connection">> => <<"close">>}),
  1262. terminate(State, Reason).
  1263. early_error(StatusCode, State, Reason, PartialReq) ->
  1264. early_error(StatusCode, State, Reason, PartialReq, #{}).
  1265. early_error(StatusCode0, #state{socket=Socket, transport=Transport,
  1266. opts=Opts, in_streamid=StreamID}, Reason, PartialReq, RespHeaders0) ->
  1267. RespHeaders1 = RespHeaders0#{<<"content-length">> => <<"0">>},
  1268. Resp = {response, StatusCode0, RespHeaders1, <<>>},
  1269. try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts) of
  1270. {response, StatusCode, RespHeaders, RespBody} ->
  1271. Transport:send(Socket, [
  1272. cow_http:response(StatusCode, 'HTTP/1.1', maps:to_list(RespHeaders)),
  1273. %% @todo We shouldn't send the body when the method is HEAD.
  1274. %% @todo Technically we allow the sendfile tuple.
  1275. RespBody
  1276. ])
  1277. catch Class:Exception ->
  1278. cowboy:log(cowboy_stream:make_error_log(early_error,
  1279. [StreamID, Reason, PartialReq, Resp, Opts],
  1280. Class, Exception, erlang:get_stacktrace()), Opts),
  1281. %% We still need to send an error response, so send what we initially
  1282. %% wanted to send. It's better than nothing.
  1283. Transport:send(Socket, cow_http:response(StatusCode0,
  1284. 'HTTP/1.1', maps:to_list(RespHeaders1)))
  1285. end,
  1286. ok.
  1287. -spec terminate(_, _) -> no_return().
  1288. terminate(undefined, Reason) ->
  1289. exit({shutdown, Reason});
  1290. terminate(State=#state{streams=Streams, children=Children}, Reason) ->
  1291. terminate_all_streams(State, Streams, Reason),
  1292. cowboy_children:terminate(Children),
  1293. terminate_linger(State),
  1294. exit({shutdown, Reason}).
  1295. terminate_all_streams(_, [], _) ->
  1296. ok;
  1297. terminate_all_streams(State, [#stream{id=StreamID, state=StreamState}|Tail], Reason) ->
  1298. stream_call_terminate(StreamID, Reason, StreamState, State),
  1299. terminate_all_streams(State, Tail, Reason).
  1300. terminate_linger(State=#state{socket=Socket, transport=Transport, opts=Opts}) ->
  1301. case Transport:shutdown(Socket, write) of
  1302. ok ->
  1303. case maps:get(linger_timeout, Opts, 1000) of
  1304. 0 ->
  1305. ok;
  1306. infinity ->
  1307. terminate_linger_loop(State, undefined);
  1308. Timeout ->
  1309. TimerRef = erlang:start_timer(Timeout, self(), linger_timeout),
  1310. terminate_linger_loop(State, TimerRef)
  1311. end;
  1312. {error, _} ->
  1313. ok
  1314. end.
  1315. terminate_linger_loop(State=#state{socket=Socket, transport=Transport}, TimerRef) ->
  1316. {OK, Closed, Error} = Transport:messages(),
  1317. %% We may already have a message in the mailbox when we do this
  1318. %% but it's OK because we are shutting down anyway.
  1319. case Transport:setopts(Socket, [{active, once}]) of
  1320. ok ->
  1321. receive
  1322. {OK, Socket, _} ->
  1323. terminate_linger_loop(State, TimerRef);
  1324. {Closed, Socket} ->
  1325. ok;
  1326. {Error, Socket, _} ->
  1327. ok;
  1328. {timeout, TimerRef, linger_timeout} ->
  1329. ok;
  1330. _ ->
  1331. terminate_linger_loop(State, TimerRef)
  1332. end;
  1333. {error, _} ->
  1334. ok
  1335. end.
  1336. %% System callbacks.
  1337. -spec system_continue(_, _, {#state{}, binary()}) -> ok.
  1338. system_continue(_, _, {State, Buffer}) ->
  1339. loop(State, Buffer).
  1340. -spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return().
  1341. system_terminate(Reason, _, _, {State, _}) ->
  1342. terminate(State, {stop, {exit, Reason}, 'sys:terminate/2,3 was called.'}).
  1343. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  1344. system_code_change(Misc, _, _, _) ->
  1345. {ok, Misc}.