cowboy_http.erl 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407
  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. {_, undefined, 'HTTP/1.1'} ->
  893. {State0#state{out_state=chunked}, Headers0#{<<"transfer-encoding">> => <<"chunked">>}};
  894. %% Close the connection after streaming without content-length to HTTP/1.0 client.
  895. {_, undefined, 'HTTP/1.0'} ->
  896. {State0#state{out_state=streaming, last_streamid=StreamID}, Headers0};
  897. %% Stream the response body without chunked transfer-encoding.
  898. _ ->
  899. ExpectedSize = cow_http_hd:parse_content_length(ContentLength),
  900. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  901. Stream#stream{local_expected_size=ExpectedSize}),
  902. {State0#state{out_state=streaming, streams=Streams}, Headers0}
  903. end,
  904. Headers2 = case stream_te(OutState, Stream) of
  905. trailers -> Headers1;
  906. _ -> maps:remove(<<"trailer">>, Headers1)
  907. end,
  908. {State, Headers} = connection(State1, Headers2, StreamID, Version),
  909. Transport:send(Socket, cow_http:response(StatusCode, 'HTTP/1.1', headers_to_list(Headers))),
  910. commands(State, StreamID, Tail);
  911. %% Send a response body chunk.
  912. %% @todo We need to kill the stream if it tries to send data before headers.
  913. commands(State0=#state{socket=Socket, transport=Transport, streams=Streams0, out_state=OutState},
  914. StreamID, [{data, IsFin, Data}|Tail]) ->
  915. %% Do not send anything when the user asks to send an empty
  916. %% data frame, as that would break the protocol.
  917. Size = case Data of
  918. {sendfile, _, B, _} -> B;
  919. _ -> iolist_size(Data)
  920. end,
  921. %% Depending on the current state we may need to send nothing,
  922. %% the last chunk, chunked data with/without the last chunk,
  923. %% or just the data as-is.
  924. Stream = case lists:keyfind(StreamID, #stream.id, Streams0) of
  925. Stream0=#stream{method= <<"HEAD">>} ->
  926. Stream0;
  927. Stream0 when Size =:= 0, IsFin =:= fin, OutState =:= chunked ->
  928. Transport:send(Socket, <<"0\r\n\r\n">>),
  929. Stream0;
  930. Stream0 when Size =:= 0 ->
  931. Stream0;
  932. Stream0 when is_tuple(Data), OutState =:= chunked ->
  933. Transport:send(Socket, [integer_to_binary(Size, 16), <<"\r\n">>]),
  934. sendfile(State0, Data),
  935. Transport:send(Socket,
  936. case IsFin of
  937. fin -> <<"\r\n0\r\n\r\n">>;
  938. nofin -> <<"\r\n">>
  939. end),
  940. Stream0;
  941. Stream0 when OutState =:= chunked ->
  942. Transport:send(Socket, [
  943. integer_to_binary(Size, 16), <<"\r\n">>, Data,
  944. case IsFin of
  945. fin -> <<"\r\n0\r\n\r\n">>;
  946. nofin -> <<"\r\n">>
  947. end
  948. ]),
  949. Stream0;
  950. Stream0 when OutState =:= streaming ->
  951. #stream{local_sent_size=SentSize0, local_expected_size=ExpectedSize} = Stream0,
  952. SentSize = SentSize0 + Size,
  953. if
  954. %% ExpectedSize may be undefined, which is > any integer value.
  955. SentSize > ExpectedSize ->
  956. terminate(State0, response_body_too_large);
  957. is_tuple(Data) ->
  958. sendfile(State0, Data);
  959. true ->
  960. Transport:send(Socket, Data)
  961. end,
  962. Stream0#stream{local_sent_size=SentSize}
  963. end,
  964. State = case IsFin of
  965. fin -> State0#state{out_state=done};
  966. nofin -> State0
  967. end,
  968. Streams = lists:keyreplace(StreamID, #stream.id, Streams0, Stream),
  969. commands(State#state{streams=Streams}, StreamID, Tail);
  970. commands(State=#state{socket=Socket, transport=Transport, streams=Streams, out_state=OutState},
  971. StreamID, [{trailers, Trailers}|Tail]) ->
  972. case stream_te(OutState, lists:keyfind(StreamID, #stream.id, Streams)) of
  973. trailers ->
  974. Transport:send(Socket, [
  975. <<"0\r\n">>,
  976. cow_http:headers(maps:to_list(Trailers)),
  977. <<"\r\n">>
  978. ]);
  979. no_trailers ->
  980. Transport:send(Socket, <<"0\r\n\r\n">>);
  981. not_chunked ->
  982. ok
  983. end,
  984. commands(State#state{out_state=done}, StreamID, Tail);
  985. %% Protocol takeover.
  986. commands(State0=#state{ref=Ref, parent=Parent, socket=Socket, transport=Transport,
  987. out_state=OutState, opts=Opts, children=Children}, StreamID,
  988. [{switch_protocol, Headers, Protocol, InitialState}|_Tail]) ->
  989. %% @todo This should be the last stream running otherwise we need to wait before switching.
  990. %% @todo If there's streams opened after this one, fail instead of 101.
  991. State = cancel_timeout(State0),
  992. %% Before we send the 101 response we need to stop receiving data
  993. %% from the socket, otherwise the data might be receive before the
  994. %% call to flush/0 and we end up inadvertently dropping a packet.
  995. %%
  996. %% @todo Handle cases where the request came with a body. We need
  997. %% to process or skip the body before the upgrade can be completed.
  998. Transport:setopts(Socket, [{active, false}]),
  999. %% Send a 101 response if necessary, then terminate the stream.
  1000. #state{streams=Streams} = case OutState of
  1001. wait -> info(State, StreamID, {inform, 101, Headers});
  1002. _ -> State
  1003. end,
  1004. #stream{state=StreamState} = lists:keyfind(StreamID, #stream.id, Streams),
  1005. %% @todo We need to shutdown processes here first.
  1006. stream_call_terminate(StreamID, switch_protocol, StreamState, State),
  1007. %% Terminate children processes and flush any remaining messages from the mailbox.
  1008. cowboy_children:terminate(Children),
  1009. flush(Parent),
  1010. %% @todo This is no good because commands return a state normally and here it doesn't
  1011. %% we need to let this module go entirely. Perhaps it should be handled directly in
  1012. %% cowboy_clear/cowboy_tls?
  1013. Protocol:takeover(Parent, Ref, Socket, Transport, Opts, <<>>, InitialState);
  1014. %% Stream shutdown.
  1015. commands(State, StreamID, [stop|Tail]) ->
  1016. %% @todo Do we want to run the commands after a stop?
  1017. %% @todo We currently wait for the stop command before we
  1018. %% continue with the next request/response. In theory, if
  1019. %% the request body was read fully and the response body
  1020. %% was sent fully we should be able to start working on
  1021. %% the next request concurrently. This can be done as a
  1022. %% future optimization.
  1023. maybe_terminate(State, StreamID, Tail);
  1024. %% Log event.
  1025. commands(State=#state{opts=Opts}, StreamID, [Log={log, _, _, _}|Tail]) ->
  1026. cowboy:log(Log, Opts),
  1027. commands(State, StreamID, Tail);
  1028. %% HTTP/1.1 does not support push; ignore.
  1029. commands(State, StreamID, [{push, _, _, _, _, _, _, _}|Tail]) ->
  1030. commands(State, StreamID, Tail).
  1031. %% The set-cookie header is special; we can only send one cookie per header.
  1032. headers_to_list(Headers0=#{<<"set-cookie">> := SetCookies}) ->
  1033. Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  1034. Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies];
  1035. headers_to_list(Headers) ->
  1036. maps:to_list(Headers).
  1037. %% We wrap the sendfile call into a try/catch because on OTP-20
  1038. %% and earlier a few different crashes could occur for sockets
  1039. %% that were closing or closed. For example a badarg in
  1040. %% erlang:port_get_data(#Port<...>) or a badmatch like
  1041. %% {{badmatch,{error,einval}},[{prim_file,sendfile,8,[]}...
  1042. %%
  1043. %% OTP-21 uses a NIF instead of a port so the implementation
  1044. %% and behavior has dramatically changed and it is unclear
  1045. %% whether it will be necessary in the future.
  1046. %%
  1047. %% This try/catch prevents some noisy logs to be written
  1048. %% when these errors occur.
  1049. sendfile(State=#state{socket=Socket, transport=Transport, opts=Opts},
  1050. {sendfile, Offset, Bytes, Path}) ->
  1051. try
  1052. %% When sendfile is disabled we explicitly use the fallback.
  1053. _ = case maps:get(sendfile, Opts, true) of
  1054. true -> Transport:sendfile(Socket, Path, Offset, Bytes);
  1055. false -> ranch_transport:sendfile(Transport, Socket, Path, Offset, Bytes, [])
  1056. end,
  1057. ok
  1058. catch _:_ ->
  1059. terminate(State, {socket_error, sendfile_crash,
  1060. 'An error occurred when using the sendfile function.'})
  1061. end.
  1062. %% Flush messages specific to cowboy_http before handing over the
  1063. %% connection to another protocol.
  1064. flush(Parent) ->
  1065. receive
  1066. {timeout, _, _} ->
  1067. flush(Parent);
  1068. {{Pid, _}, _} when Pid =:= self() ->
  1069. flush(Parent);
  1070. {'EXIT', Pid, _} when Pid =/= Parent ->
  1071. flush(Parent)
  1072. after 0 ->
  1073. ok
  1074. end.
  1075. %% @todo In these cases I'm not sure if we should continue processing commands.
  1076. maybe_terminate(State=#state{last_streamid=StreamID}, StreamID, _Tail) ->
  1077. terminate(stream_terminate(State, StreamID, normal), normal); %% @todo Reason ok?
  1078. maybe_terminate(State, StreamID, _Tail) ->
  1079. stream_terminate(State, StreamID, normal).
  1080. stream_reset(State, StreamID, StreamError={internal_error, _, _}) ->
  1081. %% @todo headers
  1082. %% @todo Don't send this if there are no streams left.
  1083. % Transport:send(Socket, cow_http:response(500, 'HTTP/1.1', [
  1084. % {<<"content-length">>, <<"0">>}
  1085. % ])),
  1086. %% @todo update IsFin local
  1087. % stream_terminate(State#state{out_state=done}, StreamID, StreamError).
  1088. stream_terminate(State, StreamID, StreamError).
  1089. stream_terminate(State0=#state{opts=Opts, in_streamid=InStreamID, in_state=InState,
  1090. out_streamid=OutStreamID, out_state=OutState, streams=Streams0,
  1091. children=Children0}, StreamID, Reason) ->
  1092. #stream{version=Version, local_expected_size=ExpectedSize, local_sent_size=SentSize}
  1093. = lists:keyfind(StreamID, #stream.id, Streams0),
  1094. State1 = #state{streams=Streams1} = case OutState of
  1095. wait when element(1, Reason) =:= internal_error ->
  1096. info(State0, StreamID, {response, 500, #{<<"content-length">> => <<"0">>}, <<>>});
  1097. wait when element(1, Reason) =:= connection_error ->
  1098. info(State0, StreamID, {response, 400, #{<<"content-length">> => <<"0">>}, <<>>});
  1099. wait ->
  1100. info(State0, StreamID, {response, 204, #{}, <<>>});
  1101. chunked when Version =:= 'HTTP/1.1' ->
  1102. info(State0, StreamID, {data, fin, <<>>});
  1103. streaming when ExpectedSize < SentSize ->
  1104. terminate(State0, response_body_too_small);
  1105. _ -> %% done or Version =:= 'HTTP/1.0'
  1106. State0
  1107. end,
  1108. %% Remove the stream from the state.
  1109. {value, #stream{state=StreamState}, Streams}
  1110. = lists:keytake(StreamID, #stream.id, Streams1),
  1111. State2 = State1#state{streams=Streams},
  1112. %% Stop the stream.
  1113. stream_call_terminate(StreamID, Reason, StreamState, State2),
  1114. Children = cowboy_children:shutdown(Children0, StreamID),
  1115. %% We reset the timeout if there are no active streams anymore.
  1116. State = case Streams of
  1117. [] -> set_timeout(State2);
  1118. _ -> State2
  1119. end,
  1120. %% We want to drop the connection if the body was not read fully
  1121. %% and we don't know its length or more remains to be read than
  1122. %% configuration allows.
  1123. %% @todo Only do this if Current =:= StreamID.
  1124. MaxSkipBodyLength = maps:get(max_skip_body_length, Opts, 1000000),
  1125. case InState of
  1126. #ps_body{length=undefined}
  1127. when InStreamID =:= OutStreamID ->
  1128. terminate(State#state{streams=Streams, children=Children}, skip_body_unknown_length);
  1129. #ps_body{length=Len, received=Received}
  1130. when InStreamID =:= OutStreamID, Received + MaxSkipBodyLength < Len ->
  1131. terminate(State#state{streams=Streams, children=Children}, skip_body_too_large);
  1132. _ ->
  1133. %% Move on to the next stream.
  1134. NextOutStreamID = OutStreamID + 1,
  1135. case lists:keyfind(NextOutStreamID, #stream.id, Streams) of
  1136. false ->
  1137. %% @todo This is clearly wrong, if the stream is gone we need to check if
  1138. %% there used to be such a stream, and if there was to send an error.
  1139. State#state{out_streamid=NextOutStreamID, out_state=wait,
  1140. streams=Streams, children=Children};
  1141. #stream{queue=Commands} ->
  1142. %% @todo Remove queue from the stream.
  1143. commands(State#state{out_streamid=NextOutStreamID, out_state=wait,
  1144. streams=Streams, children=Children}, NextOutStreamID, Commands)
  1145. end
  1146. end.
  1147. stream_call_terminate(StreamID, Reason, StreamState, #state{opts=Opts}) ->
  1148. try
  1149. cowboy_stream:terminate(StreamID, Reason, StreamState)
  1150. catch Class:Exception ->
  1151. cowboy:log(cowboy_stream:make_error_log(terminate,
  1152. [StreamID, Reason, StreamState],
  1153. Class, Exception, erlang:get_stacktrace()), Opts)
  1154. end.
  1155. maybe_req_close(#state{opts=#{http10_keepalive := false}}, _, 'HTTP/1.0') ->
  1156. close;
  1157. maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.0') ->
  1158. Conns = cow_http_hd:parse_connection(Conn),
  1159. case lists:member(<<"keep-alive">>, Conns) of
  1160. true -> keepalive;
  1161. false -> close
  1162. end;
  1163. maybe_req_close(_, _, 'HTTP/1.0') ->
  1164. close;
  1165. maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.1') ->
  1166. case connection_hd_is_close(Conn) of
  1167. true -> close;
  1168. false -> keepalive
  1169. end;
  1170. maybe_req_close(_, _, _) ->
  1171. keepalive.
  1172. connection(State=#state{last_streamid=StreamID}, Headers=#{<<"connection">> := Conn}, StreamID, _) ->
  1173. case connection_hd_is_close(Conn) of
  1174. true -> {State, Headers};
  1175. %% @todo Here we need to remove keep-alive and add close, not just add close.
  1176. false -> {State, Headers#{<<"connection">> => [<<"close, ">>, Conn]}}
  1177. end;
  1178. connection(State=#state{last_streamid=StreamID}, Headers, StreamID, _) ->
  1179. {State, Headers#{<<"connection">> => <<"close">>}};
  1180. connection(State, Headers=#{<<"connection">> := Conn}, StreamID, _) ->
  1181. case connection_hd_is_close(Conn) of
  1182. true -> {State#state{last_streamid=StreamID}, Headers};
  1183. %% @todo Here we need to set keep-alive only if it wasn't set before.
  1184. false -> {State, Headers}
  1185. end;
  1186. connection(State, Headers, _, 'HTTP/1.0') ->
  1187. {State, Headers#{<<"connection">> => <<"keep-alive">>}};
  1188. connection(State, Headers, _, _) ->
  1189. {State, Headers}.
  1190. connection_hd_is_close(Conn) ->
  1191. Conns = cow_http_hd:parse_connection(iolist_to_binary(Conn)),
  1192. lists:member(<<"close">>, Conns).
  1193. stream_te(streaming, _) ->
  1194. not_chunked;
  1195. %% No TE header was sent.
  1196. stream_te(_, #stream{te=undefined}) ->
  1197. no_trailers;
  1198. stream_te(_, #stream{te=TE0}) ->
  1199. try cow_http_hd:parse_te(TE0) of
  1200. {TE1, _} -> TE1
  1201. catch _:_ ->
  1202. %% If we can't parse the TE header, assume we can't send trailers.
  1203. no_trailers
  1204. end.
  1205. %% This function is only called when an error occurs on a new stream.
  1206. -spec error_terminate(cowboy:http_status(), #state{}, _) -> no_return().
  1207. error_terminate(StatusCode, State=#state{ref=Ref, peer=Peer, in_state=StreamState}, Reason) ->
  1208. PartialReq = case StreamState of
  1209. #ps_request_line{} -> #{
  1210. ref => Ref,
  1211. peer => Peer
  1212. };
  1213. #ps_header{method=Method, path=Path, qs=Qs,
  1214. version=Version, headers=ReqHeaders} -> #{
  1215. ref => Ref,
  1216. peer => Peer,
  1217. method => Method,
  1218. path => Path,
  1219. qs => Qs,
  1220. version => Version,
  1221. headers => case ReqHeaders of
  1222. undefined -> #{};
  1223. _ -> ReqHeaders
  1224. end
  1225. }
  1226. end,
  1227. early_error(StatusCode, State, Reason, PartialReq, #{<<"connection">> => <<"close">>}),
  1228. terminate(State, Reason).
  1229. early_error(StatusCode, State, Reason, PartialReq) ->
  1230. early_error(StatusCode, State, Reason, PartialReq, #{}).
  1231. early_error(StatusCode0, #state{socket=Socket, transport=Transport,
  1232. opts=Opts, in_streamid=StreamID}, Reason, PartialReq, RespHeaders0) ->
  1233. RespHeaders1 = RespHeaders0#{<<"content-length">> => <<"0">>},
  1234. Resp = {response, StatusCode0, RespHeaders1, <<>>},
  1235. try cowboy_stream:early_error(StreamID, Reason, PartialReq, Resp, Opts) of
  1236. {response, StatusCode, RespHeaders, RespBody} ->
  1237. Transport:send(Socket, [
  1238. cow_http:response(StatusCode, 'HTTP/1.1', maps:to_list(RespHeaders)),
  1239. %% @todo We shouldn't send the body when the method is HEAD.
  1240. %% @todo Technically we allow the sendfile tuple.
  1241. RespBody
  1242. ])
  1243. catch Class:Exception ->
  1244. cowboy:log(cowboy_stream:make_error_log(early_error,
  1245. [StreamID, Reason, PartialReq, Resp, Opts],
  1246. Class, Exception, erlang:get_stacktrace()), Opts),
  1247. %% We still need to send an error response, so send what we initially
  1248. %% wanted to send. It's better than nothing.
  1249. Transport:send(Socket, cow_http:response(StatusCode0,
  1250. 'HTTP/1.1', maps:to_list(RespHeaders1)))
  1251. end,
  1252. ok.
  1253. -spec terminate(_, _) -> no_return().
  1254. terminate(undefined, Reason) ->
  1255. exit({shutdown, Reason});
  1256. terminate(State=#state{streams=Streams, children=Children}, Reason) ->
  1257. terminate_all_streams(State, Streams, Reason),
  1258. cowboy_children:terminate(Children),
  1259. terminate_linger(State),
  1260. exit({shutdown, Reason}).
  1261. terminate_all_streams(_, [], _) ->
  1262. ok;
  1263. terminate_all_streams(State, [#stream{id=StreamID, state=StreamState}|Tail], Reason) ->
  1264. stream_call_terminate(StreamID, Reason, StreamState, State),
  1265. terminate_all_streams(State, Tail, Reason).
  1266. terminate_linger(State=#state{socket=Socket, transport=Transport, opts=Opts}) ->
  1267. case Transport:shutdown(Socket, write) of
  1268. ok ->
  1269. case maps:get(linger_timeout, Opts, 1000) of
  1270. 0 ->
  1271. ok;
  1272. infinity ->
  1273. terminate_linger_loop(State, undefined);
  1274. Timeout ->
  1275. TimerRef = erlang:start_timer(Timeout, self(), linger_timeout),
  1276. terminate_linger_loop(State, TimerRef)
  1277. end;
  1278. {error, _} ->
  1279. ok
  1280. end.
  1281. terminate_linger_loop(State=#state{socket=Socket, transport=Transport}, TimerRef) ->
  1282. {OK, Closed, Error} = Transport:messages(),
  1283. %% We may already have a message in the mailbox when we do this
  1284. %% but it's OK because we are shutting down anyway.
  1285. case Transport:setopts(Socket, [{active, once}]) of
  1286. ok ->
  1287. receive
  1288. {OK, Socket, _} ->
  1289. terminate_linger_loop(State, TimerRef);
  1290. {Closed, Socket} ->
  1291. ok;
  1292. {Error, Socket, _} ->
  1293. ok;
  1294. {timeout, TimerRef, linger_timeout} ->
  1295. ok;
  1296. _ ->
  1297. terminate_linger_loop(State, TimerRef)
  1298. end;
  1299. {error, _} ->
  1300. ok
  1301. end.
  1302. %% System callbacks.
  1303. -spec system_continue(_, _, {#state{}, binary()}) -> ok.
  1304. system_continue(_, _, {State, Buffer}) ->
  1305. loop(State, Buffer).
  1306. -spec system_terminate(any(), _, _, {#state{}, binary()}) -> no_return().
  1307. system_terminate(Reason, _, _, {State, _}) ->
  1308. terminate(State, {stop, {exit, Reason}, 'sys:terminate/2,3 was called.'}).
  1309. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  1310. system_code_change(Misc, _, _, _) ->
  1311. {ok, Misc}.