cowboy_rest.erl 33 KB

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