cowboy_http.erl 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. %% @todo Bad value returned here. Crashes.
  236. ok
  237. %% @todo Status code.
  238. % stream_reset(State, StreamID, {internal_error, {Class, Reason},
  239. % 'Exception occurred in StreamHandler:init/10 call.'}) %% @todo Check final arity.
  240. end;
  241. %% Streams are sequential so the body is always about the last stream created
  242. %% unless that stream has terminated.
  243. after_parse({data, StreamID, IsFin, Data, State=#state{handler=Handler,
  244. streams=Streams0=[Stream=#stream{id=StreamID, state=StreamState0}|_]}, Buffer}) ->
  245. try Handler:data(StreamID, IsFin, Data, StreamState0) of
  246. {Commands, StreamState} ->
  247. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  248. Stream#stream{state=StreamState}),
  249. parse(Buffer, commands(State#state{streams=Streams}, StreamID, Commands))
  250. catch Class:Reason ->
  251. error_logger:error_msg("Exception occurred in ~s:data(~p, ~p, ~p, ~p) with reason ~p:~p.",
  252. [Handler, StreamID, IsFin, Data, StreamState0, Class, Reason]),
  253. %% @todo Bad value returned here. Crashes.
  254. ok
  255. %% @todo
  256. % stream_reset(State, StreamID, {internal_error, {Class, Reason},
  257. % 'Exception occurred in StreamHandler:data/4 call.'})
  258. end;
  259. %% No corresponding stream, skip.
  260. after_parse({data, _, _, _, State, Buffer}) ->
  261. before_loop(State, Buffer);
  262. after_parse({more, State, Buffer}) ->
  263. before_loop(State, Buffer).
  264. %% Request-line.
  265. -spec parse_request(binary(), #state{}, non_neg_integer()) -> ok.
  266. %% Empty lines must be using \r\n.
  267. parse_request(<< $\n, _/bits >>, State, _) ->
  268. error_terminate(400, State, {connection_error, protocol_error,
  269. ''}); %% @todo
  270. parse_request(<< $\s, _/bits >>, State, _) ->
  271. error_terminate(400, State, {connection_error, protocol_error,
  272. ''}); %% @todo
  273. %% We limit the length of the Request-line to MaxLength to avoid endlessly
  274. %% reading from the socket and eventually crashing.
  275. parse_request(Buffer, State=#state{opts=Opts, in_streamid=InStreamID}, EmptyLines) ->
  276. MaxLength = maps:get(max_request_line_length, Opts, 8000),
  277. MaxEmptyLines = maps:get(max_empty_lines, Opts, 5),
  278. case match_eol(Buffer, 0) of
  279. nomatch when byte_size(Buffer) > MaxLength ->
  280. error_terminate(414, State, {connection_error, limit_reached,
  281. ''}); %% @todo
  282. nomatch ->
  283. {more, State#state{in_state=#ps_request_line{empty_lines=EmptyLines}}, Buffer};
  284. 1 when EmptyLines =:= MaxEmptyLines ->
  285. error_terminate(400, State, {connection_error, limit_reached,
  286. ''}); %% @todo
  287. 1 ->
  288. << _:16, Rest/bits >> = Buffer,
  289. parse_request(Rest, State, EmptyLines + 1);
  290. _ ->
  291. case Buffer of
  292. %% @todo * is only for server-wide OPTIONS request (RFC7230 5.3.4); tests
  293. << "OPTIONS * ", Rest/bits >> ->
  294. parse_version(Rest, State, <<"OPTIONS">>, <<"*">>, <<>>);
  295. % << "CONNECT ", Rest/bits >> ->
  296. % parse_authority( %% @todo
  297. %% Accept direct HTTP/2 only at the beginning of the connection.
  298. << "PRI * HTTP/2.0\r\n", _/bits >> when InStreamID =:= 1 ->
  299. %% @todo Might be worth throwing to get a clean stacktrace.
  300. http2_upgrade(State, Buffer);
  301. _ ->
  302. parse_method(Buffer, State, <<>>,
  303. maps:get(max_method_length, Opts, 32))
  304. end
  305. end.
  306. match_eol(<< $\n, _/bits >>, N) ->
  307. N;
  308. match_eol(<< _, Rest/bits >>, N) ->
  309. match_eol(Rest, N + 1);
  310. match_eol(_, _) ->
  311. nomatch.
  312. parse_method(_, State, _, 0) ->
  313. error_terminate(501, State, {connection_error, limit_reached,
  314. 'The method name is longer than configuration allows. (RFC7230 3.1.1)'});
  315. parse_method(<< C, Rest/bits >>, State, SoFar, Remaining) ->
  316. case C of
  317. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  318. ''}); %% @todo
  319. $\s -> parse_uri(Rest, State, SoFar);
  320. _ when ?IS_TOKEN(C) -> parse_method(Rest, State, << SoFar/binary, C >>, Remaining - 1);
  321. _ -> error_terminate(400, State, {connection_error, protocol_error,
  322. 'The method name must contain only valid token characters. (RFC7230 3.1.1)'})
  323. end.
  324. parse_uri(<< H, T, T, P, "://", Rest/bits >>, State, Method)
  325. when H =:= $h orelse H =:= $H, T =:= $t orelse T =:= $T;
  326. P =:= $p orelse P =:= $P ->
  327. parse_uri_skip_host(Rest, State, Method);
  328. parse_uri(<< H, T, T, P, S, "://", Rest/bits >>, State, Method)
  329. when H =:= $h orelse H =:= $H, T =:= $t orelse T =:= $T;
  330. P =:= $p orelse P =:= $P; S =:= $s orelse S =:= $S ->
  331. parse_uri_skip_host(Rest, State, Method);
  332. parse_uri(<< $/, Rest/bits >>, State, Method) ->
  333. parse_uri_path(Rest, State, Method, << $/ >>);
  334. parse_uri(_, State, _) ->
  335. error_terminate(400, State, {connection_error, protocol_error,
  336. 'Invalid request-line or request-target. (RFC7230 3.1.1, RFC7230 5.3)'}).
  337. parse_uri_skip_host(<< C, Rest/bits >>, State, Method) ->
  338. case C of
  339. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  340. ''}); %% @todo
  341. $/ -> parse_uri_path(Rest, State, Method, <<"/">>);
  342. $\s -> parse_version(Rest, State, Method, <<"/">>, <<>>);
  343. $? -> parse_uri_query(Rest, State, Method, <<"/">>, <<>>);
  344. $# -> skip_uri_fragment(Rest, State, Method, <<"/">>, <<>>);
  345. _ -> parse_uri_skip_host(Rest, State, Method)
  346. end.
  347. parse_uri_path(<< C, Rest/bits >>, State, Method, SoFar) ->
  348. case C of
  349. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  350. ''}); %% @todo
  351. $\s -> parse_version(Rest, State, Method, SoFar, <<>>);
  352. $? -> parse_uri_query(Rest, State, Method, SoFar, <<>>);
  353. $# -> skip_uri_fragment(Rest, State, Method, SoFar, <<>>);
  354. _ -> parse_uri_path(Rest, State, Method, << SoFar/binary, C >>)
  355. end.
  356. parse_uri_query(<< C, Rest/bits >>, State, M, P, SoFar) ->
  357. case C of
  358. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  359. ''}); %% @todo
  360. $\s -> parse_version(Rest, State, M, P, SoFar);
  361. $# -> skip_uri_fragment(Rest, State, M, P, SoFar);
  362. _ -> parse_uri_query(Rest, State, M, P, << SoFar/binary, C >>)
  363. end.
  364. skip_uri_fragment(<< C, Rest/bits >>, State, M, P, Q) ->
  365. case C of
  366. $\r -> error_terminate(400, State, {connection_error, protocol_error,
  367. ''}); %% @todo
  368. $\s -> parse_version(Rest, State, M, P, Q);
  369. _ -> skip_uri_fragment(Rest, State, M, P, Q)
  370. end.
  371. %% @todo Calls to parse_header should update the state.
  372. parse_version(<< "HTTP/1.1\r\n", Rest/bits >>, State, M, P, Q) ->
  373. parse_headers(Rest, State, M, P, Q, 'HTTP/1.1');
  374. parse_version(<< "HTTP/1.0\r\n", Rest/bits >>, State, M, P, Q) ->
  375. parse_headers(Rest, State, M, P, Q, 'HTTP/1.0');
  376. parse_version(<< "HTTP/1.", _, C, _/bits >>, State, _, _, _) when C =:= $\s; C =:= $\t ->
  377. error_terminate(400, State, {connection_error, protocol_error,
  378. 'Whitespace is not allowed after the HTTP version. (RFC7230 3.1.1)'});
  379. parse_version(<< C, _/bits >>, State, _, _, _) when C =:= $\s; C =:= $\t ->
  380. error_terminate(400, State, {connection_error, protocol_error,
  381. 'The separator between request target and version must be a single SP.'});
  382. parse_version(_, State, _, _, _) ->
  383. error_terminate(505, State, {connection_error, protocol_error,
  384. ''}). %% @todo
  385. parse_headers(Rest, State, M, P, Q, V) ->
  386. %% @todo Figure out the parse states.
  387. parse_header(Rest, State#state{in_state=#ps_header{
  388. method=M, path=P, qs=Q, version=V}}, #{}).
  389. %% Headers.
  390. %% We need two or more bytes in the buffer to continue.
  391. parse_header(Rest, State=#state{in_state=PS}, Headers) when byte_size(Rest) < 2 ->
  392. {more, State#state{in_state=PS#ps_header{headers=Headers}}, Rest};
  393. parse_header(<< $\r, $\n, Rest/bits >>, S, Headers) ->
  394. request(Rest, S, Headers);
  395. parse_header(Buffer, State=#state{opts=Opts, in_state=PS}, Headers) ->
  396. MaxLength = maps:get(max_header_name_length, Opts, 64),
  397. MaxHeaders = maps:get(max_headers, Opts, 100),
  398. case match_colon(Buffer, 0) of
  399. nomatch when byte_size(Buffer) > MaxLength ->
  400. error_terminate(400, State, {connection_error, limit_reached,
  401. ''}); %% @todo
  402. nomatch when length(Headers) >= MaxHeaders ->
  403. error_terminate(400, State, {connection_error, limit_reached,
  404. ''}); %% @todo
  405. nomatch ->
  406. {more, State#state{in_state=PS#ps_header{headers=Headers}}, Buffer};
  407. _ ->
  408. parse_hd_name(Buffer, State, Headers, <<>>)
  409. end.
  410. match_colon(<< $:, _/bits >>, N) ->
  411. N;
  412. match_colon(<< _, Rest/bits >>, N) ->
  413. match_colon(Rest, N + 1);
  414. match_colon(_, _) ->
  415. nomatch.
  416. parse_hd_name(<< $:, Rest/bits >>, State, H, SoFar) ->
  417. parse_hd_before_value(Rest, State, H, SoFar);
  418. parse_hd_name(<< C, _/bits >>, State, _, <<>>) when ?IS_WS(C) ->
  419. error_terminate(400, State, {connection_error, protocol_error,
  420. ''}); %% @todo
  421. parse_hd_name(<< C, Rest/bits >>, State, H, SoFar) when ?IS_WS(C) ->
  422. parse_hd_name_ws(Rest, State, H, SoFar);
  423. parse_hd_name(<< C, Rest/bits >>, State, H, SoFar) ->
  424. ?LOWER(parse_hd_name, Rest, State, H, SoFar).
  425. parse_hd_name_ws(<< C, Rest/bits >>, S, H, Name) ->
  426. case C of
  427. $\s -> parse_hd_name_ws(Rest, S, H, Name);
  428. $\t -> parse_hd_name_ws(Rest, S, H, Name);
  429. $: -> parse_hd_before_value(Rest, S, H, Name)
  430. end.
  431. parse_hd_before_value(<< $\s, Rest/bits >>, S, H, N) ->
  432. parse_hd_before_value(Rest, S, H, N);
  433. parse_hd_before_value(<< $\t, Rest/bits >>, S, H, N) ->
  434. parse_hd_before_value(Rest, S, H, N);
  435. parse_hd_before_value(Buffer, State=#state{opts=Opts, in_state=PS}, H, N) ->
  436. MaxLength = maps:get(max_header_value_length, Opts, 4096),
  437. case match_eol(Buffer, 0) of
  438. nomatch when byte_size(Buffer) > MaxLength ->
  439. error_terminate(400, State, {connection_error, limit_reached,
  440. ''}); %% @todo
  441. nomatch ->
  442. {more, State#state{in_state=PS#ps_header{headers=H, name=N}}, Buffer};
  443. _ ->
  444. parse_hd_value(Buffer, State, H, N, <<>>)
  445. end.
  446. parse_hd_value(<< $\r, $\n, Rest/bits >>, S, Headers0, Name, SoFar) ->
  447. Value = clean_value_ws_end(SoFar, byte_size(SoFar) - 1),
  448. Headers = case maps:get(Name, Headers0, undefined) of
  449. undefined -> Headers0#{Name => Value};
  450. %% The cookie header does not use proper HTTP header lists.
  451. Value0 when Name =:= <<"cookie">> -> Headers0#{Name => << Value0/binary, "; ", Value/binary >>};
  452. Value0 -> Headers0#{Name => << Value0/binary, ", ", Value/binary >>}
  453. end,
  454. parse_header(Rest, S, Headers);
  455. parse_hd_value(<< C, Rest/bits >>, S, H, N, SoFar) ->
  456. parse_hd_value(Rest, S, H, N, << SoFar/binary, C >>).
  457. clean_value_ws_end(_, -1) ->
  458. <<>>;
  459. clean_value_ws_end(Value, N) ->
  460. case binary:at(Value, N) of
  461. $\s -> clean_value_ws_end(Value, N - 1);
  462. $\t -> clean_value_ws_end(Value, N - 1);
  463. _ ->
  464. S = N + 1,
  465. << Value2:S/binary, _/bits >> = Value,
  466. Value2
  467. end.
  468. -ifdef(TEST).
  469. clean_value_ws_end_test_() ->
  470. Tests = [
  471. {<<>>, <<>>},
  472. {<<" ">>, <<>>},
  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 \t \t ">>,
  475. <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  476. "text/html;level=2;q=0.4, */*;q=0.5">>}
  477. ],
  478. [{V, fun() -> R = clean_value_ws_end(V, byte_size(V) - 1) end} || {V, R} <- Tests].
  479. horse_clean_value_ws_end() ->
  480. horse:repeat(200000,
  481. clean_value_ws_end(
  482. <<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  483. "text/html;level=2;q=0.4, */*;q=0.5 ">>,
  484. byte_size(<<"text/*;q=0.3, text/html;q=0.7, text/html;level=1, "
  485. "text/html;level=2;q=0.4, */*;q=0.5 ">>) - 1)
  486. ).
  487. -endif.
  488. request(Buffer, State=#state{transport=Transport, in_streamid=StreamID,
  489. in_state=#ps_header{version=Version}}, Headers) ->
  490. case maps:get(<<"host">>, Headers, undefined) of
  491. undefined when Version =:= 'HTTP/1.1' ->
  492. %% @todo Might want to not close the connection on this and next one.
  493. error_terminate(400, State, {stream_error, StreamID, protocol_error,
  494. ''}); %% @todo
  495. undefined ->
  496. request(Buffer, State, Headers, <<>>, default_port(Transport:secure()));
  497. RawHost ->
  498. try cow_http_hd:parse_host(RawHost) of
  499. {Host, undefined} ->
  500. request(Buffer, State, Headers, Host, default_port(Transport:secure()));
  501. {Host, Port} ->
  502. request(Buffer, State, Headers, Host, Port)
  503. catch _:_ ->
  504. error_terminate(400, State, {stream_error, StreamID, protocol_error,
  505. ''}) %% @todo
  506. end
  507. end.
  508. -spec default_port(boolean()) -> 80 | 443.
  509. default_port(true) -> 443;
  510. default_port(_) -> 80.
  511. %% End of request parsing.
  512. request(Buffer, State0=#state{ref=Ref, transport=Transport, peer=Peer, in_streamid=StreamID,
  513. in_state=#ps_header{method=Method, path=Path, qs=Qs, version=Version}},
  514. Headers, Host, Port) ->
  515. Scheme = case Transport:secure() of
  516. true -> <<"https">>;
  517. false -> <<"http">>
  518. end,
  519. {HasBody, BodyLength, TDecodeFun, TDecodeState} = case Headers of
  520. #{<<"content-length">> := <<"0">>} ->
  521. {false, 0, undefined, undefined};
  522. #{<<"content-length">> := BinLength} ->
  523. Length = try
  524. cow_http_hd:parse_content_length(BinLength)
  525. catch _:_ ->
  526. error_terminate(400, State0, {stream_error, StreamID, protocol_error,
  527. ''}) %% @todo
  528. %% @todo Err should terminate here...
  529. end,
  530. {true, Length, fun cow_http_te:stream_identity/2, {0, Length}};
  531. %% @todo Better handling of transfer decoding.
  532. #{<<"transfer-encoding">> := <<"chunked">>} ->
  533. {true, undefined, fun cow_http_te:stream_chunked/2, {0, 0}};
  534. _ ->
  535. {false, 0, undefined, undefined}
  536. end,
  537. Req = #{
  538. ref => Ref,
  539. pid => self(),
  540. streamid => StreamID,
  541. peer => Peer,
  542. method => Method,
  543. scheme => Scheme,
  544. host => Host,
  545. port => Port,
  546. %% @todo So the path component needs to be normalized.
  547. path => Path,
  548. qs => Qs,
  549. version => Version,
  550. %% We are transparently taking care of transfer-encodings so
  551. %% the user code has no need to know about it.
  552. headers => maps:remove(<<"transfer-encoding">>, Headers),
  553. has_body => HasBody,
  554. body_length => BodyLength
  555. %% @todo multipart? keep state separate
  556. %% meta values (cowboy_websocket, cowboy_rest)
  557. },
  558. case is_http2_upgrade(Headers, Version) of
  559. false ->
  560. State = case HasBody of
  561. true ->
  562. cancel_request_timeout(State0#state{in_state=#ps_body{
  563. %% @todo Don't need length anymore?
  564. transfer_decode_fun = TDecodeFun,
  565. transfer_decode_state = TDecodeState
  566. }});
  567. false ->
  568. set_request_timeout(State0#state{in_streamid=StreamID + 1, in_state=#ps_request_line{}})
  569. end,
  570. {request, Req, State, Buffer};
  571. {true, HTTP2Settings} ->
  572. http2_upgrade(State0, Buffer, HTTP2Settings, Req)
  573. end.
  574. %% HTTP/2 upgrade.
  575. is_http2_upgrade(#{<<"connection">> := Conn, <<"upgrade">> := Upgrade,
  576. <<"http2-settings">> := HTTP2Settings}, 'HTTP/1.1') ->
  577. Conns = cow_http_hd:parse_connection(Conn),
  578. case {lists:member(<<"upgrade">>, Conns), lists:member(<<"http2-settings">>, Conns)} of
  579. {true, true} ->
  580. Protocols = cow_http_hd:parse_upgrade(Upgrade),
  581. case lists:member(<<"h2c">>, Protocols) of
  582. true ->
  583. {true, HTTP2Settings};
  584. false ->
  585. false
  586. end;
  587. _ ->
  588. false
  589. end;
  590. is_http2_upgrade(_, _) ->
  591. false.
  592. %% Upgrade through an HTTP/1.1 request.
  593. %% Prior knowledge upgrade, without an HTTP/1.1 request.
  594. http2_upgrade(State=#state{parent=Parent, ref=Ref, socket=Socket, transport=Transport,
  595. opts=Opts, handler=Handler, peer=Peer}, Buffer) ->
  596. case Transport:secure() of
  597. false ->
  598. _ = cancel_request_timeout(State),
  599. cowboy_http2:init(Parent, Ref, Socket, Transport, Opts, Handler, Peer, Buffer);
  600. true ->
  601. error_terminate(400, State, {connection_error, protocol_error,
  602. 'Clients that support HTTP/2 over TLS MUST use ALPN. (RFC7540 3.4)'})
  603. end.
  604. http2_upgrade(State=#state{parent=Parent, ref=Ref, socket=Socket, transport=Transport,
  605. opts=Opts, handler=Handler, peer=Peer}, Buffer, HTTP2Settings, Req) ->
  606. %% @todo
  607. %% However if the client sent a body, we need to read the body in full
  608. %% and if we can't do that, return a 413 response. Some options are in order.
  609. %% Always half-closed stream coming from this side.
  610. try cow_http_hd:parse_http2_settings(HTTP2Settings) of
  611. Settings ->
  612. Transport:send(Socket, cow_http:response(101, 'HTTP/1.1', maps:to_list(#{
  613. <<"connection">> => <<"Upgrade">>,
  614. <<"upgrade">> => <<"h2c">>
  615. }))),
  616. %% @todo Possibly redirect the request if it was https.
  617. _ = cancel_request_timeout(State),
  618. cowboy_http2:init(Parent, Ref, Socket, Transport, Opts, Handler, Peer, Buffer, Settings, Req)
  619. catch _:_ ->
  620. error_terminate(400, State, {connection_error, protocol_error,
  621. 'The HTTP2-Settings header contains a base64 SETTINGS payload. (RFC7540 3.2, RFC7540 3.2.1)'})
  622. end.
  623. %% Request body parsing.
  624. parse_body(Buffer, State=#state{in_streamid=StreamID, in_state=
  625. PS=#ps_body{transfer_decode_fun=TDecode, transfer_decode_state=TState0}}) ->
  626. %% @todo Proper trailers.
  627. case TDecode(Buffer, TState0) of
  628. more ->
  629. %% @todo Asks for 0 or more bytes.
  630. {more, State, Buffer};
  631. {more, Data, TState} ->
  632. %% @todo Asks for 0 or more bytes.
  633. {data, StreamID, nofin, Data, State#state{in_state=
  634. PS#ps_body{transfer_decode_state=TState}}, <<>>};
  635. {more, Data, _Length, TState} when is_integer(_Length) ->
  636. %% @todo Asks for Length more bytes.
  637. {data, StreamID, nofin, Data, State#state{in_state=
  638. PS#ps_body{transfer_decode_state=TState}}, <<>>};
  639. {more, Data, Rest, TState} ->
  640. %% @todo Asks for 0 or more bytes.
  641. {data, StreamID, nofin, Data, State#state{in_state=
  642. PS#ps_body{transfer_decode_state=TState}}, Rest};
  643. {done, TotalLength, Rest} ->
  644. {data, StreamID, {fin, TotalLength}, <<>>, set_request_timeout(
  645. State#state{in_streamid=StreamID + 1, in_state=#ps_request_line{}}), Rest};
  646. {done, Data, TotalLength, Rest} ->
  647. {data, StreamID, {fin, TotalLength}, Data, set_request_timeout(
  648. State#state{in_streamid=StreamID + 1, in_state=#ps_request_line{}}), Rest}
  649. end.
  650. %% Message handling.
  651. %% @todo There is a difference in behavior between HTTP/1.1 and HTTP/2
  652. %% when an error or crash occurs after sending a 500 response. In HTTP/2
  653. %% the error will be printed, in HTTP/1.1 the error will be ignored.
  654. %% This is due to HTTP/1.1 disabling streams differently after both
  655. %% requests and responses have been sent.
  656. down(State=#state{children=Children0}, Pid, Msg) ->
  657. case lists:keytake(Pid, 1, Children0) of
  658. {value, {_, undefined, _}, Children} ->
  659. State#state{children=Children};
  660. {value, {_, StreamID, _}, Children} ->
  661. info(State#state{children=Children}, StreamID, Msg);
  662. false ->
  663. error_logger:error_msg("Received EXIT signal ~p for unknown process ~p.~n", [Msg, Pid]),
  664. State
  665. end.
  666. info(State=#state{handler=Handler, streams=Streams0}, StreamID, Msg) ->
  667. case lists:keyfind(StreamID, #stream.id, Streams0) of
  668. Stream = #stream{state=StreamState0} ->
  669. try Handler:info(StreamID, Msg, StreamState0) of
  670. {Commands, StreamState} ->
  671. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  672. Stream#stream{state=StreamState}),
  673. commands(State#state{streams=Streams}, StreamID, Commands)
  674. catch Class:Reason ->
  675. error_logger:error_msg("Exception occurred in ~s:info(~p, ~p, ~p) with reason ~p:~p.",
  676. [Handler, StreamID, Msg, StreamState0, Class, Reason]),
  677. ok
  678. %% @todo
  679. % stream_reset(State, StreamID, {internal_error, {Class, Reason},
  680. % 'Exception occurred in StreamHandler:info/3 call.'})
  681. end;
  682. false ->
  683. error_logger:error_msg("Received message ~p for unknown stream ~p.~n", [Msg, StreamID]),
  684. State
  685. end.
  686. %% Commands.
  687. commands(State, _, []) ->
  688. State;
  689. %% Supervise a child process.
  690. commands(State=#state{children=Children}, StreamID, [{spawn, Pid, Shutdown}|Tail]) ->
  691. commands(State#state{children=[{Pid, StreamID, Shutdown}|Children]}, StreamID, Tail);
  692. %% Error handling.
  693. commands(State, StreamID, [Error = {internal_error, _, _}|Tail]) ->
  694. commands(stream_reset(State, StreamID, Error), StreamID, Tail);
  695. %% Commands for a stream currently inactive.
  696. commands(State=#state{out_streamid=Current, streams=Streams0}, StreamID, Commands)
  697. when Current =/= StreamID ->
  698. %% @todo We still want to handle some commands...
  699. Stream = #stream{queue=Queue} = lists:keyfind(StreamID, #stream.id, Streams0),
  700. Streams = lists:keyreplace(StreamID, #stream.id, Streams0,
  701. Stream#stream{queue=Queue ++ Commands}),
  702. State#state{streams=Streams};
  703. %% Read the request body.
  704. commands(State, StreamID, [{flow, _Length}|Tail]) ->
  705. %% @todo We only read from socket if buffer is empty, otherwise
  706. %% we decode the buffer.
  707. %% @todo Set the body reading length to min(Length, BodyLength)
  708. commands(State, StreamID, Tail);
  709. %% Error responses are sent only if a response wasn't sent already.
  710. commands(State=#state{out_state=wait}, StreamID, [{error_response, StatusCode, Headers, Body}|Tail]) ->
  711. commands(State, StreamID, [{response, StatusCode, Headers, Body}|Tail]);
  712. commands(State, StreamID, [{error_response, _, _, _}|Tail]) ->
  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. %% @todo We probably want to allow Data to be the {sendfile, ...} tuple also.
  757. commands(State=#state{socket=Socket, transport=Transport, streams=Streams}, StreamID,
  758. [{data, IsFin, Data}|Tail]) ->
  759. %% @todo We need to kill the stream if it tries to send data before headers.
  760. %% @todo Same as above.
  761. case lists:keyfind(StreamID, #stream.id, Streams) of
  762. #stream{version='HTTP/1.1'} ->
  763. Size = iolist_size(Data),
  764. Transport:send(Socket, [integer_to_binary(Size, 16), <<"\r\n">>, Data, <<"\r\n">>]);
  765. #stream{version='HTTP/1.0'} ->
  766. Transport:send(Socket, Data)
  767. end,
  768. maybe_terminate(State, StreamID, Tail, IsFin);
  769. %% Send a file.
  770. commands(State=#state{socket=Socket, transport=Transport}, StreamID,
  771. [{sendfile, IsFin, Offset, Bytes, Path}|Tail]) ->
  772. Transport:sendfile(Socket, Path, Offset, Bytes),
  773. maybe_terminate(State, StreamID, Tail, IsFin);
  774. %% Protocol takeover.
  775. commands(State0=#state{ref=Ref, parent=Parent, socket=Socket, transport=Transport,
  776. opts=Opts, children=Children}, StreamID,
  777. [{switch_protocol, Headers, Protocol, InitialState}|_Tail]) ->
  778. %% @todo This should be the last stream running otherwise we need to wait before switching.
  779. %% @todo If there's streams opened after this one, fail instead of 101.
  780. State = cancel_request_timeout(State0),
  781. %% @todo When we actually do the upgrade, we only have the one stream left, plus
  782. %% possibly some processes terminating. We need a smart strategy for handling the
  783. %% children shutdown. We can start with brutal_kill and discarding the EXIT messages
  784. %% received before switching to Websocket. Something better would be to let the
  785. %% stream processes finish but that implies the Websocket module to know about
  786. %% them and filter the messages. For now, kill them all and discard all messages
  787. %% in the mailbox.
  788. _ = [exit(Pid, kill) || {Pid, _, _} <- Children],
  789. flush(),
  790. %% Everything good, upgrade!
  791. _ = commands(State, StreamID, [{response, 101, Headers, <<>>}]),
  792. %% @todo This is no good because commands return a state normally and here it doesn't
  793. %% we need to let this module go entirely. Perhaps it should be handled directly in
  794. %% cowboy_clear/cowboy_tls? Perhaps not. We do want that Buffer.
  795. Protocol:takeover(Parent, Ref, Socket, Transport, Opts, <<>>, InitialState);
  796. %% Stream shutdown.
  797. commands(State, StreamID, [stop|Tail]) ->
  798. %% @todo Do we want to run the commands after a stop?
  799. % commands(stream_terminate(State, StreamID, stop), StreamID, Tail).
  800. %% @todo I think that's where we need to terminate streams.
  801. maybe_terminate(State, StreamID, Tail, fin);
  802. %% HTTP/1.1 does not support push; ignore.
  803. commands(State, StreamID, [{push, _, _, _, _, _, _, _}|Tail]) ->
  804. commands(State, StreamID, Tail).
  805. %% The set-cookie header is special; we can only send one cookie per header.
  806. headers_to_list(Headers0=#{<<"set-cookie">> := SetCookies}) ->
  807. Headers1 = maps:to_list(maps:remove(<<"set-cookie">>, Headers0)),
  808. Headers1 ++ [{<<"set-cookie">>, Value} || Value <- SetCookies];
  809. headers_to_list(Headers) ->
  810. maps:to_list(Headers).
  811. flush() ->
  812. receive _ -> flush() after 0 -> ok end.
  813. maybe_terminate(State, StreamID, Tail, nofin) ->
  814. commands(State, StreamID, Tail);
  815. %% @todo In these cases I'm not sure if we should continue processing commands.
  816. maybe_terminate(State=#state{last_streamid=StreamID}, StreamID, _Tail, fin) ->
  817. terminate(stream_terminate(State, StreamID, normal), normal); %% @todo Reason ok?
  818. maybe_terminate(State, StreamID, _Tail, fin) ->
  819. stream_terminate(State, StreamID, normal).
  820. stream_reset(State, StreamID, StreamError={internal_error, _, _}) ->
  821. %% @todo headers
  822. %% @todo Don't send this if there are no streams left.
  823. % Transport:send(Socket, cow_http:response(500, 'HTTP/1.1', [
  824. % {<<"content-length">>, <<"0">>}
  825. % ])),
  826. %% @todo update IsFin local
  827. % stream_terminate(State#state{out_state=done}, StreamID, StreamError).
  828. stream_terminate(State, StreamID, StreamError).
  829. stream_terminate(State=#state{socket=Socket, transport=Transport, handler=Handler,
  830. out_streamid=OutStreamID, out_state=OutState,
  831. streams=Streams0, children=Children0}, StreamID, Reason) ->
  832. {value, #stream{state=StreamState, version=Version}, Streams}
  833. = lists:keytake(StreamID, #stream.id, Streams0),
  834. _ = case OutState of
  835. wait ->
  836. Transport:send(Socket, cow_http:response(204, 'HTTP/1.1', []));
  837. chunked when Version =:= 'HTTP/1.1' ->
  838. Transport:send(Socket, <<"0\r\n\r\n">>);
  839. _ -> %% done or Version =:= 'HTTP/1.0'
  840. ok
  841. end,
  842. stream_call_terminate(StreamID, Reason, Handler, StreamState),
  843. %% @todo initiate children shutdown
  844. % Children = stream_terminate_children(Children0, StreamID, []),
  845. Children = [case C of
  846. {Pid, StreamID, Shutdown} -> {Pid, undefined, Shutdown};
  847. _ -> C
  848. end || C <- Children0],
  849. %% @todo Skip the body, if any, or drop the connection if too large.
  850. %% @todo Only do this if Current =:= StreamID.
  851. NextOutStreamID = OutStreamID + 1,
  852. case lists:keyfind(NextOutStreamID, #stream.id, Streams) of
  853. false ->
  854. %% @todo This is clearly wrong, if the stream is gone we need to check if
  855. %% there used to be such a stream, and if there was to send an error.
  856. State#state{out_streamid=NextOutStreamID, out_state=wait, streams=Streams, children=Children};
  857. #stream{queue=Commands} ->
  858. %% @todo Remove queue from the stream.
  859. commands(State#state{out_streamid=NextOutStreamID, out_state=wait,
  860. streams=Streams, children=Children}, NextOutStreamID, Commands)
  861. end.
  862. %% @todo Taken directly from _http2
  863. stream_call_terminate(StreamID, Reason, Handler, StreamState) ->
  864. try
  865. Handler:terminate(StreamID, Reason, StreamState),
  866. ok
  867. catch Class:Reason ->
  868. error_logger:error_msg("Exception occurred in ~s:terminate(~p, ~p, ~p) with reason ~p:~p.",
  869. [Handler, StreamID, Reason, StreamState, Class, Reason])
  870. end.
  871. %stream_terminate_children([], _, Acc) ->
  872. % Acc;
  873. %stream_terminate_children([{Pid, StreamID}|Tail], StreamID, Acc) ->
  874. % exit(Pid, kill),
  875. % stream_terminate_children(Tail, StreamID, Acc);
  876. %stream_terminate_children([Child|Tail], StreamID, Acc) ->
  877. % stream_terminate_children(Tail, StreamID, [Child|Acc]).
  878. %% @todo max_reqs also
  879. maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.0') ->
  880. Conns = cow_http_hd:parse_connection(Conn),
  881. case lists:member(<<"keep-alive">>, Conns) of
  882. true -> keepalive;
  883. false -> close
  884. end;
  885. maybe_req_close(_, _, 'HTTP/1.0') ->
  886. close;
  887. maybe_req_close(_, #{<<"connection">> := Conn}, 'HTTP/1.1') ->
  888. case connection_hd_is_close(Conn) of
  889. true -> close;
  890. false -> keepalive
  891. end;
  892. maybe_req_close(_State, _, _) ->
  893. keepalive.
  894. connection(State=#state{last_streamid=StreamID}, Headers=#{<<"connection">> := Conn}, StreamID, _) ->
  895. case connection_hd_is_close(Conn) of
  896. true -> {State, Headers};
  897. %% @todo Here we need to remove keep-alive and add close, not just add close.
  898. false -> {State, Headers#{<<"connection">> => [<<"close, ">>, Conn]}}
  899. end;
  900. connection(State=#state{last_streamid=StreamID}, Headers, StreamID, _) ->
  901. {State, Headers#{<<"connection">> => <<"close">>}};
  902. connection(State, Headers=#{<<"connection">> := Conn}, StreamID, _) ->
  903. case connection_hd_is_close(Conn) of
  904. true -> {State#state{last_streamid=StreamID}, Headers};
  905. %% @todo Here we need to set keep-alive only if it wasn't set before.
  906. false -> {State, Headers}
  907. end;
  908. connection(State, Headers, _, 'HTTP/1.0') ->
  909. {State, Headers#{<<"connection">> => <<"keep-alive">>}};
  910. connection(State, Headers, _, _) ->
  911. {State, Headers}.
  912. connection_hd_is_close(Conn) ->
  913. Conns = cow_http_hd:parse_connection(iolist_to_binary(Conn)),
  914. lists:member(<<"close">>, Conns).
  915. error_terminate(StatusCode, State=#state{socket=Socket, transport=Transport}, Reason) ->
  916. Transport:send(Socket, cow_http:response(StatusCode, 'HTTP/1.1', [
  917. {<<"content-length">>, <<"0">>}
  918. ])),
  919. terminate(State, Reason).
  920. terminate(_State, _Reason) ->
  921. exit(normal). %% @todo
  922. %% System callbacks.
  923. -spec system_continue(_, _, #state{}) -> ok.
  924. system_continue(_, _, {State, Buffer}) ->
  925. loop(State, Buffer).
  926. -spec system_terminate(any(), _, _, _) -> no_return().
  927. system_terminate(Reason, _, _, _) ->
  928. exit(Reason).
  929. -spec system_code_change(Misc, _, _, _) -> {ok, Misc} when Misc::{#state{}, binary()}.
  930. system_code_change(Misc, _, _, _) ->
  931. {ok, Misc}.