cowboy_http.erl 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. %% Copyright (c) 2016, 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. -export([init/6]).
  16. -export([system_continue/3]).
  17. -export([system_terminate/4]).
  18. -export([system_code_change/4]).
  19. %% @todo map
  20. -type opts() :: [{compress, boolean()}
  21. | {env, cowboy_middleware:env()}
  22. | {max_empty_lines, non_neg_integer()}
  23. | {max_header_name_length, non_neg_integer()}
  24. | {max_header_value_length, non_neg_integer()}
  25. | {max_headers, non_neg_integer()}
  26. | {max_keepalive, non_neg_integer()}
  27. | {max_request_line_length, non_neg_integer()}
  28. | {middlewares, [module()]}
  29. | {onresponse, cowboy:onresponse_fun()}
  30. | {timeout, timeout()}].
  31. -export_type([opts/0]).
  32. -record(ps_request_line, {
  33. empty_lines = 0 :: non_neg_integer()
  34. }).
  35. -record(ps_header, {
  36. method = undefined :: binary(),
  37. path = undefined :: binary(),
  38. qs = undefined :: binary(),
  39. version = undefined :: cowboy:http_version(),
  40. headers = undefined :: map() | undefined, %% @todo better type than map()
  41. name = undefined :: binary()
  42. }).
  43. %% @todo We need a state where we wait for the stream process to ask for the body.
  44. %% OR DO WE
  45. %% In HTTP/2 we start receiving data before the body asks for it, even if optionally
  46. %% (and by default), so we need to be able to do the same for HTTP/1.1 too. This means
  47. %% that when we receive data (up to a certain limit, we read from the socket and decode.
  48. %% When we reach a limit, we stop reading from the socket momentarily until the stream
  49. %% process asks for more or the stream ends.
  50. %% This means that we need to keep a buffer in the stream handler (until the stream
  51. %% process asks for it). And that we need the body state to indicate how much we have
  52. %% left to read (and stop/start reading from the socket depending on value).
  53. -record(ps_body, {
  54. %% @todo flow
  55. transfer_decode_fun :: fun(), %% @todo better type
  56. transfer_decode_state :: any() %% @todo better type
  57. }).
  58. -record(stream, {
  59. %% Stream identifier.
  60. id = undefined :: cowboy_stream:streamid(),
  61. %% Stream handler state.
  62. state = undefined :: any(),
  63. %% Client HTTP version for this stream.
  64. version = undefined :: cowboy:http_version(),
  65. %% Commands queued.
  66. queue = [] :: [] %% @todo better type
  67. }).
  68. -type stream() :: #stream{}.
  69. -record(state, {
  70. parent :: pid(),
  71. ref :: ranch:ref(),
  72. socket :: inet:socket(),
  73. transport :: module(),
  74. opts = #{} :: map(),
  75. handler :: module(),
  76. %% Remote address and port for the connection.
  77. peer = undefined :: {inet:ip_address(), inet:port_number()},
  78. timer = undefined :: undefined | reference(),
  79. %% Identifier for the stream currently being read (or waiting to be received).
  80. in_streamid = 1 :: pos_integer(),
  81. %% Parsing state for the current stream or stream-to-be.
  82. in_state = #ps_request_line{} :: #ps_request_line{} | #ps_header{} | #ps_body{},
  83. %% Identifier for the stream currently being written.
  84. %% Note that out_streamid =< in_streamid.
  85. out_streamid = 1 :: pos_integer(),
  86. %% Whether we finished writing data for the current stream.
  87. out_state = wait :: wait | headers | chunked,
  88. %% The connection will be closed after this stream.
  89. last_streamid = undefined :: pos_integer(),
  90. %% Currently active HTTP/1.1 streams.
  91. streams = [] :: [stream()],
  92. %% Children which are in the process of shutting down.
  93. children = [] :: [{pid(), cowboy_stream:streamid(), timeout()}]
  94. %% @todo Automatic compression. (compress option?)
  95. %% @todo onresponse? Equivalent using streams.
  96. }).
  97. -include_lib("cowlib/include/cow_inline.hrl").
  98. -include_lib("cowlib/include/cow_parse.hrl").
  99. -spec init(pid(), ranch:ref(), inet:socket(), module(), cowboy:opts(), module()) -> ok.
  100. init(Parent, Ref, Socket, Transport, Opts, Handler) ->
  101. case Transport:peername(Socket) of
  102. {ok, Peer} ->
  103. LastStreamID = maps:get(max_keepalive, Opts, 100),
  104. before_loop(set_request_timeout(#state{
  105. parent=Parent, ref=Ref, socket=Socket,
  106. transport=Transport, opts=Opts, handler=Handler,
  107. peer=Peer, last_streamid=LastStreamID}), <<>>);
  108. {error, Reason} ->
  109. %% Couldn't read the peer address; connection is gone.
  110. terminate(undefined, {socket_error, Reason, 'An error has occurred on the socket.'})
  111. end.
  112. %% @todo Send a response depending on in_state and whether one was already sent.
  113. %% @todo
  114. %% Timeouts:
  115. %% - waiting for new request (if no stream is currently running)
  116. %% -> request_timeout: for whole request/headers, set at init/when we set ps_request_line{} state
  117. %% - waiting for body (if a stream requested the body to be read)
  118. %% -> read_body_timeout: amount of time we wait without receiving any data when reading the body
  119. %% - if we skip the body, skip only for a specific duration
  120. %% -> skip_body_timeout: also have a skip_body_length
  121. %% - none if we have a stream running and it didn't request the body to be read
  122. %% - global
  123. %% -> inactivity_timeout: max time to wait without anything happening before giving up
  124. before_loop(State=#state{socket=Socket, transport=Transport}, Buffer) ->
  125. %% @todo disable this when we get to the body, until the stream asks for it?
  126. %% Perhaps have a threshold for how much we're willing to read before waiting.
  127. Transport:setopts(Socket, [{active, once}]),
  128. loop(State, Buffer).
  129. loop(State=#state{parent=Parent, socket=Socket, transport=Transport,
  130. handler=_Handler, timer=TimerRef, children=Children}, Buffer) ->
  131. {OK, Closed, Error} = Transport:messages(),
  132. receive
  133. %% Socket messages.
  134. {OK, Socket, Data} ->
  135. parse(<< Buffer/binary, Data/binary >>, State);
  136. {Closed, Socket} ->
  137. terminate(State, {socket_error, closed, 'The socket has been closed.'});
  138. {Error, Socket, Reason} ->
  139. terminate(State, {socket_error, Reason, 'An error has occurred on the socket.'});
  140. %% Timeouts.
  141. {timeout, TimerRef, Reason} ->
  142. timeout(State, Reason);
  143. {timeout, _, _} ->
  144. loop(State, Buffer);
  145. %% System messages.
  146. {'EXIT', Parent, Reason} ->
  147. exit(Reason);
  148. {system, From, Request} ->
  149. sys:handle_system_msg(Request, From, Parent, ?MODULE, [], {State, Buffer});
  150. %% Messages pertaining to a stream.
  151. {{Pid, StreamID}, Msg} when Pid =:= self() ->
  152. loop(info(State, StreamID, Msg), Buffer);
  153. %% Exit signal from children.
  154. Msg = {'EXIT', Pid, _} ->
  155. loop(down(State, Pid, Msg), Buffer);
  156. %% Calls from supervisor module.
  157. {'$gen_call', {From, Tag}, which_children} ->
  158. Workers = [{?MODULE, Pid, worker, [?MODULE]} || {Pid, _, _} <- Children],
  159. From ! {Tag, Workers},
  160. loop(State, Buffer);
  161. {'$gen_call', {From, Tag}, count_children} ->
  162. NbChildren = length(Children),
  163. Counts = [{specs, 1}, {active, NbChildren},
  164. {supervisors, 0}, {workers, NbChildren}],
  165. From ! {Tag, Counts},
  166. loop(State, Buffer);
  167. {'$gen_call', {From, Tag}, _} ->
  168. From ! {Tag, {error, ?MODULE}},
  169. loop(State, Buffer);
  170. %% Unknown messages.
  171. Msg ->
  172. error_logger:error_msg("Received stray message ~p.~n", [Msg]),
  173. loop(State, Buffer)
  174. %% @todo Configurable timeout. This should be a global inactivity timeout
  175. %% that triggers when really nothing happens (ie something went really wrong).
  176. after 300000 ->
  177. terminate(State, {internal_error, timeout, 'No message or data received before timeout.'})
  178. end.
  179. set_request_timeout(State0=#state{opts=Opts}) ->
  180. State = cancel_request_timeout(State0),
  181. Timeout = maps:get(request_timeout, Opts, 5000),
  182. TimerRef = erlang:start_timer(Timeout, self(), request_timeout),
  183. State#state{timer=TimerRef}.
  184. cancel_request_timeout(State=#state{timer=TimerRef}) ->
  185. ok = case TimerRef of
  186. undefined -> ok;
  187. _ -> erlang:cancel_timer(TimerRef, [{async, true}, {info, false}])
  188. end,
  189. State#state{timer=undefined}.
  190. %% @todo Honestly it would be much better if we didn't enable pipelining yet.
  191. timeout(State=#state{in_state=#ps_request_line{}}, request_timeout) ->
  192. %% @todo If other streams are running, just set the connection to be closed
  193. %% and stop trying to read from the socket?
  194. terminate(State, {connection_error, timeout, 'No request-line received before timeout.'});
  195. timeout(State=#state{socket=Socket, transport=Transport, in_state=#ps_header{}}, request_timeout) ->
  196. %% @todo If other streams are running, maybe wait for their reply before sending 408?
  197. %% -> Definitely. Either way, stop reading from the socket and make that stream the last.
  198. Transport:send(Socket, cow_http:response(408, 'HTTP/1.1', [])),
  199. terminate(State, {connection_error, timeout, 'Request headers not received before timeout.'}).
  200. %% Request-line.
  201. parse(<<>>, State) ->
  202. before_loop(State, <<>>);
  203. parse(Buffer, State=#state{in_state=#ps_request_line{empty_lines=EmptyLines}}) ->
  204. after_parse(parse_request(Buffer, State, EmptyLines));
  205. parse(Buffer, State=#state{in_state=PS=#ps_header{headers=Headers, name=undefined}}) ->
  206. after_parse(parse_header(Buffer,
  207. State#state{in_state=PS#ps_header{headers=undefined}},
  208. Headers));
  209. parse(Buffer, State=#state{in_state=PS=#ps_header{headers=Headers, name=Name}}) ->
  210. after_parse(parse_hd_before_value(Buffer,
  211. State#state{in_state=PS#ps_header{headers=undefined, name=undefined}},
  212. Headers, Name));
  213. parse(Buffer, State=#state{in_state=#ps_body{}}) ->
  214. %% @todo We do not want to get the body automatically if the request doesn't ask for it.
  215. %% We may want to get bodies that are below a threshold without waiting, and buffer them
  216. %% until the request asks, though.
  217. %% @todo Transfer-decoding must be done here.
  218. after_parse(parse_body(Buffer, State)).
  219. %% @todo Don't parse if body is finished but request isn't. Let's not parallelize for now.
  220. after_parse({request, Req=#{streamid := StreamID, headers := Headers, version := Version},
  221. State0=#state{handler=Handler, opts=Opts, streams=Streams0}, Buffer}) ->
  222. %% @todo Opts at the end. Maybe pass the same Opts we got?
  223. try Handler:init(StreamID, Req, Opts) of
  224. {Commands, StreamState} ->
  225. Streams = [#stream{id=StreamID, state=StreamState, version=Version}|Streams0],
  226. State = case maybe_req_close(State0, Headers, Version) of
  227. close -> State0#state{streams=Streams, last_streamid=StreamID};
  228. keepalive -> State0#state{streams=Streams}
  229. end,
  230. parse(Buffer, commands(State, StreamID, Commands))
  231. catch Class:Reason ->
  232. error_logger:error_msg("Exception occurred in ~s:init(~p, ~p, ~p) "
  233. "with reason ~p:~p.",
  234. [Handler, StreamID, Req, Opts, Class, Reason]),
  235. ok
  236. %% @todo Status code.
  237. % stream_reset(State, StreamID, {internal_error, {Class, Reason},
  238. % 'Exception occurred in StreamHandler:init/10 call.'}) %% @todo Check final arity.
  239. end;
  240. %% Streams are sequential so the body is always about the last stream created
  241. %% unless that stream has terminated.
  242. after_parse({data, StreamID, IsFin, Data, State=#state{handler=Handler,
  243. streams=Streams0=[Stream=#stream{id=StreamID, state=StreamState0}|_]}, Buffer}) ->
  244. try Handler:data(StreamID, IsFin, Data, StreamState0) of
  245. {Commands, StreamState} ->
  246. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  247. Stream#stream{state=StreamState}),
  248. parse(Buffer, commands(State#state{streams=Streams}, StreamID, Commands))
  249. catch Class:Reason ->
  250. error_logger:error_msg("Exception occurred in ~s:data(~p, ~p, ~p, ~p) with reason ~p:~p.",
  251. [Handler, StreamID, IsFin, Data, StreamState0, Class, Reason]),
  252. ok
  253. %% @todo
  254. % stream_reset(State, StreamID, {internal_error, {Class, Reason},
  255. % 'Exception occurred in StreamHandler:data/4 call.'})
  256. end;
  257. %% No corresponding stream, skip.
  258. after_parse({data, _, _, _, State, Buffer}) ->
  259. before_loop(State, Buffer);
  260. after_parse({more, State, Buffer}) ->
  261. before_loop(State, Buffer).
  262. %% Request-line.
  263. -spec parse_request(binary(), #state{}, non_neg_integer()) -> ok.
  264. %% Empty lines must be using \r\n.
  265. parse_request(<< $\n, _/bits >>, State, _) ->
  266. error_terminate(400, State, {connection_error, protocol_error,
  267. ''}); %% @todo
  268. parse_request(<< $\s, _/bits >>, State, _) ->
  269. error_terminate(400, State, {connection_error, protocol_error,
  270. ''}); %% @todo
  271. %% We limit the length of the Request-line to MaxLength to avoid endlessly
  272. %% reading from the socket and eventually crashing.
  273. parse_request(Buffer, State=#state{opts=Opts, in_streamid=InStreamID}, EmptyLines) ->
  274. MaxLength = maps:get(max_request_line_length, Opts, 8000),
  275. MaxEmptyLines = maps:get(max_empty_lines, Opts, 5),
  276. case match_eol(Buffer, 0) of
  277. nomatch when byte_size(Buffer) > MaxLength ->
  278. error_terminate(414, State, {connection_error, limit_reached,
  279. ''}); %% @todo
  280. nomatch ->
  281. {more, State#state{in_state=#ps_request_line{empty_lines=EmptyLines}}, Buffer};
  282. 1 when EmptyLines =:= MaxEmptyLines ->
  283. error_terminate(400, State, {connection_error, limit_reached,
  284. ''}); %% @todo
  285. 1 ->
  286. << _:16, Rest/bits >> = Buffer,
  287. parse_request(Rest, State, EmptyLines + 1);
  288. _ ->
  289. case Buffer of
  290. %% @todo * is only for server-wide OPTIONS request (RFC7230 5.3.4); tests
  291. << "OPTIONS * ", Rest/bits >> ->
  292. parse_version(Rest, State, <<"OPTIONS">>, <<"*">>, <<>>);
  293. % << "CONNECT ", Rest/bits >> ->
  294. % parse_authority( %% @todo
  295. %% Accept direct HTTP/2 only at the beginning of the connection.
  296. << "PRI * HTTP/2.0\r\n", _/bits >> when InStreamID =:= 1 ->
  297. %% @todo Might be worth throwing to get a clean stacktrace.
  298. http2_upgrade(State, Buffer);
  299. _ ->
  300. parse_method(Buffer, State, <<>>,
  301. maps:get(max_method_length, Opts, 32))
  302. end
  303. end.
  304. match_eol(<< $\n, _/bits >>, N) ->
  305. N;
  306. match_eol(<< _, Rest/bits >>, N) ->
  307. match_eol(Rest, N + 1);
  308. match_eol(_, _) ->
  309. nomatch.
  310. parse_method(_, State, _, 0) ->
  311. error_terminate(501, State, {connection_error, limit_reached,
  312. 'The method name is longer than configuration allows. (RFC7230 3.1.1)'});
  313. parse_method(<< C, Rest/bits >>, State, SoFar, Remaining) ->
  314. case C of
  315. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  316. ''}); %% @todo
  317. $\s -> parse_uri(Rest, State, SoFar);
  318. _ when ?IS_TOKEN(C) -> parse_method(Rest, State, << SoFar/binary, C >>, Remaining - 1);
  319. _ -> error_terminate(400, State, {connection_error, protocol_error,
  320. 'The method name must contain only valid token characters. (RFC7230 3.1.1)'})
  321. end.
  322. parse_uri(<< H, T, T, P, "://", Rest/bits >>, State, Method)
  323. when H =:= $h orelse H =:= $H, T =:= $t orelse T =:= $T;
  324. P =:= $p orelse P =:= $P ->
  325. parse_uri_skip_host(Rest, State, Method);
  326. parse_uri(<< H, T, T, P, S, "://", Rest/bits >>, State, Method)
  327. when H =:= $h orelse H =:= $H, T =:= $t orelse T =:= $T;
  328. P =:= $p orelse P =:= $P; S =:= $s orelse S =:= $S ->
  329. parse_uri_skip_host(Rest, State, Method);
  330. parse_uri(<< $/, Rest/bits >>, State, Method) ->
  331. parse_uri_path(Rest, State, Method, << $/ >>);
  332. parse_uri(_, State, _) ->
  333. error_terminate(400, State, {connection_error, protocol_error,
  334. 'Invalid request-line or request-target. (RFC7230 3.1.1, RFC7230 5.3)'}).
  335. parse_uri_skip_host(<< C, Rest/bits >>, State, Method) ->
  336. case C of
  337. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  338. ''}); %% @todo
  339. $/ -> parse_uri_path(Rest, State, Method, <<"/">>);
  340. $\s -> parse_version(Rest, State, Method, <<"/">>, <<>>);
  341. $? -> parse_uri_query(Rest, State, Method, <<"/">>, <<>>);
  342. $# -> skip_uri_fragment(Rest, State, Method, <<"/">>, <<>>);
  343. _ -> parse_uri_skip_host(Rest, State, Method)
  344. end.
  345. parse_uri_path(<< C, Rest/bits >>, State, Method, SoFar) ->
  346. case C of
  347. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  348. ''}); %% @todo
  349. $\s -> parse_version(Rest, State, Method, SoFar, <<>>);
  350. $? -> parse_uri_query(Rest, State, Method, SoFar, <<>>);
  351. $# -> skip_uri_fragment(Rest, State, Method, SoFar, <<>>);
  352. _ -> parse_uri_path(Rest, State, Method, << SoFar/binary, C >>)
  353. end.
  354. parse_uri_query(<< C, Rest/bits >>, State, M, P, SoFar) ->
  355. case C of
  356. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  357. ''}); %% @todo
  358. $\s -> parse_version(Rest, State, M, P, SoFar);
  359. $# -> skip_uri_fragment(Rest, State, M, P, SoFar);
  360. _ -> parse_uri_query(Rest, State, M, P, << SoFar/binary, C >>)
  361. end.
  362. skip_uri_fragment(<< C, Rest/bits >>, State, M, P, Q) ->
  363. case C of
  364. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  365. ''}); %% @todo
  366. $\s -> parse_version(Rest, State, M, P, Q);
  367. _ -> skip_uri_fragment(Rest, State, M, P, Q)
  368. end.
  369. %% @todo Calls to parse_header should update the state.
  370. parse_version(<< "HTTP/1.1\r\n", Rest/bits >>, State, M, P, Q) ->
  371. parse_headers(Rest, State, M, P, Q, 'HTTP/1.1');
  372. parse_version(<< "HTTP/1.0\r\n", Rest/bits >>, State, M, P, Q) ->
  373. parse_headers(Rest, State, M, P, Q, 'HTTP/1.0');
  374. parse_version(<< "HTTP/1.", _, C, _/bits >>, State, _, _, _) when C =:= $\s; C =:= $\t ->
  375. error_terminate(400, State, {connection_error, protocol_error,
  376. 'Whitespace is not allowed after the HTTP version. (RFC7230 3.1.1)'});
  377. parse_version(<< C, _/bits >>, State, _, _, _) when C =:= $\s; C =:= $\t ->
  378. error_terminate(400, State, {connection_error, protocol_error,
  379. 'The separator between request target and version must be a single SP.'});
  380. parse_version(_, State, _, _, _) ->
  381. error_terminate(505, State, {connection_error, protocol_error,
  382. ''}). %% @todo
  383. parse_headers(Rest, State, M, P, Q, V) ->
  384. %% @todo Figure out the parse states.
  385. parse_header(Rest, State#state{in_state=#ps_header{
  386. method=M, path=P, qs=Q, version=V}}, #{}).
  387. %% Headers.
  388. %% We need two or more bytes in the buffer to continue.
  389. parse_header(Rest, State=#state{in_state=PS}, Headers) when byte_size(Rest) < 2 ->
  390. {more, State#state{in_state=PS#ps_header{headers=Headers}}, Rest};
  391. parse_header(<< $\r, $\n, Rest/bits >>, S, Headers) ->
  392. request(Rest, S, Headers);
  393. parse_header(Buffer, State=#state{opts=Opts, in_state=PS}, Headers) ->
  394. MaxLength = maps:get(max_header_name_length, Opts, 64),
  395. MaxHeaders = maps:get(max_headers, Opts, 100),
  396. case match_colon(Buffer, 0) of
  397. nomatch when byte_size(Buffer) > MaxLength ->
  398. error_terminate(400, State, {connection_error, limit_reached,
  399. ''}); %% @todo
  400. nomatch when length(Headers) >= MaxHeaders ->
  401. error_terminate(400, State, {connection_error, limit_reached,
  402. ''}); %% @todo
  403. nomatch ->
  404. {more, State#state{in_state=PS#ps_header{headers=Headers}}, Buffer};
  405. _ ->
  406. parse_hd_name(Buffer, State, Headers, <<>>)
  407. end.
  408. match_colon(<< $:, _/bits >>, N) ->
  409. N;
  410. match_colon(<< _, Rest/bits >>, N) ->
  411. match_colon(Rest, N + 1);
  412. match_colon(_, _) ->
  413. nomatch.
  414. parse_hd_name(<< $:, Rest/bits >>, State, H, SoFar) ->
  415. parse_hd_before_value(Rest, State, H, SoFar);
  416. parse_hd_name(<< C, _/bits >>, State, _, <<>>) when ?IS_WS(C) ->
  417. error_terminate(400, State, {connection_error, protocol_error,
  418. ''}); %% @todo
  419. parse_hd_name(<< C, Rest/bits >>, State, H, SoFar) when ?IS_WS(C) ->
  420. parse_hd_name_ws(Rest, State, H, SoFar);
  421. parse_hd_name(<< C, Rest/bits >>, State, H, SoFar) ->
  422. ?LOWER(parse_hd_name, Rest, State, H, SoFar).
  423. parse_hd_name_ws(<< C, Rest/bits >>, S, H, Name) ->
  424. case C of
  425. $\s -> parse_hd_name_ws(Rest, S, H, Name);
  426. $\t -> parse_hd_name_ws(Rest, S, H, Name);
  427. $: -> parse_hd_before_value(Rest, S, H, Name)
  428. end.
  429. parse_hd_before_value(<< $\s, Rest/bits >>, S, H, N) ->
  430. parse_hd_before_value(Rest, S, H, N);
  431. parse_hd_before_value(<< $\t, Rest/bits >>, S, H, N) ->
  432. parse_hd_before_value(Rest, S, H, N);
  433. parse_hd_before_value(Buffer, State=#state{opts=Opts, in_state=PS}, H, N) ->
  434. MaxLength = maps:get(max_header_value_length, Opts, 4096),
  435. case match_eol(Buffer, 0) of
  436. nomatch when byte_size(Buffer) > MaxLength ->
  437. error_terminate(400, State, {connection_error, limit_reached,
  438. ''}); %% @todo
  439. nomatch ->
  440. {more, State#state{in_state=PS#ps_header{headers=H, name=N}}, Buffer};
  441. _ ->
  442. parse_hd_value(Buffer, State, H, N, <<>>)
  443. end.
  444. parse_hd_value(<< $\r, $\n, Rest/bits >>, S, Headers0, Name, SoFar) ->
  445. Value = clean_value_ws_end(SoFar, byte_size(SoFar) - 1),
  446. Headers = case maps:get(Name, Headers0, undefined) of
  447. undefined -> Headers0#{Name => Value};
  448. %% The cookie header does not use proper HTTP header lists.
  449. Value0 when Name =:= <<"cookie">> -> Headers0#{Name => << Value0/binary, "; ", Value/binary >>};
  450. Value0 -> Headers0#{Name => << Value0/binary, ", ", Value/binary >>}
  451. end,
  452. parse_header(Rest, S, Headers);
  453. parse_hd_value(<< C, Rest/bits >>, S, H, N, SoFar) ->
  454. parse_hd_value(Rest, S, H, N, << SoFar/binary, C >>).
  455. clean_value_ws_end(_, -1) ->
  456. <<>>;
  457. clean_value_ws_end(Value, N) ->
  458. case binary:at(Value, N) of
  459. $\s -> clean_value_ws_end(Value, N - 1);
  460. $\t -> clean_value_ws_end(Value, N - 1);
  461. _ ->
  462. S = N + 1,
  463. << Value2:S/binary, _/bits >> = Value,
  464. Value2
  465. end.
  466. -ifdef(TEST).
  467. clean_value_ws_end_test_() ->
  468. Tests = [
  469. {<<>>, <<>>},
  470. {<<" ">>, <<>>},
  471. {<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  472. "text/html;level=2;q=0.4, */*;q=0.5 \t \t ">>,
  473. <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  474. "text/html;level=2;q=0.4, */*;q=0.5">>}
  475. ],
  476. [{V, fun() -> R = clean_value_ws_end(V, byte_size(V) - 1) end} || {V, R} <- Tests].
  477. horse_clean_value_ws_end() ->
  478. horse:repeat(200000,
  479. clean_value_ws_end(
  480. <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  481. "text/html;level=2;q=0.4, */*;q=0.5 ">>,
  482. byte_size(<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  483. "text/html;level=2;q=0.4, */*;q=0.5 ">>) - 1)
  484. ).
  485. -endif.
  486. request(Buffer, State=#state{transport=Transport, in_streamid=StreamID,
  487. in_state=#ps_header{version=Version}}, Headers) ->
  488. case maps:get(<<"host">>, Headers, undefined) of
  489. undefined when Version =:= 'HTTP/1.1' ->
  490. %% @todo Might want to not close the connection on this and next one.
  491. error_terminate(400, State, {stream_error, StreamID, protocol_error,
  492. ''}); %% @todo
  493. undefined ->
  494. request(Buffer, State, Headers, <<>>, default_port(Transport:secure()));
  495. RawHost ->
  496. try parse_host(RawHost, false, <<>>) of
  497. {Host, undefined} ->
  498. request(Buffer, State, Headers, Host, default_port(Transport:secure()));
  499. {Host, Port} ->
  500. request(Buffer, State, Headers, Host, Port)
  501. catch _:_ ->
  502. error_terminate(400, State, {stream_error, StreamID, protocol_error,
  503. ''}) %% @todo
  504. end
  505. end.
  506. -spec default_port(boolean()) -> 80 | 443.
  507. default_port(true) -> 443;
  508. default_port(_) -> 80.
  509. %% @todo Yeah probably just call the cowlib function.
  510. %% Same code as cow_http:parse_fullhost/1, but inline because we
  511. %% really want this to go fast.
  512. parse_host(<< $[, Rest/bits >>, false, <<>>) ->
  513. parse_host(Rest, true, << $[ >>);
  514. parse_host(<<>>, false, Acc) ->
  515. {Acc, undefined};
  516. parse_host(<< $:, Rest/bits >>, false, Acc) ->
  517. {Acc, list_to_integer(binary_to_list(Rest))};
  518. parse_host(<< $], Rest/bits >>, true, Acc) ->
  519. parse_host(Rest, false, << Acc/binary, $] >>);
  520. parse_host(<< C, Rest/bits >>, E, Acc) ->
  521. ?LOWER(parse_host, Rest, E, Acc).
  522. %% End of request parsing.
  523. request(Buffer, State0=#state{ref=Ref, transport=Transport, peer=Peer, in_streamid=StreamID,
  524. in_state=#ps_header{method=Method, path=Path, qs=Qs, version=Version}},
  525. Headers, Host, Port) ->
  526. Scheme = case Transport:secure() of
  527. true -> <<"https">>;
  528. false -> <<"http">>
  529. end,
  530. {HasBody, BodyLength, TDecodeFun, TDecodeState} = case Headers of
  531. #{<<"content-length">> := <<"0">>} ->
  532. {false, 0, undefined, undefined};
  533. #{<<"content-length">> := BinLength} ->
  534. Length = try
  535. cow_http_hd:parse_content_length(BinLength)
  536. catch _:_ ->
  537. error_terminate(400, State0, {stream_error, StreamID, protocol_error,
  538. ''}) %% @todo
  539. %% @todo Err should terminate here...
  540. end,
  541. {true, Length, fun cow_http_te:stream_identity/2, {0, Length}};
  542. %% @todo Better handling of transfer decoding.
  543. #{<<"transfer-encoding">> := <<"chunked">>} ->
  544. {true, undefined, fun cow_http_te:stream_chunked/2, {0, 0}};
  545. _ ->
  546. {false, 0, undefined, undefined}
  547. end,
  548. Req = #{
  549. ref => Ref,
  550. pid => self(),
  551. streamid => StreamID,
  552. peer => Peer,
  553. method => Method,
  554. scheme => Scheme,
  555. host => Host,
  556. port => Port,
  557. path => Path,
  558. qs => Qs,
  559. version => Version,
  560. %% We are transparently taking care of transfer-encodings so
  561. %% the user code has no need to know about it.
  562. headers => maps:remove(<<"transfer-encoding">>, Headers),
  563. has_body => HasBody,
  564. body_length => BodyLength
  565. %% @todo multipart? keep state separate
  566. %% meta values (cowboy_websocket, cowboy_rest)
  567. },
  568. case is_http2_upgrade(Headers, Version) of
  569. false ->
  570. State = case HasBody of
  571. true ->
  572. cancel_request_timeout(State0#state{in_state=#ps_body{
  573. %% @todo Don't need length anymore?
  574. transfer_decode_fun = TDecodeFun,
  575. transfer_decode_state = TDecodeState
  576. }});
  577. false ->
  578. set_request_timeout(State0#state{in_streamid=StreamID + 1, in_state=#ps_request_line{}})
  579. end,
  580. {request, Req, State, Buffer};
  581. {true, HTTP2Settings} ->
  582. http2_upgrade(State0, Buffer, HTTP2Settings, Req)
  583. end.
  584. %% HTTP/2 upgrade.
  585. is_http2_upgrade(#{<<"connection">> := Conn, <<"upgrade">> := Upgrade,
  586. <<"http2-settings">> := HTTP2Settings}, 'HTTP/1.1') ->
  587. Conns = cow_http_hd:parse_connection(Conn),
  588. case {lists:member(<<"upgrade">>, Conns), lists:member(<<"http2-settings">>, Conns)} of
  589. {true, true} ->
  590. Protocols = cow_http_hd:parse_upgrade(Upgrade),
  591. case lists:member(<<"h2c">>, Protocols) of
  592. true ->
  593. {true, HTTP2Settings};
  594. false ->
  595. false
  596. end;
  597. _ ->
  598. false
  599. end;
  600. is_http2_upgrade(_, _) ->
  601. false.
  602. %% Upgrade through an HTTP/1.1 request.
  603. %% Prior knowledge upgrade, without an HTTP/1.1 request.
  604. http2_upgrade(State=#state{parent=Parent, ref=Ref, socket=Socket, transport=Transport,
  605. opts=Opts, handler=Handler, peer=Peer}, Buffer) ->
  606. case Transport:secure() of
  607. false ->
  608. _ = cancel_request_timeout(State),
  609. cowboy_http2:init(Parent, Ref, Socket, Transport, Opts, Handler, Peer, Buffer);
  610. true ->
  611. error_terminate(400, State, {connection_error, protocol_error,
  612. 'Clients that support HTTP/2 over TLS MUST use ALPN. (RFC7540 3.4)'})
  613. end.
  614. http2_upgrade(State=#state{parent=Parent, ref=Ref, socket=Socket, transport=Transport,
  615. opts=Opts, handler=Handler, peer=Peer}, Buffer, HTTP2Settings, Req) ->
  616. %% @todo
  617. %% However if the client sent a body, we need to read the body in full
  618. %% and if we can't do that, return a 413 response. Some options are in order.
  619. %% Always half-closed stream coming from this side.
  620. try cow_http_hd:parse_http2_settings(HTTP2Settings) of
  621. Settings ->
  622. Transport:send(Socket, cow_http:response(101, 'HTTP/1.1', maps:to_list(#{
  623. <<"connection">> => <<"Upgrade">>,
  624. <<"upgrade">> => <<"h2c">>
  625. }))),
  626. %% @todo Possibly redirect the request if it was https.
  627. _ = cancel_request_timeout(State),
  628. cowboy_http2:init(Parent, Ref, Socket, Transport, Opts, Handler, Peer, Buffer, Settings, Req)
  629. catch _:_ ->
  630. error_terminate(400, State, {connection_error, protocol_error,
  631. 'The HTTP2-Settings header contains a base64 SETTINGS payload. (RFC7540 3.2, RFC7540 3.2.1)'})
  632. end.
  633. %% Request body parsing.
  634. parse_body(Buffer, State=#state{in_streamid=StreamID, in_state=
  635. PS=#ps_body{transfer_decode_fun=TDecode, transfer_decode_state=TState0}}) ->
  636. %% @todo Proper trailers.
  637. case TDecode(Buffer, TState0) of
  638. more ->
  639. %% @todo Asks for 0 or more bytes.
  640. {more, State, Buffer};
  641. {more, Data, TState} ->
  642. %% @todo Asks for 0 or more bytes.
  643. {data, StreamID, nofin, Data, State#state{in_state=
  644. PS#ps_body{transfer_decode_state=TState}}, <<>>};
  645. {more, Data, _Length, TState} when is_integer(_Length) ->
  646. %% @todo Asks for Length more bytes.
  647. {data, StreamID, nofin, Data, State#state{in_state=
  648. PS#ps_body{transfer_decode_state=TState}}, <<>>};
  649. {more, Data, Rest, TState} ->
  650. %% @todo Asks for 0 or more bytes.
  651. {data, StreamID, nofin, Data, State#state{in_state=
  652. PS#ps_body{transfer_decode_state=TState}}, Rest};
  653. {done, TotalLength, Rest} ->
  654. {data, StreamID, {fin, TotalLength}, <<>>, set_request_timeout(
  655. State#state{in_streamid=StreamID + 1, in_state=#ps_request_line{}}), Rest};
  656. {done, Data, TotalLength, Rest} ->
  657. {data, StreamID, {fin, TotalLength}, Data, set_request_timeout(
  658. State#state{in_streamid=StreamID + 1, in_state=#ps_request_line{}}), Rest}
  659. end.
  660. %% Message handling.
  661. down(State=#state{children=Children0}, Pid, Msg) ->
  662. case lists:keytake(Pid, 1, Children0) of
  663. {value, {_, undefined, _}, Children} ->
  664. State#state{children=Children};
  665. {value, {_, StreamID, _}, Children} ->
  666. info(State#state{children=Children}, StreamID, Msg);
  667. false ->
  668. error_logger:error_msg("Received EXIT signal ~p for unknown process ~p.~n", [Msg, Pid]),
  669. State
  670. end.
  671. info(State=#state{handler=Handler, streams=Streams0}, StreamID, Msg) ->
  672. case lists:keyfind(StreamID, #stream.id, Streams0) of
  673. Stream = #stream{state=StreamState0} ->
  674. try Handler:info(StreamID, Msg, StreamState0) of
  675. {Commands, StreamState} ->
  676. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  677. Stream#stream{state=StreamState}),
  678. commands(State#state{streams=Streams}, StreamID, Commands)
  679. catch Class:Reason ->
  680. error_logger:error_msg("Exception occurred in ~s:info(~p, ~p, ~p) with reason ~p:~p.",
  681. [Handler, StreamID, Msg, StreamState0, Class, Reason]),
  682. ok
  683. %% @todo
  684. % stream_reset(State, StreamID, {internal_error, {Class, Reason},
  685. % 'Exception occurred in StreamHandler:info/3 call.'})
  686. end;
  687. false ->
  688. error_logger:error_msg("Received message ~p for unknown stream ~p.~n", [Msg, StreamID]),
  689. State
  690. end.
  691. %% Commands.
  692. commands(State, _, []) ->
  693. State;
  694. %% Supervise a child process.
  695. commands(State=#state{children=Children}, StreamID, [{spawn, Pid, Shutdown}|Tail]) ->
  696. commands(State#state{children=[{Pid, StreamID, Shutdown}|Children]}, StreamID, Tail);
  697. %% Error handling.
  698. commands(State, StreamID, [Error = {internal_error, _, _}|Tail]) ->
  699. commands(stream_reset(State, StreamID, Error), StreamID, Tail);
  700. %% Commands for a stream currently inactive.
  701. commands(State=#state{out_streamid=Current, streams=Streams0}, StreamID, Commands)
  702. when Current =/= StreamID ->
  703. %% @todo We still want to handle some commands...
  704. Stream = #stream{queue=Queue} = lists:keyfind(StreamID, #stream.id, Streams0),
  705. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  706. Stream#stream{queue=Queue ++ Commands}),
  707. State#state{streams=Streams};
  708. %% Read the request body.
  709. commands(State, StreamID, [{flow, _Length}|Tail]) ->
  710. %% @todo We only read from socket if buffer is empty, otherwise
  711. %% we decode the buffer.
  712. %% @todo Set the body reading length to min(Length, BodyLength)
  713. commands(State, StreamID, Tail);
  714. %% Send a full response.
  715. %%
  716. %% @todo Kill the stream if it sent a response when one has already been sent.
  717. %% @todo Keep IsFin in the state.
  718. %% @todo Same two things above apply to DATA, possibly promise too.
  719. commands(State0=#state{socket=Socket, transport=Transport, out_state=wait, streams=Streams}, StreamID,
  720. [{response, StatusCode, Headers0, Body}|Tail]) ->
  721. %% @todo I'm pretty sure the last stream in the list is the one we want
  722. %% considering all others are queued.
  723. #stream{version=Version} = lists:keyfind(StreamID, #stream.id, Streams),
  724. {State, Headers} = connection(State0, Headers0, StreamID, Version),
  725. %% @todo Ensure content-length is set.
  726. Response = cow_http:response(StatusCode, 'HTTP/1.1', headers_to_list(Headers)),
  727. case Body of
  728. {sendfile, O, B, P} ->
  729. Transport:send(Socket, Response),
  730. commands(State#state{out_state=done}, StreamID, [{sendfile, fin, O, B, P}|Tail]);
  731. _ ->
  732. Transport:send(Socket, [Response, Body]),
  733. %% @todo If max number of requests, close connection.
  734. %% @todo If IsFin, maybe skip body of current request.
  735. maybe_terminate(State#state{out_state=done}, StreamID, Tail, fin)
  736. end;
  737. %% Send response headers and initiate chunked encoding.
  738. commands(State0=#state{socket=Socket, transport=Transport, streams=Streams}, StreamID,
  739. [{headers, StatusCode, Headers0}|Tail]) ->
  740. %% @todo Same as above.
  741. #stream{version=Version} = lists:keyfind(StreamID, #stream.id, Streams),
  742. {State1, Headers1} = case Version of
  743. 'HTTP/1.1' ->
  744. {State0, Headers0#{<<"transfer-encoding">> => <<"chunked">>}};
  745. %% Close the connection after streaming the data to HTTP/1.0 client.
  746. %% @todo I'm guessing we need to differentiate responses with a content-length and others.
  747. 'HTTP/1.0' ->
  748. {State0#state{last_streamid=StreamID}, Headers0}
  749. end,
  750. {State, Headers} = connection(State1, Headers1, StreamID, Version),
  751. Transport:send(Socket, cow_http:response(StatusCode, 'HTTP/1.1', headers_to_list(Headers))),
  752. commands(State#state{out_state=chunked}, StreamID, Tail);
  753. %% Send a response body chunk.
  754. %%
  755. %% @todo WINDOW_UPDATE stuff require us to buffer some data.
  756. commands(State=#state{socket=Socket, transport=Transport, streams=Streams}, StreamID,
  757. [{data, IsFin, Data}|Tail]) ->
  758. %% @todo Same as above.
  759. case lists:keyfind(StreamID, #stream.id, Streams) of
  760. #stream{version='HTTP/1.1'} ->
  761. Size = iolist_size(Data),
  762. Transport:send(Socket, [integer_to_list(Size, 16), <<"\r\n">>, Data, <<"\r\n">>]);
  763. #stream{version='HTTP/1.0'} ->
  764. Transport:send(Socket, Data)
  765. end,
  766. maybe_terminate(State, StreamID, Tail, IsFin);
  767. %% Send a file.
  768. commands(State=#state{socket=Socket, transport=Transport}, StreamID,
  769. [{sendfile, IsFin, Offset, Bytes, Path}|Tail]) ->
  770. Transport:sendfile(Socket, Path, Offset, Bytes),
  771. maybe_terminate(State, StreamID, Tail, IsFin);
  772. %% Protocol takeover.
  773. commands(State0=#state{ref=Ref, parent=Parent, socket=Socket, transport=Transport,
  774. opts=Opts, children=Children}, StreamID,
  775. [{switch_protocol, Headers, Protocol, InitialState}|_Tail]) ->
  776. %% @todo This should be the last stream running otherwise we need to wait before switching.
  777. %% @todo If there's streams opened after this one, fail instead of 101.
  778. State = cancel_request_timeout(State0),
  779. %% @todo When we actually do the upgrade, we only have the one stream left, plus
  780. %% possibly some processes terminating. We need a smart strategy for handling the
  781. %% children shutdown. We can start with brutal_kill and discarding the EXIT messages
  782. %% received before switching to Websocket. Something better would be to let the
  783. %% stream processes finish but that implies the Websocket module to know about
  784. %% them and filter the messages. For now, kill them all and discard all messages
  785. %% in the mailbox.
  786. _ = [exit(Pid, kill) || {Pid, _, _} <- Children],
  787. flush(),
  788. %% Everything good, upgrade!
  789. _ = commands(State, StreamID, [{response, 101, Headers, <<>>}]),
  790. %% @todo This is no good because commands return a state normally and here it doesn't
  791. %% we need to let this module go entirely. Perhaps it should be handled directly in
  792. %% cowboy_clear/cowboy_tls? Perhaps not. We do want that Buffer.
  793. Protocol:takeover(Parent, Ref, Socket, Transport, Opts, <<>>, InitialState);
  794. %% Stream shutdown.
  795. commands(State, StreamID, [stop|Tail]) ->
  796. %% @todo Do we want to run the commands after a stop?
  797. % commands(stream_terminate(State, StreamID, stop), StreamID, Tail).
  798. maybe_terminate(State, StreamID, Tail, fin);
  799. %% HTTP/1.1 does not support push; ignore.
  800. commands(State, StreamID, [{push, _, _, _, _, _, _, _}|Tail]) ->
  801. commands(State, StreamID, Tail).
  802. %% The set-cookie header is special; we can only send one cookie per header.
  803. headers_to_list(Headers0=#{<<"set-cookie">> := SetCookies}) ->
  804. Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  805. Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies];
  806. headers_to_list(Headers) ->
  807. maps:to_list(Headers).
  808. flush() ->
  809. receive _ -> flush() after 0 -> ok end.
  810. maybe_terminate(State, StreamID, Tail, nofin) ->
  811. commands(State, StreamID, Tail);
  812. %% @todo In these cases I'm not sure if we should continue processing commands.
  813. maybe_terminate(State=#state{last_streamid=StreamID}, StreamID, _Tail, fin) ->
  814. terminate(stream_terminate(State, StreamID, normal), normal); %% @todo Reason ok?
  815. maybe_terminate(State, StreamID, _Tail, fin) ->
  816. stream_terminate(State, StreamID, normal).
  817. stream_reset(State, StreamID, StreamError={internal_error, _, _}) ->
  818. %% @todo headers
  819. %% @todo Don't send this if there are no streams left.
  820. % Transport:send(Socket, cow_http:response(500, 'HTTP/1.1', [
  821. % {<<"content-length">>, <<"0">>}
  822. % ])),
  823. %% @todo update IsFin local
  824. % stream_terminate(State#state{out_state=done}, StreamID, StreamError).
  825. stream_terminate(State, StreamID, StreamError).
  826. stream_terminate(State=#state{socket=Socket, transport=Transport, handler=Handler,
  827. out_streamid=OutStreamID, out_state=OutState,
  828. streams=Streams0, children=Children0}, StreamID, Reason) ->
  829. {value, #stream{state=StreamState, version=Version}, Streams}
  830. = lists:keytake(StreamID, #stream.id, Streams0),
  831. _ = case OutState of
  832. wait ->
  833. Transport:send(Socket, cow_http:response(204, 'HTTP/1.1', []));
  834. chunked when Version =:= 'HTTP/1.1' ->
  835. Transport:send(Socket, <<"0\r\n\r\n">>);
  836. _ -> %% done or Version =:= 'HTTP/1.0'
  837. ok
  838. end,
  839. stream_call_terminate(StreamID, Reason, Handler, StreamState),
  840. %% @todo initiate children shutdown
  841. % Children = stream_terminate_children(Children0, StreamID, []),
  842. Children = [case C of
  843. {Pid, StreamID, Shutdown} -> {Pid, undefined, Shutdown};
  844. _ -> C
  845. end || C <- Children0],
  846. %% @todo Skip the body, if any, or drop the connection if too large.
  847. %% @todo Only do this if Current =:= StreamID.
  848. NextOutStreamID = OutStreamID + 1,
  849. case lists:keyfind(NextOutStreamID, #stream.id, Streams) of
  850. false ->
  851. %% @todo This is clearly wrong, if the stream is gone we need to check if
  852. %% there used to be such a stream, and if there was to send an error.
  853. State#state{out_streamid=NextOutStreamID, out_state=wait, streams=Streams, children=Children};
  854. #stream{queue=Commands} ->
  855. %% @todo Remove queue from the stream.
  856. commands(State#state{out_streamid=NextOutStreamID, out_state=wait,
  857. streams=Streams, children=Children}, NextOutStreamID, Commands)
  858. end.
  859. %% @todo Taken directly from _http2
  860. stream_call_terminate(StreamID, Reason, Handler, StreamState) ->
  861. try
  862. Handler:terminate(StreamID, Reason, StreamState),
  863. ok
  864. catch Class:Reason ->
  865. error_logger:error_msg("Exception occurred in ~s:terminate(~p, ~p, ~p) with reason ~p:~p.",
  866. [Handler, StreamID, Reason, StreamState, Class, Reason])
  867. end.
  868. %stream_terminate_children([], _, Acc) ->
  869. % Acc;
  870. %stream_terminate_children([{Pid, StreamID}|Tail], StreamID, Acc) ->
  871. % exit(Pid, kill),
  872. % stream_terminate_children(Tail, StreamID, Acc);
  873. %stream_terminate_children([Child|Tail], StreamID, Acc) ->
  874. % stream_terminate_children(Tail, StreamID, [Child|Acc]).
  875. %% @todo max_reqs also
  876. maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.0') ->
  877. Conns = cow_http_hd:parse_connection(Conn),
  878. case lists:member(<<"keep-alive">>, Conns) of
  879. true -> keepalive;
  880. false -> close
  881. end;
  882. maybe_req_close(_, _, 'HTTP/1.0') ->
  883. close;
  884. maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.1') ->
  885. case connection_hd_is_close(Conn) of
  886. true -> close;
  887. false -> keepalive
  888. end;
  889. maybe_req_close(_State, _, _) ->
  890. keepalive.
  891. connection(State=#state{last_streamid=StreamID}, Headers=#{<<"connection">> := Conn}, StreamID, _) ->
  892. case connection_hd_is_close(Conn) of
  893. true -> {State, Headers};
  894. %% @todo Here we need to remove keep-alive and add close, not just add close.
  895. false -> {State, Headers#{<<"connection">> => [<<"close, ">>, Conn]}}
  896. end;
  897. connection(State=#state{last_streamid=StreamID}, Headers, StreamID, _) ->
  898. {State, Headers#{<<"connection">> => <<"close">>}};
  899. connection(State, Headers=#{<<"connection">> := Conn}, StreamID, _) ->
  900. case connection_hd_is_close(Conn) of
  901. true -> {State#state{last_streamid=StreamID}, Headers};
  902. %% @todo Here we need to set keep-alive only if it wasn't set before.
  903. false -> {State, Headers}
  904. end;
  905. connection(State, Headers, _, 'HTTP/1.0') ->
  906. {State, Headers#{<<"connection">> => <<"keep-alive">>}};
  907. connection(State, Headers, _, _) ->
  908. {State, Headers}.
  909. connection_hd_is_close(Conn) ->
  910. Conns = cow_http_hd:parse_connection(iolist_to_binary(Conn)),
  911. lists:member(<<"close">>, Conns).
  912. error_terminate(StatusCode, State=#state{socket=Socket, transport=Transport}, Reason) ->
  913. Transport:send(Socket, cow_http:response(StatusCode, 'HTTP/1.1', [
  914. {<<"content-length">>, <<"0">>}
  915. ])),
  916. terminate(State, Reason).
  917. terminate(_State, _Reason) ->
  918. exit(normal). %% @todo
  919. %% System callbacks.
  920. -spec system_continue(_, _, #state{}) -> ok.
  921. system_continue(_, _, {State, Buffer}) ->
  922. loop(State, Buffer).
  923. -spec system_terminate(any(), _, _, _) -> no_return().
  924. system_terminate(Reason, _, _, _) ->
  925. exit(Reason).
  926. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  927. system_code_change(Misc, _, _, _) ->
  928. {ok, Misc}.