Debian Codegraph @

src/cowboy_req.erl

raw
1 %% Copyright (c) Loïc Hoguin <[email protected]>
2 %% Copyright (c) Anthony Ramine <[email protected]>
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
16 -module(cowboy_req).
17
18 %% Request.
19 -export([method/1]).
20 -export([version/1]).
21 -export([peer/1]).
22 -export([sock/1]).
23 -export([cert/1]).
24 -export([scheme/1]).
25 -export([host/1]).
26 -export([host_info/1]).
27 -export([port/1]).
28 -export([path/1]).
29 -export([path_info/1]).
30 -export([qs/1]).
31 -export([parse_qs/1]).
32 -export([parse_qs/2]).
33 -export([match_qs/2]).
34 -export([match_qs/3]).
35 -export([uri/1]).
36 -export([uri/2]).
37 -export([binding/2]).
38 -export([binding/3]).
39 -export([bindings/1]).
40 -export([header/2]).
41 -export([header/3]).
42 -export([headers/1]).
43 -export([parse_header/2]).
44 -export([parse_header/3]).
45 -export([filter_cookies/2]).
46 -export([parse_cookies/1]).
47 -export([parse_cookies/2]).
48 -export([match_cookies/2]).
49 -export([match_cookies/3]).
50
51 %% Request body.
52 -export([has_body/1]).
53 -export([body_length/1]).
54 -export([read_body/1]).
55 -export([read_body/2]).
56 -export([read_urlencoded_body/1]).
57 -export([read_urlencoded_body/2]).
58 -export([read_and_match_urlencoded_body/2]).
59 -export([read_and_match_urlencoded_body/3]).
60
61 %% Multipart.
62 -export([read_part/1]).
63 -export([read_part/2]).
64 -export([read_part_body/1]).
65 -export([read_part_body/2]).
66
67 %% Response.
68 -export([set_resp_cookie/3]).
69 -export([set_resp_cookie/4]).
70 -export([resp_header/2]).
71 -export([resp_header/3]).
72 -export([resp_headers/1]).
73 -export([set_resp_header/3]).
74 -export([set_resp_headers/2]).
75 -export([has_resp_header/2]).
76 -export([delete_resp_header/2]).
77 -export([set_resp_body/2]).
78 %% @todo set_resp_body/3 with a ContentType or even Headers argument, to set content headers.
79 -export([has_resp_body/1]).
80 -export([inform/2]).
81 -export([inform/3]).
82 -export([reply/2]).
83 -export([reply/3]).
84 -export([reply/4]).
85 -export([stream_reply/2]).
86 -export([stream_reply/3]).
87 %% @todo stream_body/2 (nofin)
88 -export([stream_body/3]).
89 %% @todo stream_events/2 (nofin)
90 -export([stream_events/3]).
91 -export([stream_trailers/2]).
92 -export([push/3]).
93 -export([push/4]).
94
95 %% Stream handlers.
96 -export([cast/2]).
97
98 %% Internal.
99 -export([response_headers/2]).
100
101 -type read_body_opts() :: #{
102 length => non_neg_integer() | infinity,
103 period => non_neg_integer(),
104 timeout => timeout(),
105
106 %% Only used in read_{and_match_}urlencoded_body.
107 max_keys => non_neg_integer()
108 }.
109 -export_type([read_body_opts/0]).
110
111 %% While sendfile allows a Len of 0 that means "everything past Offset",
112 %% Cowboy expects the real length as it is used as metadata.
113 -type resp_body() :: iodata()
114 | {sendfile, non_neg_integer(), non_neg_integer(), file:name_all()}.
115 -export_type([resp_body/0]).
116
117 -type push_opts() :: #{
118 method => binary(),
119 scheme => binary(),
120 host => binary(),
121 port => inet:port_number(),
122 qs => binary()
123 }.
124 -export_type([push_opts/0]).
125
126 -type req() :: #{
127 %% Public interface.
128 method := binary(),
129 version := cowboy:http_version() | atom(),
130 scheme := binary(),
131 host := binary(),
132 port := inet:port_number(),
133 path := binary(),
134 qs := binary(),
135 headers := cowboy:http_headers(),
136 peer := {inet:ip_address(), inet:port_number()},
137 sock := {inet:ip_address(), inet:port_number()},
138 cert := binary() | undefined,
139
140 %% Private interface.
141 ref := ranch:ref(),
142 pid := pid(),
143 streamid := cowboy_stream:streamid(),
144
145 host_info => cowboy_router:tokens(),
146 path_info => cowboy_router:tokens(),
147 bindings => cowboy_router:bindings(),
148
149 has_body := boolean(),
150 body_length := non_neg_integer() | undefined,
151 has_read_body => true,
152 multipart => {binary(), binary()} | done,
153
154 has_sent_resp => headers | true,
155 resp_cookies => #{iodata() => iodata()},
156 resp_headers => #{binary() => iodata()},
157 resp_body => resp_body(),
158
159 proxy_header => ranch_proxy_header:proxy_info(),
160 media_type => {binary(), binary(), [{binary(), binary()}]},
161 language => binary() | undefined,
162 charset => binary() | undefined,
163 range => {binary(), binary()
164 | [{non_neg_integer(), non_neg_integer() | infinity} | neg_integer()]},
165 websocket_version => 7 | 8 | 13,
166
167 %% The user is encouraged to use the Req to store information
168 %% when no better solution is available.
169 _ => _
170 }.
171 -export_type([req/0]).
172
173 -ifdef(TEST).
174 -include_lib("stdlib/include/assert.hrl").
175 -endif.
176
177 %% Request.
178
179 -spec method(req()) -> binary().
180 method(#{method := Method}) ->
181 Method.
182
183 -spec version(req()) -> cowboy:http_version().
184 version(#{version := Version}) ->
185 Version.
186
187 -spec peer(req()) -> {inet:ip_address(), inet:port_number()}.
188 peer(#{peer := Peer}) ->
189 Peer.
190
191 -spec sock(req()) -> {inet:ip_address(), inet:port_number()}.
192 sock(#{sock := Sock}) ->
193 Sock.
194
195 -spec cert(req()) -> binary() | undefined.
196 cert(#{cert := Cert}) ->
197 Cert.
198
199 -spec scheme(req()) -> binary().
200 scheme(#{scheme := Scheme}) ->
201 Scheme.
202
203 -spec host(req()) -> binary().
204 host(#{host := Host}) ->
205 Host.
206
207 %% @todo The host_info is undefined if cowboy_router isn't used. Do we want to crash?
208 -spec host_info(req()) -> cowboy_router:tokens() | undefined.
209 host_info(#{host_info := HostInfo}) ->
210 HostInfo.
211
212 -spec port(req()) -> inet:port_number().
213 port(#{port := Port}) ->
214 Port.
215
216 -spec path(req()) -> binary().
217 path(#{path := Path}) ->
218 Path.
219
220 %% @todo The path_info is undefined if cowboy_router isn't used. Do we want to crash?
221 -spec path_info(req()) -> cowboy_router:tokens() | undefined.
222 path_info(#{path_info := PathInfo}) ->
223 PathInfo.
224
225 -spec qs(req()) -> binary().
226 qs(#{qs := Qs}) ->
227 Qs.
228
229 -spec parse_qs(req())
230 -> [{binary(), binary() | true}].
231
232 parse_qs(Req) ->
233 parse_qs(Req, #{}).
234
235 -spec parse_qs(req(), cow_qs:parse_opts())
236 -> [{binary(), binary() | true}].
237
238 parse_qs(#{qs := Qs}, Opts) ->
239 try
240 cow_qs:parse_qs(Qs, Opts)
241 catch
242 error:limit_reached:Stacktrace ->
243 erlang:raise(exit, {request_error, limit_reached,
244 'Limit reached while parsing query string.'
245 }, Stacktrace);
246 _:_:Stacktrace ->
247 erlang:raise(exit, {request_error, qs,
248 'Malformed query string; application/x-www-form-urlencoded expected.'
249 }, Stacktrace)
250 end.
251
252 -spec match_qs(cowboy:fields(), req()) -> map().
253
254 match_qs(Fields, Req) ->
255 match_qs(Fields, Req, #{}).
256
257 -spec match_qs(cowboy:fields(), req(), cow_qs:parse_opts()) -> map().
258
259 match_qs(Fields, Req, Opts) ->
260 case filter(Fields, kvlist_to_map(Fields, parse_qs(Req, Opts))) of
261 {ok, Map} ->
262 Map;
263 {error, Errors} ->
264 exit({request_error, {match_qs, Errors},
265 'Query string validation constraints failed for the reasons provided.'})
266 end.
267
268 -spec uri(req()) -> iodata().
269 uri(Req) ->
270 uri(Req, #{}).
271
272 -spec uri(req(), map()) -> iodata().
273 uri(#{scheme := Scheme0, host := Host0, port := Port0,
274 path := Path0, qs := Qs0}, Opts) ->
275 Scheme = case maps:get(scheme, Opts, Scheme0) of
276 S = undefined -> S;
277 S -> iolist_to_binary(S)
278 end,
279 Host = maps:get(host, Opts, Host0),
280 Port = maps:get(port, Opts, Port0),
281 {Path, Qs} = case maps:get(path, Opts, Path0) of
282 <<"*">> -> {<<>>, <<>>};
283 P -> {P, maps:get(qs, Opts, Qs0)}
284 end,
285 Fragment = maps:get(fragment, Opts, undefined),
286 [uri_host(Scheme, Scheme0, Port, Host), uri_path(Path), uri_qs(Qs), uri_fragment(Fragment)].
287
288 uri_host(_, _, _, undefined) -> <<>>;
289 uri_host(Scheme, Scheme0, Port, Host) ->
290 case iolist_size(Host) of
291 0 -> <<>>;
292 _ -> [uri_scheme(Scheme), <<"//">>, Host, uri_port(Scheme, Scheme0, Port)]
293 end.
294
295 uri_scheme(undefined) -> <<>>;
296 uri_scheme(Scheme) ->
297 case iolist_size(Scheme) of
298 0 -> Scheme;
299 _ -> [Scheme, $:]
300 end.
301
302 uri_port(_, _, undefined) -> <<>>;
303 uri_port(undefined, <<"http">>, 80) -> <<>>;
304 uri_port(undefined, <<"https">>, 443) -> <<>>;
305 uri_port(<<"http">>, _, 80) -> <<>>;
306 uri_port(<<"https">>, _, 443) -> <<>>;
307 uri_port(_, _, Port) ->
308 [$:, integer_to_binary(Port)].
309
310 uri_path(undefined) -> <<>>;
311 uri_path(Path) -> Path.
312
313 uri_qs(undefined) -> <<>>;
314 uri_qs(Qs) ->
315 case iolist_size(Qs) of
316 0 -> Qs;
317 _ -> [$?, Qs]
318 end.
319
320 uri_fragment(undefined) -> <<>>;
321 uri_fragment(Fragment) ->
322 case iolist_size(Fragment) of
323 0 -> Fragment;
324 _ -> [$#, Fragment]
325 end.
326
327 -ifdef(TEST).
328 uri1_test() ->
329 <<"http://localhost/path">> = iolist_to_binary(uri(#{
330 scheme => <<"http">>, host => <<"localhost">>, port => 80,
331 path => <<"/path">>, qs => <<>>})),
332 <<"http://localhost:443/path">> = iolist_to_binary(uri(#{
333 scheme => <<"http">>, host => <<"localhost">>, port => 443,
334 path => <<"/path">>, qs => <<>>})),
335 <<"http://localhost:8080/path">> = iolist_to_binary(uri(#{
336 scheme => <<"http">>, host => <<"localhost">>, port => 8080,
337 path => <<"/path">>, qs => <<>>})),
338 <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(#{
339 scheme => <<"http">>, host => <<"localhost">>, port => 8080,
340 path => <<"/path">>, qs => <<"dummy=2785">>})),
341 <<"https://localhost/path">> = iolist_to_binary(uri(#{
342 scheme => <<"https">>, host => <<"localhost">>, port => 443,
343 path => <<"/path">>, qs => <<>>})),
344 <<"https://localhost:8443/path">> = iolist_to_binary(uri(#{
345 scheme => <<"https">>, host => <<"localhost">>, port => 8443,
346 path => <<"/path">>, qs => <<>>})),
347 <<"https://localhost:8443/path?dummy=2785">> = iolist_to_binary(uri(#{
348 scheme => <<"https">>, host => <<"localhost">>, port => 8443,
349 path => <<"/path">>, qs => <<"dummy=2785">>})),
350 ok.
351
352 uri2_test() ->
353 Req = #{
354 scheme => <<"http">>, host => <<"localhost">>, port => 8080,
355 path => <<"/path">>, qs => <<"dummy=2785">>
356 },
357 <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{})),
358 %% Disable individual components.
359 <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => undefined})),
360 <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => undefined})),
361 <<"http://localhost/path?dummy=2785">> = iolist_to_binary(uri(Req, #{port => undefined})),
362 <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => undefined})),
363 <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => undefined})),
364 <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => undefined})),
365 <<"http://localhost:8080">> = iolist_to_binary(uri(Req, #{path => undefined, qs => undefined})),
366 <<>> = iolist_to_binary(uri(Req, #{host => undefined, path => undefined, qs => undefined})),
367 %% Empty values.
368 <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => <<>>})),
369 <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => ""})),
370 <<"//localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => [<<>>]})),
371 <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => <<>>})),
372 <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => ""})),
373 <<"/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => [<<>>]})),
374 <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => <<>>})),
375 <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => ""})),
376 <<"http://localhost:8080?dummy=2785">> = iolist_to_binary(uri(Req, #{path => [<<>>]})),
377 <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => <<>>})),
378 <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => ""})),
379 <<"http://localhost:8080/path">> = iolist_to_binary(uri(Req, #{qs => [<<>>]})),
380 <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => <<>>})),
381 <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => ""})),
382 <<"http://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{fragment => [<<>>]})),
383 %% Port is integer() | undefined.
384 ?assertError(badarg, iolist_to_binary(uri(Req, #{port => <<>>}))),
385 ?assertError(badarg, iolist_to_binary(uri(Req, #{port => ""}))),
386 ?assertError(badarg, iolist_to_binary(uri(Req, #{port => [<<>>]}))),
387 %% Update components.
388 <<"https://localhost:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => "https"})),
389 <<"http://example.org:8080/path?dummy=2785">> = iolist_to_binary(uri(Req, #{host => "example.org"})),
390 <<"http://localhost:123/path?dummy=2785">> = iolist_to_binary(uri(Req, #{port => 123})),
391 <<"http://localhost:8080/custom?dummy=2785">> = iolist_to_binary(uri(Req, #{path => "/custom"})),
392 <<"http://localhost:8080/path?smart=42">> = iolist_to_binary(uri(Req, #{qs => "smart=42"})),
393 <<"http://localhost:8080/path?dummy=2785#intro">> = iolist_to_binary(uri(Req, #{fragment => "intro"})),
394 %% Interesting combinations.
395 <<"http://localhost/path?dummy=2785">> = iolist_to_binary(uri(Req, #{port => 80})),
396 <<"https://localhost/path?dummy=2785">> = iolist_to_binary(uri(Req, #{scheme => "https", port => 443})),
397 ok.
398 -endif.
399
400 -spec binding(atom(), req()) -> any() | undefined.
401 binding(Name, Req) ->
402 binding(Name, Req, undefined).
403
404 -spec binding(atom(), req(), Default) -> any() | Default when Default::any().
405 binding(Name, #{bindings := Bindings}, Default) when is_atom(Name) ->
406 case Bindings of
407 #{Name := Value} -> Value;
408 _ -> Default
409 end;
410 binding(Name, _, Default) when is_atom(Name) ->
411 Default.
412
413 -spec bindings(req()) -> cowboy_router:bindings().
414 bindings(#{bindings := Bindings}) ->
415 Bindings;
416 bindings(_) ->
417 #{}.
418
419 -spec header(binary(), req()) -> binary() | undefined.
420 header(Name, Req) ->
421 header(Name, Req, undefined).
422
423 -spec header(binary(), req(), Default) -> binary() | Default when Default::any().
424 header(Name, #{headers := Headers}, Default) ->
425 maps:get(Name, Headers, Default).
426
427 -spec headers(req()) -> cowboy:http_headers().
428 headers(#{headers := Headers}) ->
429 Headers.
430
431 -spec parse_header(binary(), Req) -> any() when Req::req().
432 parse_header(Name = <<"content-length">>, Req) ->
433 parse_header(Name, Req, 0);
434 parse_header(Name = <<"cookie">>, Req) ->
435 parse_header(Name, Req, []);
436 parse_header(Name, Req) ->
437 parse_header(Name, Req, undefined).
438
439 -spec parse_header(binary(), Req, any()) -> any() when Req::req().
440 parse_header(Name, Req, Default) ->
441 try
442 parse_header(Name, Req, Default, parse_header_fun(Name))
443 catch _:_:Stacktrace ->
444 erlang:raise(exit, {request_error, {header, Name},
445 'Malformed header. Please consult the relevant specification.'
446 }, Stacktrace)
447 end.
448
449 parse_header_fun(<<"accept">>) -> fun cow_http_hd:parse_accept/1;
450 parse_header_fun(<<"accept-charset">>) -> fun cow_http_hd:parse_accept_charset/1;
451 parse_header_fun(<<"accept-encoding">>) -> fun cow_http_hd:parse_accept_encoding/1;
452 parse_header_fun(<<"accept-language">>) -> fun cow_http_hd:parse_accept_language/1;
453 parse_header_fun(<<"access-control-request-headers">>) -> fun cow_http_hd:parse_access_control_request_headers/1;
454 parse_header_fun(<<"access-control-request-method">>) -> fun cow_http_hd:parse_access_control_request_method/1;
455 parse_header_fun(<<"authorization">>) -> fun cow_http_hd:parse_authorization/1;
456 parse_header_fun(<<"connection">>) -> fun cow_http_hd:parse_connection/1;
457 parse_header_fun(<<"content-encoding">>) -> fun cow_http_hd:parse_content_encoding/1;
458 parse_header_fun(<<"content-language">>) -> fun cow_http_hd:parse_content_language/1;
459 parse_header_fun(<<"content-length">>) -> fun cow_http_hd:parse_content_length/1;
460 parse_header_fun(<<"content-type">>) -> fun cow_http_hd:parse_content_type/1;
461 parse_header_fun(<<"cookie">>) -> fun cow_cookie:parse_cookie/1;
462 parse_header_fun(<<"expect">>) -> fun cow_http_hd:parse_expect/1;
463 parse_header_fun(<<"if-match">>) -> fun cow_http_hd:parse_if_match/1;
464 parse_header_fun(<<"if-modified-since">>) -> fun cow_http_hd:parse_if_modified_since/1;
465 parse_header_fun(<<"if-none-match">>) -> fun cow_http_hd:parse_if_none_match/1;
466 parse_header_fun(<<"if-range">>) -> fun cow_http_hd:parse_if_range/1;
467 parse_header_fun(<<"if-unmodified-since">>) -> fun cow_http_hd:parse_if_unmodified_since/1;
468 parse_header_fun(<<"max-forwards">>) -> fun cow_http_hd:parse_max_forwards/1;
469 parse_header_fun(<<"origin">>) -> fun cow_http_hd:parse_origin/1;
470 parse_header_fun(<<"proxy-authorization">>) -> fun cow_http_hd:parse_proxy_authorization/1;
471 parse_header_fun(<<"range">>) -> fun cow_http_hd:parse_range/1;
472 parse_header_fun(<<"sec-websocket-extensions">>) -> fun cow_http_hd:parse_sec_websocket_extensions/1;
473 parse_header_fun(<<"sec-websocket-protocol">>) -> fun cow_http_hd:parse_sec_websocket_protocol_req/1;
474 parse_header_fun(<<"sec-websocket-version">>) -> fun cow_http_hd:parse_sec_websocket_version_req/1;
475 parse_header_fun(<<"trailer">>) -> fun cow_http_hd:parse_trailer/1;
476 parse_header_fun(<<"upgrade">>) -> fun cow_http_hd:parse_upgrade/1;
477 parse_header_fun(<<"wt-available-protocols">>) -> fun cow_http_hd:parse_wt_available_protocols/1;
478 parse_header_fun(<<"x-forwarded-for">>) -> fun cow_http_hd:parse_x_forwarded_for/1.
479
480 parse_header(Name, Req, Default, ParseFun) ->
481 case header(Name, Req) of
482 undefined -> Default;
483 Value -> ParseFun(Value)
484 end.
485
486 -spec filter_cookies([atom() | binary()], Req) -> Req when Req::req().
487 filter_cookies(Names0, Req=#{headers := Headers}) ->
488 Names = [if
489 is_atom(N) -> atom_to_binary(N, utf8);
490 true -> N
491 end || N <- Names0],
492 case header(<<"cookie">>, Req) of
493 undefined -> Req;
494 Value0 ->
495 Cookies0 = binary:split(Value0, <<$;>>, [global]),
496 Cookies = lists:filter(fun(Cookie) ->
497 lists:member(cookie_name(Cookie), Names)
498 end, Cookies0),
499 Value = iolist_to_binary(lists:join($;, Cookies)),
500 Req#{headers => Headers#{<<"cookie">> => Value}}
501 end.
502
503 %% This is a specialized function to extract a cookie name
504 %% regardless of whether the name is valid or not. We skip
505 %% whitespace at the beginning and take whatever's left to
506 %% be the cookie name, up to the = sign.
507 cookie_name(<<$\s, Rest/binary>>) -> cookie_name(Rest);
508 cookie_name(<<$\t, Rest/binary>>) -> cookie_name(Rest);
509 cookie_name(Name) -> cookie_name(Name, <<>>).
510
511 cookie_name(<<>>, Name) -> Name;
512 cookie_name(<<$=, _/bits>>, Name) -> Name;
513 cookie_name(<<C, Rest/bits>>, Acc) -> cookie_name(Rest, <<Acc/binary, C>>).
514
515 -spec parse_cookies(req()) -> [{binary(), binary()}].
516 parse_cookies(Req) ->
517 parse_cookies(Req, #{}).
518
519 -spec parse_cookies(req(), cow_cookie:parse_opts()) -> [{binary(), binary()}].
520 parse_cookies(Req, Opts) ->
521 try
522 case header(<<"cookie">>, Req, undefined) of
523 undefined -> [];
524 Cookie -> cow_cookie:parse_cookie(Cookie, Opts)
525 end
526 catch
527 error:limit_reached:Stacktrace ->
528 erlang:raise(exit, {request_error, limit_reached,
529 'Limit reached while parsing cookie header.'
530 }, Stacktrace);
531 _:_:Stacktrace ->
532 erlang:raise(exit, {request_error, {header, <<"cookie">>},
533 'Malformed header. Please consult the relevant specification.'
534 }, Stacktrace)
535 end.
536
537 -spec match_cookies(cowboy:fields(), req()) -> map().
538 match_cookies(Fields, Req) ->
539 match_cookies(Fields, Req, #{}).
540
541 -spec match_cookies(cowboy:fields(), req(), cow_cookie:parse_opts()) -> map().
542 match_cookies(Fields, Req, Opts) ->
543 case filter(Fields, kvlist_to_map(Fields, parse_cookies(Req, Opts))) of
544 {ok, Map} ->
545 Map;
546 {error, Errors} ->
547 exit({request_error, {match_cookies, Errors},
548 'Cookie validation constraints failed for the reasons provided.'})
549 end.
550
551 %% Request body.
552
553 -spec has_body(req()) -> boolean().
554 has_body(#{has_body := HasBody}) ->
555 HasBody.
556
557 %% The length may not be known if HTTP/1.1 with a transfer-encoding;
558 %% or HTTP/2 with no content-length header. The length is always
559 %% known once the body has been completely read.
560 -spec body_length(req()) -> undefined | non_neg_integer().
561 body_length(#{body_length := Length}) ->
562 Length.
563
564 -spec read_body(Req) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req().
565 read_body(Req) ->
566 read_body(Req, #{}).
567
568 -spec read_body(Req, read_body_opts()) -> {ok, binary(), Req} | {more, binary(), Req} when Req::req().
569 read_body(Req=#{has_body := false}, _) ->
570 {ok, <<>>, Req};
571 read_body(Req=#{has_read_body := true}, _) ->
572 {ok, <<>>, Req};
573 read_body(Req, Opts) ->
574 Length = maps:get(length, Opts, 8000000),
575 Period = maps:get(period, Opts, 15000),
576 DefaultTimeout = case Period of
577 infinity -> infinity; %% infinity + 1000 = infinity.
578 _ -> Period + 1000
579 end,
580 Timeout = maps:get(timeout, Opts, DefaultTimeout),
581 Ref = make_ref(),
582 cast({read_body, self(), Ref, Length, Period}, Req),
583 receive
584 {request_body, Ref, nofin, Body} ->
585 {more, Body, Req};
586 {request_body, Ref, fin, BodyLength, Body} ->
587 {ok, Body, set_body_length(Req, BodyLength)}
588 after Timeout ->
589 exit(timeout)
590 end.
591
592 set_body_length(Req=#{headers := Headers}, BodyLength) ->
593 Req#{
594 headers => Headers#{<<"content-length">> => integer_to_binary(BodyLength)},
595 body_length => BodyLength,
596 has_read_body => true
597 }.
598
599 -spec read_urlencoded_body(Req) -> {ok, [{binary(), binary() | true}], Req} when Req::req().
600 read_urlencoded_body(Req) ->
601 read_urlencoded_body(Req, #{}).
602
603 -spec read_urlencoded_body(Req, read_body_opts()) -> {ok, [{binary(), binary() | true}], Req} when Req::req().
604 read_urlencoded_body(Req0, Opts0) ->
605 Opts = maps:merge(#{length => 64000, period => 5000}, Opts0),
606 case read_body(Req0, Opts) of
607 {ok, Body, Req} ->
608 try
609 {ok, cow_qs:parse_qs(Body, maps:with([max_keys], Opts)), Req}
610 catch _:_:Stacktrace ->
611 erlang:raise(exit, {request_error, urlencoded_body,
612 'Malformed body; application/x-www-form-urlencoded expected.'
613 }, Stacktrace)
614 end;
615 {more, Body, _} ->
616 Length = maps:get(length, Opts, 64000),
617 if
618 byte_size(Body) < Length ->
619 exit({request_error, timeout,
620 'The request body was not received within the configured time.'});
621 true ->
622 exit({request_error, payload_too_large,
623 'The request body is larger than allowed by configuration.'})
624 end
625 end.
626
627 -spec read_and_match_urlencoded_body(cowboy:fields(), Req)
628 -> {ok, map(), Req} when Req::req().
629 read_and_match_urlencoded_body(Fields, Req) ->
630 read_and_match_urlencoded_body(Fields, Req, #{}).
631
632 -spec read_and_match_urlencoded_body(cowboy:fields(), Req, read_body_opts())
633 -> {ok, map(), Req} when Req::req().
634 read_and_match_urlencoded_body(Fields, Req0, Opts) ->
635 {ok, Qs, Req} = read_urlencoded_body(Req0, Opts),
636 case filter(Fields, kvlist_to_map(Fields, Qs)) of
637 {ok, Map} ->
638 {ok, Map, Req};
639 {error, Errors} ->
640 exit({request_error, {read_and_match_urlencoded_body, Errors},
641 'Urlencoded request body validation constraints failed for the reasons provided.'})
642 end.
643
644 %% Multipart.
645
646 -spec read_part(Req)
647 -> {ok, cowboy:http_headers(), Req} | {done, Req}
648 when Req::req().
649 read_part(Req) ->
650 read_part(Req, #{length => 64000, period => 5000}).
651
652 -spec read_part(Req, read_body_opts())
653 -> {ok, cowboy:http_headers(), Req} | {done, Req}
654 when Req::req().
655 read_part(Req, Opts) ->
656 case maps:is_key(multipart, Req) of
657 true ->
658 {Data, Req2} = stream_multipart(Req, Opts, headers),
659 read_part(Data, Opts, Req2);
660 false ->
661 read_part(init_multipart(Req), Opts)
662 end.
663
664 read_part(Buffer, Opts, Req=#{multipart := {Boundary, _}}) ->
665 try cow_multipart:parse_headers(Buffer, Boundary) of
666 more ->
667 read_part_more(Buffer, Opts, Req);
668 {more, Buffer2} ->
669 read_part_more(Buffer2, Opts, Req);
670 {ok, Headers0, Rest} ->
671 Headers = maps:from_list(Headers0),
672 %% Reject multipart content containing duplicate headers.
673 true = map_size(Headers) =:= length(Headers0),
674 {ok, Headers, Req#{multipart => {Boundary, Rest}}};
675 %% Ignore epilogue.
676 {done, _} ->
677 {done, Req#{multipart => done}}
678 catch _:_:Stacktrace ->
679 erlang:raise(exit, {request_error, {multipart, headers},
680 'Malformed body; multipart expected.'
681 }, Stacktrace)
682 end.
683
684 %% We reject multipart header blocks that are twice the maximum
685 %% size of the largest expected multipart header blocks.
686 read_part_more(Buffer, _, _) when byte_size(Buffer) > 2048 ->
687 exit({request_error, {multipart, headers},
688 'Malformed body; multipart header block too large.'
689 });
690 read_part_more(Buffer, Opts, Req0) ->
691 {Data, Req} = stream_multipart(Req0, Opts, headers),
692 read_part(<<Buffer/binary, Data/binary>>, Opts, Req).
693
694 -spec read_part_body(Req)
695 -> {ok, binary(), Req} | {more, binary(), Req}
696 when Req::req().
697 read_part_body(Req) ->
698 read_part_body(Req, #{}).
699
700 -spec read_part_body(Req, read_body_opts())
701 -> {ok, binary(), Req} | {more, binary(), Req}
702 when Req::req().
703 read_part_body(Req, Opts) ->
704 case maps:is_key(multipart, Req) of
705 true ->
706 read_part_body(<<>>, Opts, Req, <<>>);
707 false ->
708 read_part_body(init_multipart(Req), Opts)
709 end.
710
711 read_part_body(Buffer, Opts, Req=#{multipart := {Boundary, _}}, Acc) ->
712 Length = maps:get(length, Opts, 8000000),
713 case byte_size(Acc) > Length of
714 true ->
715 {more, Acc, Req#{multipart => {Boundary, Buffer}}};
716 false ->
717 {Data, Req2} = stream_multipart(Req, Opts, body),
718 case cow_multipart:parse_body(<< Buffer/binary, Data/binary >>, Boundary) of
719 {ok, Body} ->
720 read_part_body(<<>>, Opts, Req2, << Acc/binary, Body/binary >>);
721 {ok, Body, Rest} ->
722 read_part_body(Rest, Opts, Req2, << Acc/binary, Body/binary >>);
723 done ->
724 {ok, Acc, Req2};
725 {done, Body} ->
726 {ok, << Acc/binary, Body/binary >>, Req2};
727 {done, Body, Rest} ->
728 {ok, << Acc/binary, Body/binary >>,
729 Req2#{multipart => {Boundary, Rest}}}
730 end
731 end.
732
733 init_multipart(Req) ->
734 {<<"multipart">>, _, Params} = parse_header(<<"content-type">>, Req),
735 case lists:keyfind(<<"boundary">>, 1, Params) of
736 {_, Boundary} ->
737 Req#{multipart => {Boundary, <<>>}};
738 false ->
739 exit({request_error, {multipart, boundary},
740 'Missing boundary parameter for multipart media type.'})
741 end.
742
743 stream_multipart(Req=#{multipart := done}, _, _) ->
744 {<<>>, Req};
745 stream_multipart(Req=#{multipart := {_, <<>>}}, Opts, Type) ->
746 case read_body(Req, Opts) of
747 {more, Data, Req2} ->
748 {Data, Req2};
749 %% We crash when the data ends unexpectedly.
750 {ok, <<>>, _} ->
751 exit({request_error, {multipart, Type},
752 'Malformed body; multipart expected.'});
753 {ok, Data, Req2} ->
754 {Data, Req2}
755 end;
756 stream_multipart(Req=#{multipart := {Boundary, Buffer}}, _, _) ->
757 {Buffer, Req#{multipart => {Boundary, <<>>}}}.
758
759 %% Response.
760
761 -spec set_resp_cookie(iodata(), iodata(), Req)
762 -> Req when Req::req().
763 set_resp_cookie(Name, Value, Req) ->
764 set_resp_cookie(Name, Value, Req, #{}).
765
766 %% The cookie name cannot contain any of the following characters:
767 %% =,;\s\t\r\n\013\014
768 %%
769 %% The cookie value cannot contain any of the following characters:
770 %% ,; \t\r\n\013\014
771 -spec set_resp_cookie(binary(), iodata(), Req, cow_cookie:cookie_opts())
772 -> Req when Req::req().
773 set_resp_cookie(Name, Value, Req, Opts) ->
774 Cookie = cow_cookie:setcookie(Name, Value, Opts),
775 RespCookies = maps:get(resp_cookies, Req, #{}),
776 Req#{resp_cookies => RespCookies#{Name => Cookie}}.
777
778 %% @todo We could add has_resp_cookie and unset_resp_cookie now.
779
780 -spec set_resp_header(binary(), iodata(), Req)
781 -> Req when Req::req().
782 set_resp_header(<<"set-cookie">>, _, _) ->
783 exit({response_error, invalid_header,
784 'Response cookies must be set using cowboy_req:set_resp_cookie/3,4.'});
785 set_resp_header(Name, Value, Req=#{resp_headers := RespHeaders}) ->
786 Req#{resp_headers => RespHeaders#{Name => Value}};
787 set_resp_header(Name,Value, Req) ->
788 Req#{resp_headers => #{Name => Value}}.
789
790 -spec set_resp_headers(cowboy:http_headers() | [{binary(), iodata()}], Req)
791 -> Req when Req::req().
792 set_resp_headers(Headers, Req) when is_list(Headers) ->
793 set_resp_headers_list(Headers, Req, #{});
794 set_resp_headers(#{<<"set-cookie">> := _}, _) ->
795 exit({response_error, invalid_header,
796 'Response cookies must be set using cowboy_req:set_resp_cookie/3,4.'});
797 set_resp_headers(Headers, Req=#{resp_headers := RespHeaders}) ->
798 Req#{resp_headers => maps:merge(RespHeaders, Headers)};
799 set_resp_headers(Headers, Req) ->
800 Req#{resp_headers => Headers}.
801
802 set_resp_headers_list([], Req, Acc) ->
803 set_resp_headers(Acc, Req);
804 set_resp_headers_list([{<<"set-cookie">>, _}|_], _, _) ->
805 exit({response_error, invalid_header,
806 'Response cookies must be set using cowboy_req:set_resp_cookie/3,4.'});
807 set_resp_headers_list([{Name, Value}|Tail], Req, Acc) ->
808 case Acc of
809 #{Name := ValueAcc} ->
810 set_resp_headers_list(Tail, Req, Acc#{Name => [ValueAcc, <<", ">>, Value]});
811 _ ->
812 set_resp_headers_list(Tail, Req, Acc#{Name => Value})
813 end.
814
815 -spec resp_header(binary(), req()) -> binary() | undefined.
816 resp_header(Name, Req) ->
817 resp_header(Name, Req, undefined).
818
819 -spec resp_header(binary(), req(), Default)
820 -> binary() | Default when Default::any().
821 resp_header(Name, #{resp_headers := Headers}, Default) ->
822 maps:get(Name, Headers, Default);
823 resp_header(_, #{}, Default) ->
824 Default.
825
826 -spec resp_headers(req()) -> cowboy:http_headers().
827 resp_headers(#{resp_headers := RespHeaders}) ->
828 RespHeaders;
829 resp_headers(#{}) ->
830 #{}.
831
832 -spec set_resp_body(resp_body(), Req) -> Req when Req::req().
833 set_resp_body(Body, Req) ->
834 Req#{resp_body => Body}.
835
836 -spec has_resp_header(binary(), req()) -> boolean().
837 has_resp_header(Name, #{resp_headers := RespHeaders}) ->
838 maps:is_key(Name, RespHeaders);
839 has_resp_header(_, _) ->
840 false.
841
842 -spec has_resp_body(req()) -> boolean().
843 has_resp_body(#{resp_body := {sendfile, _, _, _}}) ->
844 true;
845 has_resp_body(#{resp_body := RespBody}) ->
846 iolist_size(RespBody) > 0;
847 has_resp_body(_) ->
848 false.
849
850 -spec delete_resp_header(binary(), Req)
851 -> Req when Req::req().
852 delete_resp_header(Name, Req=#{resp_headers := RespHeaders}) ->
853 Req#{resp_headers => maps:remove(Name, RespHeaders)};
854 %% There are no resp headers so we have nothing to delete.
855 delete_resp_header(_, Req) ->
856 Req.
857
858 -spec inform(cowboy:http_status(), req()) -> ok.
859 inform(Status, Req) ->
860 inform(Status, #{}, Req).
861
862 -spec inform(cowboy:http_status(), cowboy:http_headers(), req()) -> ok.
863 inform(_, _, #{has_sent_resp := _}) ->
864 exit({response_error, response_already_sent,
865 'The final response has already been sent.'});
866 inform(_, #{<<"set-cookie">> := _}, _) ->
867 exit({response_error, invalid_header,
868 'Response cookies must be set using cowboy_req:set_resp_cookie/3,4.'});
869 inform(Status, Headers, Req) when is_integer(Status); is_binary(Status) ->
870 cast({inform, Status, Headers}, Req).
871
872 -spec reply(cowboy:http_status(), Req) -> Req when Req::req().
873 reply(Status, Req) ->
874 reply(Status, #{}, Req).
875
876 -spec reply(cowboy:http_status(), cowboy:http_headers(), Req)
877 -> Req when Req::req().
878 reply(Status, Headers, Req=#{resp_body := Body}) ->
879 reply(Status, Headers, Body, Req);
880 reply(Status, Headers, Req) ->
881 reply(Status, Headers, <<>>, Req).
882
883 -spec reply(cowboy:http_status(), cowboy:http_headers(), resp_body(), Req)
884 -> Req when Req::req().
885 reply(_, _, _, #{has_sent_resp := _}) ->
886 exit({response_error, response_already_sent,
887 'The final response has already been sent.'});
888 reply(_, #{<<"set-cookie">> := _}, _, _) ->
889 exit({response_error, invalid_header,
890 'Response cookies must be set using cowboy_req:set_resp_cookie/3,4.'});
891 reply(Status, Headers, {sendfile, _, 0, _}, Req)
892 when is_integer(Status); is_binary(Status) ->
893 do_reply(Status, Headers#{
894 <<"content-length">> => <<"0">>
895 }, <<>>, Req);
896 reply(Status, Headers, SendFile = {sendfile, _, Len, _}, Req)
897 when is_integer(Status); is_binary(Status) ->
898 do_reply(Status, Headers#{
899 <<"content-length">> => integer_to_binary(Len)
900 }, SendFile, Req);
901 %% 204 responses must not include content-length. 304 responses may
902 %% but only when set explicitly. (RFC7230 3.3.1, RFC7230 3.3.2)
903 %% Neither status code must include a response body. (RFC7230 3.3)
904 reply(Status, Headers, Body, Req)
905 when Status =:= 204; Status =:= 304 ->
906 do_reply_ensure_no_body(Status, Headers, Body, Req);
907 reply(Status = <<"204",_/bits>>, Headers, Body, Req) ->
908 do_reply_ensure_no_body(Status, Headers, Body, Req);
909 reply(Status = <<"304",_/bits>>, Headers, Body, Req) ->
910 do_reply_ensure_no_body(Status, Headers, Body, Req);
911 reply(Status, Headers, Body, Req)
912 when is_integer(Status); is_binary(Status) ->
913 do_reply(Status, Headers#{
914 <<"content-length">> => integer_to_binary(iolist_size(Body))
915 }, Body, Req).
916
917 do_reply_ensure_no_body(Status, Headers, Body, Req) ->
918 case iolist_size(Body) of
919 0 ->
920 do_reply(Status, Headers, Body, Req);
921 _ ->
922 exit({response_error, payload_too_large,
923 '204 and 304 responses must not include a body. (RFC7230 3.3)'})
924 end.
925
926 %% Don't send any body for HEAD responses. While the protocol code is
927 %% supposed to enforce this rule, we prefer to avoid copying too much
928 %% data around if we can avoid it.
929 do_reply(Status, Headers, _, Req=#{method := <<"HEAD">>}) ->
930 cast({response, Status, response_headers(Headers, Req), <<>>}, Req),
931 done_replying(Req, true);
932 do_reply(Status, Headers, Body, Req) ->
933 cast({response, Status, response_headers(Headers, Req), Body}, Req),
934 done_replying(Req, true).
935
936 done_replying(Req, HasSentResp) ->
937 maps:without([resp_cookies, resp_headers, resp_body], Req#{has_sent_resp => HasSentResp}).
938
939 -spec stream_reply(cowboy:http_status(), Req) -> Req when Req::req().
940 stream_reply(Status, Req) ->
941 stream_reply(Status, #{}, Req).
942
943 -spec stream_reply(cowboy:http_status(), cowboy:http_headers(), Req)
944 -> Req when Req::req().
945 stream_reply(_, _, #{has_sent_resp := _}) ->
946 exit({response_error, response_already_sent,
947 'The final response has already been sent.'});
948 stream_reply(_, #{<<"set-cookie">> := _}, _) ->
949 exit({response_error, invalid_header,
950 'Response cookies must be set using cowboy_req:set_resp_cookie/3,4.'});
951 %% 204 and 304 responses must NOT send a body. We therefore
952 %% transform the call to a full response and expect the user
953 %% to NOT call stream_body/3 afterwards. (RFC7230 3.3)
954 stream_reply(Status, Headers=#{}, Req)
955 when Status =:= 204; Status =:= 304 ->
956 reply(Status, Headers, <<>>, Req);
957 stream_reply(Status = <<"204",_/bits>>, Headers=#{}, Req) ->
958 reply(Status, Headers, <<>>, Req);
959 stream_reply(Status = <<"304",_/bits>>, Headers=#{}, Req) ->
960 reply(Status, Headers, <<>>, Req);
961 stream_reply(Status, Headers=#{}, Req) when is_integer(Status); is_binary(Status) ->
962 cast({headers, Status, response_headers(Headers, Req)}, Req),
963 done_replying(Req, headers).
964
965 -spec stream_body(resp_body(), fin | nofin, req()) -> ok.
966 %% Error out if headers were not sent.
967 %% Don't send any body for HEAD responses.
968 stream_body(_, _, #{method := <<"HEAD">>, has_sent_resp := headers}) ->
969 ok;
970 %% Don't send a message if the data is empty, except for the
971 %% very last message with IsFin=fin. When using sendfile this
972 %% is converted to a data tuple, however.
973 stream_body({sendfile, _, 0, _}, nofin, _) ->
974 ok;
975 stream_body({sendfile, _, 0, _}, IsFin=fin, Req=#{has_sent_resp := headers}) ->
976 stream_body({data, self(), IsFin, <<>>}, Req);
977 stream_body({sendfile, O, B, P}, IsFin, Req=#{has_sent_resp := headers})
978 when is_integer(O), O >= 0, is_integer(B), B > 0 ->
979 stream_body({data, self(), IsFin, {sendfile, O, B, P}}, Req);
980 stream_body(Data, IsFin=nofin, Req=#{has_sent_resp := headers})
981 when not is_tuple(Data) ->
982 case iolist_size(Data) of
983 0 -> ok;
984 _ -> stream_body({data, self(), IsFin, Data}, Req)
985 end;
986 stream_body(Data, IsFin, Req=#{has_sent_resp := headers})
987 when not is_tuple(Data) ->
988 stream_body({data, self(), IsFin, Data}, Req).
989
990 %% @todo Do we need a timeout?
991 stream_body(Msg, Req=#{pid := Pid}) ->
992 cast(Msg, Req),
993 receive {data_ack, Pid} -> ok end.
994
995 -spec stream_events(cow_sse:event() | [cow_sse:event()], fin | nofin, req()) -> ok.
996 stream_events(Event, IsFin, Req) when is_map(Event) ->
997 stream_events([Event], IsFin, Req);
998 stream_events(Events, IsFin, Req=#{has_sent_resp := headers}) ->
999 stream_body({data, self(), IsFin, cow_sse:events(Events)}, Req).
1000
1001 -spec stream_trailers(cowboy:http_headers(), req()) -> ok.
1002 stream_trailers(#{<<"set-cookie">> := _}, _) ->
1003 exit({response_error, invalid_header,
1004 'Response cookies must be set using cowboy_req:set_resp_cookie/3,4.'});
1005 stream_trailers(Trailers, Req=#{has_sent_resp := headers}) ->
1006 cast({trailers, Trailers}, Req).
1007
1008 -spec push(iodata(), cowboy:http_headers(), req()) -> ok.
1009 push(Path, Headers, Req) ->
1010 push(Path, Headers, Req, #{}).
1011
1012 %% @todo Optimization: don't send anything at all for HTTP/1.0 and HTTP/1.1.
1013 %% @todo Path, Headers, Opts, everything should be in proper binary,
1014 %% or normalized when creating the Req object.
1015 -spec push(iodata(), cowboy:http_headers(), req(), push_opts()) -> ok.
1016 push(_, _, #{has_sent_resp := _}, _) ->
1017 exit({response_error, response_already_sent,
1018 'The final response has already been sent.'});
1019 push(Path, Headers, Req=#{scheme := Scheme0, host := Host0, port := Port0}, Opts) ->
1020 Method = maps:get(method, Opts, <<"GET">>),
1021 Scheme = maps:get(scheme, Opts, Scheme0),
1022 Host = maps:get(host, Opts, Host0),
1023 Port = maps:get(port, Opts, Port0),
1024 Qs = maps:get(qs, Opts, <<>>),
1025 cast({push, Method, Scheme, Host, Port, Path, Qs, Headers}, Req).
1026
1027 %% Stream handlers.
1028
1029 -spec cast(any(), req()) -> ok.
1030 cast(Msg, #{pid := Pid, streamid := StreamID}) ->
1031 Pid ! {{Pid, StreamID}, Msg},
1032 ok.
1033
1034 %% Internal.
1035
1036 %% @todo What about set-cookie headers set through set_resp_header or reply?
1037 -spec response_headers(Headers, req()) -> Headers when Headers::cowboy:http_headers().
1038 response_headers(Headers0, Req) ->
1039 RespHeaders = maps:get(resp_headers, Req, #{}),
1040 Headers = maps:merge(#{
1041 <<"date">> => cowboy_clock:rfc1123(),
1042 <<"server">> => <<"Cowboy">>
1043 }, maps:merge(RespHeaders, Headers0)),
1044 %% The set-cookie header is special; we can only send one cookie per header.
1045 %% We send the list of values for many cookies in one key of the map,
1046 %% and let the protocols deal with it directly.
1047 case maps:get(resp_cookies, Req, undefined) of
1048 undefined -> Headers;
1049 RespCookies -> Headers#{<<"set-cookie">> => maps:values(RespCookies)}
1050 end.
1051
1052 %% Create map, convert keys to atoms and group duplicate keys into lists.
1053 %% Keys that are not found in the user provided list are entirely skipped.
1054 %% @todo Can probably be done directly while parsing.
1055 kvlist_to_map(Fields, KvList) ->
1056 Keys = [case K of
1057 {Key, _} -> Key;
1058 {Key, _, _} -> Key;
1059 Key -> Key
1060 end || K <- Fields],
1061 kvlist_to_map(Keys, KvList, #{}).
1062
1063 kvlist_to_map(_, [], Map) ->
1064 Map;
1065 kvlist_to_map(Keys, [{Key, Value}|Tail], Map) ->
1066 try binary_to_existing_atom(Key, utf8) of
1067 Atom ->
1068 case lists:member(Atom, Keys) of
1069 true ->
1070 case maps:find(Atom, Map) of
1071 {ok, MapValue} when is_list(MapValue) ->
1072 kvlist_to_map(Keys, Tail,
1073 Map#{Atom => [Value|MapValue]});
1074 {ok, MapValue} ->
1075 kvlist_to_map(Keys, Tail,
1076 Map#{Atom => [Value, MapValue]});
1077 error ->
1078 kvlist_to_map(Keys, Tail,
1079 Map#{Atom => Value})
1080 end;
1081 false ->
1082 kvlist_to_map(Keys, Tail, Map)
1083 end
1084 catch error:badarg ->
1085 kvlist_to_map(Keys, Tail, Map)
1086 end.
1087
1088 filter(Fields, Map0) ->
1089 filter(Fields, Map0, #{}).
1090
1091 %% Loop through fields, if value is missing and no default,
1092 %% record the error; else if value is missing and has a
1093 %% default, set default; otherwise apply constraints. If
1094 %% constraint fails, record the error.
1095 %%
1096 %% When there is an error at the end, crash.
1097 filter([], Map, Errors) ->
1098 case maps:size(Errors) of
1099 0 -> {ok, Map};
1100 _ -> {error, Errors}
1101 end;
1102 filter([{Key, Constraints}|Tail], Map, Errors) ->
1103 case maps:find(Key, Map) of
1104 {ok, Value} ->
1105 filter_constraints(Tail, Map, Errors, Key, Value, Constraints);
1106 error ->
1107 filter(Tail, Map, Errors#{Key => required})
1108 end;
1109 filter([{Key, Constraints, Default}|Tail], Map, Errors) ->
1110 case maps:find(Key, Map) of
1111 {ok, Value} ->
1112 filter_constraints(Tail, Map, Errors, Key, Value, Constraints);
1113 error ->
1114 filter(Tail, Map#{Key => Default}, Errors)
1115 end;
1116 filter([Key|Tail], Map, Errors) ->
1117 case maps:is_key(Key, Map) of
1118 true ->
1119 filter(Tail, Map, Errors);
1120 false ->
1121 filter(Tail, Map, Errors#{Key => required})
1122 end.
1123
1124 filter_constraints(Tail, Map, Errors, Key, Value0, Constraints) ->
1125 case cowboy_constraints:validate(Value0, Constraints) of
1126 {ok, Value} ->
1127 filter(Tail, Map#{Key => Value}, Errors);
1128 {error, Reason} ->
1129 filter(Tail, Map, Errors#{Key => Reason})
1130 end.