cowboy_req.erl 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  1. %% Copyright (c) 2011-2017, 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.
  17. -export([method/1]).
  18. -export([version/1]).
  19. -export([peer/1]).
  20. -export([scheme/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([uri/1]).
  30. -export([uri/2]).
  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. %% Request body.
  42. -export([has_body/1]).
  43. -export([body_length/1]).
  44. -export([read_body/1]).
  45. -export([read_body/2]).
  46. -export([read_urlencoded_body/1]).
  47. -export([read_urlencoded_body/2]).
  48. %% @todo read_and_match_urlencoded_body?
  49. %% Multipart.
  50. -export([read_part/1]).
  51. -export([read_part/2]).
  52. -export([read_part_body/1]).
  53. -export([read_part_body/2]).
  54. %% Response.
  55. -export([set_resp_cookie/3]).
  56. -export([set_resp_cookie/4]).
  57. -export([set_resp_header/3]).
  58. %% @todo set_resp_headers/2
  59. -export([has_resp_header/2]).
  60. %% @todo resp_header
  61. -export([delete_resp_header/2]).
  62. -export([set_resp_body/2]).
  63. %% @todo set_resp_body/3 with a ContentType or even Headers argument, to set content headers.
  64. -export([has_resp_body/1]).
  65. -export([reply/2]).
  66. -export([reply/3]).
  67. -export([reply/4]).
  68. -export([stream_reply/2]).
  69. -export([stream_reply/3]).
  70. %% @todo stream_reply/2 (nofin)
  71. -export([stream_body/3]).
  72. %% @todo stream_event/2,3
  73. -export([push/3]).
  74. -export([push/4]).
  75. %% Internal.
  76. -export([response_headers/2]).
  77. %% @todo Get rid of this type, use cow_cookie directly.
  78. -type cookie_opts() :: map().
  79. -export_type([cookie_opts/0]).
  80. -type read_body_opts() :: #{
  81. length => non_neg_integer(),
  82. period => non_neg_integer(),
  83. timeout => timeout()
  84. }.
  85. -export_type([read_body_opts/0]).
  86. %% While sendfile allows a Len of 0 that means "everything past Offset",
  87. %% Cowboy expects the real length as it is used as metadata.
  88. %% @todo We should probably explicitly reject it.
  89. -type resp_body() :: iodata()
  90. | {sendfile, non_neg_integer(), pos_integer(), file:name_all()}.
  91. -export_type([resp_body/0]).
  92. -type push_opts() :: #{
  93. method => binary(),
  94. scheme => binary(),
  95. host => binary(),
  96. port => binary(),
  97. qs => binary()
  98. }.
  99. -export_type([push_opts/0]).
  100. -type req() :: map(). %% @todo #{
  101. % ref := ranch:ref(),
  102. % pid := pid(),
  103. % streamid := cowboy_stream:streamid(),
  104. % peer := {inet:ip_address(), inet:port_number()},
  105. %
  106. % method := binary(), %% case sensitive
  107. % version := cowboy:http_version() | atom(),
  108. % scheme := binary(), %% <<"http">> or <<"https">>
  109. % host := binary(), %% lowercase; case insensitive
  110. % port := inet:port_number(),
  111. % path := binary(), %% case sensitive
  112. % qs := binary(), %% case sensitive
  113. % headers := cowboy:http_headers(),
  114. %
  115. % host_info => cowboy_router:tokens(),
  116. % path_info => cowboy_router:tokens(),
  117. % bindings => cowboy_router:bindings(),
  118. %
  119. % has_body := boolean(),
  120. % has_read_body => true,
  121. % body_length := undefined | non_neg_integer()
  122. %
  123. %% @todo resp_*
  124. %}.
  125. -export_type([req/0]).
  126. %% Request.
  127. -spec method(req()) -> binary().
  128. method(#{method := Method}) ->
  129. Method.
  130. -spec version(req()) -> cowboy:http_version().
  131. version(#{version := Version}) ->
  132. Version.
  133. -spec peer(req()) -> {inet:ip_address(), inet:port_number()}.
  134. peer(#{peer := Peer}) ->
  135. Peer.
  136. -spec scheme(req()) -> binary().
  137. scheme(#{scheme := Scheme}) ->
  138. Scheme.
  139. -spec host(req()) -> binary().
  140. host(#{host := Host}) ->
  141. Host.
  142. %% @todo The host_info is undefined if cowboy_router isn't used. Do we want to crash?
  143. -spec host_info(req()) -> cowboy_router:tokens() | undefined.
  144. host_info(#{host_info := HostInfo}) ->
  145. HostInfo.
  146. -spec port(req()) -> inet:port_number().
  147. port(#{port := Port}) ->
  148. Port.
  149. -spec path(req()) -> binary().
  150. path(#{path := Path}) ->
  151. Path.
  152. %% @todo The path_info is undefined if cowboy_router isn't used. Do we want to crash?
  153. -spec path_info(req()) -> cowboy_router:tokens() | undefined.
  154. path_info(#{path_info := PathInfo}) ->
  155. PathInfo.
  156. -spec qs(req()) -> binary().
  157. qs(#{qs := Qs}) ->
  158. Qs.
  159. %% @todo Might be useful to limit the number of keys.
  160. -spec parse_qs(req()) -> [{binary(), binary() | true}].
  161. parse_qs(#{qs := Qs}) ->
  162. cow_qs:parse_qs(Qs).
  163. -spec match_qs(cowboy:fields(), req()) -> map().
  164. match_qs(Fields, Req) ->
  165. filter(Fields, kvlist_to_map(Fields, parse_qs(Req))).
  166. -spec uri(req()) -> iodata().
  167. uri(Req) ->
  168. uri(Req, #{}).
  169. -spec uri(req(), map()) -> iodata().
  170. uri(#{scheme := Scheme0, host := Host0, port := Port0,
  171. path := Path0, qs := Qs0}, Opts) ->
  172. Scheme = case maps:get(scheme, Opts, Scheme0) of
  173. S = undefined -> S;
  174. S -> iolist_to_binary(S)
  175. end,
  176. Host = maps:get(host, Opts, Host0),
  177. Port = maps:get(port, Opts, Port0),
  178. Path = maps:get(path, Opts, Path0),
  179. Qs = maps:get(qs, Opts, Qs0),
  180. Fragment = maps:get(fragment, Opts, undefined),
  181. [uri_host(Scheme, Scheme0, Port, Host), uri_path(Path), uri_qs(Qs), uri_fragment(Fragment)].
  182. uri_host(_, _, _, undefined) -> <<>>;
  183. uri_host(Scheme, Scheme0, Port, Host) ->
  184. case iolist_size(Host) of
  185. 0 -> <<>>;
  186. _ -> [uri_scheme(Scheme), <<"//">>, Host, uri_port(Scheme, Scheme0, Port)]
  187. end.
  188. uri_scheme(undefined) -> <<>>;
  189. uri_scheme(Scheme) ->
  190. case iolist_size(Scheme) of
  191. 0 -> Scheme;
  192. _ -> [Scheme, $:]
  193. end.
  194. uri_port(_, _, undefined) -> <<>>;
  195. uri_port(undefined, <<"http">>, 80) -> <<>>;
  196. uri_port(undefined, <<"https">>, 443) -> <<>>;
  197. uri_port(<<"http">>, _, 80) -> <<>>;
  198. uri_port(<<"https">>, _, 443) -> <<>>;
  199. uri_port(_, _, Port) ->
  200. [$:, integer_to_binary(Port)].
  201. uri_path(undefined) -> <<>>;
  202. uri_path(Path) -> Path.
  203. uri_qs(undefined) -> <<>>;
  204. uri_qs(Qs) ->
  205. case iolist_size(Qs) of
  206. 0 -> Qs;
  207. _ -> [$?, Qs]
  208. end.
  209. uri_fragment(undefined) -> <<>>;
  210. uri_fragment(Fragment) ->
  211. case iolist_size(Fragment) of
  212. 0 -> Fragment;
  213. _ -> [$#, Fragment]
  214. end.
  215. -ifdef(TEST).
  216. uri1_test() ->
  217. <<"http://localhost/path">> = iolist_to_binary(uri(#{
  218. scheme => <<"http">>, host => <<"localhost">>, port => 80,
  219. path => <<"/path">>, qs => <<>>})),
  220. <<"http://localhost:443/path">> = iolist_to_binary(uri(#{
  221. scheme => <<"http">>, host => <<"localhost">>, port => 443,
  222. path => <<"/path">>, qs => <<>>})),
  223. <<"http://localhost:8080/path">> = iolist_to_binary(uri(#{
  224. scheme => <<"http">>, host => <<"localhost">>, port => 8080,
  225. path => <<"/path">>, qs => <<>>})),
  226. <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(#{
  227. scheme => <<"http">>, host => <<"localhost">>, port => 8080,
  228. path => <<"/path">>, qs => <<"dummy=2785">>})),
  229. <<"https://localhost/path">> = iolist_to_binary(uri(#{
  230. scheme => <<"https">>, host => <<"localhost">>, port => 443,
  231. path => <<"/path">>, qs => <<>>})),
  232. <<"https://localhost:8443/path">> = iolist_to_binary(uri(#{
  233. scheme => <<"https">>, host => <<"localhost">>, port => 8443,
  234. path => <<"/path">>, qs => <<>>})),
  235. <<"https://localhost:8443/path?dummy=2785">> = iolist_to_binary(uri(#{
  236. scheme => <<"https">>, host => <<"localhost">>, port => 8443,
  237. path => <<"/path">>, qs => <<"dummy=2785">>})),
  238. ok.
  239. uri2_test() ->
  240. Req = #{
  241. scheme => <<"http">>, host => <<"localhost">>, port => 8080,
  242. path => <<"/path">>, qs => <<"dummy=2785">>
  243. },
  244. <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{})),
  245. %% Disable individual components.
  246. <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => undefined})),
  247. <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => undefined})),
  248. <<"http://localhost/path?dummy=2785">> = iolist_to_binary(uri(Req, #{port => undefined})),
  249. <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => undefined})),
  250. <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => undefined})),
  251. <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => undefined})),
  252. <<"http://localhost:8080">> = iolist_to_binary(uri(Req, #{path => undefined, qs => undefined})),
  253. <<>> = iolist_to_binary(uri(Req, #{host => undefined, path => undefined, qs => undefined})),
  254. %% Empty values.
  255. <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => <<>>})),
  256. <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => ""})),
  257. <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => [<<>>]})),
  258. <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => <<>>})),
  259. <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => ""})),
  260. <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => [<<>>]})),
  261. <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => <<>>})),
  262. <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => ""})),
  263. <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => [<<>>]})),
  264. <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => <<>>})),
  265. <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => ""})),
  266. <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => [<<>>]})),
  267. <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => <<>>})),
  268. <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => ""})),
  269. <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => [<<>>]})),
  270. %% Port is integer() | undefined.
  271. {'EXIT', _} = (catch iolist_to_binary(uri(Req, #{port => <<>>}))),
  272. {'EXIT', _} = (catch iolist_to_binary(uri(Req, #{port => ""}))),
  273. {'EXIT', _} = (catch iolist_to_binary(uri(Req, #{port => [<<>>]}))),
  274. %% Update components.
  275. <<"https://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => "https"})),
  276. <<"http://example.org:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => "example.org"})),
  277. <<"http://localhost:123/path?dummy=2785">> = iolist_to_binary(uri(Req, #{port => 123})),
  278. <<"http://localhost:8080/custom?dummy=2785">> = iolist_to_binary(uri(Req, #{path => "/custom"})),
  279. <<"http://localhost:8080/path?smart=42">> = iolist_to_binary(uri(Req, #{qs => "smart=42"})),
  280. <<"http://localhost:8080/path?dummy=2785#intro">> = iolist_to_binary(uri(Req, #{fragment => "intro"})),
  281. %% Interesting combinations.
  282. <<"http://localhost/path?dummy=2785">> = iolist_to_binary(uri(Req, #{port => 80})),
  283. <<"https://localhost/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => "https", port => 443})),
  284. ok.
  285. -endif.
  286. -spec binding(atom(), req()) -> any() | undefined.
  287. binding(Name, Req) ->
  288. binding(Name, Req, undefined).
  289. -spec binding(atom(), req(), Default) -> any() | Default when Default::any().
  290. binding(Name, #{bindings := Bindings}, Default) when is_atom(Name) ->
  291. case lists:keyfind(Name, 1, Bindings) of
  292. {_, Value} -> Value;
  293. false -> Default
  294. end;
  295. binding(Name, _, Default) when is_atom(Name) ->
  296. Default.
  297. -spec bindings(req()) -> [{atom(), any()}].
  298. bindings(#{bindings := Bindings}) ->
  299. Bindings;
  300. bindings(_) ->
  301. [].
  302. -spec header(binary(), req()) -> binary() | undefined.
  303. header(Name, Req) ->
  304. header(Name, Req, undefined).
  305. -spec header(binary(), req(), Default) -> binary() | Default when Default::any().
  306. header(Name, #{headers := Headers}, Default) ->
  307. maps:get(Name, Headers, Default).
  308. -spec headers(req()) -> cowboy:http_headers().
  309. headers(#{headers := Headers}) ->
  310. Headers.
  311. -spec parse_header(binary(), Req) -> any() when Req::req().
  312. parse_header(Name = <<"content-length">>, Req) ->
  313. parse_header(Name, Req, 0, fun cow_http_hd:parse_content_length/1);
  314. parse_header(Name = <<"cookie">>, Req) ->
  315. parse_header(Name, Req, [], fun cow_cookie:parse_cookie/1);
  316. %% @todo That header is abstracted out and should never reach cowboy_req.
  317. parse_header(Name = <<"transfer-encoding">>, Req) ->
  318. parse_header(Name, Req, [<<"identity">>], fun cow_http_hd:parse_transfer_encoding/1);
  319. parse_header(Name, Req) ->
  320. parse_header(Name, Req, undefined).
  321. -spec parse_header(binary(), Req, any()) -> any() when Req::req().
  322. parse_header(Name, Req, Default) ->
  323. parse_header(Name, Req, Default, parse_header_fun(Name)).
  324. parse_header_fun(<<"accept">>) -> fun cow_http_hd:parse_accept/1;
  325. parse_header_fun(<<"accept-charset">>) -> fun cow_http_hd:parse_accept_charset/1;
  326. parse_header_fun(<<"accept-encoding">>) -> fun cow_http_hd:parse_accept_encoding/1;
  327. parse_header_fun(<<"accept-language">>) -> fun cow_http_hd:parse_accept_language/1;
  328. parse_header_fun(<<"authorization">>) -> fun cow_http_hd:parse_authorization/1;
  329. parse_header_fun(<<"connection">>) -> fun cow_http_hd:parse_connection/1;
  330. parse_header_fun(<<"content-length">>) -> fun cow_http_hd:parse_content_length/1;
  331. parse_header_fun(<<"content-type">>) -> fun cow_http_hd:parse_content_type/1;
  332. parse_header_fun(<<"cookie">>) -> fun cow_cookie:parse_cookie/1;
  333. parse_header_fun(<<"expect">>) -> fun cow_http_hd:parse_expect/1;
  334. parse_header_fun(<<"if-match">>) -> fun cow_http_hd:parse_if_match/1;
  335. parse_header_fun(<<"if-modified-since">>) -> fun cow_http_hd:parse_if_modified_since/1;
  336. parse_header_fun(<<"if-none-match">>) -> fun cow_http_hd:parse_if_none_match/1;
  337. parse_header_fun(<<"if-unmodified-since">>) -> fun cow_http_hd:parse_if_unmodified_since/1;
  338. parse_header_fun(<<"range">>) -> fun cow_http_hd:parse_range/1;
  339. parse_header_fun(<<"sec-websocket-extensions">>) -> fun cow_http_hd:parse_sec_websocket_extensions/1;
  340. parse_header_fun(<<"sec-websocket-protocol">>) -> fun cow_http_hd:parse_sec_websocket_protocol_req/1;
  341. parse_header_fun(<<"transfer-encoding">>) -> fun cow_http_hd:parse_transfer_encoding/1;
  342. parse_header_fun(<<"upgrade">>) -> fun cow_http_hd:parse_upgrade/1;
  343. parse_header_fun(<<"x-forwarded-for">>) -> fun cow_http_hd:parse_x_forwarded_for/1.
  344. parse_header(Name, Req, Default, ParseFun) ->
  345. case header(Name, Req) of
  346. undefined -> Default;
  347. Value -> ParseFun(Value)
  348. end.
  349. -spec parse_cookies(req()) -> [{binary(), binary()}].
  350. parse_cookies(Req) ->
  351. parse_header(<<"cookie">>, Req).
  352. -spec match_cookies(cowboy:fields(), req()) -> map().
  353. match_cookies(Fields, Req) ->
  354. filter(Fields, kvlist_to_map(Fields, parse_cookies(Req))).
  355. %% Request body.
  356. -spec has_body(req()) -> boolean().
  357. has_body(#{has_body := HasBody}) ->
  358. HasBody.
  359. %% The length may not be known if HTTP/1.1 with a transfer-encoding;
  360. %% or HTTP/2 with no content-length header. The length is always
  361. %% known once the body has been completely read.
  362. -spec body_length(req()) -> undefined | non_neg_integer().
  363. body_length(#{body_length := Length}) ->
  364. Length.
  365. -spec read_body(Req) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req().
  366. read_body(Req) ->
  367. read_body(Req, #{}).
  368. -spec read_body(Req, read_body_opts()) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req().
  369. read_body(Req=#{has_body := false}, _) ->
  370. {ok, <<>>, Req};
  371. read_body(Req=#{has_read_body := true}, _) ->
  372. {ok, <<>>, Req};
  373. read_body(Req=#{pid := Pid, streamid := StreamID}, Opts) ->
  374. Length = maps:get(length, Opts, 8000000),
  375. Period = maps:get(period, Opts, 15000),
  376. Timeout = maps:get(timeout, Opts, Period + 1000),
  377. Ref = make_ref(),
  378. Pid ! {{Pid, StreamID}, {read_body, Ref, Length, Period}},
  379. receive
  380. {request_body, Ref, nofin, Body} ->
  381. {more, Body, Req};
  382. {request_body, Ref, {fin, BodyLength}, Body} ->
  383. {ok, Body, set_body_length(Req, BodyLength)}
  384. after Timeout ->
  385. exit(timeout)
  386. end.
  387. set_body_length(Req=#{headers := Headers}, BodyLength) ->
  388. Req#{
  389. headers => Headers#{<<"content-length">> => integer_to_binary(BodyLength)},
  390. body_length => BodyLength,
  391. has_read_body => true
  392. }.
  393. -spec read_urlencoded_body(Req) -> {ok, [{binary(), binary() | true}], Req} when Req::req().
  394. read_urlencoded_body(Req) ->
  395. read_urlencoded_body(Req, #{length => 64000, period => 5000}).
  396. -spec read_urlencoded_body(Req, read_body_opts()) -> {ok, [{binary(), binary() | true}], Req} when Req::req().
  397. read_urlencoded_body(Req0, Opts) ->
  398. {ok, Body, Req} = read_body(Req0, Opts),
  399. {ok, cow_qs:parse_qs(Body), Req}.
  400. %% Multipart.
  401. -spec read_part(Req)
  402. -> {ok, cow_multipart:headers(), Req} | {done, Req}
  403. when Req::req().
  404. read_part(Req) ->
  405. read_part(Req, #{length => 64000, period => 5000}).
  406. -spec read_part(Req, read_body_opts())
  407. -> {ok, cow_multipart:headers(), Req} | {done, Req}
  408. when Req::req().
  409. read_part(Req, Opts) ->
  410. case maps:is_key(multipart, Req) of
  411. true ->
  412. {Data, Req2} = stream_multipart(Req, Opts),
  413. read_part(Data, Opts, Req2);
  414. false ->
  415. read_part(init_multipart(Req), Opts)
  416. end.
  417. read_part(Buffer, Opts, Req=#{multipart := {Boundary, _}}) ->
  418. case cow_multipart:parse_headers(Buffer, Boundary) of
  419. more ->
  420. {Data, Req2} = stream_multipart(Req, Opts),
  421. read_part(<< Buffer/binary, Data/binary >>, Opts, Req2);
  422. {more, Buffer2} ->
  423. {Data, Req2} = stream_multipart(Req, Opts),
  424. read_part(<< Buffer2/binary, Data/binary >>, Opts, Req2);
  425. {ok, Headers, Rest} ->
  426. %% @todo We may want headers as a map. Need to check the
  427. %% rules for multipart header parsing before taking a decision.
  428. {ok, Headers, Req#{multipart => {Boundary, Rest}}};
  429. %% Ignore epilogue.
  430. {done, _} ->
  431. {done, Req#{multipart => done}}
  432. end.
  433. -spec read_part_body(Req)
  434. -> {ok, binary(), Req} | {more, binary(), Req}
  435. when Req::req().
  436. read_part_body(Req) ->
  437. read_part_body(Req, #{}).
  438. -spec read_part_body(Req, read_body_opts())
  439. -> {ok, binary(), Req} | {more, binary(), Req}
  440. when Req::req().
  441. read_part_body(Req, Opts) ->
  442. case maps:is_key(multipart, Req) of
  443. true ->
  444. read_part_body(<<>>, Opts, Req, <<>>);
  445. false ->
  446. read_part_body(init_multipart(Req), Opts)
  447. end.
  448. read_part_body(Buffer, Opts, Req=#{multipart := {Boundary, _}}, Acc) ->
  449. Length = maps:get(length, Opts, 8000000),
  450. case byte_size(Acc) > Length of
  451. true ->
  452. {more, Acc, Req#{multipart => {Boundary, Buffer}}};
  453. false ->
  454. {Data, Req2} = stream_multipart(Req, Opts),
  455. case cow_multipart:parse_body(<< Buffer/binary, Data/binary >>, Boundary) of
  456. {ok, Body} ->
  457. read_part_body(<<>>, Opts, Req2, << Acc/binary, Body/binary >>);
  458. {ok, Body, Rest} ->
  459. read_part_body(Rest, Opts, Req2, << Acc/binary, Body/binary >>);
  460. done ->
  461. {ok, Acc, Req2};
  462. {done, Body} ->
  463. {ok, << Acc/binary, Body/binary >>, Req2};
  464. {done, Body, Rest} ->
  465. {ok, << Acc/binary, Body/binary >>,
  466. Req2#{multipart => {Boundary, Rest}}}
  467. end
  468. end.
  469. init_multipart(Req) ->
  470. {<<"multipart">>, _, Params} = parse_header(<<"content-type">>, Req),
  471. {_, Boundary} = lists:keyfind(<<"boundary">>, 1, Params),
  472. Req#{multipart => {Boundary, <<>>}}.
  473. stream_multipart(Req=#{multipart := done}, _) ->
  474. {<<>>, Req};
  475. stream_multipart(Req=#{multipart := {_, <<>>}}, Opts) ->
  476. {_, Data, Req2} = read_body(Req, Opts),
  477. {Data, Req2};
  478. stream_multipart(Req=#{multipart := {Boundary, Buffer}}, _) ->
  479. {Buffer, Req#{multipart => {Boundary, <<>>}}}.
  480. %% Response.
  481. -spec set_resp_cookie(iodata(), iodata(), Req)
  482. -> Req when Req::req().
  483. set_resp_cookie(Name, Value, Req) ->
  484. set_resp_cookie(Name, Value, #{}, Req).
  485. %% The cookie name cannot contain any of the following characters:
  486. %% =,;\s\t\r\n\013\014
  487. %%
  488. %% The cookie value cannot contain any of the following characters:
  489. %% ,; \t\r\n\013\014
  490. %% @todo Fix the cookie_opts() type.
  491. -spec set_resp_cookie(iodata(), iodata(), cookie_opts(), Req)
  492. -> Req when Req::req().
  493. set_resp_cookie(Name, Value, Opts, Req) ->
  494. Cookie = cow_cookie:setcookie(Name, Value, maps:to_list(Opts)),
  495. RespCookies = maps:get(resp_cookies, Req, #{}),
  496. Req#{resp_cookies => RespCookies#{Name => Cookie}}.
  497. %% @todo We could add has_resp_cookie and delete_resp_cookie now.
  498. -spec set_resp_header(binary(), iodata(), Req)
  499. -> Req when Req::req().
  500. set_resp_header(Name, Value, Req=#{resp_headers := RespHeaders}) ->
  501. Req#{resp_headers => RespHeaders#{Name => Value}};
  502. set_resp_header(Name,Value, Req) ->
  503. Req#{resp_headers => #{Name => Value}}.
  504. -spec set_resp_body(resp_body(), Req) -> Req when Req::req().
  505. set_resp_body(Body, Req) ->
  506. Req#{resp_body => Body}.
  507. -spec has_resp_header(binary(), req()) -> boolean().
  508. has_resp_header(Name, #{resp_headers := RespHeaders}) ->
  509. maps:is_key(Name, RespHeaders);
  510. has_resp_header(_, _) ->
  511. false.
  512. -spec has_resp_body(req()) -> boolean().
  513. has_resp_body(#{resp_body := {sendfile, _, _, _}}) ->
  514. true;
  515. has_resp_body(#{resp_body := RespBody}) ->
  516. iolist_size(RespBody) > 0;
  517. has_resp_body(_) ->
  518. false.
  519. -spec delete_resp_header(binary(), Req)
  520. -> Req when Req::req().
  521. delete_resp_header(Name, Req=#{resp_headers := RespHeaders}) ->
  522. Req#{resp_headers => maps:remove(Name, RespHeaders)}.
  523. -spec reply(cowboy:http_status(), Req) -> Req when Req::req().
  524. reply(Status, Req) ->
  525. reply(Status, #{}, Req).
  526. -spec reply(cowboy:http_status(), cowboy:http_headers(), Req)
  527. -> Req when Req::req().
  528. reply(Status, Headers, Req=#{resp_body := Body}) ->
  529. reply(Status, Headers, Body, Req);
  530. reply(Status, Headers, Req) ->
  531. reply(Status, Headers, <<>>, Req).
  532. -spec reply(cowboy:http_status(), cowboy:http_headers(), resp_body(), Req)
  533. -> Req when Req::req().
  534. reply(_, _, _, #{has_sent_resp := _}) ->
  535. error(function_clause);
  536. reply(Status, Headers, SendFile = {sendfile, _, Len, _}, Req)
  537. when is_integer(Status); is_binary(Status) ->
  538. do_reply(Status, Headers#{
  539. <<"content-length">> => integer_to_binary(Len)
  540. }, SendFile, Req);
  541. reply(Status, Headers, Body, Req)
  542. when is_integer(Status); is_binary(Status) ->
  543. do_reply(Status, Headers#{
  544. <<"content-length">> => integer_to_binary(iolist_size(Body))
  545. }, Body, Req).
  546. %% Don't send any body for HEAD responses. While the protocol code is
  547. %% supposed to enforce this rule, we prefer to avoid copying too much
  548. %% data around if we can avoid it.
  549. do_reply(Status, Headers, _, Req=#{pid := Pid, streamid := StreamID, method := <<"HEAD">>}) ->
  550. Pid ! {{Pid, StreamID}, {response, Status, response_headers(Headers, Req), <<>>}},
  551. done_replying(Req, true);
  552. do_reply(Status, Headers, Body, Req=#{pid := Pid, streamid := StreamID}) ->
  553. Pid ! {{Pid, StreamID}, {response, Status, response_headers(Headers, Req), Body}},
  554. done_replying(Req, true).
  555. done_replying(Req, HasSentResp) ->
  556. maps:without([resp_cookies, resp_headers, resp_body], Req#{has_sent_resp => HasSentResp}).
  557. -spec stream_reply(cowboy:http_status(), Req) -> Req when Req::req().
  558. stream_reply(Status, Req) ->
  559. stream_reply(Status, #{}, Req).
  560. -spec stream_reply(cowboy:http_status(), cowboy:http_headers(), Req)
  561. -> Req when Req::req().
  562. stream_reply(_, _, #{has_sent_resp := _}) ->
  563. error(function_clause);
  564. stream_reply(Status, Headers=#{}, Req=#{pid := Pid, streamid := StreamID})
  565. when is_integer(Status); is_binary(Status) ->
  566. Pid ! {{Pid, StreamID}, {headers, Status, response_headers(Headers, Req)}},
  567. done_replying(Req, headers).
  568. -spec stream_body(iodata(), fin | nofin, req()) -> ok.
  569. %% Error out if headers were not sent.
  570. %% Don't send any body for HEAD responses.
  571. stream_body(_, _, #{method := <<"HEAD">>, has_sent_resp := headers}) ->
  572. ok;
  573. %% Don't send a message if the data is empty, except for the
  574. %% very last message with IsFin=fin.
  575. stream_body(Data, IsFin=nofin, #{pid := Pid, streamid := StreamID, has_sent_resp := headers}) ->
  576. case iolist_size(Data) of
  577. 0 -> ok;
  578. _ ->
  579. Pid ! {{Pid, StreamID}, {data, IsFin, Data}},
  580. ok
  581. end;
  582. stream_body(Data, IsFin, #{pid := Pid, streamid := StreamID, has_sent_resp := headers}) ->
  583. Pid ! {{Pid, StreamID}, {data, IsFin, Data}},
  584. ok.
  585. -spec push(binary(), cowboy:http_headers(), req()) -> ok.
  586. push(Path, Headers, Req) ->
  587. push(Path, Headers, Req, #{}).
  588. %% @todo Optimization: don't send anything at all for HTTP/1.0 and HTTP/1.1.
  589. %% @todo Path, Headers, Opts, everything should be in proper binary,
  590. %% or normalized when creating the Req object.
  591. -spec push(iodata(), cowboy:http_headers(), req(), push_opts()) -> ok.
  592. push(Path, Headers, #{pid := Pid, streamid := StreamID,
  593. scheme := Scheme0, host := Host0, port := Port0}, Opts) ->
  594. Method = maps:get(method, Opts, <<"GET">>),
  595. Scheme = maps:get(scheme, Opts, Scheme0),
  596. Host = maps:get(host, Opts, Host0),
  597. Port = maps:get(port, Opts, Port0),
  598. Qs = maps:get(qs, Opts, <<>>),
  599. Pid ! {{Pid, StreamID}, {push, Method, Scheme, Host, Port, Path, Qs, Headers}},
  600. ok.
  601. %% Internal.
  602. %% @todo What about set-cookie headers set through set_resp_header or reply?
  603. -spec response_headers(Headers, req()) -> Headers when Headers::cowboy:http_headers().
  604. response_headers(Headers0, Req) ->
  605. RespHeaders = maps:get(resp_headers, Req, #{}),
  606. Headers = maps:merge(#{
  607. <<"date">> => cowboy_clock:rfc1123(),
  608. <<"server">> => <<"Cowboy">>
  609. }, maps:merge(RespHeaders, Headers0)),
  610. %% The set-cookie header is special; we can only send one cookie per header.
  611. %% We send the list of values for many cookies in one key of the map,
  612. %% and let the protocols deal with it directly.
  613. case maps:get(resp_cookies, Req, undefined) of
  614. undefined -> Headers;
  615. RespCookies -> Headers#{<<"set-cookie">> => maps:values(RespCookies)}
  616. end.
  617. %% Create map, convert keys to atoms and group duplicate keys into lists.
  618. %% Keys that are not found in the user provided list are entirely skipped.
  619. %% @todo Can probably be done directly while parsing.
  620. kvlist_to_map(Fields, KvList) ->
  621. Keys = [case K of
  622. {Key, _} -> Key;
  623. {Key, _, _} -> Key;
  624. Key -> Key
  625. end || K <- Fields],
  626. kvlist_to_map(Keys, KvList, #{}).
  627. kvlist_to_map(_, [], Map) ->
  628. Map;
  629. kvlist_to_map(Keys, [{Key, Value}|Tail], Map) ->
  630. try binary_to_existing_atom(Key, utf8) of
  631. Atom ->
  632. case lists:member(Atom, Keys) of
  633. true ->
  634. case maps:find(Atom, Map) of
  635. {ok, MapValue} when is_list(MapValue) ->
  636. kvlist_to_map(Keys, Tail,
  637. Map#{Atom => [Value|MapValue]});
  638. {ok, MapValue} ->
  639. kvlist_to_map(Keys, Tail,
  640. Map#{Atom => [Value, MapValue]});
  641. error ->
  642. kvlist_to_map(Keys, Tail,
  643. Map#{Atom => Value})
  644. end;
  645. false ->
  646. kvlist_to_map(Keys, Tail, Map)
  647. end
  648. catch error:badarg ->
  649. kvlist_to_map(Keys, Tail, Map)
  650. end.
  651. %% Loop through fields, if value is missing and no default, crash;
  652. %% else if value is missing and has a default, set default;
  653. %% otherwise apply constraints. If constraint fails, crash.
  654. filter([], Map) ->
  655. Map;
  656. filter([{Key, Constraints}|Tail], Map) ->
  657. filter_constraints(Tail, Map, Key, maps:get(Key, Map), Constraints);
  658. filter([{Key, Constraints, Default}|Tail], Map) ->
  659. case maps:find(Key, Map) of
  660. {ok, Value} ->
  661. filter_constraints(Tail, Map, Key, Value, Constraints);
  662. error ->
  663. filter(Tail, Map#{Key => Default})
  664. end;
  665. filter([Key|Tail], Map) ->
  666. true = maps:is_key(Key, Map),
  667. filter(Tail, Map).
  668. filter_constraints(Tail, Map, Key, Value, Constraints) ->
  669. case cowboy_constraints:validate(Value, Constraints) of
  670. true ->
  671. filter(Tail, Map);
  672. {true, Value2} ->
  673. filter(Tail, Map#{Key => Value2})
  674. end.