cowboy_rest.erl 33 KB

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