cowboy_http.erl 48 KB

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