| 1 |
%% Copyright (c) Loïc Hoguin <[email protected]> |
| 2 |
%% |
| 3 |
%% Permission to use, copy, modify, and/or distribute this software for any |
| 4 |
%% purpose with or without fee is hereby granted, provided that the above |
| 5 |
%% copyright notice and this permission notice appear in all copies. |
| 6 |
%% |
| 7 |
%% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES |
| 8 |
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF |
| 9 |
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR |
| 10 |
%% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES |
| 11 |
%% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN |
| 12 |
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF |
| 13 |
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. |
| 14 |
|
| 15 |
%% Originally based on the Webmachine Diagram from Alan Dean and |
| 16 |
%% Justin Sheehy. |
| 17 |
-module(cowboy_rest). |
| 18 |
-behaviour(cowboy_sub_protocol). |
| 19 |
|
| 20 |
-export([upgrade/4]). |
| 21 |
-export([upgrade/5]). |
| 22 |
|
| 23 |
-type switch_handler() :: {switch_handler, module()} |
| 24 |
| {switch_handler, module(), any()}. |
| 25 |
|
| 26 |
%% Common handler callbacks. |
| 27 |
|
| 28 |
-callback init(Req, any()) |
| 29 |
-> {ok | module(), Req, any()} |
| 30 |
| {module(), Req, any(), any()} |
| 31 |
when Req::cowboy_req:req(). |
| 32 |
|
| 33 |
-callback terminate(any(), cowboy_req:req(), any()) -> ok. |
| 34 |
-optional_callbacks([terminate/3]). |
| 35 |
|
| 36 |
%% REST handler callbacks. |
| 37 |
|
| 38 |
-callback allowed_methods(Req, State) |
| 39 |
-> {[binary()], Req, State} |
| 40 |
| {stop, Req, State} |
| 41 |
| {switch_handler(), Req, State} |
| 42 |
when Req::cowboy_req:req(), State::any(). |
| 43 |
-optional_callbacks([allowed_methods/2]). |
| 44 |
|
| 45 |
-callback allow_missing_post(Req, State) |
| 46 |
-> {boolean(), Req, State} |
| 47 |
| {stop, Req, State} |
| 48 |
| {switch_handler(), Req, State} |
| 49 |
when Req::cowboy_req:req(), State::any(). |
| 50 |
-optional_callbacks([allow_missing_post/2]). |
| 51 |
|
| 52 |
-callback charsets_provided(Req, State) |
| 53 |
-> {[binary()], Req, State} |
| 54 |
| {stop, Req, State} |
| 55 |
| {switch_handler(), Req, State} |
| 56 |
when Req::cowboy_req:req(), State::any(). |
| 57 |
-optional_callbacks([charsets_provided/2]). |
| 58 |
|
| 59 |
-callback content_types_accepted(Req, State) |
| 60 |
-> {[{'*' | binary() | {binary(), binary(), '*' | [{binary(), binary()}]}, atom()}], Req, State} |
| 61 |
| {stop, Req, State} |
| 62 |
| {switch_handler(), Req, State} |
| 63 |
when Req::cowboy_req:req(), State::any(). |
| 64 |
-optional_callbacks([content_types_accepted/2]). |
| 65 |
|
| 66 |
-callback content_types_provided(Req, State) |
| 67 |
-> {[{binary() | {binary(), binary(), '*' | [{binary(), binary()}]}, atom()}], Req, State} |
| 68 |
| {stop, Req, State} |
| 69 |
| {switch_handler(), Req, State} |
| 70 |
when Req::cowboy_req:req(), State::any(). |
| 71 |
-optional_callbacks([content_types_provided/2]). |
| 72 |
|
| 73 |
-callback delete_completed(Req, State) |
| 74 |
-> {boolean(), Req, State} |
| 75 |
| {stop, Req, State} |
| 76 |
| {switch_handler(), Req, State} |
| 77 |
when Req::cowboy_req:req(), State::any(). |
| 78 |
-optional_callbacks([delete_completed/2]). |
| 79 |
|
| 80 |
-callback delete_resource(Req, State) |
| 81 |
-> {boolean(), Req, State} |
| 82 |
| {stop, Req, State} |
| 83 |
| {switch_handler(), Req, State} |
| 84 |
when Req::cowboy_req:req(), State::any(). |
| 85 |
-optional_callbacks([delete_resource/2]). |
| 86 |
|
| 87 |
-callback expires(Req, State) |
| 88 |
-> {calendar:datetime() | binary() | undefined, Req, State} |
| 89 |
when Req::cowboy_req:req(), State::any(). |
| 90 |
-optional_callbacks([expires/2]). |
| 91 |
|
| 92 |
-callback forbidden(Req, State) |
| 93 |
-> {boolean(), Req, State} |
| 94 |
| {stop, Req, State} |
| 95 |
| {switch_handler(), Req, State} |
| 96 |
when Req::cowboy_req:req(), State::any(). |
| 97 |
-optional_callbacks([forbidden/2]). |
| 98 |
|
| 99 |
-callback generate_etag(Req, State) |
| 100 |
-> {binary() | {weak | strong, binary()} | undefined, Req, State} |
| 101 |
when Req::cowboy_req:req(), State::any(). |
| 102 |
-optional_callbacks([generate_etag/2]). |
| 103 |
|
| 104 |
-callback is_authorized(Req, State) |
| 105 |
-> {true | {false, iodata()}, Req, State} |
| 106 |
| {stop, Req, State} |
| 107 |
| {switch_handler(), Req, State} |
| 108 |
when Req::cowboy_req:req(), State::any(). |
| 109 |
-optional_callbacks([is_authorized/2]). |
| 110 |
|
| 111 |
-callback is_conflict(Req, State) |
| 112 |
-> {boolean(), Req, State} |
| 113 |
| {stop, Req, State} |
| 114 |
| {switch_handler(), Req, State} |
| 115 |
when Req::cowboy_req:req(), State::any(). |
| 116 |
-optional_callbacks([is_conflict/2]). |
| 117 |
|
| 118 |
-callback known_methods(Req, State) |
| 119 |
-> {[binary()], Req, State} |
| 120 |
| {stop, Req, State} |
| 121 |
| {switch_handler(), Req, State} |
| 122 |
when Req::cowboy_req:req(), State::any(). |
| 123 |
-optional_callbacks([known_methods/2]). |
| 124 |
|
| 125 |
-callback languages_provided(Req, State) |
| 126 |
-> {[binary()], Req, State} |
| 127 |
| {stop, Req, State} |
| 128 |
| {switch_handler(), Req, State} |
| 129 |
when Req::cowboy_req:req(), State::any(). |
| 130 |
-optional_callbacks([languages_provided/2]). |
| 131 |
|
| 132 |
-callback last_modified(Req, State) |
| 133 |
-> {calendar:datetime() | undefined, Req, State} |
| 134 |
when Req::cowboy_req:req(), State::any(). |
| 135 |
-optional_callbacks([last_modified/2]). |
| 136 |
|
| 137 |
-callback malformed_request(Req, State) |
| 138 |
-> {boolean(), Req, State} |
| 139 |
| {stop, Req, State} |
| 140 |
| {switch_handler(), Req, State} |
| 141 |
when Req::cowboy_req:req(), State::any(). |
| 142 |
-optional_callbacks([malformed_request/2]). |
| 143 |
|
| 144 |
-callback moved_permanently(Req, State) |
| 145 |
-> {{true, iodata()} | false, Req, State} |
| 146 |
| {stop, Req, State} |
| 147 |
| {switch_handler(), Req, State} |
| 148 |
when Req::cowboy_req:req(), State::any(). |
| 149 |
-optional_callbacks([moved_permanently/2]). |
| 150 |
|
| 151 |
-callback moved_temporarily(Req, State) |
| 152 |
-> {{true, iodata()} | false, Req, State} |
| 153 |
| {stop, Req, State} |
| 154 |
| {switch_handler(), Req, State} |
| 155 |
when Req::cowboy_req:req(), State::any(). |
| 156 |
-optional_callbacks([moved_temporarily/2]). |
| 157 |
|
| 158 |
-callback multiple_choices(Req, State) |
| 159 |
-> {boolean(), Req, State} |
| 160 |
| {stop, Req, State} |
| 161 |
| {switch_handler(), Req, State} |
| 162 |
when Req::cowboy_req:req(), State::any(). |
| 163 |
-optional_callbacks([multiple_choices/2]). |
| 164 |
|
| 165 |
-callback options(Req, State) |
| 166 |
-> {ok, Req, State} |
| 167 |
| {stop, Req, State} |
| 168 |
| {switch_handler(), Req, State} |
| 169 |
when Req::cowboy_req:req(), State::any(). |
| 170 |
-optional_callbacks([options/2]). |
| 171 |
|
| 172 |
-callback previously_existed(Req, State) |
| 173 |
-> {boolean(), Req, State} |
| 174 |
| {stop, Req, State} |
| 175 |
| {switch_handler(), Req, State} |
| 176 |
when Req::cowboy_req:req(), State::any(). |
| 177 |
-optional_callbacks([previously_existed/2]). |
| 178 |
|
| 179 |
-callback range_satisfiable(Req, State) |
| 180 |
-> {boolean() | {false, non_neg_integer() | iodata()}, Req, State} |
| 181 |
| {stop, Req, State} |
| 182 |
| {switch_handler(), Req, State} |
| 183 |
when Req::cowboy_req:req(), State::any(). |
| 184 |
-optional_callbacks([range_satisfiable/2]). |
| 185 |
|
| 186 |
-callback ranges_provided(Req, State) |
| 187 |
-> {[{binary(), atom()}], Req, State} |
| 188 |
| {stop, Req, State} |
| 189 |
| {switch_handler(), Req, State} |
| 190 |
when Req::cowboy_req:req(), State::any(). |
| 191 |
-optional_callbacks([ranges_provided/2]). |
| 192 |
|
| 193 |
-callback rate_limited(Req, State) |
| 194 |
-> {{true, non_neg_integer() | calendar:datetime()} | false, Req, State} |
| 195 |
| {stop, Req, State} |
| 196 |
| {switch_handler(), Req, State} |
| 197 |
when Req::cowboy_req:req(), State::any(). |
| 198 |
-optional_callbacks([rate_limited/2]). |
| 199 |
|
| 200 |
-callback resource_exists(Req, State) |
| 201 |
-> {boolean(), Req, State} |
| 202 |
| {stop, Req, State} |
| 203 |
| {switch_handler(), Req, State} |
| 204 |
when Req::cowboy_req:req(), State::any(). |
| 205 |
-optional_callbacks([resource_exists/2]). |
| 206 |
|
| 207 |
-callback service_available(Req, State) |
| 208 |
-> {boolean(), Req, State} |
| 209 |
| {stop, Req, State} |
| 210 |
| {switch_handler(), Req, State} |
| 211 |
when Req::cowboy_req:req(), State::any(). |
| 212 |
-optional_callbacks([service_available/2]). |
| 213 |
|
| 214 |
-callback uri_too_long(Req, State) |
| 215 |
-> {boolean(), Req, State} |
| 216 |
| {stop, Req, State} |
| 217 |
| {switch_handler(), Req, State} |
| 218 |
when Req::cowboy_req:req(), State::any(). |
| 219 |
-optional_callbacks([uri_too_long/2]). |
| 220 |
|
| 221 |
-callback valid_content_headers(Req, State) |
| 222 |
-> {boolean(), Req, State} |
| 223 |
| {stop, Req, State} |
| 224 |
| {switch_handler(), Req, State} |
| 225 |
when Req::cowboy_req:req(), State::any(). |
| 226 |
-optional_callbacks([valid_content_headers/2]). |
| 227 |
|
| 228 |
-callback valid_entity_length(Req, State) |
| 229 |
-> {boolean(), Req, State} |
| 230 |
| {stop, Req, State} |
| 231 |
| {switch_handler(), Req, State} |
| 232 |
when Req::cowboy_req:req(), State::any(). |
| 233 |
-optional_callbacks([valid_entity_length/2]). |
| 234 |
|
| 235 |
-callback variances(Req, State) |
| 236 |
-> {[binary()], Req, State} |
| 237 |
when Req::cowboy_req:req(), State::any(). |
| 238 |
-optional_callbacks([variances/2]). |
| 239 |
|
| 240 |
%% End of REST callbacks. Whew! |
| 241 |
|
| 242 |
-record(state, { |
| 243 |
method = undefined :: binary(), |
| 244 |
|
| 245 |
%% Handler. |
| 246 |
handler :: atom(), |
| 247 |
handler_state :: any(), |
| 248 |
|
| 249 |
%% Media type. |
| 250 |
content_types_p = [] :: |
| 251 |
[{binary() | {binary(), binary(), [{binary(), binary()}] | '*'}, |
| 252 |
atom()}], |
| 253 |
content_type_a :: undefined |
| 254 |
| {binary() | {binary(), binary(), [{binary(), binary()}] | '*'}, |
| 255 |
atom()}, |
| 256 |
|
| 257 |
%% Language. |
| 258 |
languages_p = [] :: [binary()], |
| 259 |
language_a :: undefined | binary(), |
| 260 |
|
| 261 |
%% Charset. |
| 262 |
charsets_p = undefined :: undefined | [binary()], |
| 263 |
charset_a :: undefined | binary(), |
| 264 |
|
| 265 |
%% Range units. |
| 266 |
ranges_a = [] :: [{binary(), atom()}], |
| 267 |
|
| 268 |
%% Whether the resource exists. |
| 269 |
exists = false :: boolean(), |
| 270 |
|
| 271 |
%% Cached resource calls. |
| 272 |
etag :: undefined | no_call | {strong | weak, binary()}, |
| 273 |
last_modified :: undefined | no_call | calendar:datetime(), |
| 274 |
expires :: undefined | no_call | calendar:datetime() | binary() |
| 275 |
}). |
| 276 |
|
| 277 |
-spec upgrade(Req, Env, module(), any()) |
| 278 |
-> {ok, Req, Env} when Req::cowboy_req:req(), Env::cowboy_middleware:env(). |
| 279 |
upgrade(Req0, Env, Handler, HandlerState0) -> |
| 280 |
Method = cowboy_req:method(Req0), |
| 281 |
case service_available(Req0, #state{method=Method, |
| 282 |
handler=Handler, handler_state=HandlerState0}) of |
| 283 |
{ok, Req, Result} -> |
| 284 |
{ok, Req, Env#{result => Result}}; |
| 285 |
{Mod, Req, HandlerState} -> |
| 286 |
Mod:upgrade(Req, Env, Handler, HandlerState); |
| 287 |
{Mod, Req, HandlerState, Opts} -> |
| 288 |
Mod:upgrade(Req, Env, Handler, HandlerState, Opts) |
| 289 |
end. |
| 290 |
|
| 291 |
-spec upgrade(Req, Env, module(), any(), any()) |
| 292 |
-> {ok, Req, Env} when Req::cowboy_req:req(), Env::cowboy_middleware:env(). |
| 293 |
%% cowboy_rest takes no options. |
| 294 |
upgrade(Req, Env, Handler, HandlerState, _Opts) -> |
| 295 |
upgrade(Req, Env, Handler, HandlerState). |
| 296 |
|
| 297 |
service_available(Req, State) -> |
| 298 |
expect(Req, State, service_available, true, fun known_methods/2, 503). |
| 299 |
|
| 300 |
%% known_methods/2 should return a list of binary methods. |
| 301 |
known_methods(Req, State=#state{method=Method}) -> |
| 302 |
case call(Req, State, known_methods) of |
| 303 |
no_call when Method =:= <<"HEAD">>; Method =:= <<"GET">>; |
| 304 |
Method =:= <<"POST">>; Method =:= <<"PUT">>; |
| 305 |
Method =:= <<"PATCH">>; Method =:= <<"DELETE">>; |
| 306 |
Method =:= <<"OPTIONS">> -> |
| 307 |
uri_too_long(Req, State); |
| 308 |
no_call -> |
| 309 |
respond(Req, State, 501); |
| 310 |
{stop, Req2, State2} -> |
| 311 |
terminate(Req2, State2); |
| 312 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 313 |
switch_handler(Switch, Req2, State2); |
| 314 |
{List, Req2, State2} -> |
| 315 |
case lists:member(Method, List) of |
| 316 |
true -> uri_too_long(Req2, State2); |
| 317 |
false -> respond(Req2, State2, 501) |
| 318 |
end |
| 319 |
end. |
| 320 |
|
| 321 |
uri_too_long(Req, State) -> |
| 322 |
expect(Req, State, uri_too_long, false, fun allowed_methods/2, 414). |
| 323 |
|
| 324 |
%% allowed_methods/2 should return a list of binary methods. |
| 325 |
allowed_methods(Req, State=#state{method=Method}) -> |
| 326 |
case call(Req, State, allowed_methods) of |
| 327 |
no_call when Method =:= <<"HEAD">>; Method =:= <<"GET">>; Method =:= <<"OPTIONS">> -> |
| 328 |
Req2 = cowboy_req:set_resp_header(<<"allow">>, <<"HEAD, GET, OPTIONS">>, Req), |
| 329 |
malformed_request(Req2, State); |
| 330 |
no_call -> |
| 331 |
Req2 = cowboy_req:set_resp_header(<<"allow">>, <<"HEAD, GET, OPTIONS">>, Req), |
| 332 |
respond(Req2, State, 405); |
| 333 |
{stop, Req2, State2} -> |
| 334 |
terminate(Req2, State2); |
| 335 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 336 |
switch_handler(Switch, Req2, State2); |
| 337 |
{List, Req2, State2} -> |
| 338 |
Req3 = cowboy_req:set_resp_header(<<"allow">>, cow_http_hd:allow(List), Req2), |
| 339 |
case lists:member(Method, List) of |
| 340 |
true -> |
| 341 |
malformed_request(Req3, State2); |
| 342 |
false -> |
| 343 |
respond(Req3, State2, 405) |
| 344 |
end |
| 345 |
end. |
| 346 |
|
| 347 |
malformed_request(Req, State) -> |
| 348 |
expect(Req, State, malformed_request, false, fun is_authorized/2, 400). |
| 349 |
|
| 350 |
%% is_authorized/2 should return true or {false, WwwAuthenticateHeader}. |
| 351 |
is_authorized(Req, State) -> |
| 352 |
case call(Req, State, is_authorized) of |
| 353 |
no_call -> |
| 354 |
forbidden(Req, State); |
| 355 |
{stop, Req2, State2} -> |
| 356 |
terminate(Req2, State2); |
| 357 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 358 |
switch_handler(Switch, Req2, State2); |
| 359 |
{true, Req2, State2} -> |
| 360 |
forbidden(Req2, State2); |
| 361 |
{{false, AuthHead}, Req2, State2} -> |
| 362 |
Req3 = cowboy_req:set_resp_header( |
| 363 |
<<"www-authenticate">>, AuthHead, Req2), |
| 364 |
respond(Req3, State2, 401) |
| 365 |
end. |
| 366 |
|
| 367 |
forbidden(Req, State) -> |
| 368 |
expect(Req, State, forbidden, false, fun rate_limited/2, 403). |
| 369 |
|
| 370 |
rate_limited(Req, State) -> |
| 371 |
case call(Req, State, rate_limited) of |
| 372 |
no_call -> |
| 373 |
valid_content_headers(Req, State); |
| 374 |
{stop, Req2, State2} -> |
| 375 |
terminate(Req2, State2); |
| 376 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 377 |
switch_handler(Switch, Req2, State2); |
| 378 |
{false, Req2, State2} -> |
| 379 |
valid_content_headers(Req2, State2); |
| 380 |
{{true, RetryAfter0}, Req2, State2} -> |
| 381 |
RetryAfter = if |
| 382 |
is_integer(RetryAfter0), RetryAfter0 >= 0 -> |
| 383 |
integer_to_binary(RetryAfter0); |
| 384 |
is_tuple(RetryAfter0) -> |
| 385 |
cowboy_clock:rfc1123(RetryAfter0) |
| 386 |
end, |
| 387 |
Req3 = cowboy_req:set_resp_header(<<"retry-after">>, RetryAfter, Req2), |
| 388 |
respond(Req3, State2, 429) |
| 389 |
end. |
| 390 |
|
| 391 |
valid_content_headers(Req, State) -> |
| 392 |
expect(Req, State, valid_content_headers, true, |
| 393 |
fun valid_entity_length/2, 501). |
| 394 |
|
| 395 |
valid_entity_length(Req, State) -> |
| 396 |
expect(Req, State, valid_entity_length, true, fun options/2, 413). |
| 397 |
|
| 398 |
%% If you need to add additional headers to the response at this point, |
| 399 |
%% you should do it directly in the options/2 call using set_resp_headers. |
| 400 |
options(Req, State=#state{method= <<"OPTIONS">>}) -> |
| 401 |
case call(Req, State, options) of |
| 402 |
no_call -> |
| 403 |
respond(Req, State, 200); |
| 404 |
{stop, Req2, State2} -> |
| 405 |
terminate(Req2, State2); |
| 406 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 407 |
switch_handler(Switch, Req2, State2); |
| 408 |
{ok, Req2, State2} -> |
| 409 |
respond(Req2, State2, 200) |
| 410 |
end; |
| 411 |
options(Req, State) -> |
| 412 |
content_types_provided(Req, State). |
| 413 |
|
| 414 |
%% content_types_provided/2 should return a list of content types and their |
| 415 |
%% associated callback function as a tuple: {{Type, SubType, Params}, Fun}. |
| 416 |
%% Type and SubType are the media type as binary. Params is a list of |
| 417 |
%% Key/Value tuple, with Key and Value a binary. Fun is the name of the |
| 418 |
%% callback that will be used to return the content of the response. It is |
| 419 |
%% given as an atom. |
| 420 |
%% |
| 421 |
%% An example of such return value would be: |
| 422 |
%% {{<<"text">>, <<"html">>, []}, to_html} |
| 423 |
%% |
| 424 |
%% Note that it is also possible to return a binary content type that will |
| 425 |
%% then be parsed by Cowboy. However note that while this may make your |
| 426 |
%% resources a little more readable, this is a lot less efficient. |
| 427 |
%% |
| 428 |
%% An example of such return value would be: |
| 429 |
%% {<<"text/html">>, to_html} |
| 430 |
content_types_provided(Req, State) -> |
| 431 |
case call(Req, State, content_types_provided) of |
| 432 |
no_call -> |
| 433 |
State2 = State#state{ |
| 434 |
content_types_p=[{{<<"text">>, <<"html">>, '*'}, to_html}]}, |
| 435 |
try cowboy_req:parse_header(<<"accept">>, Req) of |
| 436 |
undefined -> |
| 437 |
languages_provided( |
| 438 |
Req#{media_type => {<<"text">>, <<"html">>, []}}, |
| 439 |
State2#state{content_type_a={{<<"text">>, <<"html">>, []}, to_html}}); |
| 440 |
Accept -> |
| 441 |
choose_media_type(Req, State2, prioritize_accept(Accept)) |
| 442 |
catch _:_ -> |
| 443 |
respond(Req, State2, 400) |
| 444 |
end; |
| 445 |
{stop, Req2, State2} -> |
| 446 |
terminate(Req2, State2); |
| 447 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 448 |
switch_handler(Switch, Req2, State2); |
| 449 |
{[], Req2, State2} -> |
| 450 |
not_acceptable(Req2, State2); |
| 451 |
{CTP, Req2, State2} -> |
| 452 |
CTP2 = [normalize_content_types(P, provide) || P <- CTP], |
| 453 |
State3 = State2#state{content_types_p=CTP2}, |
| 454 |
try cowboy_req:parse_header(<<"accept">>, Req2) of |
| 455 |
undefined -> |
| 456 |
{PMT0, _Fun} = HeadCTP = hd(CTP2), |
| 457 |
%% We replace the wildcard by an empty list of parameters. |
| 458 |
PMT = case PMT0 of |
| 459 |
{Type, SubType, '*'} -> {Type, SubType, []}; |
| 460 |
_ -> PMT0 |
| 461 |
end, |
| 462 |
languages_provided( |
| 463 |
Req2#{media_type => PMT}, |
| 464 |
State3#state{content_type_a=HeadCTP}); |
| 465 |
Accept -> |
| 466 |
choose_media_type(Req2, State3, prioritize_accept(Accept)) |
| 467 |
catch _:_ -> |
| 468 |
respond(Req2, State3, 400) |
| 469 |
end |
| 470 |
end. |
| 471 |
|
| 472 |
normalize_content_types({ContentType, Callback}, _) |
| 473 |
when is_binary(ContentType) -> |
| 474 |
{cow_http_hd:parse_content_type(ContentType), Callback}; |
| 475 |
normalize_content_types(Normalized = {{Type, SubType, _}, _}, _) |
| 476 |
when is_binary(Type), is_binary(SubType) -> |
| 477 |
Normalized; |
| 478 |
%% Wildcard for content_types_accepted. |
| 479 |
normalize_content_types(Normalized = {'*', _}, accept) -> |
| 480 |
Normalized. |
| 481 |
|
| 482 |
prioritize_accept(Accept) -> |
| 483 |
lists:sort( |
| 484 |
fun ({MediaTypeA, Quality, _AcceptParamsA}, |
| 485 |
{MediaTypeB, Quality, _AcceptParamsB}) -> |
| 486 |
%% Same quality, check precedence in more details. |
| 487 |
prioritize_mediatype(MediaTypeA, MediaTypeB); |
| 488 |
({_MediaTypeA, QualityA, _AcceptParamsA}, |
| 489 |
{_MediaTypeB, QualityB, _AcceptParamsB}) -> |
| 490 |
%% Just compare the quality. |
| 491 |
QualityA > QualityB |
| 492 |
end, Accept). |
| 493 |
|
| 494 |
%% Media ranges can be overridden by more specific media ranges or |
| 495 |
%% specific media types. If more than one media range applies to a given |
| 496 |
%% type, the most specific reference has precedence. |
| 497 |
%% |
| 498 |
%% We always choose B over A when we can't decide between the two. |
| 499 |
prioritize_mediatype({TypeA, SubTypeA, ParamsA}, {TypeB, SubTypeB, ParamsB}) -> |
| 500 |
case TypeB of |
| 501 |
TypeA -> |
| 502 |
case SubTypeB of |
| 503 |
SubTypeA -> length(ParamsA) > length(ParamsB); |
| 504 |
<<"*">> -> true; |
| 505 |
_Any -> false |
| 506 |
end; |
| 507 |
<<"*">> -> true; |
| 508 |
_Any -> false |
| 509 |
end. |
| 510 |
|
| 511 |
%% Ignoring the rare AcceptParams. Not sure what should be done about them. |
| 512 |
choose_media_type(Req, State, []) -> |
| 513 |
not_acceptable(Req, State); |
| 514 |
choose_media_type(Req, State=#state{content_types_p=CTP}, |
| 515 |
[MediaType|Tail]) -> |
| 516 |
match_media_type(Req, State, Tail, CTP, MediaType). |
| 517 |
|
| 518 |
match_media_type(Req, State, Accept, [], _MediaType) -> |
| 519 |
choose_media_type(Req, State, Accept); |
| 520 |
match_media_type(Req, State, Accept, CTP, |
| 521 |
MediaType = {{<<"*">>, <<"*">>, _Params_A}, _QA, _APA}) -> |
| 522 |
match_media_type_params(Req, State, Accept, CTP, MediaType); |
| 523 |
match_media_type(Req, State, Accept, |
| 524 |
CTP = [{{Type, SubType_P, _PP}, _Fun}|_Tail], |
| 525 |
MediaType = {{Type, SubType_A, _PA}, _QA, _APA}) |
| 526 |
when SubType_P =:= SubType_A; SubType_A =:= <<"*">> -> |
| 527 |
match_media_type_params(Req, State, Accept, CTP, MediaType); |
| 528 |
match_media_type(Req, State, Accept, [_Any|Tail], MediaType) -> |
| 529 |
match_media_type(Req, State, Accept, Tail, MediaType). |
| 530 |
|
| 531 |
match_media_type_params(Req, State, Accept, |
| 532 |
[Provided = {{TP, STP, '*'}, _Fun}|Tail], |
| 533 |
MediaType = {{TA, _STA, Params_A0}, _QA, _APA}) -> |
| 534 |
case lists:keytake(<<"charset">>, 1, Params_A0) of |
| 535 |
{value, {_, Charset}, Params_A} when TA =:= <<"text">> -> |
| 536 |
%% When we match against a wildcard, the media type is text |
| 537 |
%% and has a charset parameter, we call charsets_provided |
| 538 |
%% and check that the charset is provided. If the callback |
| 539 |
%% is not exported, we accept inconditionally but ignore |
| 540 |
%% the given charset so as to not send a wrong value back. |
| 541 |
case call(Req, State, charsets_provided) of |
| 542 |
no_call -> |
| 543 |
languages_provided(Req#{media_type => {TP, STP, Params_A0}}, |
| 544 |
State#state{content_type_a=Provided}); |
| 545 |
{stop, Req2, State2} -> |
| 546 |
terminate(Req2, State2); |
| 547 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 548 |
switch_handler(Switch, Req2, State2); |
| 549 |
{CP, Req2, State2} -> |
| 550 |
State3 = State2#state{charsets_p=CP}, |
| 551 |
case lists:member(Charset, CP) of |
| 552 |
false -> |
| 553 |
match_media_type(Req2, State3, Accept, Tail, MediaType); |
| 554 |
true -> |
| 555 |
languages_provided(Req2#{media_type => {TP, STP, Params_A}}, |
| 556 |
State3#state{content_type_a=Provided, |
| 557 |
charset_a=Charset}) |
| 558 |
end |
| 559 |
end; |
| 560 |
_ -> |
| 561 |
languages_provided(Req#{media_type => {TP, STP, Params_A0}}, |
| 562 |
State#state{content_type_a=Provided}) |
| 563 |
end; |
| 564 |
match_media_type_params(Req, State, Accept, |
| 565 |
[Provided = {PMT = {TP, STP, Params_P0}, Fun}|Tail], |
| 566 |
MediaType = {{_TA, _STA, Params_A}, _QA, _APA}) -> |
| 567 |
case lists:sort(Params_P0) =:= lists:sort(Params_A) of |
| 568 |
true when TP =:= <<"text">> -> |
| 569 |
%% When a charset was provided explicitly in both the charset header |
| 570 |
%% and the media types provided and the negotiation is successful, |
| 571 |
%% we keep the charset and don't call charsets_provided. This only |
| 572 |
%% applies to text media types, however. |
| 573 |
{Charset, Params_P} = case lists:keytake(<<"charset">>, 1, Params_P0) of |
| 574 |
false -> {undefined, Params_P0}; |
| 575 |
{value, {_, Charset0}, Params_P1} -> {Charset0, Params_P1} |
| 576 |
end, |
| 577 |
languages_provided(Req#{media_type => {TP, STP, Params_P}}, |
| 578 |
State#state{content_type_a={{TP, STP, Params_P}, Fun}, |
| 579 |
charset_a=Charset}); |
| 580 |
true -> |
| 581 |
languages_provided(Req#{media_type => PMT}, |
| 582 |
State#state{content_type_a=Provided}); |
| 583 |
false -> |
| 584 |
match_media_type(Req, State, Accept, Tail, MediaType) |
| 585 |
end. |
| 586 |
|
| 587 |
%% languages_provided should return a list of binary values indicating |
| 588 |
%% which languages are accepted by the resource. |
| 589 |
%% |
| 590 |
%% @todo I suppose we should also ask the resource if it wants to |
| 591 |
%% set a language itself or if it wants it to be automatically chosen. |
| 592 |
languages_provided(Req, State) -> |
| 593 |
case call(Req, State, languages_provided) of |
| 594 |
no_call -> |
| 595 |
charsets_provided(Req, State); |
| 596 |
{stop, Req2, State2} -> |
| 597 |
terminate(Req2, State2); |
| 598 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 599 |
switch_handler(Switch, Req2, State2); |
| 600 |
{[], Req2, State2} -> |
| 601 |
not_acceptable(Req2, State2); |
| 602 |
{LP, Req2, State2} -> |
| 603 |
State3 = State2#state{languages_p=LP}, |
| 604 |
case cowboy_req:parse_header(<<"accept-language">>, Req2) of |
| 605 |
undefined -> |
| 606 |
set_language(Req2, State3#state{language_a=hd(LP)}); |
| 607 |
AcceptLanguage -> |
| 608 |
AcceptLanguage2 = prioritize_languages(AcceptLanguage), |
| 609 |
choose_language(Req2, State3, AcceptLanguage2) |
| 610 |
end |
| 611 |
end. |
| 612 |
|
| 613 |
%% A language-range matches a language-tag if it exactly equals the tag, |
| 614 |
%% or if it exactly equals a prefix of the tag such that the first tag |
| 615 |
%% character following the prefix is "-". The special range "*", if |
| 616 |
%% present in the Accept-Language field, matches every tag not matched |
| 617 |
%% by any other range present in the Accept-Language field. |
| 618 |
%% |
| 619 |
%% @todo The last sentence probably means we should always put '*' |
| 620 |
%% at the end of the list. |
| 621 |
prioritize_languages(AcceptLanguages) -> |
| 622 |
lists:sort( |
| 623 |
fun ({_TagA, QualityA}, {_TagB, QualityB}) -> |
| 624 |
QualityA > QualityB |
| 625 |
end, AcceptLanguages). |
| 626 |
|
| 627 |
choose_language(Req, State, []) -> |
| 628 |
not_acceptable(Req, State); |
| 629 |
choose_language(Req, State=#state{languages_p=LP}, [Language|Tail]) -> |
| 630 |
match_language(Req, State, Tail, LP, Language). |
| 631 |
|
| 632 |
match_language(Req, State, Accept, [], _Language) -> |
| 633 |
choose_language(Req, State, Accept); |
| 634 |
match_language(Req, State, _Accept, [Provided|_Tail], {'*', _Quality}) -> |
| 635 |
set_language(Req, State#state{language_a=Provided}); |
| 636 |
match_language(Req, State, _Accept, [Provided|_Tail], {Provided, _Quality}) -> |
| 637 |
set_language(Req, State#state{language_a=Provided}); |
| 638 |
match_language(Req, State, Accept, [Provided|Tail], |
| 639 |
Language = {Tag, _Quality}) -> |
| 640 |
Length = byte_size(Tag), |
| 641 |
case Provided of |
| 642 |
<< Tag:Length/binary, $-, _Any/bits >> -> |
| 643 |
set_language(Req, State#state{language_a=Provided}); |
| 644 |
_Any -> |
| 645 |
match_language(Req, State, Accept, Tail, Language) |
| 646 |
end. |
| 647 |
|
| 648 |
set_language(Req, State=#state{language_a=Language}) -> |
| 649 |
Req2 = cowboy_req:set_resp_header(<<"content-language">>, Language, Req), |
| 650 |
charsets_provided(Req2#{language => Language}, State). |
| 651 |
|
| 652 |
%% charsets_provided should return a list of binary values indicating |
| 653 |
%% which charsets are accepted by the resource. |
| 654 |
%% |
| 655 |
%% A charset may have been selected while negotiating the accept header. |
| 656 |
%% There's no need to select one again. |
| 657 |
charsets_provided(Req, State=#state{charset_a=Charset}) |
| 658 |
when Charset =/= undefined -> |
| 659 |
set_content_type(Req, State); |
| 660 |
%% If charsets_p is defined, use it instead of calling charsets_provided |
| 661 |
%% again. We also call this clause during normal execution to avoid |
| 662 |
%% duplicating code. |
| 663 |
charsets_provided(Req, State=#state{charsets_p=[]}) -> |
| 664 |
not_acceptable(Req, State); |
| 665 |
charsets_provided(Req, State=#state{charsets_p=CP}) |
| 666 |
when CP =/= undefined -> |
| 667 |
case cowboy_req:parse_header(<<"accept-charset">>, Req) of |
| 668 |
undefined -> |
| 669 |
set_content_type(Req, State#state{charset_a=hd(CP)}); |
| 670 |
AcceptCharset0 -> |
| 671 |
AcceptCharset = prioritize_charsets(AcceptCharset0), |
| 672 |
choose_charset(Req, State, AcceptCharset) |
| 673 |
end; |
| 674 |
charsets_provided(Req, State) -> |
| 675 |
case call(Req, State, charsets_provided) of |
| 676 |
no_call -> |
| 677 |
set_content_type(Req, State); |
| 678 |
{stop, Req2, State2} -> |
| 679 |
terminate(Req2, State2); |
| 680 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 681 |
switch_handler(Switch, Req2, State2); |
| 682 |
{CP, Req2, State2} -> |
| 683 |
charsets_provided(Req2, State2#state{charsets_p=CP}) |
| 684 |
end. |
| 685 |
|
| 686 |
prioritize_charsets(AcceptCharsets) -> |
| 687 |
lists:sort( |
| 688 |
fun ({_CharsetA, QualityA}, {_CharsetB, QualityB}) -> |
| 689 |
QualityA > QualityB |
| 690 |
end, AcceptCharsets). |
| 691 |
|
| 692 |
choose_charset(Req, State, []) -> |
| 693 |
not_acceptable(Req, State); |
| 694 |
%% A q-value of 0 means not acceptable. |
| 695 |
choose_charset(Req, State, [{_, 0}|Tail]) -> |
| 696 |
choose_charset(Req, State, Tail); |
| 697 |
choose_charset(Req, State=#state{charsets_p=CP}, [Charset|Tail]) -> |
| 698 |
match_charset(Req, State, Tail, CP, Charset). |
| 699 |
|
| 700 |
match_charset(Req, State, Accept, [], _Charset) -> |
| 701 |
choose_charset(Req, State, Accept); |
| 702 |
match_charset(Req, State, _Accept, [Provided|_], {<<"*">>, _}) -> |
| 703 |
set_content_type(Req, State#state{charset_a=Provided}); |
| 704 |
match_charset(Req, State, _Accept, [Provided|_], {Provided, _}) -> |
| 705 |
set_content_type(Req, State#state{charset_a=Provided}); |
| 706 |
match_charset(Req, State, Accept, [_|Tail], Charset) -> |
| 707 |
match_charset(Req, State, Accept, Tail, Charset). |
| 708 |
|
| 709 |
set_content_type(Req, State=#state{ |
| 710 |
content_type_a={{Type, SubType, Params}, _Fun}, |
| 711 |
charset_a=Charset}) -> |
| 712 |
ParamsBin = set_content_type_build_params(Params, []), |
| 713 |
ContentType = [Type, <<"/">>, SubType, ParamsBin], |
| 714 |
ContentType2 = case {Type, Charset} of |
| 715 |
{<<"text">>, Charset} when Charset =/= undefined -> |
| 716 |
[ContentType, <<"; charset=">>, Charset]; |
| 717 |
_ -> |
| 718 |
ContentType |
| 719 |
end, |
| 720 |
Req2 = cowboy_req:set_resp_header(<<"content-type">>, ContentType2, Req), |
| 721 |
encodings_provided(Req2#{charset => Charset}, State). |
| 722 |
|
| 723 |
set_content_type_build_params('*', []) -> |
| 724 |
<<>>; |
| 725 |
set_content_type_build_params([], []) -> |
| 726 |
<<>>; |
| 727 |
set_content_type_build_params([], Acc) -> |
| 728 |
lists:reverse(Acc); |
| 729 |
set_content_type_build_params([{Attr, Value}|Tail], Acc) -> |
| 730 |
set_content_type_build_params(Tail, [[Attr, <<"=">>, Value], <<";">>|Acc]). |
| 731 |
|
| 732 |
%% @todo Match for identity as we provide nothing else for now. |
| 733 |
%% @todo Don't forget to set the Content-Encoding header when we reply a body |
| 734 |
%% and the found encoding is something other than identity. |
| 735 |
encodings_provided(Req, State) -> |
| 736 |
ranges_provided(Req, State). |
| 737 |
|
| 738 |
not_acceptable(Req, State) -> |
| 739 |
respond(Req, State, 406). |
| 740 |
|
| 741 |
ranges_provided(Req, State) -> |
| 742 |
case call(Req, State, ranges_provided) of |
| 743 |
no_call -> |
| 744 |
variances(Req, State); |
| 745 |
{stop, Req2, State2} -> |
| 746 |
terminate(Req2, State2); |
| 747 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 748 |
switch_handler(Switch, Req2, State2); |
| 749 |
{[], Req2, State2} -> |
| 750 |
Req3 = cowboy_req:set_resp_header(<<"accept-ranges">>, <<"none">>, Req2), |
| 751 |
variances(Req3, State2#state{ranges_a=[]}); |
| 752 |
{RP, Req2, State2} -> |
| 753 |
<<", ", AcceptRanges/binary>> = <<<<", ", R/binary>> || {R, _} <- RP>>, |
| 754 |
Req3 = cowboy_req:set_resp_header(<<"accept-ranges">>, AcceptRanges, Req2), |
| 755 |
variances(Req3, State2#state{ranges_a=RP}) |
| 756 |
end. |
| 757 |
|
| 758 |
%% variances/2 should return a list of headers that will be added |
| 759 |
%% to the Vary response header. The Accept, Accept-Language, |
| 760 |
%% Accept-Charset and Accept-Encoding headers do not need to be |
| 761 |
%% specified. |
| 762 |
%% |
| 763 |
%% @todo Do Accept-Encoding too when we handle it. |
| 764 |
%% @todo Does the order matter? |
| 765 |
variances(Req, State=#state{content_types_p=CTP, |
| 766 |
languages_p=LP, charsets_p=CP}) -> |
| 767 |
Variances = case CTP of |
| 768 |
[] -> []; |
| 769 |
[_] -> []; |
| 770 |
[_|_] -> [<<"accept">>] |
| 771 |
end, |
| 772 |
Variances2 = case LP of |
| 773 |
[] -> Variances; |
| 774 |
[_] -> Variances; |
| 775 |
[_|_] -> [<<"accept-language">>|Variances] |
| 776 |
end, |
| 777 |
Variances3 = case CP of |
| 778 |
undefined -> Variances2; |
| 779 |
[] -> Variances2; |
| 780 |
[_] -> Variances2; |
| 781 |
[_|_] -> [<<"accept-charset">>|Variances2] |
| 782 |
end, |
| 783 |
try variances(Req, State, Variances3) of |
| 784 |
{Variances4, Req2, State2} -> |
| 785 |
case [[<<", ">>, V] || V <- Variances4] of |
| 786 |
[] -> |
| 787 |
resource_exists(Req2, State2); |
| 788 |
[[<<", ">>, H]|Variances5] -> |
| 789 |
Req3 = cowboy_req:set_resp_header( |
| 790 |
<<"vary">>, [H|Variances5], Req2), |
| 791 |
resource_exists(Req3, State2) |
| 792 |
end |
| 793 |
catch Class:Reason:Stacktrace -> |
| 794 |
error_terminate(Req, State, Class, Reason, Stacktrace) |
| 795 |
end. |
| 796 |
|
| 797 |
variances(Req, State, Variances) -> |
| 798 |
case unsafe_call(Req, State, variances) of |
| 799 |
no_call -> |
| 800 |
{Variances, Req, State}; |
| 801 |
{HandlerVariances, Req2, State2} -> |
| 802 |
{Variances ++ HandlerVariances, Req2, State2} |
| 803 |
end. |
| 804 |
|
| 805 |
resource_exists(Req, State) -> |
| 806 |
expect(Req, State, resource_exists, true, |
| 807 |
fun if_match_exists/2, fun if_match_must_not_exist/2). |
| 808 |
|
| 809 |
if_match_exists(Req, State) -> |
| 810 |
State2 = State#state{exists=true}, |
| 811 |
case cowboy_req:parse_header(<<"if-match">>, Req) of |
| 812 |
undefined -> |
| 813 |
if_unmodified_since_exists(Req, State2); |
| 814 |
'*' -> |
| 815 |
if_unmodified_since_exists(Req, State2); |
| 816 |
ETagsList -> |
| 817 |
if_match(Req, State2, ETagsList) |
| 818 |
end. |
| 819 |
|
| 820 |
if_match(Req, State, EtagsList) -> |
| 821 |
try generate_etag(Req, State) of |
| 822 |
%% Strong Etag comparison: weak Etag never matches. |
| 823 |
{{weak, _}, Req2, State2} -> |
| 824 |
precondition_failed(Req2, State2); |
| 825 |
{Etag, Req2, State2} -> |
| 826 |
case lists:member(Etag, EtagsList) of |
| 827 |
true -> if_none_match_exists(Req2, State2); |
| 828 |
%% Etag may be `undefined' which cannot be a member. |
| 829 |
false -> precondition_failed(Req2, State2) |
| 830 |
end |
| 831 |
catch Class:Reason:Stacktrace -> |
| 832 |
error_terminate(Req, State, Class, Reason, Stacktrace) |
| 833 |
end. |
| 834 |
|
| 835 |
if_match_must_not_exist(Req, State) -> |
| 836 |
case cowboy_req:header(<<"if-match">>, Req) of |
| 837 |
undefined -> is_put_to_missing_resource(Req, State); |
| 838 |
_ -> precondition_failed(Req, State) |
| 839 |
end. |
| 840 |
|
| 841 |
if_unmodified_since_exists(Req, State) -> |
| 842 |
try cowboy_req:parse_header(<<"if-unmodified-since">>, Req) of |
| 843 |
undefined -> |
| 844 |
if_none_match_exists(Req, State); |
| 845 |
IfUnmodifiedSince -> |
| 846 |
if_unmodified_since(Req, State, IfUnmodifiedSince) |
| 847 |
catch _:_ -> |
| 848 |
if_none_match_exists(Req, State) |
| 849 |
end. |
| 850 |
|
| 851 |
%% If LastModified is the atom 'no_call', we continue. |
| 852 |
if_unmodified_since(Req, State, IfUnmodifiedSince) -> |
| 853 |
try last_modified(Req, State) of |
| 854 |
{LastModified, Req2, State2} -> |
| 855 |
case LastModified > IfUnmodifiedSince of |
| 856 |
true -> precondition_failed(Req2, State2); |
| 857 |
false -> if_none_match_exists(Req2, State2) |
| 858 |
end |
| 859 |
catch Class:Reason:Stacktrace -> |
| 860 |
error_terminate(Req, State, Class, Reason, Stacktrace) |
| 861 |
end. |
| 862 |
|
| 863 |
if_none_match_exists(Req, State) -> |
| 864 |
case cowboy_req:parse_header(<<"if-none-match">>, Req) of |
| 865 |
undefined -> |
| 866 |
if_modified_since_exists(Req, State); |
| 867 |
'*' -> |
| 868 |
precondition_is_head_get(Req, State); |
| 869 |
EtagsList -> |
| 870 |
if_none_match(Req, State, EtagsList) |
| 871 |
end. |
| 872 |
|
| 873 |
if_none_match(Req, State, EtagsList) -> |
| 874 |
try generate_etag(Req, State) of |
| 875 |
{Etag, Req2, State2} -> |
| 876 |
case Etag of |
| 877 |
undefined -> |
| 878 |
precondition_failed(Req2, State2); |
| 879 |
Etag -> |
| 880 |
case is_weak_match(Etag, EtagsList) of |
| 881 |
true -> precondition_is_head_get(Req2, State2); |
| 882 |
false -> method(Req2, State2) |
| 883 |
end |
| 884 |
end |
| 885 |
catch Class:Reason:Stacktrace -> |
| 886 |
error_terminate(Req, State, Class, Reason, Stacktrace) |
| 887 |
end. |
| 888 |
|
| 889 |
%% Weak Etag comparison: only check the opaque tag. |
| 890 |
is_weak_match(_, []) -> |
| 891 |
false; |
| 892 |
is_weak_match({_, Tag}, [{_, Tag}|_]) -> |
| 893 |
true; |
| 894 |
is_weak_match(Etag, [_|Tail]) -> |
| 895 |
is_weak_match(Etag, Tail). |
| 896 |
|
| 897 |
precondition_is_head_get(Req, State=#state{method=Method}) |
| 898 |
when Method =:= <<"HEAD">>; Method =:= <<"GET">> -> |
| 899 |
not_modified(Req, State); |
| 900 |
precondition_is_head_get(Req, State) -> |
| 901 |
precondition_failed(Req, State). |
| 902 |
|
| 903 |
if_modified_since_exists(Req, State) -> |
| 904 |
try cowboy_req:parse_header(<<"if-modified-since">>, Req) of |
| 905 |
undefined -> |
| 906 |
method(Req, State); |
| 907 |
IfModifiedSince -> |
| 908 |
if_modified_since_now(Req, State, IfModifiedSince) |
| 909 |
catch _:_ -> |
| 910 |
method(Req, State) |
| 911 |
end. |
| 912 |
|
| 913 |
if_modified_since_now(Req, State, IfModifiedSince) -> |
| 914 |
case IfModifiedSince > erlang:universaltime() of |
| 915 |
true -> method(Req, State); |
| 916 |
false -> if_modified_since(Req, State, IfModifiedSince) |
| 917 |
end. |
| 918 |
|
| 919 |
if_modified_since(Req, State, IfModifiedSince) -> |
| 920 |
try last_modified(Req, State) of |
| 921 |
{undefined, Req2, State2} -> |
| 922 |
method(Req2, State2); |
| 923 |
{LastModified, Req2, State2} -> |
| 924 |
case LastModified > IfModifiedSince of |
| 925 |
true -> method(Req2, State2); |
| 926 |
false -> not_modified(Req2, State2) |
| 927 |
end |
| 928 |
catch Class:Reason:Stacktrace -> |
| 929 |
error_terminate(Req, State, Class, Reason, Stacktrace) |
| 930 |
end. |
| 931 |
|
| 932 |
not_modified(Req, State) -> |
| 933 |
Req2 = cowboy_req:delete_resp_header(<<"content-type">>, Req), |
| 934 |
try set_resp_etag(Req2, State) of |
| 935 |
{Req3, State2} -> |
| 936 |
try set_resp_expires(Req3, State2) of |
| 937 |
{Req4, State3} -> |
| 938 |
respond(Req4, State3, 304) |
| 939 |
catch Class:Reason:Stacktrace -> |
| 940 |
error_terminate(Req, State2, Class, Reason, Stacktrace) |
| 941 |
end |
| 942 |
catch Class:Reason:Stacktrace -> |
| 943 |
error_terminate(Req, State, Class, Reason, Stacktrace) |
| 944 |
end. |
| 945 |
|
| 946 |
precondition_failed(Req, State) -> |
| 947 |
respond(Req, State, 412). |
| 948 |
|
| 949 |
is_put_to_missing_resource(Req, State=#state{method= <<"PUT">>}) -> |
| 950 |
moved_permanently(Req, State, fun is_conflict/2); |
| 951 |
is_put_to_missing_resource(Req, State) -> |
| 952 |
previously_existed(Req, State). |
| 953 |
|
| 954 |
%% moved_permanently/2 should return either false or {true, Location} |
| 955 |
%% with Location the full new URI of the resource. |
| 956 |
moved_permanently(Req, State, OnFalse) -> |
| 957 |
case call(Req, State, moved_permanently) of |
| 958 |
{{true, Location}, Req2, State2} -> |
| 959 |
Req3 = cowboy_req:set_resp_header( |
| 960 |
<<"location">>, Location, Req2), |
| 961 |
respond(Req3, State2, 301); |
| 962 |
{false, Req2, State2} -> |
| 963 |
OnFalse(Req2, State2); |
| 964 |
{stop, Req2, State2} -> |
| 965 |
terminate(Req2, State2); |
| 966 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 967 |
switch_handler(Switch, Req2, State2); |
| 968 |
no_call -> |
| 969 |
OnFalse(Req, State) |
| 970 |
end. |
| 971 |
|
| 972 |
previously_existed(Req, State) -> |
| 973 |
expect(Req, State, previously_existed, false, |
| 974 |
fun (R, S) -> is_post_to_missing_resource(R, S, 404) end, |
| 975 |
fun (R, S) -> moved_permanently(R, S, fun moved_temporarily/2) end). |
| 976 |
|
| 977 |
%% moved_temporarily/2 should return either false or {true, Location} |
| 978 |
%% with Location the full new URI of the resource. |
| 979 |
moved_temporarily(Req, State) -> |
| 980 |
case call(Req, State, moved_temporarily) of |
| 981 |
{{true, Location}, Req2, State2} -> |
| 982 |
Req3 = cowboy_req:set_resp_header( |
| 983 |
<<"location">>, Location, Req2), |
| 984 |
respond(Req3, State2, 307); |
| 985 |
{false, Req2, State2} -> |
| 986 |
is_post_to_missing_resource(Req2, State2, 410); |
| 987 |
{stop, Req2, State2} -> |
| 988 |
terminate(Req2, State2); |
| 989 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 990 |
switch_handler(Switch, Req2, State2); |
| 991 |
no_call -> |
| 992 |
is_post_to_missing_resource(Req, State, 410) |
| 993 |
end. |
| 994 |
|
| 995 |
is_post_to_missing_resource(Req, State=#state{method= <<"POST">>}, OnFalse) -> |
| 996 |
allow_missing_post(Req, State, OnFalse); |
| 997 |
is_post_to_missing_resource(Req, State, OnFalse) -> |
| 998 |
respond(Req, State, OnFalse). |
| 999 |
|
| 1000 |
allow_missing_post(Req, State, OnFalse) -> |
| 1001 |
expect(Req, State, allow_missing_post, true, fun accept_resource/2, OnFalse). |
| 1002 |
|
| 1003 |
method(Req, State=#state{method= <<"DELETE">>}) -> |
| 1004 |
delete_resource(Req, State); |
| 1005 |
method(Req, State=#state{method= <<"PUT">>}) -> |
| 1006 |
is_conflict(Req, State); |
| 1007 |
method(Req, State=#state{method=Method}) |
| 1008 |
when Method =:= <<"POST">>; Method =:= <<"PATCH">> -> |
| 1009 |
accept_resource(Req, State); |
| 1010 |
method(Req, State=#state{method=Method}) |
| 1011 |
when Method =:= <<"GET">>; Method =:= <<"HEAD">> -> |
| 1012 |
set_resp_body_etag(Req, State); |
| 1013 |
method(Req, State) -> |
| 1014 |
multiple_choices(Req, State). |
| 1015 |
|
| 1016 |
%% delete_resource/2 should start deleting the resource and return. |
| 1017 |
delete_resource(Req, State) -> |
| 1018 |
expect(Req, State, delete_resource, false, 500, fun delete_completed/2). |
| 1019 |
|
| 1020 |
%% delete_completed/2 indicates whether the resource has been deleted yet. |
| 1021 |
delete_completed(Req, State) -> |
| 1022 |
expect(Req, State, delete_completed, true, fun has_resp_body/2, 202). |
| 1023 |
|
| 1024 |
is_conflict(Req, State) -> |
| 1025 |
expect(Req, State, is_conflict, false, fun accept_resource/2, 409). |
| 1026 |
|
| 1027 |
%% content_types_accepted should return a list of media types and their |
| 1028 |
%% associated callback functions in the same format as content_types_provided. |
| 1029 |
%% |
| 1030 |
%% The callback will then be called and is expected to process the content |
| 1031 |
%% pushed to the resource in the request body. |
| 1032 |
%% |
| 1033 |
%% content_types_accepted SHOULD return a different list |
| 1034 |
%% for each HTTP method. |
| 1035 |
accept_resource(Req, State) -> |
| 1036 |
case call(Req, State, content_types_accepted) of |
| 1037 |
no_call -> |
| 1038 |
respond(Req, State, 415); |
| 1039 |
{stop, Req2, State2} -> |
| 1040 |
terminate(Req2, State2); |
| 1041 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 1042 |
switch_handler(Switch, Req2, State2); |
| 1043 |
{CTA, Req2, State2} -> |
| 1044 |
CTA2 = [normalize_content_types(P, accept) || P <- CTA], |
| 1045 |
try cowboy_req:parse_header(<<"content-type">>, Req2) of |
| 1046 |
%% We do not match against the boundary parameter for multipart. |
| 1047 |
{Type = <<"multipart">>, SubType, Params} -> |
| 1048 |
ContentType = {Type, SubType, lists:keydelete(<<"boundary">>, 1, Params)}, |
| 1049 |
choose_content_type(Req2, State2, ContentType, CTA2); |
| 1050 |
ContentType -> |
| 1051 |
choose_content_type(Req2, State2, ContentType, CTA2) |
| 1052 |
catch _:_ -> |
| 1053 |
respond(Req2, State2, 415) |
| 1054 |
end |
| 1055 |
end. |
| 1056 |
|
| 1057 |
%% The special content type '*' will always match. It can be used as a |
| 1058 |
%% catch-all content type for accepting any kind of request content. |
| 1059 |
%% Note that because it will always match, it should be the last of the |
| 1060 |
%% list of content types, otherwise it'll shadow the ones following. |
| 1061 |
choose_content_type(Req, State, _ContentType, []) -> |
| 1062 |
respond(Req, State, 415); |
| 1063 |
choose_content_type(Req, State, ContentType, [{Accepted, Fun}|_Tail]) |
| 1064 |
when Accepted =:= '*'; Accepted =:= ContentType -> |
| 1065 |
process_content_type(Req, State, Fun); |
| 1066 |
%% The special parameter '*' will always match any kind of content type |
| 1067 |
%% parameters. |
| 1068 |
%% Note that because it will always match, it should be the last of the |
| 1069 |
%% list for specific content type, otherwise it'll shadow the ones following. |
| 1070 |
choose_content_type(Req, State, {Type, SubType, Param}, |
| 1071 |
[{{Type, SubType, AcceptedParam}, Fun}|_Tail]) |
| 1072 |
when AcceptedParam =:= '*'; AcceptedParam =:= Param -> |
| 1073 |
process_content_type(Req, State, Fun); |
| 1074 |
choose_content_type(Req, State, ContentType, [_Any|Tail]) -> |
| 1075 |
choose_content_type(Req, State, ContentType, Tail). |
| 1076 |
|
| 1077 |
process_content_type(Req, State=#state{method=Method, exists=Exists}, Fun) -> |
| 1078 |
try case call(Req, State, Fun) of |
| 1079 |
{stop, Req2, State2} -> |
| 1080 |
terminate(Req2, State2); |
| 1081 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 1082 |
switch_handler(Switch, Req2, State2); |
| 1083 |
{true, Req2, State2} when Exists -> |
| 1084 |
has_resp_body(Req2, State2); |
| 1085 |
{true, Req2, State2} -> |
| 1086 |
maybe_created(Req2, State2); |
| 1087 |
{false, Req2, State2} -> |
| 1088 |
respond(Req2, State2, 400); |
| 1089 |
{{created, ResURL}, Req2, State2} when Method =:= <<"POST">> -> |
| 1090 |
Req3 = cowboy_req:set_resp_header( |
| 1091 |
<<"location">>, ResURL, Req2), |
| 1092 |
respond(Req3, State2, 201); |
| 1093 |
{{see_other, ResURL}, Req2, State2} when Method =:= <<"POST">> -> |
| 1094 |
Req3 = cowboy_req:set_resp_header( |
| 1095 |
<<"location">>, ResURL, Req2), |
| 1096 |
respond(Req3, State2, 303); |
| 1097 |
{{true, ResURL}, Req2, State2} when Method =:= <<"POST">> -> |
| 1098 |
Req3 = cowboy_req:set_resp_header( |
| 1099 |
<<"location">>, ResURL, Req2), |
| 1100 |
if |
| 1101 |
Exists -> respond(Req3, State2, 303); |
| 1102 |
true -> respond(Req3, State2, 201) |
| 1103 |
end |
| 1104 |
end catch Class:Reason = {case_clause, no_call}:Stacktrace -> |
| 1105 |
error_terminate(Req, State, Class, Reason, Stacktrace) |
| 1106 |
end. |
| 1107 |
|
| 1108 |
%% If PUT was used then the resource has been created at the current URL. |
| 1109 |
%% Otherwise, if a location header has been set then the resource has been |
| 1110 |
%% created at a new URL. If not, send a 200 or 204 as expected from a |
| 1111 |
%% POST or PATCH request. |
| 1112 |
maybe_created(Req, State=#state{method= <<"PUT">>}) -> |
| 1113 |
respond(Req, State, 201); |
| 1114 |
maybe_created(Req, State) -> |
| 1115 |
case cowboy_req:has_resp_header(<<"location">>, Req) of |
| 1116 |
true -> respond(Req, State, 201); |
| 1117 |
false -> has_resp_body(Req, State) |
| 1118 |
end. |
| 1119 |
|
| 1120 |
has_resp_body(Req, State) -> |
| 1121 |
case cowboy_req:has_resp_body(Req) of |
| 1122 |
true -> multiple_choices(Req, State); |
| 1123 |
false -> respond(Req, State, 204) |
| 1124 |
end. |
| 1125 |
|
| 1126 |
%% Set the Etag header if any for the response provided. |
| 1127 |
set_resp_body_etag(Req, State) -> |
| 1128 |
try set_resp_etag(Req, State) of |
| 1129 |
{Req2, State2} -> |
| 1130 |
set_resp_body_last_modified(Req2, State2) |
| 1131 |
catch Class:Reason:Stacktrace -> |
| 1132 |
error_terminate(Req, State, Class, Reason, Stacktrace) |
| 1133 |
end. |
| 1134 |
|
| 1135 |
%% Set the Last-Modified header if any for the response provided. |
| 1136 |
set_resp_body_last_modified(Req, State) -> |
| 1137 |
try last_modified(Req, State) of |
| 1138 |
{LastModified, Req2, State2} -> |
| 1139 |
case LastModified of |
| 1140 |
LastModified when is_atom(LastModified) -> |
| 1141 |
set_resp_body_expires(Req2, State2); |
| 1142 |
LastModified -> |
| 1143 |
LastModifiedBin = cowboy_clock:rfc1123(LastModified), |
| 1144 |
Req3 = cowboy_req:set_resp_header( |
| 1145 |
<<"last-modified">>, LastModifiedBin, Req2), |
| 1146 |
set_resp_body_expires(Req3, State2) |
| 1147 |
end |
| 1148 |
catch Class:Reason:Stacktrace -> |
| 1149 |
error_terminate(Req, State, Class, Reason, Stacktrace) |
| 1150 |
end. |
| 1151 |
|
| 1152 |
%% Set the Expires header if any for the response provided. |
| 1153 |
set_resp_body_expires(Req, State) -> |
| 1154 |
try set_resp_expires(Req, State) of |
| 1155 |
{Req2, State2} -> |
| 1156 |
if_range(Req2, State2) |
| 1157 |
catch Class:Reason:Stacktrace -> |
| 1158 |
error_terminate(Req, State, Class, Reason, Stacktrace) |
| 1159 |
end. |
| 1160 |
|
| 1161 |
%% When both the if-range and range headers are set, we perform |
| 1162 |
%% a strong comparison. If it fails, we send a full response. |
| 1163 |
if_range(Req=#{headers := #{<<"if-range">> := _, <<"range">> := _}}, |
| 1164 |
State=#state{etag=Etag}) -> |
| 1165 |
try cowboy_req:parse_header(<<"if-range">>, Req) of |
| 1166 |
%% Strong etag comparison is an exact match with the generate_etag result. |
| 1167 |
Etag={strong, _} -> |
| 1168 |
range(Req, State); |
| 1169 |
%% We cannot do a strong date comparison because we have |
| 1170 |
%% no way of knowing whether the representation changed |
| 1171 |
%% twice during the second covered by the presented |
| 1172 |
%% validator. (RFC7232 2.2.2) |
| 1173 |
_ -> |
| 1174 |
set_resp_body(Req, State) |
| 1175 |
catch _:_ -> |
| 1176 |
set_resp_body(Req, State) |
| 1177 |
end; |
| 1178 |
if_range(Req, State) -> |
| 1179 |
range(Req, State). |
| 1180 |
|
| 1181 |
%% @todo This can probably be moved to if_range directly. |
| 1182 |
range(Req, State=#state{ranges_a=[]}) -> |
| 1183 |
set_resp_body(Req, State); |
| 1184 |
range(Req, State) -> |
| 1185 |
try cowboy_req:parse_header(<<"range">>, Req) of |
| 1186 |
undefined -> |
| 1187 |
set_resp_body(Req, State); |
| 1188 |
%% @todo Maybe change parse_header to return <<"bytes">> in 3.0. |
| 1189 |
{bytes, BytesRange} -> |
| 1190 |
choose_range(Req, State, {<<"bytes">>, BytesRange}); |
| 1191 |
Range -> |
| 1192 |
choose_range(Req, State, Range) |
| 1193 |
catch _:_ -> |
| 1194 |
%% We send a 416 response back when we can't parse the |
| 1195 |
%% range header at all. I'm not sure this is the right |
| 1196 |
%% way to go but at least this can help clients identify |
| 1197 |
%% what went wrong when their range requests never work. |
| 1198 |
range_not_satisfiable(Req, State, undefined) |
| 1199 |
end. |
| 1200 |
|
| 1201 |
choose_range(Req, State=#state{ranges_a=RangesAccepted}, Range={RangeUnit, _}) -> |
| 1202 |
case lists:keyfind(RangeUnit, 1, RangesAccepted) of |
| 1203 |
{_, Callback} -> |
| 1204 |
%% We pass the selected range onward in the Req. |
| 1205 |
range_satisfiable(Req#{range => Range}, State, Callback); |
| 1206 |
false -> |
| 1207 |
set_resp_body(Req, State) |
| 1208 |
end. |
| 1209 |
|
| 1210 |
range_satisfiable(Req, State, Callback) -> |
| 1211 |
case call(Req, State, range_satisfiable) of |
| 1212 |
no_call -> |
| 1213 |
set_ranged_body(Req, State, Callback); |
| 1214 |
{stop, Req2, State2} -> |
| 1215 |
terminate(Req2, State2); |
| 1216 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 1217 |
switch_handler(Switch, Req2, State2); |
| 1218 |
{true, Req2, State2} -> |
| 1219 |
set_ranged_body(Req2, State2, Callback); |
| 1220 |
{false, Req2, State2} -> |
| 1221 |
range_not_satisfiable(Req2, State2, undefined); |
| 1222 |
{{false, Int}, Req2, State2} when is_integer(Int) -> |
| 1223 |
range_not_satisfiable(Req2, State2, [<<"*/">>, integer_to_binary(Int)]); |
| 1224 |
{{false, Iodata}, Req2, State2} when is_binary(Iodata); is_list(Iodata) -> |
| 1225 |
range_not_satisfiable(Req2, State2, Iodata) |
| 1226 |
end. |
| 1227 |
|
| 1228 |
%% When the callback selected is 'auto' and the range unit |
| 1229 |
%% is bytes, we call the normal provide callback and split |
| 1230 |
%% the content automatically. |
| 1231 |
set_ranged_body(Req=#{range := {<<"bytes">>, _}}, State, auto) -> |
| 1232 |
set_ranged_body_auto(Req, State); |
| 1233 |
set_ranged_body(Req, State, Callback) -> |
| 1234 |
set_ranged_body_callback(Req, State, Callback). |
| 1235 |
|
| 1236 |
set_ranged_body_auto(Req, State=#state{handler=Handler, content_type_a={_, Callback}}) -> |
| 1237 |
try case call(Req, State, Callback) of |
| 1238 |
{stop, Req2, State2} -> |
| 1239 |
terminate(Req2, State2); |
| 1240 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 1241 |
switch_handler(Switch, Req2, State2); |
| 1242 |
{Body, Req2, State2} -> |
| 1243 |
maybe_set_ranged_body_auto(Req2, State2, Body) |
| 1244 |
end catch Class:{case_clause, no_call}:Stacktrace -> |
| 1245 |
error_terminate(Req, State, Class, {error, {missing_callback, {Handler, Callback, 2}}, |
| 1246 |
'A callback specified in content_types_provided/2 is not exported.'}, |
| 1247 |
Stacktrace) |
| 1248 |
end. |
| 1249 |
|
| 1250 |
maybe_set_ranged_body_auto(Req=#{range := {_, Ranges}}, State, Body) -> |
| 1251 |
Size = case Body of |
| 1252 |
{sendfile, _, Bytes, _} -> Bytes; |
| 1253 |
_ -> iolist_size(Body) |
| 1254 |
end, |
| 1255 |
Checks = [case Range of |
| 1256 |
{From, infinity} -> From < Size; |
| 1257 |
{From, To} -> (From < Size) andalso (From =< To) andalso (To =< Size); |
| 1258 |
Neg -> (Neg =/= 0) andalso (-Neg < Size) |
| 1259 |
end || Range <- Ranges], |
| 1260 |
case lists:usort(Checks) of |
| 1261 |
[true] -> set_ranged_body_auto(Req, State, Body); |
| 1262 |
_ -> range_not_satisfiable(Req, State, [<<"*/">>, integer_to_binary(Size)]) |
| 1263 |
end. |
| 1264 |
|
| 1265 |
%% We might also want to have some checks about range order, |
| 1266 |
%% number of ranges, and perhaps also join ranges that are |
| 1267 |
%% too close into one contiguous range. Some of these can |
| 1268 |
%% be done before calling the ProvideCallback. |
| 1269 |
|
| 1270 |
set_ranged_body_auto(Req=#{range := {_, Ranges}}, State, Body) -> |
| 1271 |
Parts = [ranged_partition(Range, Body) || Range <- Ranges], |
| 1272 |
case Parts of |
| 1273 |
[OnePart] -> set_one_ranged_body(Req, State, OnePart); |
| 1274 |
_ when is_tuple(Body) -> send_multipart_ranged_body(Req, State, Parts); |
| 1275 |
_ -> set_multipart_ranged_body(Req, State, Parts) |
| 1276 |
end. |
| 1277 |
|
| 1278 |
ranged_partition(Range, {sendfile, Offset0, Bytes0, Path}) -> |
| 1279 |
{From, To, Offset, Bytes} = case Range of |
| 1280 |
{From0, infinity} -> {From0, Bytes0 - 1, Offset0 + From0, Bytes0 - From0}; |
| 1281 |
{From0, To0} -> {From0, To0, Offset0 + From0, 1 + To0 - From0}; |
| 1282 |
Neg -> {Bytes0 + Neg, Bytes0 - 1, Offset0 + Bytes0 + Neg, -Neg} |
| 1283 |
end, |
| 1284 |
{{From, To, Bytes0}, {sendfile, Offset, Bytes, Path}}; |
| 1285 |
ranged_partition(Range, Data0) -> |
| 1286 |
Total = iolist_size(Data0), |
| 1287 |
{From, To, Data} = case Range of |
| 1288 |
{From0, infinity} -> |
| 1289 |
{_, Data1} = cow_iolists:split(From0, Data0), |
| 1290 |
{From0, Total - 1, Data1}; |
| 1291 |
{From0, To0} -> |
| 1292 |
{_, Data1} = cow_iolists:split(From0, Data0), |
| 1293 |
{Data2, _} = cow_iolists:split(To0 - From0 + 1, Data1), |
| 1294 |
{From0, To0, Data2}; |
| 1295 |
Neg -> |
| 1296 |
{_, Data1} = cow_iolists:split(Total + Neg, Data0), |
| 1297 |
{Total + Neg, Total - 1, Data1} |
| 1298 |
end, |
| 1299 |
{{From, To, Total}, Data}. |
| 1300 |
|
| 1301 |
-ifdef(TEST). |
| 1302 |
ranged_partition_test_() -> |
| 1303 |
Tests = [ |
| 1304 |
%% Sendfile with open-ended range. |
| 1305 |
{{0, infinity}, {sendfile, 0, 12, "t"}, {{0, 11, 12}, {sendfile, 0, 12, "t"}}}, |
| 1306 |
{{6, infinity}, {sendfile, 0, 12, "t"}, {{6, 11, 12}, {sendfile, 6, 6, "t"}}}, |
| 1307 |
{{11, infinity}, {sendfile, 0, 12, "t"}, {{11, 11, 12}, {sendfile, 11, 1, "t"}}}, |
| 1308 |
%% Sendfile with open-ended range. Sendfile tuple has an offset originally. |
| 1309 |
{{0, infinity}, {sendfile, 3, 12, "t"}, {{0, 11, 12}, {sendfile, 3, 12, "t"}}}, |
| 1310 |
{{6, infinity}, {sendfile, 3, 12, "t"}, {{6, 11, 12}, {sendfile, 9, 6, "t"}}}, |
| 1311 |
{{11, infinity}, {sendfile, 3, 12, "t"}, {{11, 11, 12}, {sendfile, 14, 1, "t"}}}, |
| 1312 |
%% Sendfile with a specific range. |
| 1313 |
{{0, 11}, {sendfile, 0, 12, "t"}, {{0, 11, 12}, {sendfile, 0, 12, "t"}}}, |
| 1314 |
{{6, 11}, {sendfile, 0, 12, "t"}, {{6, 11, 12}, {sendfile, 6, 6, "t"}}}, |
| 1315 |
{{11, 11}, {sendfile, 0, 12, "t"}, {{11, 11, 12}, {sendfile, 11, 1, "t"}}}, |
| 1316 |
{{1, 10}, {sendfile, 0, 12, "t"}, {{1, 10, 12}, {sendfile, 1, 10, "t"}}}, |
| 1317 |
%% Sendfile with a specific range. Sendfile tuple has an offset originally. |
| 1318 |
{{0, 11}, {sendfile, 3, 12, "t"}, {{0, 11, 12}, {sendfile, 3, 12, "t"}}}, |
| 1319 |
{{6, 11}, {sendfile, 3, 12, "t"}, {{6, 11, 12}, {sendfile, 9, 6, "t"}}}, |
| 1320 |
{{11, 11}, {sendfile, 3, 12, "t"}, {{11, 11, 12}, {sendfile, 14, 1, "t"}}}, |
| 1321 |
{{1, 10}, {sendfile, 3, 12, "t"}, {{1, 10, 12}, {sendfile, 4, 10, "t"}}}, |
| 1322 |
%% Sendfile with negative range. |
| 1323 |
{-12, {sendfile, 0, 12, "t"}, {{0, 11, 12}, {sendfile, 0, 12, "t"}}}, |
| 1324 |
{-6, {sendfile, 0, 12, "t"}, {{6, 11, 12}, {sendfile, 6, 6, "t"}}}, |
| 1325 |
{-1, {sendfile, 0, 12, "t"}, {{11, 11, 12}, {sendfile, 11, 1, "t"}}}, |
| 1326 |
%% Sendfile with negative range. Sendfile tuple has an offset originally. |
| 1327 |
{-12, {sendfile, 3, 12, "t"}, {{0, 11, 12}, {sendfile, 3, 12, "t"}}}, |
| 1328 |
{-6, {sendfile, 3, 12, "t"}, {{6, 11, 12}, {sendfile, 9, 6, "t"}}}, |
| 1329 |
{-1, {sendfile, 3, 12, "t"}, {{11, 11, 12}, {sendfile, 14, 1, "t"}}}, |
| 1330 |
%% Iodata with open-ended range. |
| 1331 |
{{0, infinity}, <<"Hello world!">>, {{0, 11, 12}, <<"Hello world!">>}}, |
| 1332 |
{{6, infinity}, <<"Hello world!">>, {{6, 11, 12}, <<"world!">>}}, |
| 1333 |
{{11, infinity}, <<"Hello world!">>, {{11, 11, 12}, <<"!">>}}, |
| 1334 |
%% Iodata with a specific range. The resulting data is |
| 1335 |
%% wrapped in a list because of how cow_iolists:split/2 works. |
| 1336 |
{{0, 11}, <<"Hello world!">>, {{0, 11, 12}, [<<"Hello world!">>]}}, |
| 1337 |
{{6, 11}, <<"Hello world!">>, {{6, 11, 12}, [<<"world!">>]}}, |
| 1338 |
{{11, 11}, <<"Hello world!">>, {{11, 11, 12}, [<<"!">>]}}, |
| 1339 |
{{1, 10}, <<"Hello world!">>, {{1, 10, 12}, [<<"ello world">>]}}, |
| 1340 |
%% Iodata with negative range. |
| 1341 |
{-12, <<"Hello world!">>, {{0, 11, 12}, <<"Hello world!">>}}, |
| 1342 |
{-6, <<"Hello world!">>, {{6, 11, 12}, <<"world!">>}}, |
| 1343 |
{-1, <<"Hello world!">>, {{11, 11, 12}, <<"!">>}} |
| 1344 |
], |
| 1345 |
[{iolist_to_binary(io_lib:format("range ~p data ~p", [VR, VD])), |
| 1346 |
fun() -> R = ranged_partition(VR, VD) end} || {VR, VD, R} <- Tests]. |
| 1347 |
-endif. |
| 1348 |
|
| 1349 |
set_ranged_body_callback(Req, State=#state{handler=Handler}, Callback) -> |
| 1350 |
try case call(Req, State, Callback) of |
| 1351 |
{stop, Req2, State2} -> |
| 1352 |
terminate(Req2, State2); |
| 1353 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 1354 |
switch_handler(Switch, Req2, State2); |
| 1355 |
%% When we receive a single range, we send it directly. |
| 1356 |
{[OneRange], Req2, State2} -> |
| 1357 |
set_one_ranged_body(Req2, State2, OneRange); |
| 1358 |
%% When we receive multiple ranges we have to send them as multipart/byteranges. |
| 1359 |
%% This also applies to non-bytes units. (RFC7233 A) If users don't want to use |
| 1360 |
%% this for non-bytes units they can always return a single range with a binary |
| 1361 |
%% content-range information. |
| 1362 |
{Ranges, Req2, State2} when length(Ranges) > 1 -> |
| 1363 |
%% We have to check whether there are sendfile tuples in the |
| 1364 |
%% ranges to be sent. If there are we must use stream_reply. |
| 1365 |
HasSendfile = [] =/= [true || {_, {sendfile, _, _, _}} <- Ranges], |
| 1366 |
case HasSendfile of |
| 1367 |
true -> send_multipart_ranged_body(Req2, State2, Ranges); |
| 1368 |
false -> set_multipart_ranged_body(Req2, State2, Ranges) |
| 1369 |
end |
| 1370 |
end catch Class:{case_clause, no_call}:Stacktrace -> |
| 1371 |
error_terminate(Req, State, Class, {error, {missing_callback, {Handler, Callback, 2}}, |
| 1372 |
'A callback specified in ranges_provided/2 is not exported.'}, |
| 1373 |
Stacktrace) |
| 1374 |
end. |
| 1375 |
|
| 1376 |
set_one_ranged_body(Req0, State, OneRange) -> |
| 1377 |
{ContentRange, Body} = prepare_range(Req0, OneRange), |
| 1378 |
Req1 = cowboy_req:set_resp_header(<<"content-range">>, ContentRange, Req0), |
| 1379 |
Req = cowboy_req:set_resp_body(Body, Req1), |
| 1380 |
respond(Req, State, 206). |
| 1381 |
|
| 1382 |
set_multipart_ranged_body(Req, State, [FirstRange|MoreRanges]) -> |
| 1383 |
Boundary = cow_multipart:boundary(), |
| 1384 |
ContentType = cowboy_req:resp_header(<<"content-type">>, Req), |
| 1385 |
{FirstContentRange, FirstPartBody} = prepare_range(Req, FirstRange), |
| 1386 |
FirstPartHead = cow_multipart:first_part(Boundary, [ |
| 1387 |
{<<"content-type">>, ContentType}, |
| 1388 |
{<<"content-range">>, FirstContentRange} |
| 1389 |
]), |
| 1390 |
MoreParts = [begin |
| 1391 |
{NextContentRange, NextPartBody} = prepare_range(Req, NextRange), |
| 1392 |
NextPartHead = cow_multipart:part(Boundary, [ |
| 1393 |
{<<"content-type">>, ContentType}, |
| 1394 |
{<<"content-range">>, NextContentRange} |
| 1395 |
]), |
| 1396 |
[NextPartHead, NextPartBody] |
| 1397 |
end || NextRange <- MoreRanges], |
| 1398 |
Body = [FirstPartHead, FirstPartBody, MoreParts, cow_multipart:close(Boundary)], |
| 1399 |
Req2 = cowboy_req:set_resp_header(<<"content-type">>, |
| 1400 |
[<<"multipart/byteranges; boundary=">>, Boundary], Req), |
| 1401 |
Req3 = cowboy_req:set_resp_body(Body, Req2), |
| 1402 |
respond(Req3, State, 206). |
| 1403 |
|
| 1404 |
%% Similar to set_multipart_ranged_body except we have to stream |
| 1405 |
%% the data because the parts contain sendfile tuples. |
| 1406 |
send_multipart_ranged_body(Req, State, [FirstRange|MoreRanges]) -> |
| 1407 |
Boundary = cow_multipart:boundary(), |
| 1408 |
ContentType = cowboy_req:resp_header(<<"content-type">>, Req), |
| 1409 |
Req2 = cowboy_req:set_resp_header(<<"content-type">>, |
| 1410 |
[<<"multipart/byteranges; boundary=">>, Boundary], Req), |
| 1411 |
Req3 = cowboy_req:stream_reply(206, Req2), |
| 1412 |
{FirstContentRange, FirstPartBody} = prepare_range(Req, FirstRange), |
| 1413 |
FirstPartHead = cow_multipart:first_part(Boundary, [ |
| 1414 |
{<<"content-type">>, ContentType}, |
| 1415 |
{<<"content-range">>, FirstContentRange} |
| 1416 |
]), |
| 1417 |
cowboy_req:stream_body(FirstPartHead, nofin, Req3), |
| 1418 |
cowboy_req:stream_body(FirstPartBody, nofin, Req3), |
| 1419 |
_ = [begin |
| 1420 |
{NextContentRange, NextPartBody} = prepare_range(Req, NextRange), |
| 1421 |
NextPartHead = cow_multipart:part(Boundary, [ |
| 1422 |
{<<"content-type">>, ContentType}, |
| 1423 |
{<<"content-range">>, NextContentRange} |
| 1424 |
]), |
| 1425 |
cowboy_req:stream_body(NextPartHead, nofin, Req3), |
| 1426 |
cowboy_req:stream_body(NextPartBody, nofin, Req3), |
| 1427 |
[NextPartHead, NextPartBody] |
| 1428 |
end || NextRange <- MoreRanges], |
| 1429 |
cowboy_req:stream_body(cow_multipart:close(Boundary), fin, Req3), |
| 1430 |
terminate(Req3, State). |
| 1431 |
|
| 1432 |
prepare_range(#{range := {RangeUnit, _}}, {{From, To, Total0}, Body}) -> |
| 1433 |
Total = case Total0 of |
| 1434 |
'*' -> <<"*">>; |
| 1435 |
_ -> integer_to_binary(Total0) |
| 1436 |
end, |
| 1437 |
ContentRange = [RangeUnit, $\s, integer_to_binary(From), |
| 1438 |
$-, integer_to_binary(To), $/, Total], |
| 1439 |
{ContentRange, Body}; |
| 1440 |
prepare_range(#{range := {RangeUnit, _}}, {RangeData, Body}) -> |
| 1441 |
{[RangeUnit, $\s, RangeData], Body}. |
| 1442 |
|
| 1443 |
%% We send the content-range header when we can on error. |
| 1444 |
range_not_satisfiable(Req, State, undefined) -> |
| 1445 |
respond(Req, State, 416); |
| 1446 |
range_not_satisfiable(Req0=#{range := {RangeUnit, _}}, State, RangeData) -> |
| 1447 |
Req = cowboy_req:set_resp_header(<<"content-range">>, |
| 1448 |
[RangeUnit, $\s, RangeData], Req0), |
| 1449 |
respond(Req, State, 416). |
| 1450 |
|
| 1451 |
%% Set the response headers and call the callback found using |
| 1452 |
%% content_types_provided/2 to obtain the request body and add |
| 1453 |
%% it to the response. |
| 1454 |
set_resp_body(Req, State=#state{handler=Handler, content_type_a={_, Callback}}) -> |
| 1455 |
try case call(Req, State, Callback) of |
| 1456 |
{stop, Req2, State2} -> |
| 1457 |
terminate(Req2, State2); |
| 1458 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 1459 |
switch_handler(Switch, Req2, State2); |
| 1460 |
{Body, Req2, State2} -> |
| 1461 |
Req3 = cowboy_req:set_resp_body(Body, Req2), |
| 1462 |
multiple_choices(Req3, State2) |
| 1463 |
end catch Class:{case_clause, no_call}:Stacktrace -> |
| 1464 |
error_terminate(Req, State, Class, {error, {missing_callback, {Handler, Callback, 2}}, |
| 1465 |
'A callback specified in content_types_provided/2 is not exported.'}, |
| 1466 |
Stacktrace) |
| 1467 |
end. |
| 1468 |
|
| 1469 |
multiple_choices(Req, State) -> |
| 1470 |
expect(Req, State, multiple_choices, false, 200, 300). |
| 1471 |
|
| 1472 |
%% Response utility functions. |
| 1473 |
|
| 1474 |
set_resp_etag(Req, State) -> |
| 1475 |
{Etag, Req2, State2} = generate_etag(Req, State), |
| 1476 |
case Etag of |
| 1477 |
undefined -> |
| 1478 |
{Req2, State2}; |
| 1479 |
Etag -> |
| 1480 |
Req3 = cowboy_req:set_resp_header( |
| 1481 |
<<"etag">>, encode_etag(Etag), Req2), |
| 1482 |
{Req3, State2} |
| 1483 |
end. |
| 1484 |
|
| 1485 |
-spec encode_etag({strong | weak, binary()}) -> iolist(). |
| 1486 |
encode_etag({strong, Etag}) -> [$",Etag,$"]; |
| 1487 |
encode_etag({weak, Etag}) -> ["W/\"",Etag,$"]. |
| 1488 |
|
| 1489 |
set_resp_expires(Req, State) -> |
| 1490 |
{Expires, Req2, State2} = expires(Req, State), |
| 1491 |
case Expires of |
| 1492 |
Expires when is_atom(Expires) -> |
| 1493 |
{Req2, State2}; |
| 1494 |
Expires when is_binary(Expires) -> |
| 1495 |
Req3 = cowboy_req:set_resp_header( |
| 1496 |
<<"expires">>, Expires, Req2), |
| 1497 |
{Req3, State2}; |
| 1498 |
Expires -> |
| 1499 |
ExpiresBin = cowboy_clock:rfc1123(Expires), |
| 1500 |
Req3 = cowboy_req:set_resp_header( |
| 1501 |
<<"expires">>, ExpiresBin, Req2), |
| 1502 |
{Req3, State2} |
| 1503 |
end. |
| 1504 |
|
| 1505 |
%% Info retrieval. No logic. |
| 1506 |
|
| 1507 |
generate_etag(Req, State=#state{etag=no_call}) -> |
| 1508 |
{undefined, Req, State}; |
| 1509 |
generate_etag(Req, State=#state{etag=undefined}) -> |
| 1510 |
case unsafe_call(Req, State, generate_etag) of |
| 1511 |
no_call -> |
| 1512 |
{undefined, Req, State#state{etag=no_call}}; |
| 1513 |
%% We allow the callback to return 'undefined' |
| 1514 |
%% to allow conditionally generating etags. We |
| 1515 |
%% handle 'undefined' the same as if the function |
| 1516 |
%% was not exported. |
| 1517 |
{undefined, Req2, State2} -> |
| 1518 |
{undefined, Req2, State2#state{etag=no_call}}; |
| 1519 |
{Etag, Req2, State2} when is_binary(Etag) -> |
| 1520 |
Etag2 = cow_http_hd:parse_etag(Etag), |
| 1521 |
{Etag2, Req2, State2#state{etag=Etag2}}; |
| 1522 |
{Etag, Req2, State2} -> |
| 1523 |
{Etag, Req2, State2#state{etag=Etag}} |
| 1524 |
end; |
| 1525 |
generate_etag(Req, State=#state{etag=Etag}) -> |
| 1526 |
{Etag, Req, State}. |
| 1527 |
|
| 1528 |
last_modified(Req, State=#state{last_modified=no_call}) -> |
| 1529 |
{undefined, Req, State}; |
| 1530 |
last_modified(Req, State=#state{last_modified=undefined}) -> |
| 1531 |
case unsafe_call(Req, State, last_modified) of |
| 1532 |
no_call -> |
| 1533 |
{undefined, Req, State#state{last_modified=no_call}}; |
| 1534 |
%% We allow the callback to return 'undefined', |
| 1535 |
%% in which case the generated header would be missing |
| 1536 |
%% as if the callback was not called. |
| 1537 |
{undefined, Req2, State2} -> |
| 1538 |
{undefined, Req2, State2#state{last_modified=no_call}}; |
| 1539 |
{LastModified, Req2, State2} -> |
| 1540 |
{LastModified, Req2, State2#state{last_modified=LastModified}} |
| 1541 |
end; |
| 1542 |
last_modified(Req, State=#state{last_modified=LastModified}) -> |
| 1543 |
{LastModified, Req, State}. |
| 1544 |
|
| 1545 |
expires(Req, State=#state{expires=no_call}) -> |
| 1546 |
{undefined, Req, State}; |
| 1547 |
expires(Req, State=#state{expires=undefined}) -> |
| 1548 |
case unsafe_call(Req, State, expires) of |
| 1549 |
no_call -> |
| 1550 |
{undefined, Req, State#state{expires=no_call}}; |
| 1551 |
{Expires, Req2, State2} -> |
| 1552 |
{Expires, Req2, State2#state{expires=Expires}} |
| 1553 |
end; |
| 1554 |
expires(Req, State=#state{expires=Expires}) -> |
| 1555 |
{Expires, Req, State}. |
| 1556 |
|
| 1557 |
%% REST primitives. |
| 1558 |
|
| 1559 |
expect(Req, State, Callback, Expected, OnTrue, OnFalse) -> |
| 1560 |
case call(Req, State, Callback) of |
| 1561 |
no_call -> |
| 1562 |
next(Req, State, OnTrue); |
| 1563 |
{stop, Req2, State2} -> |
| 1564 |
terminate(Req2, State2); |
| 1565 |
{Switch, Req2, State2} when element(1, Switch) =:= switch_handler -> |
| 1566 |
switch_handler(Switch, Req2, State2); |
| 1567 |
{Expected, Req2, State2} -> |
| 1568 |
next(Req2, State2, OnTrue); |
| 1569 |
{_Unexpected, Req2, State2} -> |
| 1570 |
next(Req2, State2, OnFalse) |
| 1571 |
end. |
| 1572 |
|
| 1573 |
call(Req0, State=#state{handler=Handler, |
| 1574 |
handler_state=HandlerState0}, Callback) -> |
| 1575 |
case erlang:function_exported(Handler, Callback, 2) of |
| 1576 |
true -> |
| 1577 |
try Handler:Callback(Req0, HandlerState0) of |
| 1578 |
no_call -> |
| 1579 |
no_call; |
| 1580 |
{Result, Req, HandlerState} -> |
| 1581 |
{Result, Req, State#state{handler_state=HandlerState}} |
| 1582 |
catch Class:Reason:Stacktrace -> |
| 1583 |
error_terminate(Req0, State, Class, Reason, Stacktrace) |
| 1584 |
end; |
| 1585 |
false -> |
| 1586 |
no_call |
| 1587 |
end. |
| 1588 |
|
| 1589 |
unsafe_call(Req0, State=#state{handler=Handler, |
| 1590 |
handler_state=HandlerState0}, Callback) -> |
| 1591 |
case erlang:function_exported(Handler, Callback, 2) of |
| 1592 |
false -> |
| 1593 |
no_call; |
| 1594 |
true -> |
| 1595 |
case Handler:Callback(Req0, HandlerState0) of |
| 1596 |
no_call -> |
| 1597 |
no_call; |
| 1598 |
{Result, Req, HandlerState} -> |
| 1599 |
{Result, Req, State#state{handler_state=HandlerState}} |
| 1600 |
end |
| 1601 |
end. |
| 1602 |
|
| 1603 |
next(Req, State, Next) when is_function(Next) -> |
| 1604 |
Next(Req, State); |
| 1605 |
next(Req, State, StatusCode) when is_integer(StatusCode) -> |
| 1606 |
respond(Req, State, StatusCode). |
| 1607 |
|
| 1608 |
respond(Req0, State, StatusCode) -> |
| 1609 |
%% We remove the content-type header when there is no body, |
| 1610 |
%% except when the status code is 200 because it might have |
| 1611 |
%% been intended (for example sending an empty file). |
| 1612 |
Req = case cowboy_req:has_resp_body(Req0) of |
| 1613 |
true when StatusCode =:= 200 -> Req0; |
| 1614 |
true -> Req0; |
| 1615 |
false -> cowboy_req:delete_resp_header(<<"content-type">>, Req0) |
| 1616 |
end, |
| 1617 |
terminate(cowboy_req:reply(StatusCode, Req), State). |
| 1618 |
|
| 1619 |
switch_handler({switch_handler, Mod}, Req, #state{handler_state=HandlerState}) -> |
| 1620 |
{Mod, Req, HandlerState}; |
| 1621 |
switch_handler({switch_handler, Mod, Opts}, Req, #state{handler_state=HandlerState}) -> |
| 1622 |
{Mod, Req, HandlerState, Opts}. |
| 1623 |
|
| 1624 |
-spec error_terminate(cowboy_req:req(), #state{}, atom(), any(), any()) -> no_return(). |
| 1625 |
error_terminate(Req, #state{handler=Handler, handler_state=HandlerState}, Class, Reason, Stacktrace) -> |
| 1626 |
cowboy_handler:terminate({crash, Class, Reason}, Req, HandlerState, Handler), |
| 1627 |
erlang:raise(Class, Reason, Stacktrace). |
| 1628 |
|
| 1629 |
terminate(Req, #state{handler=Handler, handler_state=HandlerState}) -> |
| 1630 |
%% @todo I don't think the result is used anywhere? |
| 1631 |
Result = cowboy_handler:terminate(normal, Req, HandlerState, Handler), |
| 1632 |
{ok, Req, Result}. |