cowboy_rest.erl 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011
  1. %% Copyright (c) 2011-2014, Loïc Hoguin <essen@ninenines.eu>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. %% Originally based on the Webmachine Diagram from Alan Dean and
  15. %% Justin Sheehy.
  16. -module(cowboy_rest).
  17. -behaviour(cowboy_sub_protocol).
  18. -export([upgrade/4]).
  19. -record(state, {
  20. env :: cowboy_middleware:env(),
  21. method = undefined :: binary(),
  22. %% Handler.
  23. handler :: atom(),
  24. handler_state :: any(),
  25. %% Allowed methods. Only used for OPTIONS requests.
  26. allowed_methods :: [binary()],
  27. %% Media type.
  28. content_types_p = [] ::
  29. [{binary() | {binary(), binary(), [{binary(), binary()}] | '*'},
  30. atom()}],
  31. content_type_a :: undefined
  32. | {binary() | {binary(), binary(), [{binary(), binary()}] | '*'},
  33. atom()},
  34. %% Language.
  35. languages_p = [] :: [binary()],
  36. language_a :: undefined | binary(),
  37. %% Charset.
  38. charsets_p = [] :: [binary()],
  39. charset_a :: undefined | binary(),
  40. %% Whether the resource exists.
  41. exists = false :: boolean(),
  42. %% Cached resource calls.
  43. etag :: undefined | no_call | {strong | weak, binary()},
  44. last_modified :: undefined | no_call | calendar:datetime(),
  45. expires :: undefined | no_call | calendar:datetime() | binary()
  46. }).
  47. -spec upgrade(Req, Env, module(), any())
  48. -> {ok, Req, Env} when Req::cowboy_req:req(), Env::cowboy_middleware:env().
  49. upgrade(Req, Env, Handler, HandlerOpts) ->
  50. Method = cowboy_req:method(Req),
  51. case erlang:function_exported(Handler, rest_init, 2) of
  52. true ->
  53. try Handler:rest_init(Req, HandlerOpts) of
  54. {ok, Req2, HandlerState} ->
  55. service_available(Req2, #state{env=Env, method=Method,
  56. handler=Handler, handler_state=HandlerState})
  57. catch Class:Reason ->
  58. Stacktrace = erlang:get_stacktrace(),
  59. cowboy_req:maybe_reply(Stacktrace, Req),
  60. erlang:Class([
  61. {reason, Reason},
  62. {mfa, {Handler, rest_init, 2}},
  63. {stacktrace, Stacktrace},
  64. {req, cowboy_req:to_list(Req)},
  65. {opts, HandlerOpts}
  66. ])
  67. end;
  68. false ->
  69. service_available(Req, #state{env=Env, method=Method,
  70. handler=Handler})
  71. end.
  72. service_available(Req, State) ->
  73. expect(Req, State, service_available, true, fun known_methods/2, 503).
  74. %% known_methods/2 should return a list of binary methods.
  75. known_methods(Req, State=#state{method=Method}) ->
  76. case call(Req, State, known_methods) of
  77. no_call when Method =:= <<"HEAD">>; Method =:= <<"GET">>;
  78. Method =:= <<"POST">>; Method =:= <<"PUT">>;
  79. Method =:= <<"PATCH">>; Method =:= <<"DELETE">>;
  80. Method =:= <<"OPTIONS">> ->
  81. next(Req, State, fun uri_too_long/2);
  82. no_call ->
  83. next(Req, State, 501);
  84. {halt, Req2, HandlerState} ->
  85. terminate(Req2, State#state{handler_state=HandlerState});
  86. {List, Req2, HandlerState} ->
  87. State2 = State#state{handler_state=HandlerState},
  88. case lists:member(Method, List) of
  89. true -> next(Req2, State2, fun uri_too_long/2);
  90. false -> next(Req2, State2, 501)
  91. end
  92. end.
  93. uri_too_long(Req, State) ->
  94. expect(Req, State, uri_too_long, false, fun allowed_methods/2, 414).
  95. %% allowed_methods/2 should return a list of binary methods.
  96. allowed_methods(Req, State=#state{method=Method}) ->
  97. case call(Req, State, allowed_methods) of
  98. no_call when Method =:= <<"HEAD">>; Method =:= <<"GET">> ->
  99. next(Req, State, fun malformed_request/2);
  100. no_call when Method =:= <<"OPTIONS">> ->
  101. next(Req, State#state{allowed_methods=
  102. [<<"HEAD">>, <<"GET">>, <<"OPTIONS">>]},
  103. fun malformed_request/2);
  104. no_call ->
  105. method_not_allowed(Req, State,
  106. [<<"HEAD">>, <<"GET">>, <<"OPTIONS">>]);
  107. {halt, Req2, HandlerState} ->
  108. terminate(Req2, State#state{handler_state=HandlerState});
  109. {List, Req2, HandlerState} ->
  110. State2 = State#state{handler_state=HandlerState},
  111. case lists:member(Method, List) of
  112. true when Method =:= <<"OPTIONS">> ->
  113. next(Req2, State2#state{allowed_methods=List},
  114. fun malformed_request/2);
  115. true ->
  116. next(Req2, State2, fun malformed_request/2);
  117. false ->
  118. method_not_allowed(Req2, State2, List)
  119. end
  120. end.
  121. method_not_allowed(Req, State, []) ->
  122. Req2 = cowboy_req:set_resp_header(<<"allow">>, <<>>, Req),
  123. respond(Req2, State, 405);
  124. method_not_allowed(Req, State, Methods) ->
  125. << ", ", Allow/binary >> = << << ", ", M/binary >> || M <- Methods >>,
  126. Req2 = cowboy_req:set_resp_header(<<"allow">>, Allow, Req),
  127. respond(Req2, State, 405).
  128. malformed_request(Req, State) ->
  129. expect(Req, State, malformed_request, false, fun is_authorized/2, 400).
  130. %% is_authorized/2 should return true or {false, WwwAuthenticateHeader}.
  131. is_authorized(Req, State) ->
  132. case call(Req, State, is_authorized) of
  133. no_call ->
  134. forbidden(Req, State);
  135. {halt, Req2, HandlerState} ->
  136. terminate(Req2, State#state{handler_state=HandlerState});
  137. {true, Req2, HandlerState} ->
  138. forbidden(Req2, State#state{handler_state=HandlerState});
  139. {{false, AuthHead}, Req2, HandlerState} ->
  140. Req3 = cowboy_req:set_resp_header(
  141. <<"www-authenticate">>, AuthHead, Req2),
  142. respond(Req3, State#state{handler_state=HandlerState}, 401)
  143. end.
  144. forbidden(Req, State) ->
  145. expect(Req, State, forbidden, false, fun valid_content_headers/2, 403).
  146. valid_content_headers(Req, State) ->
  147. expect(Req, State, valid_content_headers, true,
  148. fun known_content_type/2, 501).
  149. known_content_type(Req, State) ->
  150. expect(Req, State, known_content_type, true,
  151. fun valid_entity_length/2, 415).
  152. valid_entity_length(Req, State) ->
  153. expect(Req, State, valid_entity_length, true, fun options/2, 413).
  154. %% If you need to add additional headers to the response at this point,
  155. %% you should do it directly in the options/2 call using set_resp_headers.
  156. options(Req, State=#state{allowed_methods=Methods, method= <<"OPTIONS">>}) ->
  157. case call(Req, State, options) of
  158. no_call when Methods =:= [] ->
  159. Req2 = cowboy_req:set_resp_header(<<"allow">>, <<>>, Req),
  160. respond(Req2, State, 200);
  161. no_call ->
  162. << ", ", Allow/binary >>
  163. = << << ", ", M/binary >> || M <- Methods >>,
  164. Req2 = cowboy_req:set_resp_header(<<"allow">>, Allow, Req),
  165. respond(Req2, State, 200);
  166. {halt, Req2, HandlerState} ->
  167. terminate(Req2, State#state{handler_state=HandlerState});
  168. {ok, Req2, HandlerState} ->
  169. respond(Req2, State#state{handler_state=HandlerState}, 200)
  170. end;
  171. options(Req, State) ->
  172. content_types_provided(Req, State).
  173. %% content_types_provided/2 should return a list of content types and their
  174. %% associated callback function as a tuple: {{Type, SubType, Params}, Fun}.
  175. %% Type and SubType are the media type as binary. Params is a list of
  176. %% Key/Value tuple, with Key and Value a binary. Fun is the name of the
  177. %% callback that will be used to return the content of the response. It is
  178. %% given as an atom.
  179. %%
  180. %% An example of such return value would be:
  181. %% {{<<"text">>, <<"html">>, []}, to_html}
  182. %%
  183. %% Note that it is also possible to return a binary content type that will
  184. %% then be parsed by Cowboy. However note that while this may make your
  185. %% resources a little more readable, this is a lot less efficient.
  186. %%
  187. %% An example of such return value would be:
  188. %% {<<"text/html">>, to_html}
  189. content_types_provided(Req, State) ->
  190. case call(Req, State, content_types_provided) of
  191. no_call ->
  192. State2 = State#state{
  193. content_types_p=[{{<<"text">>, <<"html">>, '*'}, to_html}]},
  194. try cowboy_req:parse_header(<<"accept">>, Req) of
  195. undefined ->
  196. languages_provided(
  197. cowboy_req:set_meta(media_type, {<<"text">>, <<"html">>, []}, Req),
  198. State2#state{content_type_a={{<<"text">>, <<"html">>, []}, to_html}});
  199. Accept ->
  200. choose_media_type(Req, State2, prioritize_accept(Accept))
  201. catch _:_ ->
  202. respond(Req, State2, 400)
  203. end;
  204. {halt, Req2, HandlerState} ->
  205. terminate(Req2, State#state{handler_state=HandlerState});
  206. {[], Req2, HandlerState} ->
  207. not_acceptable(Req2, State#state{handler_state=HandlerState});
  208. {CTP, Req2, HandlerState} ->
  209. CTP2 = [normalize_content_types(P) || P <- CTP],
  210. State2 = State#state{
  211. handler_state=HandlerState, content_types_p=CTP2},
  212. try cowboy_req:parse_header(<<"accept">>, Req2) of
  213. undefined ->
  214. {PMT, _Fun} = HeadCTP = hd(CTP2),
  215. languages_provided(
  216. cowboy_req:set_meta(media_type, PMT, Req2),
  217. State2#state{content_type_a=HeadCTP});
  218. Accept ->
  219. choose_media_type(Req2, State2, prioritize_accept(Accept))
  220. catch _:_ ->
  221. respond(Req2, State2, 400)
  222. end
  223. end.
  224. normalize_content_types({ContentType, Callback})
  225. when is_binary(ContentType) ->
  226. {cowboy_http:content_type(ContentType), Callback};
  227. normalize_content_types(Normalized) ->
  228. Normalized.
  229. prioritize_accept(Accept) ->
  230. lists:sort(
  231. fun ({MediaTypeA, Quality, _AcceptParamsA},
  232. {MediaTypeB, Quality, _AcceptParamsB}) ->
  233. %% Same quality, check precedence in more details.
  234. prioritize_mediatype(MediaTypeA, MediaTypeB);
  235. ({_MediaTypeA, QualityA, _AcceptParamsA},
  236. {_MediaTypeB, QualityB, _AcceptParamsB}) ->
  237. %% Just compare the quality.
  238. QualityA > QualityB
  239. end, Accept).
  240. %% Media ranges can be overridden by more specific media ranges or
  241. %% specific media types. If more than one media range applies to a given
  242. %% type, the most specific reference has precedence.
  243. %%
  244. %% We always choose B over A when we can't decide between the two.
  245. prioritize_mediatype({TypeA, SubTypeA, ParamsA}, {TypeB, SubTypeB, ParamsB}) ->
  246. case TypeB of
  247. TypeA ->
  248. case SubTypeB of
  249. SubTypeA -> length(ParamsA) > length(ParamsB);
  250. <<"*">> -> true;
  251. _Any -> false
  252. end;
  253. <<"*">> -> true;
  254. _Any -> false
  255. end.
  256. %% Ignoring the rare AcceptParams. Not sure what should be done about them.
  257. choose_media_type(Req, State, []) ->
  258. not_acceptable(Req, State);
  259. choose_media_type(Req, State=#state{content_types_p=CTP},
  260. [MediaType|Tail]) ->
  261. match_media_type(Req, State, Tail, CTP, MediaType).
  262. match_media_type(Req, State, Accept, [], _MediaType) ->
  263. choose_media_type(Req, State, Accept);
  264. match_media_type(Req, State, Accept, CTP,
  265. MediaType = {{<<"*">>, <<"*">>, _Params_A}, _QA, _APA}) ->
  266. match_media_type_params(Req, State, Accept, CTP, MediaType);
  267. match_media_type(Req, State, Accept,
  268. CTP = [{{Type, SubType_P, _PP}, _Fun}|_Tail],
  269. MediaType = {{Type, SubType_A, _PA}, _QA, _APA})
  270. when SubType_P =:= SubType_A; SubType_A =:= <<"*">> ->
  271. match_media_type_params(Req, State, Accept, CTP, MediaType);
  272. match_media_type(Req, State, Accept, [_Any|Tail], MediaType) ->
  273. match_media_type(Req, State, Accept, Tail, MediaType).
  274. match_media_type_params(Req, State, _Accept,
  275. [Provided = {{TP, STP, '*'}, _Fun}|_Tail],
  276. {{_TA, _STA, Params_A}, _QA, _APA}) ->
  277. PMT = {TP, STP, Params_A},
  278. languages_provided(cowboy_req:set_meta(media_type, PMT, Req),
  279. State#state{content_type_a=Provided});
  280. match_media_type_params(Req, State, Accept,
  281. [Provided = {PMT = {_TP, _STP, Params_P}, _Fun}|Tail],
  282. MediaType = {{_TA, _STA, Params_A}, _QA, _APA}) ->
  283. case lists:sort(Params_P) =:= lists:sort(Params_A) of
  284. true ->
  285. languages_provided(cowboy_req:set_meta(media_type, PMT, Req),
  286. State#state{content_type_a=Provided});
  287. false ->
  288. match_media_type(Req, State, Accept, Tail, MediaType)
  289. end.
  290. %% languages_provided should return a list of binary values indicating
  291. %% which languages are accepted by the resource.
  292. %%
  293. %% @todo I suppose we should also ask the resource if it wants to
  294. %% set a language itself or if it wants it to be automatically chosen.
  295. languages_provided(Req, State) ->
  296. case call(Req, State, languages_provided) of
  297. no_call ->
  298. charsets_provided(Req, State);
  299. {halt, Req2, HandlerState} ->
  300. terminate(Req2, State#state{handler_state=HandlerState});
  301. {[], Req2, HandlerState} ->
  302. not_acceptable(Req2, State#state{handler_state=HandlerState});
  303. {LP, Req2, HandlerState} ->
  304. State2 = State#state{handler_state=HandlerState, languages_p=LP},
  305. case cowboy_req:parse_header(<<"accept-language">>, Req2) of
  306. undefined ->
  307. set_language(Req2, State2#state{language_a=hd(LP)});
  308. AcceptLanguage ->
  309. AcceptLanguage2 = prioritize_languages(AcceptLanguage),
  310. choose_language(Req2, State2, AcceptLanguage2)
  311. end
  312. end.
  313. %% A language-range matches a language-tag if it exactly equals the tag,
  314. %% or if it exactly equals a prefix of the tag such that the first tag
  315. %% character following the prefix is "-". The special range "*", if
  316. %% present in the Accept-Language field, matches every tag not matched
  317. %% by any other range present in the Accept-Language field.
  318. %%
  319. %% @todo The last sentence probably means we should always put '*'
  320. %% at the end of the list.
  321. prioritize_languages(AcceptLanguages) ->
  322. lists:sort(
  323. fun ({_TagA, QualityA}, {_TagB, QualityB}) ->
  324. QualityA > QualityB
  325. end, AcceptLanguages).
  326. choose_language(Req, State, []) ->
  327. not_acceptable(Req, State);
  328. choose_language(Req, State=#state{languages_p=LP}, [Language|Tail]) ->
  329. match_language(Req, State, Tail, LP, Language).
  330. match_language(Req, State, Accept, [], _Language) ->
  331. choose_language(Req, State, Accept);
  332. match_language(Req, State, _Accept, [Provided|_Tail], {'*', _Quality}) ->
  333. set_language(Req, State#state{language_a=Provided});
  334. match_language(Req, State, _Accept, [Provided|_Tail], {Provided, _Quality}) ->
  335. set_language(Req, State#state{language_a=Provided});
  336. match_language(Req, State, Accept, [Provided|Tail],
  337. Language = {Tag, _Quality}) ->
  338. Length = byte_size(Tag),
  339. case Provided of
  340. << Tag:Length/binary, $-, _Any/bits >> ->
  341. set_language(Req, State#state{language_a=Provided});
  342. _Any ->
  343. match_language(Req, State, Accept, Tail, Language)
  344. end.
  345. set_language(Req, State=#state{language_a=Language}) ->
  346. Req2 = cowboy_req:set_resp_header(<<"content-language">>, Language, Req),
  347. charsets_provided(cowboy_req:set_meta(language, Language, Req2), State).
  348. %% charsets_provided should return a list of binary values indicating
  349. %% which charsets are accepted by the resource.
  350. charsets_provided(Req, State) ->
  351. case call(Req, State, charsets_provided) of
  352. no_call ->
  353. set_content_type(Req, State);
  354. {halt, Req2, HandlerState} ->
  355. terminate(Req2, State#state{handler_state=HandlerState});
  356. {[], Req2, HandlerState} ->
  357. not_acceptable(Req2, State#state{handler_state=HandlerState});
  358. {CP, Req2, HandlerState} ->
  359. State2 = State#state{handler_state=HandlerState, charsets_p=CP},
  360. case cowboy_req:parse_header(<<"accept-charset">>, Req2) of
  361. undefined ->
  362. set_content_type(Req2, State2#state{charset_a=hd(CP)});
  363. AcceptCharset ->
  364. AcceptCharset2 = prioritize_charsets(AcceptCharset),
  365. choose_charset(Req2, State2, AcceptCharset2)
  366. end
  367. end.
  368. %% The special value "*", if present in the Accept-Charset field,
  369. %% matches every character set (including ISO-8859-1) which is not
  370. %% mentioned elsewhere in the Accept-Charset field. If no "*" is present
  371. %% in an Accept-Charset field, then all character sets not explicitly
  372. %% mentioned get a quality value of 0, except for ISO-8859-1, which gets
  373. %% a quality value of 1 if not explicitly mentioned.
  374. prioritize_charsets(AcceptCharsets) ->
  375. AcceptCharsets2 = lists:sort(
  376. fun ({_CharsetA, QualityA}, {_CharsetB, QualityB}) ->
  377. QualityA > QualityB
  378. end, AcceptCharsets),
  379. case lists:keymember(<<"*">>, 1, AcceptCharsets2) of
  380. true -> AcceptCharsets2;
  381. false ->
  382. case lists:keymember(<<"iso-8859-1">>, 1, AcceptCharsets2) of
  383. true -> AcceptCharsets2;
  384. false -> [{<<"iso-8859-1">>, 1000}|AcceptCharsets2]
  385. end
  386. end.
  387. choose_charset(Req, State, []) ->
  388. not_acceptable(Req, State);
  389. choose_charset(Req, State=#state{charsets_p=CP}, [Charset|Tail]) ->
  390. match_charset(Req, State, Tail, CP, Charset).
  391. match_charset(Req, State, Accept, [], _Charset) ->
  392. choose_charset(Req, State, Accept);
  393. match_charset(Req, State, _Accept, [Provided|_], {Provided, _}) ->
  394. set_content_type(Req, State#state{charset_a=Provided});
  395. match_charset(Req, State, Accept, [_|Tail], Charset) ->
  396. match_charset(Req, State, Accept, Tail, Charset).
  397. set_content_type(Req, State=#state{
  398. content_type_a={{Type, SubType, Params}, _Fun},
  399. charset_a=Charset}) ->
  400. ParamsBin = set_content_type_build_params(Params, []),
  401. ContentType = [Type, <<"/">>, SubType, ParamsBin],
  402. ContentType2 = case Charset of
  403. undefined -> ContentType;
  404. Charset -> [ContentType, <<"; charset=">>, Charset]
  405. end,
  406. Req2 = cowboy_req:set_resp_header(<<"content-type">>, ContentType2, Req),
  407. encodings_provided(cowboy_req:set_meta(charset, Charset, Req2), State).
  408. set_content_type_build_params('*', []) ->
  409. <<>>;
  410. set_content_type_build_params([], []) ->
  411. <<>>;
  412. set_content_type_build_params([], Acc) ->
  413. lists:reverse(Acc);
  414. set_content_type_build_params([{Attr, Value}|Tail], Acc) ->
  415. set_content_type_build_params(Tail, [[Attr, <<"=">>, Value], <<";">>|Acc]).
  416. %% @todo Match for identity as we provide nothing else for now.
  417. %% @todo Don't forget to set the Content-Encoding header when we reply a body
  418. %% and the found encoding is something other than identity.
  419. encodings_provided(Req, State) ->
  420. variances(Req, State).
  421. not_acceptable(Req, State) ->
  422. respond(Req, State, 406).
  423. %% variances/2 should return a list of headers that will be added
  424. %% to the Vary response header. The Accept, Accept-Language,
  425. %% Accept-Charset and Accept-Encoding headers do not need to be
  426. %% specified.
  427. %%
  428. %% @todo Do Accept-Encoding too when we handle it.
  429. %% @todo Does the order matter?
  430. variances(Req, State=#state{content_types_p=CTP,
  431. languages_p=LP, charsets_p=CP}) ->
  432. Variances = case CTP of
  433. [] -> [];
  434. [_] -> [];
  435. [_|_] -> [<<"accept">>]
  436. end,
  437. Variances2 = case LP of
  438. [] -> Variances;
  439. [_] -> Variances;
  440. [_|_] -> [<<"accept-language">>|Variances]
  441. end,
  442. Variances3 = case CP of
  443. [] -> Variances2;
  444. [_] -> Variances2;
  445. [_|_] -> [<<"accept-charset">>|Variances2]
  446. end,
  447. try variances(Req, State, Variances3) of
  448. {Variances4, Req2, State2} ->
  449. case [[<<", ">>, V] || V <- Variances4] of
  450. [] ->
  451. resource_exists(Req2, State2);
  452. [[<<", ">>, H]|Variances5] ->
  453. Req3 = cowboy_req:set_resp_header(
  454. <<"vary">>, [H|Variances5], Req2),
  455. resource_exists(Req3, State2)
  456. end
  457. catch Class:Reason ->
  458. error_terminate(Req, State, Class, Reason, variances)
  459. end.
  460. variances(Req, State, Variances) ->
  461. case unsafe_call(Req, State, variances) of
  462. no_call ->
  463. {Variances, Req, State};
  464. {HandlerVariances, Req2, HandlerState} ->
  465. {Variances ++ HandlerVariances, Req2,
  466. State#state{handler_state=HandlerState}}
  467. end.
  468. resource_exists(Req, State) ->
  469. expect(Req, State, resource_exists, true,
  470. fun if_match_exists/2, fun if_match_must_not_exist/2).
  471. if_match_exists(Req, State) ->
  472. State2 = State#state{exists=true},
  473. case cowboy_req:parse_header(<<"if-match">>, Req) of
  474. undefined ->
  475. if_unmodified_since_exists(Req, State2);
  476. '*' ->
  477. if_unmodified_since_exists(Req, State2);
  478. ETagsList ->
  479. if_match(Req, State2, ETagsList)
  480. end.
  481. if_match(Req, State, EtagsList) ->
  482. try generate_etag(Req, State) of
  483. {Etag, Req2, State2} ->
  484. case lists:member(Etag, EtagsList) of
  485. true -> if_unmodified_since_exists(Req2, State2);
  486. %% Etag may be `undefined' which cannot be a member.
  487. false -> precondition_failed(Req2, State2)
  488. end
  489. catch Class:Reason ->
  490. error_terminate(Req, State, Class, Reason, generate_etag)
  491. end.
  492. if_match_must_not_exist(Req, State) ->
  493. case cowboy_req:header(<<"if-match">>, Req) of
  494. undefined -> is_put_to_missing_resource(Req, State);
  495. _ -> precondition_failed(Req, State)
  496. end.
  497. if_unmodified_since_exists(Req, State) ->
  498. try cowboy_req:parse_header(<<"if-unmodified-since">>, Req) of
  499. undefined ->
  500. if_none_match_exists(Req, State);
  501. IfUnmodifiedSince ->
  502. if_unmodified_since(Req, State, IfUnmodifiedSince)
  503. catch _:_ ->
  504. if_none_match_exists(Req, State)
  505. end.
  506. %% If LastModified is the atom 'no_call', we continue.
  507. if_unmodified_since(Req, State, IfUnmodifiedSince) ->
  508. try last_modified(Req, State) of
  509. {LastModified, Req2, State2} ->
  510. case LastModified > IfUnmodifiedSince of
  511. true -> precondition_failed(Req2, State2);
  512. false -> if_none_match_exists(Req2, State2)
  513. end
  514. catch Class:Reason ->
  515. error_terminate(Req, State, Class, Reason, last_modified)
  516. end.
  517. if_none_match_exists(Req, State) ->
  518. case cowboy_req:parse_header(<<"if-none-match">>, Req) of
  519. undefined ->
  520. if_modified_since_exists(Req, State);
  521. '*' ->
  522. precondition_is_head_get(Req, State);
  523. EtagsList ->
  524. if_none_match(Req, State, EtagsList)
  525. end.
  526. if_none_match(Req, State, EtagsList) ->
  527. try generate_etag(Req, State) of
  528. {Etag, Req2, State2} ->
  529. case Etag of
  530. undefined ->
  531. precondition_failed(Req2, State2);
  532. Etag ->
  533. case lists:member(Etag, EtagsList) of
  534. true -> precondition_is_head_get(Req2, State2);
  535. false -> if_modified_since_exists(Req2, State2)
  536. end
  537. end
  538. catch Class:Reason ->
  539. error_terminate(Req, State, Class, Reason, generate_etag)
  540. end.
  541. precondition_is_head_get(Req, State=#state{method=Method})
  542. when Method =:= <<"HEAD">>; Method =:= <<"GET">> ->
  543. not_modified(Req, State);
  544. precondition_is_head_get(Req, State) ->
  545. precondition_failed(Req, State).
  546. if_modified_since_exists(Req, State) ->
  547. try cowboy_req:parse_header(<<"if-modified-since">>, Req) of
  548. undefined ->
  549. method(Req, State);
  550. IfModifiedSince ->
  551. if_modified_since_now(Req, State, IfModifiedSince)
  552. catch _:_ ->
  553. method(Req, State)
  554. end.
  555. if_modified_since_now(Req, State, IfModifiedSince) ->
  556. case IfModifiedSince > erlang:universaltime() of
  557. true -> method(Req, State);
  558. false -> if_modified_since(Req, State, IfModifiedSince)
  559. end.
  560. if_modified_since(Req, State, IfModifiedSince) ->
  561. try last_modified(Req, State) of
  562. {no_call, Req2, State2} ->
  563. method(Req2, State2);
  564. {LastModified, Req2, State2} ->
  565. case LastModified > IfModifiedSince of
  566. true -> method(Req2, State2);
  567. false -> not_modified(Req2, State2)
  568. end
  569. catch Class:Reason ->
  570. error_terminate(Req, State, Class, Reason, last_modified)
  571. end.
  572. not_modified(Req, State) ->
  573. Req2 = cowboy_req:delete_resp_header(<<"content-type">>, Req),
  574. try set_resp_etag(Req2, State) of
  575. {Req3, State2} ->
  576. try set_resp_expires(Req3, State2) of
  577. {Req4, State3} ->
  578. respond(Req4, State3, 304)
  579. catch Class:Reason ->
  580. error_terminate(Req, State, Class, Reason, expires)
  581. end
  582. catch Class:Reason ->
  583. error_terminate(Req, State, Class, Reason, generate_etag)
  584. end.
  585. precondition_failed(Req, State) ->
  586. respond(Req, State, 412).
  587. is_put_to_missing_resource(Req, State=#state{method= <<"PUT">>}) ->
  588. moved_permanently(Req, State, fun is_conflict/2);
  589. is_put_to_missing_resource(Req, State) ->
  590. previously_existed(Req, State).
  591. %% moved_permanently/2 should return either false or {true, Location}
  592. %% with Location the full new URI of the resource.
  593. moved_permanently(Req, State, OnFalse) ->
  594. case call(Req, State, moved_permanently) of
  595. {{true, Location}, Req2, HandlerState} ->
  596. Req3 = cowboy_req:set_resp_header(
  597. <<"location">>, Location, Req2),
  598. respond(Req3, State#state{handler_state=HandlerState}, 301);
  599. {false, Req2, HandlerState} ->
  600. OnFalse(Req2, State#state{handler_state=HandlerState});
  601. {halt, Req2, HandlerState} ->
  602. terminate(Req2, State#state{handler_state=HandlerState});
  603. no_call ->
  604. OnFalse(Req, State)
  605. end.
  606. previously_existed(Req, State) ->
  607. expect(Req, State, previously_existed, false,
  608. fun (R, S) -> is_post_to_missing_resource(R, S, 404) end,
  609. fun (R, S) -> moved_permanently(R, S, fun moved_temporarily/2) end).
  610. %% moved_temporarily/2 should return either false or {true, Location}
  611. %% with Location the full new URI of the resource.
  612. moved_temporarily(Req, State) ->
  613. case call(Req, State, moved_temporarily) of
  614. {{true, Location}, Req2, HandlerState} ->
  615. Req3 = cowboy_req:set_resp_header(
  616. <<"location">>, Location, Req2),
  617. respond(Req3, State#state{handler_state=HandlerState}, 307);
  618. {false, Req2, HandlerState} ->
  619. is_post_to_missing_resource(Req2, State#state{handler_state=HandlerState}, 410);
  620. {halt, Req2, HandlerState} ->
  621. terminate(Req2, State#state{handler_state=HandlerState});
  622. no_call ->
  623. is_post_to_missing_resource(Req, State, 410)
  624. end.
  625. is_post_to_missing_resource(Req, State=#state{method= <<"POST">>}, OnFalse) ->
  626. allow_missing_post(Req, State, OnFalse);
  627. is_post_to_missing_resource(Req, State, OnFalse) ->
  628. respond(Req, State, OnFalse).
  629. allow_missing_post(Req, State, OnFalse) ->
  630. expect(Req, State, allow_missing_post, true, fun accept_resource/2, OnFalse).
  631. method(Req, State=#state{method= <<"DELETE">>}) ->
  632. delete_resource(Req, State);
  633. method(Req, State=#state{method= <<"PUT">>}) ->
  634. is_conflict(Req, State);
  635. method(Req, State=#state{method=Method})
  636. when Method =:= <<"POST">>; Method =:= <<"PATCH">> ->
  637. accept_resource(Req, State);
  638. method(Req, State=#state{method=Method})
  639. when Method =:= <<"GET">>; Method =:= <<"HEAD">> ->
  640. set_resp_body_etag(Req, State);
  641. method(Req, State) ->
  642. multiple_choices(Req, State).
  643. %% delete_resource/2 should start deleting the resource and return.
  644. delete_resource(Req, State) ->
  645. expect(Req, State, delete_resource, false, 500, fun delete_completed/2).
  646. %% delete_completed/2 indicates whether the resource has been deleted yet.
  647. delete_completed(Req, State) ->
  648. expect(Req, State, delete_completed, true, fun has_resp_body/2, 202).
  649. is_conflict(Req, State) ->
  650. expect(Req, State, is_conflict, false, fun accept_resource/2, 409).
  651. %% content_types_accepted should return a list of media types and their
  652. %% associated callback functions in the same format as content_types_provided.
  653. %%
  654. %% The callback will then be called and is expected to process the content
  655. %% pushed to the resource in the request body.
  656. %%
  657. %% content_types_accepted SHOULD return a different list
  658. %% for each HTTP method.
  659. accept_resource(Req, State) ->
  660. case call(Req, State, content_types_accepted) of
  661. no_call ->
  662. respond(Req, State, 415);
  663. {halt, Req2, HandlerState} ->
  664. terminate(Req2, State#state{handler_state=HandlerState});
  665. {CTA, Req2, HandlerState} ->
  666. CTA2 = [normalize_content_types(P) || P <- CTA],
  667. State2 = State#state{handler_state=HandlerState},
  668. try cowboy_req:parse_header(<<"content-type">>, Req2) of
  669. ContentType ->
  670. choose_content_type(Req2, State2, ContentType, CTA2)
  671. catch _:_ ->
  672. respond(Req2, State2, 415)
  673. end
  674. end.
  675. %% The special content type '*' will always match. It can be used as a
  676. %% catch-all content type for accepting any kind of request content.
  677. %% Note that because it will always match, it should be the last of the
  678. %% list of content types, otherwise it'll shadow the ones following.
  679. choose_content_type(Req, State, _ContentType, []) ->
  680. respond(Req, State, 415);
  681. choose_content_type(Req, State, ContentType, [{Accepted, Fun}|_Tail])
  682. when Accepted =:= '*'; Accepted =:= ContentType ->
  683. process_content_type(Req, State, Fun);
  684. %% The special parameter '*' will always match any kind of content type
  685. %% parameters.
  686. %% Note that because it will always match, it should be the last of the
  687. %% list for specific content type, otherwise it'll shadow the ones following.
  688. choose_content_type(Req, State, {Type, SubType, Param},
  689. [{{Type, SubType, AcceptedParam}, Fun}|_Tail])
  690. when AcceptedParam =:= '*'; AcceptedParam =:= Param ->
  691. process_content_type(Req, State, Fun);
  692. choose_content_type(Req, State, ContentType, [_Any|Tail]) ->
  693. choose_content_type(Req, State, ContentType, Tail).
  694. process_content_type(Req, State=#state{method=Method, exists=Exists}, Fun) ->
  695. try case call(Req, State, Fun) of
  696. {halt, Req2, HandlerState2} ->
  697. terminate(Req2, State#state{handler_state=HandlerState2});
  698. {true, Req2, HandlerState2} when Exists ->
  699. State2 = State#state{handler_state=HandlerState2},
  700. next(Req2, State2, fun has_resp_body/2);
  701. {true, Req2, HandlerState2} ->
  702. State2 = State#state{handler_state=HandlerState2},
  703. next(Req2, State2, fun maybe_created/2);
  704. {false, Req2, HandlerState2} ->
  705. State2 = State#state{handler_state=HandlerState2},
  706. respond(Req2, State2, 400);
  707. {{true, ResURL}, Req2, HandlerState2} when Method =:= <<"POST">> ->
  708. State2 = State#state{handler_state=HandlerState2},
  709. Req3 = cowboy_req:set_resp_header(
  710. <<"location">>, ResURL, Req2),
  711. if
  712. Exists -> respond(Req3, State2, 303);
  713. true -> respond(Req3, State2, 201)
  714. end
  715. end catch Class:Reason = {case_clause, no_call} ->
  716. error_terminate(Req, State, Class, Reason, Fun)
  717. end.
  718. %% If PUT was used then the resource has been created at the current URL.
  719. %% Otherwise, if a location header has been set then the resource has been
  720. %% created at a new URL. If not, send a 200 or 204 as expected from a
  721. %% POST or PATCH request.
  722. maybe_created(Req, State=#state{method= <<"PUT">>}) ->
  723. respond(Req, State, 201);
  724. maybe_created(Req, State) ->
  725. case cowboy_req:has_resp_header(<<"location">>, Req) of
  726. true -> respond(Req, State, 201);
  727. false -> has_resp_body(Req, State)
  728. end.
  729. has_resp_body(Req, State) ->
  730. case cowboy_req:has_resp_body(Req) of
  731. true -> multiple_choices(Req, State);
  732. false -> respond(Req, State, 204)
  733. end.
  734. %% Set the Etag header if any for the response provided.
  735. set_resp_body_etag(Req, State) ->
  736. try set_resp_etag(Req, State) of
  737. {Req2, State2} ->
  738. set_resp_body_last_modified(Req2, State2)
  739. catch Class:Reason ->
  740. error_terminate(Req, State, Class, Reason, generate_etag)
  741. end.
  742. %% Set the Last-Modified header if any for the response provided.
  743. set_resp_body_last_modified(Req, State) ->
  744. try last_modified(Req, State) of
  745. {LastModified, Req2, State2} ->
  746. case LastModified of
  747. LastModified when is_atom(LastModified) ->
  748. set_resp_body_expires(Req2, State2);
  749. LastModified ->
  750. LastModifiedBin = cowboy_clock:rfc1123(LastModified),
  751. Req3 = cowboy_req:set_resp_header(
  752. <<"last-modified">>, LastModifiedBin, Req2),
  753. set_resp_body_expires(Req3, State2)
  754. end
  755. catch Class:Reason ->
  756. error_terminate(Req, State, Class, Reason, last_modified)
  757. end.
  758. %% Set the Expires header if any for the response provided.
  759. set_resp_body_expires(Req, State) ->
  760. try set_resp_expires(Req, State) of
  761. {Req2, State2} ->
  762. set_resp_body(Req2, State2)
  763. catch Class:Reason ->
  764. error_terminate(Req, State, Class, Reason, expires)
  765. end.
  766. %% Set the response headers and call the callback found using
  767. %% content_types_provided/2 to obtain the request body and add
  768. %% it to the response.
  769. set_resp_body(Req, State=#state{content_type_a={_, Callback}}) ->
  770. try case call(Req, State, Callback) of
  771. {halt, Req2, HandlerState2} ->
  772. terminate(Req2, State#state{handler_state=HandlerState2});
  773. {Body, Req2, HandlerState2} ->
  774. State2 = State#state{handler_state=HandlerState2},
  775. Req3 = case Body of
  776. {stream, StreamFun} ->
  777. cowboy_req:set_resp_body_fun(StreamFun, Req2);
  778. {stream, Len, StreamFun} ->
  779. cowboy_req:set_resp_body_fun(Len, StreamFun, Req2);
  780. {chunked, StreamFun} ->
  781. cowboy_req:set_resp_body_fun(chunked, StreamFun, Req2);
  782. _Contents ->
  783. cowboy_req:set_resp_body(Body, Req2)
  784. end,
  785. multiple_choices(Req3, State2)
  786. end catch Class:Reason = {case_clause, no_call} ->
  787. error_terminate(Req, State, Class, Reason, Callback)
  788. end.
  789. multiple_choices(Req, State) ->
  790. expect(Req, State, multiple_choices, false, 200, 300).
  791. %% Response utility functions.
  792. set_resp_etag(Req, State) ->
  793. {Etag, Req2, State2} = generate_etag(Req, State),
  794. case Etag of
  795. undefined ->
  796. {Req2, State2};
  797. Etag ->
  798. Req3 = cowboy_req:set_resp_header(
  799. <<"etag">>, encode_etag(Etag), Req2),
  800. {Req3, State2}
  801. end.
  802. -spec encode_etag({strong | weak, binary()}) -> iolist().
  803. encode_etag({strong, Etag}) -> [$",Etag,$"];
  804. encode_etag({weak, Etag}) -> ["W/\"",Etag,$"].
  805. set_resp_expires(Req, State) ->
  806. {Expires, Req2, State2} = expires(Req, State),
  807. case Expires of
  808. Expires when is_atom(Expires) ->
  809. {Req2, State2};
  810. Expires when is_binary(Expires) ->
  811. Req3 = cowboy_req:set_resp_header(
  812. <<"expires">>, Expires, Req2),
  813. {Req3, State2};
  814. Expires ->
  815. ExpiresBin = cowboy_clock:rfc1123(Expires),
  816. Req3 = cowboy_req:set_resp_header(
  817. <<"expires">>, ExpiresBin, Req2),
  818. {Req3, State2}
  819. end.
  820. %% Info retrieval. No logic.
  821. generate_etag(Req, State=#state{etag=no_call}) ->
  822. {undefined, Req, State};
  823. generate_etag(Req, State=#state{etag=undefined}) ->
  824. case unsafe_call(Req, State, generate_etag) of
  825. no_call ->
  826. {undefined, Req, State#state{etag=no_call}};
  827. {Etag, Req2, HandlerState} when is_binary(Etag) ->
  828. [Etag2] = cowboy_http:entity_tag_match(Etag),
  829. {Etag2, Req2, State#state{handler_state=HandlerState, etag=Etag2}};
  830. {Etag, Req2, HandlerState} ->
  831. {Etag, Req2, State#state{handler_state=HandlerState, etag=Etag}}
  832. end;
  833. generate_etag(Req, State=#state{etag=Etag}) ->
  834. {Etag, Req, State}.
  835. last_modified(Req, State=#state{last_modified=no_call}) ->
  836. {undefined, Req, State};
  837. last_modified(Req, State=#state{last_modified=undefined}) ->
  838. case unsafe_call(Req, State, last_modified) of
  839. no_call ->
  840. {undefined, Req, State#state{last_modified=no_call}};
  841. {LastModified, Req2, HandlerState} ->
  842. {LastModified, Req2, State#state{handler_state=HandlerState,
  843. last_modified=LastModified}}
  844. end;
  845. last_modified(Req, State=#state{last_modified=LastModified}) ->
  846. {LastModified, Req, State}.
  847. expires(Req, State=#state{expires=no_call}) ->
  848. {undefined, Req, State};
  849. expires(Req, State=#state{expires=undefined}) ->
  850. case unsafe_call(Req, State, expires) of
  851. no_call ->
  852. {undefined, Req, State#state{expires=no_call}};
  853. {Expires, Req2, HandlerState} ->
  854. {Expires, Req2, State#state{handler_state=HandlerState,
  855. expires=Expires}}
  856. end;
  857. expires(Req, State=#state{expires=Expires}) ->
  858. {Expires, Req, State}.
  859. %% REST primitives.
  860. expect(Req, State, Callback, Expected, OnTrue, OnFalse) ->
  861. case call(Req, State, Callback) of
  862. no_call ->
  863. next(Req, State, OnTrue);
  864. {halt, Req2, HandlerState} ->
  865. terminate(Req2, State#state{handler_state=HandlerState});
  866. {Expected, Req2, HandlerState} ->
  867. next(Req2, State#state{handler_state=HandlerState}, OnTrue);
  868. {_Unexpected, Req2, HandlerState} ->
  869. next(Req2, State#state{handler_state=HandlerState}, OnFalse)
  870. end.
  871. call(Req, State=#state{handler=Handler, handler_state=HandlerState},
  872. Callback) ->
  873. case erlang:function_exported(Handler, Callback, 2) of
  874. true ->
  875. try
  876. Handler:Callback(Req, HandlerState)
  877. catch Class:Reason ->
  878. error_terminate(Req, State, Class, Reason, Callback)
  879. end;
  880. false ->
  881. no_call
  882. end.
  883. unsafe_call(Req, #state{handler=Handler, handler_state=HandlerState},
  884. Callback) ->
  885. case erlang:function_exported(Handler, Callback, 2) of
  886. true -> Handler:Callback(Req, HandlerState);
  887. false -> no_call
  888. end.
  889. next(Req, State, Next) when is_function(Next) ->
  890. Next(Req, State);
  891. next(Req, State, StatusCode) when is_integer(StatusCode) ->
  892. respond(Req, State, StatusCode).
  893. respond(Req, State, StatusCode) ->
  894. terminate(cowboy_req:reply(StatusCode, Req), State).
  895. terminate(Req, State=#state{env=Env}) ->
  896. rest_terminate(Req, State),
  897. {ok, Req, [{result, ok}|Env]}.
  898. error_terminate(Req, State=#state{handler=Handler, handler_state=HandlerState},
  899. Class, Reason, Callback) ->
  900. rest_terminate(Req, State),
  901. Stacktrace = erlang:get_stacktrace(),
  902. cowboy_req:maybe_reply(Stacktrace, Req),
  903. erlang:Class([
  904. {reason, Reason},
  905. {mfa, {Handler, Callback, 2}},
  906. {stacktrace, Stacktrace},
  907. {req, cowboy_req:to_list(Req)},
  908. {state, HandlerState}
  909. ]).
  910. rest_terminate(Req, #state{handler=Handler, handler_state=HandlerState}) ->
  911. case erlang:function_exported(Handler, rest_terminate, 2) of
  912. true -> ok = Handler:rest_terminate(
  913. cowboy_req:lock(Req), HandlerState);
  914. false -> ok
  915. end.