cowboy_req.erl 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190
  1. %% Copyright (c) 2011-2014, Loïc Hoguin <essen@ninenines.eu>
  2. %% Copyright (c) 2011, Anthony Ramine <nox@dev-extend.eu>
  3. %%
  4. %% Permission to use, copy, modify, and/or distribute this software for any
  5. %% purpose with or without fee is hereby granted, provided that the above
  6. %% copyright notice and this permission notice appear in all copies.
  7. %%
  8. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. -module(cowboy_req).
  16. %% Request API.
  17. -export([new/14]).
  18. -export([method/1]).
  19. -export([version/1]).
  20. -export([peer/1]).
  21. -export([host/1]).
  22. -export([host_info/1]).
  23. -export([port/1]).
  24. -export([path/1]).
  25. -export([path_info/1]).
  26. -export([qs/1]).
  27. -export([parse_qs/1]).
  28. -export([match_qs/2]).
  29. -export([host_url/1]).
  30. -export([url/1]).
  31. -export([binding/2]).
  32. -export([binding/3]).
  33. -export([bindings/1]).
  34. -export([header/2]).
  35. -export([header/3]).
  36. -export([headers/1]).
  37. -export([parse_header/2]).
  38. -export([parse_header/3]).
  39. -export([parse_cookies/1]).
  40. -export([match_cookies/2]).
  41. -export([meta/2]).
  42. -export([meta/3]).
  43. -export([set_meta/3]).
  44. %% Request body API.
  45. -export([has_body/1]).
  46. -export([body_length/1]).
  47. -export([read_body/1]).
  48. -export([read_body/2]).
  49. -export([body/1]).
  50. -export([body/2]).
  51. -export([body_qs/1]).
  52. -export([body_qs/2]).
  53. %% Multipart API.
  54. -export([part/1]).
  55. -export([part/2]).
  56. -export([part_body/1]).
  57. -export([part_body/2]).
  58. %% Response API.
  59. -export([set_resp_cookie/4]).
  60. -export([set_resp_header/3]).
  61. -export([set_resp_body/2]).
  62. -export([set_resp_body_fun/2]).
  63. -export([set_resp_body_fun/3]).
  64. -export([has_resp_header/2]).
  65. -export([has_resp_body/1]).
  66. -export([delete_resp_header/2]).
  67. -export([reply/2]).
  68. -export([reply/3]).
  69. -export([reply/4]).
  70. -export([send_body/3]).
  71. -export([chunked_reply/2]).
  72. -export([chunked_reply/3]).
  73. -export([chunk/2]).
  74. -export([continue/1]).
  75. -export([maybe_reply/2]).
  76. -export([ensure_response/2]).
  77. %% Private setter/getter API.
  78. -export([append_buffer/2]).
  79. -export([get/2]).
  80. -export([set/2]).
  81. -export([set_bindings/4]).
  82. -export([lock/1]).
  83. -export([to_list/1]).
  84. -type cookie_opts() :: cow_cookie:cookie_opts().
  85. -export_type([cookie_opts/0]).
  86. -type content_decode_fun() :: fun((binary()) -> binary()).
  87. -type transfer_decode_fun() :: fun((binary(), any())
  88. -> cow_http_te:decode_ret()).
  89. -type body_opts() :: [{continue, boolean()} %% doesn't apply
  90. | {length, non_neg_integer()}
  91. | {read_length, non_neg_integer()} %% to be added back later as optimization
  92. | {read_timeout, timeout()} %% same
  93. | {transfer_decode, transfer_decode_fun(), any()} %% doesn't apply
  94. | {content_decode, content_decode_fun()}]. %% does apply
  95. -export_type([body_opts/0]).
  96. -type resp_body_fun() :: fun((any(), module()) -> ok).
  97. -type send_chunk_fun() :: fun((iodata()) -> ok).
  98. -type resp_chunked_fun() :: fun((send_chunk_fun()) -> ok).
  99. -record(http_req, {
  100. %% Transport.
  101. socket = undefined :: any(),
  102. transport = undefined :: undefined | module(),
  103. connection = keepalive :: keepalive | close,
  104. %% Request.
  105. pid = undefined :: pid(),
  106. method = <<"GET">> :: binary(),
  107. version = 'HTTP/1.1' :: cowboy:http_version(),
  108. peer = undefined :: undefined | {inet:ip_address(), inet:port_number()},
  109. host = undefined :: undefined | binary(),
  110. host_info = undefined :: undefined | cowboy_router:tokens(),
  111. port = undefined :: undefined | inet:port_number(),
  112. path = undefined :: binary(),
  113. path_info = undefined :: undefined | cowboy_router:tokens(),
  114. qs = undefined :: binary(),
  115. bindings = undefined :: undefined | cowboy_router:bindings(),
  116. headers = [] :: cowboy:http_headers(),
  117. meta = [] :: [{atom(), any()}],
  118. %% Request body.
  119. body_state = waiting :: waiting | done | {stream, non_neg_integer(),
  120. transfer_decode_fun(), any(), content_decode_fun()},
  121. buffer = <<>> :: binary(),
  122. multipart = undefined :: undefined | {binary(), binary()},
  123. %% Response.
  124. resp_compress = false :: boolean(),
  125. resp_state = waiting :: locked | waiting | waiting_stream
  126. | chunks | stream | done,
  127. resp_headers = [] :: cowboy:http_headers(),
  128. resp_body = <<>> :: iodata() | resp_body_fun()
  129. | {non_neg_integer(), resp_body_fun()}
  130. | {chunked, resp_chunked_fun()},
  131. %% Functions.
  132. onresponse = undefined :: undefined | already_called
  133. | cowboy:onresponse_fun()
  134. }).
  135. -opaque req() :: #http_req{}.
  136. -export_type([req/0]).
  137. %% Request API.
  138. -spec new(any(), module(),
  139. undefined | {inet:ip_address(), inet:port_number()},
  140. binary(), binary(), binary(),
  141. cowboy:http_version(), cowboy:http_headers(), binary(),
  142. inet:port_number() | undefined, binary(), boolean(), boolean(),
  143. undefined | cowboy:onresponse_fun())
  144. -> req().
  145. new(Socket, Transport, Peer, Method, Path, Query,
  146. Version, Headers, Host, Port, Buffer, CanKeepalive,
  147. Compress, OnResponse) ->
  148. Req = #http_req{socket=Socket, transport=Transport, pid=self(), peer=Peer,
  149. method=Method, path=Path, qs=Query, version=Version,
  150. headers=Headers, host=Host, port=Port, buffer=Buffer,
  151. resp_compress=Compress, onresponse=OnResponse},
  152. case CanKeepalive of
  153. false ->
  154. Req#http_req{connection=close};
  155. true ->
  156. case parse_header(<<"connection">>, Req) of
  157. undefined ->
  158. case Version of
  159. 'HTTP/1.1' -> Req; %% keepalive
  160. 'HTTP/1.0' -> Req#http_req{connection=close}
  161. end;
  162. Tokens ->
  163. Connection = connection_to_atom(Tokens),
  164. Req#http_req{connection=Connection}
  165. end
  166. end.
  167. -spec method(req()) -> binary().
  168. method(#{method := Method}) ->
  169. Method.
  170. -spec version(req()) -> cowboy:http_version().
  171. version(#{version := Version}) ->
  172. Version.
  173. -spec peer(req()) -> {inet:ip_address(), inet:port_number()} | undefined.
  174. peer(Req) ->
  175. Req#http_req.peer.
  176. -spec host(req()) -> binary().
  177. host(#{host := Host}) ->
  178. Host.
  179. -spec host_info(req()) -> cowboy_router:tokens() | undefined.
  180. host_info(#{host_info := HostInfo}) ->
  181. HostInfo.
  182. -spec port(req()) -> inet:port_number().
  183. port(#{port := Port}) ->
  184. Port.
  185. -spec path(req()) -> binary().
  186. path(#{path := Path}) ->
  187. Path.
  188. -spec path_info(req()) -> cowboy_router:tokens() | undefined.
  189. path_info(#{path_info := PathInfo}) ->
  190. PathInfo.
  191. -spec qs(req()) -> binary().
  192. qs(#{qs := Qs}) ->
  193. Qs.
  194. -spec parse_qs(req()) -> [{binary(), binary() | true}].
  195. parse_qs(#{qs := Qs}) ->
  196. cow_qs:parse_qs(Qs).
  197. -spec match_qs(cowboy:fields(), req()) -> map().
  198. match_qs(Fields, Req) ->
  199. filter(Fields, kvlist_to_map(Fields, parse_qs(Req))).
  200. %% The URL includes the scheme, host and port only.
  201. -spec host_url(req()) -> undefined | binary().
  202. host_url(#{port := undefined}) ->
  203. undefined;
  204. host_url(#{scheme := Scheme, host := Host, port := Port}) ->
  205. PortBin = case {Scheme, Port} of
  206. {<<"https">>, 443} -> <<>>;
  207. {<<"http">>, 80} -> <<>>;
  208. _ -> << ":", (integer_to_binary(Port))/binary >>
  209. end,
  210. << Scheme/binary, "://", Host/binary, PortBin/binary >>.
  211. %% The URL includes the scheme, host, port, path and query string.
  212. -spec url(req()) -> undefined | binary().
  213. url(Req) ->
  214. url(Req, host_url(Req)).
  215. url(_, undefined) ->
  216. undefined;
  217. url(#{path := Path, qs := QS}, HostURL) ->
  218. QS2 = case QS of
  219. <<>> -> <<>>;
  220. _ -> << "?", QS/binary >>
  221. end,
  222. << HostURL/binary, Path/binary, QS2/binary >>.
  223. -spec binding(atom(), req()) -> any() | undefined.
  224. binding(Name, Req) ->
  225. binding(Name, Req, undefined).
  226. -spec binding(atom(), req(), Default) -> any() | Default when Default::any().
  227. binding(Name, #{bindings := Bindings}, Default) when is_atom(Name) ->
  228. case lists:keyfind(Name, 1, Bindings) of
  229. {_, Value} -> Value;
  230. false -> Default
  231. end;
  232. binding(Name, _, Default) when is_atom(Name) ->
  233. Default.
  234. -spec bindings(req()) -> [{atom(), any()}].
  235. bindings(#{bindings := Bindings}) ->
  236. Bindings;
  237. bindings(_) ->
  238. [].
  239. -spec header(binary(), req()) -> binary() | undefined.
  240. header(Name, Req) ->
  241. header(Name, Req, undefined).
  242. -spec header(binary(), req(), Default) -> binary() | Default when Default::any().
  243. header(Name, #{headers := Headers}, Default) ->
  244. maps:get(Name, Headers, Default).
  245. -spec headers(req()) -> cowboy:http_headers().
  246. headers(#{headers := Headers}) ->
  247. Headers.
  248. -spec parse_header(binary(), Req) -> any() when Req::req().
  249. parse_header(Name = <<"content-length">>, Req) ->
  250. parse_header(Name, Req, 0, fun cow_http_hd:parse_content_length/1);
  251. parse_header(Name = <<"cookie">>, Req) ->
  252. parse_header(Name, Req, [], fun cow_cookie:parse_cookie/1);
  253. parse_header(Name = <<"transfer-encoding">>, Req) ->
  254. parse_header(Name, Req, [<<"identity">>], fun cow_http_hd:parse_transfer_encoding/1);
  255. parse_header(Name, Req) ->
  256. parse_header(Name, Req, undefined).
  257. -spec parse_header(binary(), Req, any()) -> any() when Req::req().
  258. parse_header(Name, Req, Default) ->
  259. parse_header(Name, Req, Default, parse_header_fun(Name)).
  260. parse_header_fun(<<"accept">>) -> fun cow_http_hd:parse_accept/1;
  261. parse_header_fun(<<"accept-charset">>) -> fun cow_http_hd:parse_accept_charset/1;
  262. parse_header_fun(<<"accept-encoding">>) -> fun cow_http_hd:parse_accept_encoding/1;
  263. parse_header_fun(<<"accept-language">>) -> fun cow_http_hd:parse_accept_language/1;
  264. parse_header_fun(<<"authorization">>) -> fun cow_http_hd:parse_authorization/1;
  265. parse_header_fun(<<"connection">>) -> fun cow_http_hd:parse_connection/1;
  266. parse_header_fun(<<"content-length">>) -> fun cow_http_hd:parse_content_length/1;
  267. parse_header_fun(<<"content-type">>) -> fun cow_http_hd:parse_content_type/1;
  268. parse_header_fun(<<"cookie">>) -> fun cow_cookie:parse_cookie/1;
  269. parse_header_fun(<<"expect">>) -> fun cow_http_hd:parse_expect/1;
  270. parse_header_fun(<<"if-match">>) -> fun cow_http_hd:parse_if_match/1;
  271. parse_header_fun(<<"if-modified-since">>) -> fun cow_http_hd:parse_if_modified_since/1;
  272. parse_header_fun(<<"if-none-match">>) -> fun cow_http_hd:parse_if_none_match/1;
  273. parse_header_fun(<<"if-unmodified-since">>) -> fun cow_http_hd:parse_if_unmodified_since/1;
  274. parse_header_fun(<<"range">>) -> fun cow_http_hd:parse_range/1;
  275. parse_header_fun(<<"sec-websocket-extensions">>) -> fun cow_http_hd:parse_sec_websocket_extensions/1;
  276. parse_header_fun(<<"sec-websocket-protocol">>) -> fun cow_http_hd:parse_sec_websocket_protocol_req/1;
  277. parse_header_fun(<<"transfer-encoding">>) -> fun cow_http_hd:parse_transfer_encoding/1;
  278. parse_header_fun(<<"upgrade">>) -> fun cow_http_hd:parse_upgrade/1;
  279. parse_header_fun(<<"x-forwarded-for">>) -> fun cow_http_hd:parse_x_forwarded_for/1.
  280. parse_header(Name, Req, Default, ParseFun) ->
  281. case header(Name, Req) of
  282. undefined -> Default;
  283. Value -> ParseFun(Value)
  284. end.
  285. -spec parse_cookies(req()) -> [{binary(), binary()}].
  286. parse_cookies(Req) ->
  287. parse_header(<<"cookie">>, Req).
  288. -spec match_cookies(cowboy:fields(), req()) -> map().
  289. match_cookies(Fields, Req) ->
  290. filter(Fields, kvlist_to_map(Fields, parse_cookies(Req))).
  291. -spec meta(atom(), req()) -> any() | undefined.
  292. meta(Name, Req) ->
  293. meta(Name, Req, undefined).
  294. -spec meta(atom(), req(), any()) -> any().
  295. meta(Name, Req, Default) ->
  296. case lists:keyfind(Name, 1, Req#http_req.meta) of
  297. {Name, Value} -> Value;
  298. false -> Default
  299. end.
  300. -spec set_meta(atom(), any(), Req) -> Req when Req::req().
  301. set_meta(Name, Value, Req=#http_req{meta=Meta}) ->
  302. Req#http_req{meta=lists:keystore(Name, 1, Meta, {Name, Value})}.
  303. %% Request Body API.
  304. -spec has_body(req()) -> boolean().
  305. has_body(#{has_body := HasBody}) ->
  306. HasBody.
  307. %% The length may not be known if Transfer-Encoding is not identity,
  308. %% and the body hasn't been read at the time of the call.
  309. -spec body_length(req()) -> undefined | non_neg_integer().
  310. body_length(#{body_length := Length}) ->
  311. Length.
  312. -spec body(Req) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req().
  313. body(Req) ->
  314. body(Req, []).
  315. -spec read_body(Req) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req().
  316. read_body(Req) ->
  317. read_body(Req, []).
  318. -spec read_body(Req, body_opts()) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req().
  319. read_body(Req=#{pid := Pid, streamid := StreamID}, Opts) ->
  320. %% @todo Opts should be a map
  321. Length = case lists:keyfind(length, 1, Opts) of
  322. false -> 8000000;
  323. {_, ChunkLen0} -> ChunkLen0
  324. end,
  325. ReadTimeout = case lists:keyfind(read_timeout, 1, Opts) of
  326. false -> 15000;
  327. {_, ReadTimeout0} -> ReadTimeout0
  328. end,
  329. Ref = make_ref(),
  330. Pid ! {{Pid, StreamID}, {read_body, Ref, Length}},
  331. % io:format("READ_BODY ~p ~p ~p ~p~n", [Pid, StreamID, Ref, Length]),
  332. receive
  333. {request_body, Ref, nofin, Body} ->
  334. {more, Body, Req};
  335. {request_body, Ref, {fin, BodyLength}, Body} ->
  336. {ok, Body, set_body_length(Req, BodyLength)}
  337. after ReadTimeout ->
  338. exit(read_body_timeout)
  339. end.
  340. set_body_length(Req=#{headers := Headers}, BodyLength) ->
  341. Req#{
  342. headers => Headers#{<<"content-length">> => integer_to_binary(BodyLength)},
  343. body_length => BodyLength
  344. }.
  345. -spec body(Req, body_opts()) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req().
  346. body(Req=#http_req{body_state=waiting}, Opts) ->
  347. %% Send a 100 continue if needed (enabled by default).
  348. case lists:keyfind(continue, 1, Opts) of
  349. {_, false} ->
  350. ok;
  351. _ ->
  352. ExpectHeader = parse_header(<<"expect">>, Req),
  353. ok = case ExpectHeader of
  354. continue -> continue(Req);
  355. _ -> ok
  356. end
  357. end,
  358. %% Initialize body streaming state.
  359. CFun = case lists:keyfind(content_decode, 1, Opts) of
  360. false ->
  361. fun body_content_decode_identity/1;
  362. {_, CFun0} ->
  363. CFun0
  364. end,
  365. case lists:keyfind(transfer_decode, 1, Opts) of
  366. false ->
  367. case parse_header(<<"transfer-encoding">>, Req) of
  368. [<<"chunked">>] ->
  369. body(Req#http_req{body_state={stream, 0,
  370. fun cow_http_te:stream_chunked/2, {0, 0}, CFun}}, Opts);
  371. [<<"identity">>] ->
  372. case body_length(Req) of
  373. 0 ->
  374. {ok, <<>>, Req#http_req{body_state=done}};
  375. Len ->
  376. body(Req#http_req{body_state={stream, Len,
  377. fun cow_http_te:stream_identity/2, {0, Len},
  378. CFun}}, Opts)
  379. end
  380. end;
  381. {_, TFun, TState} ->
  382. body(Req#http_req{body_state={stream, 0,
  383. TFun, TState, CFun}}, Opts)
  384. end;
  385. body(Req=#http_req{body_state=done}, _) ->
  386. {ok, <<>>, Req};
  387. body(Req, Opts) ->
  388. ChunkLen = case lists:keyfind(length, 1, Opts) of
  389. false -> 8000000;
  390. {_, ChunkLen0} -> ChunkLen0
  391. end,
  392. ReadLen = case lists:keyfind(read_length, 1, Opts) of
  393. false -> 1000000;
  394. {_, ReadLen0} -> ReadLen0
  395. end,
  396. ReadTimeout = case lists:keyfind(read_timeout, 1, Opts) of
  397. false -> 15000;
  398. {_, ReadTimeout0} -> ReadTimeout0
  399. end,
  400. body_loop(Req, ReadTimeout, ReadLen, ChunkLen, <<>>).
  401. %% Default identity function for content decoding.
  402. %% @todo Move into cowlib when more content decode functions get implemented.
  403. body_content_decode_identity(Data) -> Data.
  404. body_loop(Req=#http_req{buffer=Buffer, body_state={stream, Length, _, _, _}},
  405. ReadTimeout, ReadLength, ChunkLength, Acc) ->
  406. {Tag, Res, Req2} = case Buffer of
  407. <<>> ->
  408. body_recv(Req, ReadTimeout, min(Length, ReadLength));
  409. _ ->
  410. body_decode(Req, ReadTimeout)
  411. end,
  412. case {Tag, Res} of
  413. {ok, Data} ->
  414. {ok, << Acc/binary, Data/binary >>, Req2};
  415. {more, Data} ->
  416. Acc2 = << Acc/binary, Data/binary >>,
  417. case byte_size(Acc2) >= ChunkLength of
  418. true -> {more, Acc2, Req2};
  419. false -> body_loop(Req2, ReadTimeout, ReadLength, ChunkLength, Acc2)
  420. end
  421. end.
  422. body_recv(Req=#http_req{transport=Transport, socket=Socket, buffer=Buffer},
  423. ReadTimeout, ReadLength) ->
  424. {ok, Data} = Transport:recv(Socket, ReadLength, ReadTimeout),
  425. body_decode(Req#http_req{buffer= << Buffer/binary, Data/binary >>}, ReadTimeout).
  426. %% Two decodings happen. First a decoding function is applied to the
  427. %% transferred data, and then another is applied to the actual content.
  428. %%
  429. %% Transfer encoding is generally used for chunked bodies. The decoding
  430. %% function uses a state to keep track of how much it has read, which is
  431. %% also initialized through this function.
  432. %%
  433. %% Content encoding is generally used for compression.
  434. %%
  435. %% @todo Handle chunked after-the-facts headers.
  436. %% @todo Depending on the length returned we might want to 0 or +5 it.
  437. body_decode(Req=#http_req{buffer=Data, body_state={stream, _,
  438. TDecode, TState, CDecode}}, ReadTimeout) ->
  439. case TDecode(Data, TState) of
  440. more ->
  441. body_recv(Req#http_req{body_state={stream, 0,
  442. TDecode, TState, CDecode}}, ReadTimeout, 0);
  443. {more, Data2, TState2} ->
  444. {more, CDecode(Data2), Req#http_req{body_state={stream, 0,
  445. TDecode, TState2, CDecode}, buffer= <<>>}};
  446. {more, Data2, Length, TState2} when is_integer(Length) ->
  447. {more, CDecode(Data2), Req#http_req{body_state={stream, Length,
  448. TDecode, TState2, CDecode}, buffer= <<>>}};
  449. {more, Data2, Rest, TState2} ->
  450. {more, CDecode(Data2), Req#http_req{body_state={stream, 0,
  451. TDecode, TState2, CDecode}, buffer=Rest}};
  452. {done, TotalLength, Rest} ->
  453. {ok, <<>>, body_decode_end(Req, TotalLength, Rest)};
  454. {done, Data2, TotalLength, Rest} ->
  455. {ok, CDecode(Data2), body_decode_end(Req, TotalLength, Rest)}
  456. end.
  457. body_decode_end(Req=#http_req{headers=Headers}, TotalLength, Rest) ->
  458. Headers2 = lists:keystore(<<"content-length">>, 1, Headers,
  459. {<<"content-length">>, integer_to_binary(TotalLength)}),
  460. %% At this point we just assume TEs were all decoded.
  461. Headers3 = lists:keydelete(<<"transfer-encoding">>, 1, Headers2),
  462. Req#http_req{buffer=Rest, body_state=done, headers=Headers3}.
  463. -spec body_qs(Req) -> {ok, [{binary(), binary() | true}], Req}
  464. | {badlength, Req} when Req::req().
  465. body_qs(Req) ->
  466. body_qs(Req, [
  467. {length, 64000},
  468. {read_length, 64000},
  469. {read_timeout, 5000}]).
  470. -spec body_qs(Req, body_opts()) -> {ok, [{binary(), binary() | true}], Req}
  471. | {badlength, Req} when Req::req().
  472. body_qs(Req, Opts) ->
  473. case read_body(Req, Opts) of
  474. {ok, Body, Req2} ->
  475. {ok, cow_qs:parse_qs(Body), Req2};
  476. {more, _, Req2} ->
  477. {badlength, Req2}
  478. end.
  479. %% Multipart API.
  480. -spec part(Req)
  481. -> {ok, cow_multipart:headers(), Req} | {done, Req}
  482. when Req::req().
  483. part(Req) ->
  484. part(Req, [
  485. {length, 64000},
  486. {read_length, 64000},
  487. {read_timeout, 5000}]).
  488. -spec part(Req, body_opts())
  489. -> {ok, cow_multipart:headers(), Req} | {done, Req}
  490. when Req::req().
  491. part(Req, Opts) ->
  492. case maps:is_key(multipart, Req) of
  493. true ->
  494. {Data, Req2} = stream_multipart(Req, Opts),
  495. part(Data, Opts, Req2);
  496. false ->
  497. part(init_multipart(Req), Opts)
  498. end.
  499. part(Buffer, Opts, Req=#{multipart := {Boundary, _}}) ->
  500. case cow_multipart:parse_headers(Buffer, Boundary) of
  501. more ->
  502. {Data, Req2} = stream_multipart(Req, Opts),
  503. part(<< Buffer/binary, Data/binary >>, Opts, Req2);
  504. {more, Buffer2} ->
  505. {Data, Req2} = stream_multipart(Req, Opts),
  506. part(<< Buffer2/binary, Data/binary >>, Opts, Req2);
  507. {ok, Headers, Rest} ->
  508. {ok, Headers, Req#{multipart => {Boundary, Rest}}};
  509. %% Ignore epilogue.
  510. {done, _} ->
  511. {done, Req#{multipart => done}}
  512. end.
  513. -spec part_body(Req)
  514. -> {ok, binary(), Req} | {more, binary(), Req}
  515. when Req::req().
  516. part_body(Req) ->
  517. part_body(Req, []).
  518. -spec part_body(Req, body_opts())
  519. -> {ok, binary(), Req} | {more, binary(), Req}
  520. when Req::req().
  521. part_body(Req, Opts) ->
  522. case maps:is_key(multipart, Req) of
  523. true ->
  524. part_body(<<>>, Opts, Req, <<>>);
  525. false ->
  526. part_body(init_multipart(Req), Opts)
  527. end.
  528. part_body(Buffer, Opts, Req=#{multipart := {Boundary, _}}, Acc) ->
  529. ChunkLen = case lists:keyfind(length, 1, Opts) of
  530. false -> 8000000;
  531. {_, ChunkLen0} -> ChunkLen0
  532. end,
  533. case byte_size(Acc) > ChunkLen of
  534. true ->
  535. {more, Acc, Req#{multipart => {Boundary, Buffer}}};
  536. false ->
  537. {Data, Req2} = stream_multipart(Req, Opts),
  538. case cow_multipart:parse_body(<< Buffer/binary, Data/binary >>, Boundary) of
  539. {ok, Body} ->
  540. part_body(<<>>, Opts, Req2, << Acc/binary, Body/binary >>);
  541. {ok, Body, Rest} ->
  542. part_body(Rest, Opts, Req2, << Acc/binary, Body/binary >>);
  543. done ->
  544. {ok, Acc, Req2};
  545. {done, Body} ->
  546. {ok, << Acc/binary, Body/binary >>, Req2};
  547. {done, Body, Rest} ->
  548. {ok, << Acc/binary, Body/binary >>,
  549. Req2#{multipart => {Boundary, Rest}}}
  550. end
  551. end.
  552. init_multipart(Req) ->
  553. {<<"multipart">>, _, Params} = parse_header(<<"content-type">>, Req),
  554. {_, Boundary} = lists:keyfind(<<"boundary">>, 1, Params),
  555. Req#{multipart => {Boundary, <<>>}}.
  556. stream_multipart(Req=#{multipart := done}, _) ->
  557. {<<>>, Req};
  558. stream_multipart(Req=#{multipart := {_, <<>>}}, Opts) ->
  559. {_, Data, Req2} = read_body(Req, Opts),
  560. {Data, Req2};
  561. stream_multipart(Req=#{multipart := {Boundary, Buffer}}, _) ->
  562. {Buffer, Req#{multipart => {Boundary, <<>>}}}.
  563. %% Response API.
  564. %% The cookie name cannot contain any of the following characters:
  565. %% =,;\s\t\r\n\013\014
  566. %%
  567. %% The cookie value cannot contain any of the following characters:
  568. %% ,; \t\r\n\013\014
  569. -spec set_resp_cookie(iodata(), iodata(), cookie_opts(), Req)
  570. -> Req when Req::req().
  571. set_resp_cookie(Name, Value, Opts, Req) ->
  572. Cookie = cow_cookie:setcookie(Name, Value, Opts),
  573. %% @todo Nah, keep separate.
  574. set_resp_header(<<"set-cookie">>, Cookie, Req).
  575. -spec set_resp_header(binary(), iodata(), Req)
  576. -> Req when Req::req().
  577. set_resp_header(Name, Value, Req=#{resp_headers := RespHeaders}) ->
  578. Req#{resp_headers => RespHeaders#{Name => Value}};
  579. set_resp_header(Name,Value, Req) ->
  580. Req#{resp_headers => #{Name => Value}}.
  581. %% @todo {sendfile, Offset, Bytes, Path} tuple
  582. -spec set_resp_body(iodata(), Req) -> Req when Req::req().
  583. set_resp_body(Body, Req) ->
  584. Req#{resp_body => Body}.
  585. %set_resp_body(Body, Req) ->
  586. % Req#http_req{resp_body=Body}.
  587. -spec set_resp_body_fun(resp_body_fun(), Req) -> Req when Req::req().
  588. set_resp_body_fun(StreamFun, Req) when is_function(StreamFun) ->
  589. Req#http_req{resp_body=StreamFun}.
  590. %% If the body function crashes while writing the response body or writes
  591. %% fewer bytes than declared the behaviour is undefined.
  592. -spec set_resp_body_fun(non_neg_integer(), resp_body_fun(), Req)
  593. -> Req when Req::req();
  594. (chunked, resp_chunked_fun(), Req)
  595. -> Req when Req::req().
  596. set_resp_body_fun(StreamLen, StreamFun, Req)
  597. when is_integer(StreamLen), is_function(StreamFun) ->
  598. Req#http_req{resp_body={StreamLen, StreamFun}};
  599. set_resp_body_fun(chunked, StreamFun, Req)
  600. when is_function(StreamFun) ->
  601. Req#http_req{resp_body={chunked, StreamFun}}.
  602. -spec has_resp_header(binary(), req()) -> boolean().
  603. has_resp_header(Name, #{resp_headers := RespHeaders}) ->
  604. maps:is_key(Name, RespHeaders);
  605. has_resp_header(_, _) ->
  606. false.
  607. -spec has_resp_body(req()) -> boolean().
  608. has_resp_body(#{resp_body := {sendfile, Len, _}}) ->
  609. Len > 0;
  610. has_resp_body(#{resp_body := RespBody}) ->
  611. iolist_size(RespBody) > 0;
  612. has_resp_body(_) ->
  613. false.
  614. %has_resp_body(#http_req{resp_body=RespBody}) when is_function(RespBody) ->
  615. % true;
  616. %has_resp_body(#http_req{resp_body={chunked, _}}) ->
  617. % true;
  618. %has_resp_body(#http_req{resp_body={Length, _}}) ->
  619. % Length > 0;
  620. %has_resp_body(#http_req{resp_body=RespBody}) ->
  621. % iolist_size(RespBody) > 0.
  622. -spec delete_resp_header(binary(), Req)
  623. -> Req when Req::req().
  624. delete_resp_header(Name, Req=#{resp_headers := RespHeaders}) ->
  625. Req#{resp_headers => maps:remove(Name, RespHeaders)}.
  626. -spec reply(cowboy:http_status(), Req) -> Req when Req::req().
  627. reply(Status, Req) ->
  628. reply(Status, #{}, Req).
  629. -spec reply(cowboy:http_status(), cowboy:http_headers(), Req)
  630. -> Req when Req::req().
  631. reply(Status, Headers, Req=#{resp_body := Body}) ->
  632. reply(Status, Headers, Body, Req);
  633. reply(Status, Headers, Req) ->
  634. reply(Status, Headers, <<>>, Req).
  635. -spec reply(cowboy:http_status(), cowboy:http_headers(),
  636. iodata() | resp_body_fun() | {non_neg_integer(), resp_body_fun()}
  637. | {chunked, resp_chunked_fun()}, Req)
  638. -> Req when Req::req().
  639. reply(Status, Headers, Stream = {stream, undefined, _}, Req) ->
  640. do_stream_reply(Status, Headers, Stream, Req);
  641. reply(Status, Headers, Stream = {stream, Len, _}, Req) ->
  642. do_stream_reply(Status, Headers#{
  643. <<"content-length">> => integer_to_binary(Len)
  644. }, Stream, Req);
  645. reply(Status, Headers, SendFile = {sendfile, _, Len, _}, Req) ->
  646. do_reply(Status, Headers#{
  647. <<"content-length">> => integer_to_binary(Len)
  648. }, SendFile, Req);
  649. reply(Status, Headers, Body, Req) ->
  650. do_reply(Status, Headers#{
  651. <<"content-length">> => integer_to_binary(iolist_size(Body))
  652. }, Body, Req).
  653. do_stream_reply(Status, Headers, {stream, _, Fun}, Req=#{pid := Pid, streamid := StreamID}) ->
  654. Pid ! {{Pid, StreamID}, {headers, Status, response_headers(Headers, Req)}},
  655. Fun(),
  656. ok.
  657. do_reply(Status, Headers, Body, Req=#{pid := Pid, streamid := StreamID}) ->
  658. Pid ! {{Pid, StreamID}, {response, Status, response_headers(Headers, Req), Body}},
  659. ok.
  660. -spec send_body(iodata(), fin | nofin, req()) -> ok.
  661. send_body(Data, IsFin, #{pid := Pid, streamid := StreamID}) ->
  662. Pid ! {{Pid, StreamID}, {data, IsFin, Data}},
  663. ok.
  664. response_headers(Headers, Req) ->
  665. RespHeaders = maps:get(resp_headers, Req, #{}),
  666. maps:merge(#{
  667. <<"date">> => cowboy_clock:rfc1123(),
  668. <<"server">> => <<"Cowboy">>
  669. }, maps:merge(RespHeaders, Headers)).
  670. %reply(Status, Headers, Body, Req=#http_req{
  671. % socket=Socket, transport=Transport,
  672. % version=Version, connection=Connection,
  673. % method=Method, resp_compress=Compress,
  674. % resp_state=RespState, resp_headers=RespHeaders})
  675. % when RespState =:= waiting; RespState =:= waiting_stream ->
  676. % Req3 = case Body of
  677. % BodyFun when is_function(BodyFun) ->
  678. % %% We stream the response body until we close the connection.
  679. % RespConn = close,
  680. % {RespType, Req2} = if
  681. % true ->
  682. % response(Status, Headers, RespHeaders, [
  683. % {<<"connection">>, <<"close">>},
  684. % {<<"date">>, cowboy_clock:rfc1123()},
  685. % {<<"server">>, <<"Cowboy">>},
  686. % {<<"transfer-encoding">>, <<"identity">>}
  687. % ], <<>>, Req)
  688. % end,
  689. % if RespType =/= hook, Method =/= <<"HEAD">> ->
  690. % BodyFun(Socket, Transport);
  691. % true -> ok
  692. % end,
  693. % Req2#http_req{connection=RespConn};
  694. % {chunked, BodyFun} ->
  695. % %% We stream the response body in chunks.
  696. % {RespType, Req2} = chunked_response(Status, Headers, Req),
  697. % if RespType =/= hook, Method =/= <<"HEAD">> ->
  698. % ChunkFun = fun(IoData) -> chunk(IoData, Req2) end,
  699. % BodyFun(ChunkFun),
  700. % %% Send the last chunk if chunked encoding was used.
  701. % if
  702. % Version =:= 'HTTP/1.0'; RespState =:= waiting_stream ->
  703. % Req2;
  704. % true ->
  705. % last_chunk(Req2)
  706. % end;
  707. % true -> Req2
  708. % end;
  709. % {ContentLength, BodyFun} ->
  710. % %% We stream the response body for ContentLength bytes.
  711. % RespConn = response_connection(Headers, Connection),
  712. % {RespType, Req2} = response(Status, Headers, RespHeaders, [
  713. % {<<"content-length">>, integer_to_list(ContentLength)},
  714. % {<<"date">>, cowboy_clock:rfc1123()},
  715. % {<<"server">>, <<"Cowboy">>}
  716. % |HTTP11Headers], stream, Req),
  717. % if RespType =/= hook, Method =/= <<"HEAD">> ->
  718. % BodyFun(Socket, Transport);
  719. % true -> ok
  720. % end,
  721. % Req2#http_req{connection=RespConn};
  722. % _ when Compress ->
  723. % RespConn = response_connection(Headers, Connection),
  724. % Req2 = reply_may_compress(Status, Headers, Body, Req,
  725. % RespHeaders, HTTP11Headers, Method),
  726. % Req2#http_req{connection=RespConn};
  727. % _ ->
  728. % RespConn = response_connection(Headers, Connection),
  729. % Req2 = reply_no_compress(Status, Headers, Body, Req,
  730. % RespHeaders, HTTP11Headers, Method, iolist_size(Body)),
  731. % Req2#http_req{connection=RespConn}
  732. % end,
  733. % Req3#http_req{resp_state=done, resp_headers=[], resp_body= <<>>}.
  734. %reply_may_compress(Status, Headers, Body, Req,
  735. % RespHeaders, HTTP11Headers, Method) ->
  736. % BodySize = iolist_size(Body),
  737. % try parse_header(<<"accept-encoding">>, Req) of
  738. % Encodings ->
  739. % CanGzip = (BodySize > 300)
  740. % andalso (false =:= lists:keyfind(<<"content-encoding">>,
  741. % 1, Headers))
  742. % andalso (false =:= lists:keyfind(<<"content-encoding">>,
  743. % 1, RespHeaders))
  744. % andalso (false =:= lists:keyfind(<<"transfer-encoding">>,
  745. % 1, Headers))
  746. % andalso (false =:= lists:keyfind(<<"transfer-encoding">>,
  747. % 1, RespHeaders))
  748. % andalso (Encodings =/= undefined)
  749. % andalso (false =/= lists:keyfind(<<"gzip">>, 1, Encodings)),
  750. % case CanGzip of
  751. % true ->
  752. % GzBody = zlib:gzip(Body),
  753. % {_, Req2} = response(Status, Headers, RespHeaders, [
  754. % {<<"content-length">>, integer_to_list(byte_size(GzBody))},
  755. % {<<"content-encoding">>, <<"gzip">>},
  756. % |HTTP11Headers],
  757. % case Method of <<"HEAD">> -> <<>>; _ -> GzBody end,
  758. % Req),
  759. % Req2;
  760. % false ->
  761. % reply_no_compress(Status, Headers, Body, Req,
  762. % RespHeaders, HTTP11Headers, Method, BodySize)
  763. % end
  764. % catch _:_ ->
  765. % reply_no_compress(Status, Headers, Body, Req,
  766. % RespHeaders, HTTP11Headers, Method, BodySize)
  767. % end.
  768. %
  769. %reply_no_compress(Status, Headers, Body, Req,
  770. % RespHeaders, HTTP11Headers, Method, BodySize) ->
  771. % {_, Req2} = response(Status, Headers, RespHeaders, [
  772. % {<<"content-length">>, integer_to_list(BodySize)},
  773. % |HTTP11Headers],
  774. % case Method of <<"HEAD">> -> <<>>; _ -> Body end,
  775. % Req),
  776. % Req2.
  777. -spec chunked_reply(cowboy:http_status(), Req) -> Req when Req::req().
  778. chunked_reply(Status, Req) ->
  779. chunked_reply(Status, #{}, Req).
  780. -spec chunked_reply(cowboy:http_status(), cowboy:http_headers(), Req)
  781. -> Req when Req::req().
  782. chunked_reply(Status, Headers, Req=#{pid := Pid, streamid := StreamID}) ->
  783. Pid ! {{Pid, StreamID}, {headers, Status, response_headers(Headers, Req)}},
  784. Req. %% @todo return ok
  785. % ok.
  786. -spec chunk(iodata(), req()) -> ok.
  787. chunk(_Data, #{method := <<"HEAD">>}) ->
  788. ok;
  789. chunk(Data, #{pid := Pid, streamid := StreamID}) ->
  790. case iolist_size(Data) of
  791. 0 -> ok;
  792. _ ->
  793. Pid ! {{Pid, StreamID}, {data, nofin, Data}},
  794. ok
  795. end.
  796. %% If ever made public, need to send nothing if HEAD.
  797. -spec last_chunk(Req) -> Req when Req::req().
  798. last_chunk(Req=#http_req{socket=Socket, transport=Transport}) ->
  799. _ = Transport:send(Socket, <<"0\r\n\r\n">>),
  800. Req#http_req{resp_state=done}.
  801. -spec continue(req()) -> ok.
  802. continue(#http_req{socket=Socket, transport=Transport,
  803. version=Version}) ->
  804. HTTPVer = atom_to_binary(Version, latin1),
  805. ok = Transport:send(Socket,
  806. << HTTPVer/binary, " ", (status(100))/binary, "\r\n\r\n" >>).
  807. %% Meant to be used internally for sending errors after crashes.
  808. -spec maybe_reply([{module(), atom(), arity() | [term()], _}], req()) -> ok.
  809. maybe_reply(Stacktrace, Req) ->
  810. receive
  811. {cowboy_req, resp_sent} -> ok
  812. after 0 ->
  813. _ = do_maybe_reply(Stacktrace, Req),
  814. ok
  815. end.
  816. do_maybe_reply([{erlang, binary_to_integer, _, _}, {cow_http_hd, parse_content_length, _, _}|_], Req) ->
  817. cowboy_req:reply(400, Req);
  818. do_maybe_reply([{cow_http_hd, _, _, _}|_], Req) ->
  819. cowboy_req:reply(400, Req);
  820. do_maybe_reply(_, Req) ->
  821. cowboy_req:reply(500, Req).
  822. -spec ensure_response(req(), cowboy:http_status()) -> ok.
  823. %% The response has already been fully sent to the client.
  824. ensure_response(#http_req{resp_state=done}, _) ->
  825. ok;
  826. %% No response has been sent but everything apparently went fine.
  827. %% Reply with the status code found in the second argument.
  828. ensure_response(Req=#http_req{resp_state=RespState}, Status)
  829. when RespState =:= waiting; RespState =:= waiting_stream ->
  830. _ = reply(Status, [], [], Req),
  831. ok;
  832. %% Terminate the chunked body for HTTP/1.1 only.
  833. ensure_response(#http_req{method= <<"HEAD">>}, _) ->
  834. ok;
  835. ensure_response(Req=#http_req{resp_state=chunks}, _) ->
  836. _ = last_chunk(Req),
  837. ok;
  838. ensure_response(#http_req{}, _) ->
  839. ok.
  840. %% Private setter/getter API.
  841. -spec append_buffer(binary(), Req) -> Req when Req::req().
  842. append_buffer(Suffix, Req=#http_req{buffer=Buffer}) ->
  843. Req#http_req{buffer= << Buffer/binary, Suffix/binary >>}.
  844. -spec get(atom(), req()) -> any(); ([atom()], req()) -> any().
  845. get(List, Req) when is_list(List) ->
  846. [g(Atom, Req) || Atom <- List];
  847. get(Atom, Req) when is_atom(Atom) ->
  848. g(Atom, Req).
  849. g(bindings, #http_req{bindings=Ret}) -> Ret;
  850. g(body_state, #http_req{body_state=Ret}) -> Ret;
  851. g(buffer, #http_req{buffer=Ret}) -> Ret;
  852. g(connection, #http_req{connection=Ret}) -> Ret;
  853. g(headers, #http_req{headers=Ret}) -> Ret;
  854. g(host, #http_req{host=Ret}) -> Ret;
  855. g(host_info, #http_req{host_info=Ret}) -> Ret;
  856. g(meta, #http_req{meta=Ret}) -> Ret;
  857. g(method, #http_req{method=Ret}) -> Ret;
  858. g(multipart, #http_req{multipart=Ret}) -> Ret;
  859. g(onresponse, #http_req{onresponse=Ret}) -> Ret;
  860. g(path, #http_req{path=Ret}) -> Ret;
  861. g(path_info, #http_req{path_info=Ret}) -> Ret;
  862. g(peer, #http_req{peer=Ret}) -> Ret;
  863. g(pid, #http_req{pid=Ret}) -> Ret;
  864. g(port, #http_req{port=Ret}) -> Ret;
  865. g(qs, #http_req{qs=Ret}) -> Ret;
  866. g(resp_body, #http_req{resp_body=Ret}) -> Ret;
  867. g(resp_compress, #http_req{resp_compress=Ret}) -> Ret;
  868. g(resp_headers, #http_req{resp_headers=Ret}) -> Ret;
  869. g(resp_state, #http_req{resp_state=Ret}) -> Ret;
  870. g(socket, #http_req{socket=Ret}) -> Ret;
  871. g(transport, #http_req{transport=Ret}) -> Ret;
  872. g(version, #http_req{version=Ret}) -> Ret.
  873. -spec set([{atom(), any()}], Req) -> Req when Req::req().
  874. set([], Req) -> Req;
  875. set([{bindings, Val}|Tail], Req) -> set(Tail, Req#http_req{bindings=Val});
  876. set([{body_state, Val}|Tail], Req) -> set(Tail, Req#http_req{body_state=Val});
  877. set([{buffer, Val}|Tail], Req) -> set(Tail, Req#http_req{buffer=Val});
  878. set([{connection, Val}|Tail], Req) -> set(Tail, Req#http_req{connection=Val});
  879. set([{headers, Val}|Tail], Req) -> set(Tail, Req#http_req{headers=Val});
  880. set([{host, Val}|Tail], Req) -> set(Tail, Req#http_req{host=Val});
  881. set([{host_info, Val}|Tail], Req) -> set(Tail, Req#http_req{host_info=Val});
  882. set([{meta, Val}|Tail], Req) -> set(Tail, Req#http_req{meta=Val});
  883. set([{method, Val}|Tail], Req) -> set(Tail, Req#http_req{method=Val});
  884. set([{multipart, Val}|Tail], Req) -> set(Tail, Req#http_req{multipart=Val});
  885. set([{onresponse, Val}|Tail], Req) -> set(Tail, Req#http_req{onresponse=Val});
  886. set([{path, Val}|Tail], Req) -> set(Tail, Req#http_req{path=Val});
  887. set([{path_info, Val}|Tail], Req) -> set(Tail, Req#http_req{path_info=Val});
  888. set([{peer, Val}|Tail], Req) -> set(Tail, Req#http_req{peer=Val});
  889. set([{pid, Val}|Tail], Req) -> set(Tail, Req#http_req{pid=Val});
  890. set([{port, Val}|Tail], Req) -> set(Tail, Req#http_req{port=Val});
  891. set([{qs, Val}|Tail], Req) -> set(Tail, Req#http_req{qs=Val});
  892. set([{resp_body, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_body=Val});
  893. set([{resp_headers, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_headers=Val});
  894. set([{resp_state, Val}|Tail], Req) -> set(Tail, Req#http_req{resp_state=Val});
  895. set([{socket, Val}|Tail], Req) -> set(Tail, Req#http_req{socket=Val});
  896. set([{transport, Val}|Tail], Req) -> set(Tail, Req#http_req{transport=Val});
  897. set([{version, Val}|Tail], Req) -> set(Tail, Req#http_req{version=Val}).
  898. -spec set_bindings(cowboy_router:tokens(), cowboy_router:tokens(),
  899. cowboy_router:bindings(), Req) -> Req when Req::req().
  900. set_bindings(HostInfo, PathInfo, Bindings, Req) ->
  901. Req#http_req{host_info=HostInfo, path_info=PathInfo,
  902. bindings=Bindings}.
  903. -spec lock(Req) -> Req when Req::req().
  904. lock(Req) ->
  905. Req#http_req{resp_state=locked}.
  906. -spec to_list(req()) -> [{atom(), any()}].
  907. to_list(Req) ->
  908. lists:zip(record_info(fields, http_req), tl(tuple_to_list(Req))).
  909. %% Internal.
  910. %% We don't match on "keep-alive" since it is the default value.
  911. -spec connection_to_atom([binary()]) -> keepalive | close.
  912. connection_to_atom([]) ->
  913. keepalive;
  914. connection_to_atom([<<"close">>|_]) ->
  915. close;
  916. connection_to_atom([_|Tail]) ->
  917. connection_to_atom(Tail).
  918. -spec status(cowboy:http_status()) -> binary().
  919. status(100) -> <<"100 Continue">>;
  920. status(101) -> <<"101 Switching Protocols">>;
  921. status(102) -> <<"102 Processing">>;
  922. status(200) -> <<"200 OK">>;
  923. status(201) -> <<"201 Created">>;
  924. status(202) -> <<"202 Accepted">>;
  925. status(203) -> <<"203 Non-Authoritative Information">>;
  926. status(204) -> <<"204 No Content">>;
  927. status(205) -> <<"205 Reset Content">>;
  928. status(206) -> <<"206 Partial Content">>;
  929. status(207) -> <<"207 Multi-Status">>;
  930. status(226) -> <<"226 IM Used">>;
  931. status(300) -> <<"300 Multiple Choices">>;
  932. status(301) -> <<"301 Moved Permanently">>;
  933. status(302) -> <<"302 Found">>;
  934. status(303) -> <<"303 See Other">>;
  935. status(304) -> <<"304 Not Modified">>;
  936. status(305) -> <<"305 Use Proxy">>;
  937. status(306) -> <<"306 Switch Proxy">>;
  938. status(307) -> <<"307 Temporary Redirect">>;
  939. status(400) -> <<"400 Bad Request">>;
  940. status(401) -> <<"401 Unauthorized">>;
  941. status(402) -> <<"402 Payment Required">>;
  942. status(403) -> <<"403 Forbidden">>;
  943. status(404) -> <<"404 Not Found">>;
  944. status(405) -> <<"405 Method Not Allowed">>;
  945. status(406) -> <<"406 Not Acceptable">>;
  946. status(407) -> <<"407 Proxy Authentication Required">>;
  947. status(408) -> <<"408 Request Timeout">>;
  948. status(409) -> <<"409 Conflict">>;
  949. status(410) -> <<"410 Gone">>;
  950. status(411) -> <<"411 Length Required">>;
  951. status(412) -> <<"412 Precondition Failed">>;
  952. status(413) -> <<"413 Request Entity Too Large">>;
  953. status(414) -> <<"414 Request-URI Too Long">>;
  954. status(415) -> <<"415 Unsupported Media Type">>;
  955. status(416) -> <<"416 Requested Range Not Satisfiable">>;
  956. status(417) -> <<"417 Expectation Failed">>;
  957. status(418) -> <<"418 I'm a teapot">>;
  958. status(422) -> <<"422 Unprocessable Entity">>;
  959. status(423) -> <<"423 Locked">>;
  960. status(424) -> <<"424 Failed Dependency">>;
  961. status(425) -> <<"425 Unordered Collection">>;
  962. status(426) -> <<"426 Upgrade Required">>;
  963. status(428) -> <<"428 Precondition Required">>;
  964. status(429) -> <<"429 Too Many Requests">>;
  965. status(431) -> <<"431 Request Header Fields Too Large">>;
  966. status(500) -> <<"500 Internal Server Error">>;
  967. status(501) -> <<"501 Not Implemented">>;
  968. status(502) -> <<"502 Bad Gateway">>;
  969. status(503) -> <<"503 Service Unavailable">>;
  970. status(504) -> <<"504 Gateway Timeout">>;
  971. status(505) -> <<"505 HTTP Version Not Supported">>;
  972. status(506) -> <<"506 Variant Also Negotiates">>;
  973. status(507) -> <<"507 Insufficient Storage">>;
  974. status(510) -> <<"510 Not Extended">>;
  975. status(511) -> <<"511 Network Authentication Required">>;
  976. status(B) when is_binary(B) -> B.
  977. %% Create map, convert keys to atoms and group duplicate keys into lists.
  978. %% Keys that are not found in the user provided list are entirely skipped.
  979. %% @todo Can probably be done directly while parsing.
  980. kvlist_to_map(Fields, KvList) ->
  981. Keys = [case K of
  982. {Key, _} -> Key;
  983. {Key, _, _} -> Key;
  984. Key -> Key
  985. end || K <- Fields],
  986. kvlist_to_map(Keys, KvList, #{}).
  987. kvlist_to_map(_, [], Map) ->
  988. Map;
  989. kvlist_to_map(Keys, [{Key, Value}|Tail], Map) ->
  990. try binary_to_existing_atom(Key, utf8) of
  991. Atom ->
  992. case lists:member(Atom, Keys) of
  993. true ->
  994. case maps:find(Atom, Map) of
  995. {ok, MapValue} when is_list(MapValue) ->
  996. kvlist_to_map(Keys, Tail,
  997. Map#{Atom => [Value|MapValue]});
  998. {ok, MapValue} ->
  999. kvlist_to_map(Keys, Tail,
  1000. Map#{Atom => [Value, MapValue]});
  1001. error ->
  1002. kvlist_to_map(Keys, Tail,
  1003. Map#{Atom => Value})
  1004. end;
  1005. false ->
  1006. kvlist_to_map(Keys, Tail, Map)
  1007. end
  1008. catch error:badarg ->
  1009. kvlist_to_map(Keys, Tail, Map)
  1010. end.
  1011. %% Loop through fields, if value is missing and no default, crash;
  1012. %% else if value is missing and has a default, set default;
  1013. %% otherwise apply constraints. If constraint fails, crash.
  1014. filter([], Map) ->
  1015. Map;
  1016. filter([{Key, Constraints}|Tail], Map) ->
  1017. filter_constraints(Tail, Map, Key, maps:get(Key, Map), Constraints);
  1018. filter([{Key, Constraints, Default}|Tail], Map) ->
  1019. case maps:find(Key, Map) of
  1020. {ok, Value} ->
  1021. filter_constraints(Tail, Map, Key, Value, Constraints);
  1022. error ->
  1023. filter(Tail, Map#{Key => Default})
  1024. end;
  1025. filter([Key|Tail], Map) ->
  1026. true = maps:is_key(Key, Map),
  1027. filter(Tail, Map).
  1028. filter_constraints(Tail, Map, Key, Value, Constraints) ->
  1029. case cowboy_constraints:validate(Value, Constraints) of
  1030. true ->
  1031. filter(Tail, Map);
  1032. {true, Value2} ->
  1033. filter(Tail, Map#{Key => Value2})
  1034. end.
  1035. %% Tests.
  1036. -ifdef(TEST).
  1037. url_test() ->
  1038. undefined =
  1039. url(#http_req{transport=ranch_tcp, host= <<>>, port= undefined,
  1040. path= <<>>, qs= <<>>, pid=self()}),
  1041. <<"http://localhost/path">> =
  1042. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=80,
  1043. path= <<"/path">>, qs= <<>>, pid=self()}),
  1044. <<"http://localhost:443/path">> =
  1045. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=443,
  1046. path= <<"/path">>, qs= <<>>, pid=self()}),
  1047. <<"http://localhost:8080/path">> =
  1048. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080,
  1049. path= <<"/path">>, qs= <<>>, pid=self()}),
  1050. <<"http://localhost:8080/path?dummy=2785">> =
  1051. url(#http_req{transport=ranch_tcp, host= <<"localhost">>, port=8080,
  1052. path= <<"/path">>, qs= <<"dummy=2785">>, pid=self()}),
  1053. <<"https://localhost/path">> =
  1054. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=443,
  1055. path= <<"/path">>, qs= <<>>, pid=self()}),
  1056. <<"https://localhost:8443/path">> =
  1057. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443,
  1058. path= <<"/path">>, qs= <<>>, pid=self()}),
  1059. <<"https://localhost:8443/path?dummy=2785">> =
  1060. url(#http_req{transport=ranch_ssl, host= <<"localhost">>, port=8443,
  1061. path= <<"/path">>, qs= <<"dummy=2785">>, pid=self()}),
  1062. ok.
  1063. connection_to_atom_test_() ->
  1064. Tests = [
  1065. {[<<"close">>], close},
  1066. {[<<"keep-alive">>], keepalive},
  1067. {[<<"keep-alive">>, <<"upgrade">>], keepalive}
  1068. ],
  1069. [{lists:flatten(io_lib:format("~p", [T])),
  1070. fun() -> R = connection_to_atom(T) end} || {T, R} <- Tests].
  1071. -endif.