cowboy_http.erl 55 KB

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