cowboy_http.erl 48 KB

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