cowboy_http.erl 41 KB

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