cowboy_rest.erl 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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 :: cowboy_http:method(),
  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(), atom()}],
  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. -include("http.hrl").
  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(pid(), module(), any(), Req)
  50. -> {ok, Req} | close when Req::cowboy_req:req().
  51. upgrade(_ListenerPid, Handler, Opts, Req) ->
  52. try
  53. {Method, Req1} = cowboy_req:method(Req),
  54. case erlang:function_exported(Handler, rest_init, 2) of
  55. true ->
  56. case Handler:rest_init(Req1, Opts) of
  57. {ok, Req2, HandlerState} ->
  58. service_available(Req2, #state{method=Method,
  59. handler=Handler, handler_state=HandlerState})
  60. end;
  61. false ->
  62. service_available(Req1, #state{method=Method,
  63. handler=Handler})
  64. end
  65. catch Class:Reason ->
  66. PLReq = cowboy_req:to_list(Req),
  67. error_logger:error_msg(
  68. "** Handler ~p terminating in rest_init/3~n"
  69. " for the reason ~p:~p~n** Options were ~p~n"
  70. "** Request was ~p~n** Stacktrace: ~p~n~n",
  71. [Handler, Class, Reason, Opts, PLReq, erlang:get_stacktrace()]),
  72. {ok, _Req2} = cowboy_req:reply(500, Req),
  73. close
  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 atoms or 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'; Method =:= 'POST';
  81. Method =:= 'PUT'; 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 atoms or 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. {ok, 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. {ok, 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, 413).
  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. An example
  176. %% of such a return value would be:
  177. %% {<<"text/html">>, to_html}
  178. content_types_provided(Req, State) ->
  179. case call(Req, State, content_types_provided) of
  180. no_call ->
  181. not_acceptable(Req, State);
  182. {halt, Req2, HandlerState} ->
  183. terminate(Req2, State#state{handler_state=HandlerState});
  184. {[], Req2, HandlerState} ->
  185. not_acceptable(Req2, State#state{handler_state=HandlerState});
  186. {CTP, Req2, HandlerState} ->
  187. CTP2 = [normalize_content_types(P) || P <- CTP],
  188. State2 = State#state{
  189. handler_state=HandlerState, content_types_p=CTP2},
  190. {Accept, Req3} = cowboy_req:parse_header('Accept', Req2),
  191. case Accept of
  192. undefined ->
  193. {PMT, _Fun} = HeadCTP = hd(CTP2),
  194. languages_provided(
  195. cowboy_req:set_meta(media_type, PMT, Req3),
  196. State2#state{content_type_a=HeadCTP});
  197. Accept ->
  198. Accept2 = prioritize_accept(Accept),
  199. choose_media_type(Req3, State2, Accept2)
  200. end
  201. end.
  202. normalize_content_types({ContentType, Callback})
  203. when is_binary(ContentType) ->
  204. {cowboy_http:content_type(ContentType), Callback};
  205. normalize_content_types(Provided) ->
  206. Provided.
  207. prioritize_accept(Accept) ->
  208. lists:sort(
  209. fun ({MediaTypeA, Quality, _AcceptParamsA},
  210. {MediaTypeB, Quality, _AcceptParamsB}) ->
  211. %% Same quality, check precedence in more details.
  212. prioritize_mediatype(MediaTypeA, MediaTypeB);
  213. ({_MediaTypeA, QualityA, _AcceptParamsA},
  214. {_MediaTypeB, QualityB, _AcceptParamsB}) ->
  215. %% Just compare the quality.
  216. QualityA > QualityB
  217. end, Accept).
  218. %% Media ranges can be overridden by more specific media ranges or
  219. %% specific media types. If more than one media range applies to a given
  220. %% type, the most specific reference has precedence.
  221. %%
  222. %% We always choose B over A when we can't decide between the two.
  223. prioritize_mediatype({TypeA, SubTypeA, ParamsA}, {TypeB, SubTypeB, ParamsB}) ->
  224. case TypeB of
  225. TypeA ->
  226. case SubTypeB of
  227. SubTypeA -> length(ParamsA) > length(ParamsB);
  228. <<"*">> -> true;
  229. _Any -> false
  230. end;
  231. <<"*">> -> true;
  232. _Any -> false
  233. end.
  234. %% Ignoring the rare AcceptParams. Not sure what should be done about them.
  235. choose_media_type(Req, State, []) ->
  236. not_acceptable(Req, State);
  237. choose_media_type(Req, State=#state{content_types_p=CTP},
  238. [MediaType|Tail]) ->
  239. match_media_type(Req, State, Tail, CTP, MediaType).
  240. match_media_type(Req, State, Accept, [], _MediaType) ->
  241. choose_media_type(Req, State, Accept);
  242. match_media_type(Req, State, Accept, CTP,
  243. MediaType = {{<<"*">>, <<"*">>, _Params_A}, _QA, _APA}) ->
  244. match_media_type_params(Req, State, Accept, CTP, MediaType);
  245. match_media_type(Req, State, Accept,
  246. CTP = [{{Type, SubType_P, _PP}, _Fun}|_Tail],
  247. MediaType = {{Type, SubType_A, _PA}, _QA, _APA})
  248. when SubType_P =:= SubType_A; SubType_A =:= <<"*">> ->
  249. match_media_type_params(Req, State, Accept, CTP, MediaType);
  250. match_media_type(Req, State, Accept, [_Any|Tail], MediaType) ->
  251. match_media_type(Req, State, Accept, Tail, MediaType).
  252. match_media_type_params(Req, State, Accept,
  253. [Provided = {PMT = {_TP, _STP, Params_P}, _Fun}|Tail],
  254. MediaType = {{_TA, _STA, Params_A}, _QA, _APA}) ->
  255. case lists:sort(Params_P) =:= lists:sort(Params_A) of
  256. true ->
  257. languages_provided(cowboy_req:set_meta(media_type, PMT, Req),
  258. State#state{content_type_a=Provided});
  259. false ->
  260. match_media_type(Req, State, Accept, Tail, MediaType)
  261. end.
  262. %% languages_provided should return a list of binary values indicating
  263. %% which languages are accepted by the resource.
  264. %%
  265. %% @todo I suppose we should also ask the resource if it wants to
  266. %% set a language itself or if it wants it to be automatically chosen.
  267. languages_provided(Req, State) ->
  268. case call(Req, State, languages_provided) of
  269. no_call ->
  270. charsets_provided(Req, State);
  271. {halt, Req2, HandlerState} ->
  272. terminate(Req2, State#state{handler_state=HandlerState});
  273. {[], Req2, HandlerState} ->
  274. not_acceptable(Req2, State#state{handler_state=HandlerState});
  275. {LP, Req2, HandlerState} ->
  276. State2 = State#state{handler_state=HandlerState, languages_p=LP},
  277. {AcceptLanguage, Req3} =
  278. cowboy_req:parse_header('Accept-Language', Req2),
  279. case AcceptLanguage of
  280. undefined ->
  281. set_language(Req3, State2#state{language_a=hd(LP)});
  282. AcceptLanguage ->
  283. AcceptLanguage2 = prioritize_languages(AcceptLanguage),
  284. choose_language(Req3, State2, AcceptLanguage2)
  285. end
  286. end.
  287. %% A language-range matches a language-tag if it exactly equals the tag,
  288. %% or if it exactly equals a prefix of the tag such that the first tag
  289. %% character following the prefix is "-". The special range "*", if
  290. %% present in the Accept-Language field, matches every tag not matched
  291. %% by any other range present in the Accept-Language field.
  292. %%
  293. %% @todo The last sentence probably means we should always put '*'
  294. %% at the end of the list.
  295. prioritize_languages(AcceptLanguages) ->
  296. lists:sort(
  297. fun ({_TagA, QualityA}, {_TagB, QualityB}) ->
  298. QualityA > QualityB
  299. end, AcceptLanguages).
  300. choose_language(Req, State, []) ->
  301. not_acceptable(Req, State);
  302. choose_language(Req, State=#state{languages_p=LP}, [Language|Tail]) ->
  303. match_language(Req, State, Tail, LP, Language).
  304. match_language(Req, State, Accept, [], _Language) ->
  305. choose_language(Req, State, Accept);
  306. match_language(Req, State, _Accept, [Provided|_Tail], {'*', _Quality}) ->
  307. set_language(Req, State#state{language_a=Provided});
  308. match_language(Req, State, _Accept, [Provided|_Tail], {Provided, _Quality}) ->
  309. set_language(Req, State#state{language_a=Provided});
  310. match_language(Req, State, Accept, [Provided|Tail],
  311. Language = {Tag, _Quality}) ->
  312. Length = byte_size(Tag),
  313. case Provided of
  314. << Tag:Length/binary, $-, _Any/bits >> ->
  315. set_language(Req, State#state{language_a=Provided});
  316. _Any ->
  317. match_language(Req, State, Accept, Tail, Language)
  318. end.
  319. set_language(Req, State=#state{language_a=Language}) ->
  320. {ok, Req2} = cowboy_req:set_resp_header(
  321. <<"Content-Language">>, Language, Req),
  322. charsets_provided(cowboy_req:set_meta(language, Language, Req2), State).
  323. %% charsets_provided should return a list of binary values indicating
  324. %% which charsets are accepted by the resource.
  325. charsets_provided(Req, State) ->
  326. case call(Req, State, charsets_provided) of
  327. no_call ->
  328. set_content_type(Req, State);
  329. {halt, Req2, HandlerState} ->
  330. terminate(Req2, State#state{handler_state=HandlerState});
  331. {[], Req2, HandlerState} ->
  332. not_acceptable(Req2, State#state{handler_state=HandlerState});
  333. {CP, Req2, HandlerState} ->
  334. State2 = State#state{handler_state=HandlerState, charsets_p=CP},
  335. {AcceptCharset, Req3} =
  336. cowboy_req:parse_header('Accept-Charset', Req2),
  337. case AcceptCharset of
  338. undefined ->
  339. set_content_type(Req3, State2#state{
  340. charset_a=element(1, hd(CP))});
  341. AcceptCharset ->
  342. AcceptCharset2 = prioritize_charsets(AcceptCharset),
  343. choose_charset(Req3, State2, AcceptCharset2)
  344. end
  345. end.
  346. %% The special value "*", if present in the Accept-Charset field,
  347. %% matches every character set (including ISO-8859-1) which is not
  348. %% mentioned elsewhere in the Accept-Charset field. If no "*" is present
  349. %% in an Accept-Charset field, then all character sets not explicitly
  350. %% mentioned get a quality value of 0, except for ISO-8859-1, which gets
  351. %% a quality value of 1 if not explicitly mentioned.
  352. prioritize_charsets(AcceptCharsets) ->
  353. AcceptCharsets2 = lists:sort(
  354. fun ({_CharsetA, QualityA}, {_CharsetB, QualityB}) ->
  355. QualityA > QualityB
  356. end, AcceptCharsets),
  357. case lists:keymember(<<"*">>, 1, AcceptCharsets2) of
  358. true -> AcceptCharsets2;
  359. false -> [{<<"iso-8859-1">>, 1000}|AcceptCharsets2]
  360. end.
  361. choose_charset(Req, State, []) ->
  362. not_acceptable(Req, State);
  363. choose_charset(Req, State=#state{charsets_p=CP}, [Charset|Tail]) ->
  364. match_charset(Req, State, Tail, CP, Charset).
  365. match_charset(Req, State, Accept, [], _Charset) ->
  366. choose_charset(Req, State, Accept);
  367. match_charset(Req, State, _Accept, [{Provided, _}|_], {Provided, _}) ->
  368. set_content_type(Req, State#state{charset_a=Provided});
  369. match_charset(Req, State, Accept, [_|Tail], Charset) ->
  370. match_charset(Req, State, Accept, Tail, Charset).
  371. set_content_type(Req, State=#state{
  372. content_type_a={{Type, SubType, Params}, _Fun},
  373. charset_a=Charset}) ->
  374. ParamsBin = set_content_type_build_params(Params, []),
  375. ContentType = [Type, <<"/">>, SubType, ParamsBin],
  376. ContentType2 = case Charset of
  377. undefined -> ContentType;
  378. Charset -> [ContentType, <<"; charset=">>, Charset]
  379. end,
  380. {ok, Req2} = cowboy_req:set_resp_header(
  381. <<"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. {ok, Req4} = cowboy_req:set_resp_header(
  432. <<"Variances">>, [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_musnt_exist/2).
  438. if_match_exists(Req, State) ->
  439. case cowboy_req:parse_header('If-Match', Req) of
  440. {undefined, Req2} ->
  441. if_unmodified_since_exists(Req2, State);
  442. {'*', Req2} ->
  443. if_unmodified_since_exists(Req2, State);
  444. {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_musnt_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. {undefined, Req2} ->
  462. if_none_match_exists(Req2, State);
  463. {{error, badarg}, Req2} ->
  464. if_none_match_exists(Req2, State);
  465. {IfUnmodifiedSince, Req2} ->
  466. if_unmodified_since(Req2, State, IfUnmodifiedSince)
  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. {undefined, Req2} ->
  478. if_modified_since_exists(Req2, State);
  479. {'*', Req2} ->
  480. precondition_is_head_get(Req2, State);
  481. {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. {undefined, Req2} ->
  503. method(Req2, State);
  504. {{error, badarg}, Req2} ->
  505. method(Req2, State);
  506. {IfModifiedSince, Req2} ->
  507. if_modified_since_now(Req2, State, IfModifiedSince)
  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=#http_req{resp_headers=RespHeaders}, State) ->
  526. RespHeaders2 = lists:keydelete(<<"Content-Type">>, 1, RespHeaders),
  527. Req2 = Req#http_req{resp_headers=RespHeaders2},
  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. {ok, 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. {ok, 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. Location = create_path_location(Req2, Path),
  606. State2 = State#state{handler_state=HandlerState},
  607. {ok, Req3} = cowboy_req:set_resp_header(
  608. <<"Location">>, Location, Req2),
  609. put_resource(cowboy_req:set_meta(put_path, Path, Req3),
  610. State2, 303)
  611. end.
  612. create_path_location(#http_req{transport=Transport, host=Host,
  613. port=Port}, Path) ->
  614. TransportName = Transport:name(),
  615. << (create_path_location_protocol(TransportName))/binary, "://",
  616. Host/binary, (create_path_location_port(TransportName, Port))/binary,
  617. Path/binary >>.
  618. create_path_location_protocol(ssl) -> <<"https">>;
  619. create_path_location_protocol(_) -> <<"http">>.
  620. create_path_location_port(ssl, 443) ->
  621. <<>>;
  622. create_path_location_port(tcp, 80) ->
  623. <<>>;
  624. create_path_location_port(_, Port) ->
  625. <<":", (list_to_binary(integer_to_list(Port)))/binary>>.
  626. %% process_post should return true when the POST body could be processed
  627. %% and false when it hasn't, in which case a 500 error is sent.
  628. process_post(Req, State) ->
  629. case call(Req, State, process_post) of
  630. {halt, Req2, HandlerState} ->
  631. terminate(Req2, State#state{handler_state=HandlerState});
  632. {true, Req2, HandlerState} ->
  633. State2 = State#state{handler_state=HandlerState},
  634. next(Req2, State2, fun is_new_resource/2);
  635. {false, Req2, HandlerState} ->
  636. State2 = State#state{handler_state=HandlerState},
  637. respond(Req2, State2, 500)
  638. end.
  639. is_conflict(Req, State) ->
  640. expect(Req, State, is_conflict, false, fun put_resource/2, 409).
  641. put_resource(Req=#http_req{path=RawPath}, State) ->
  642. put_resource(cowboy_req:set_meta(put_path, RawPath, Req),
  643. State, fun is_new_resource/2).
  644. %% content_types_accepted should return a list of media types and their
  645. %% associated callback functions in the same format as content_types_provided.
  646. %%
  647. %% The callback will then be called and is expected to process the content
  648. %% pushed to the resource in the request body. The path to the new resource
  649. %% may be different from the request path, and is stored as request metadata.
  650. %% It is always defined past this point. It can be retrieved as demonstrated:
  651. %% {PutPath, Req2} = cowboy_req:meta(put_path, Req)
  652. put_resource(Req, State, OnTrue) ->
  653. case call(Req, State, content_types_accepted) of
  654. no_call ->
  655. respond(Req, State, 415);
  656. {halt, Req2, HandlerState} ->
  657. terminate(Req2, State#state{handler_state=HandlerState});
  658. {CTA, Req2, HandlerState} ->
  659. CTA2 = [normalize_content_types(P) || P <- CTA],
  660. State2 = State#state{handler_state=HandlerState},
  661. {ContentType, Req3}
  662. = cowboy_req:parse_header('Content-Type', Req2),
  663. choose_content_type(Req3, State2, OnTrue, ContentType, CTA2)
  664. end.
  665. %% The special content type '*' will always match. It can be used as a
  666. %% catch-all content type for accepting any kind of request content.
  667. %% Note that because it will always match, it should be the last of the
  668. %% list of content types, otherwise it'll shadow the ones following.
  669. choose_content_type(Req, State, _OnTrue, _ContentType, []) ->
  670. respond(Req, State, 415);
  671. choose_content_type(Req, State, OnTrue, ContentType, [{Accepted, Fun}|_Tail])
  672. when Accepted =:= '*' orelse Accepted =:= ContentType ->
  673. case call(Req, State, Fun) of
  674. {halt, Req2, HandlerState} ->
  675. terminate(Req2, State#state{handler_state=HandlerState});
  676. {true, Req2, HandlerState} ->
  677. State2 = State#state{handler_state=HandlerState},
  678. next(Req2, State2, OnTrue);
  679. {false, Req2, HandlerState} ->
  680. State2 = State#state{handler_state=HandlerState},
  681. respond(Req2, State2, 500)
  682. end;
  683. choose_content_type(Req, State, OnTrue, ContentType, [_Any|Tail]) ->
  684. choose_content_type(Req, State, OnTrue, ContentType, Tail).
  685. %% Whether we created a new resource, either through PUT or POST.
  686. %% This is easily testable because we would have set the Location
  687. %% header by this point if we did so.
  688. is_new_resource(Req, State) ->
  689. case cowboy_req:has_resp_header(<<"Location">>, Req) of
  690. true -> respond(Req, State, 201);
  691. false -> has_resp_body(Req, State)
  692. end.
  693. has_resp_body(Req, State) ->
  694. case cowboy_req:has_resp_body(Req) of
  695. true -> multiple_choices(Req, State);
  696. false -> respond(Req, State, 204)
  697. end.
  698. %% Set the response headers and call the callback found using
  699. %% content_types_provided/2 to obtain the request body and add
  700. %% it to the response.
  701. set_resp_body(Req, State=#state{content_type_a={_Type, Fun}}) ->
  702. {Req2, State2} = set_resp_etag(Req, State),
  703. {LastModified, Req3, State3} = last_modified(Req2, State2),
  704. case LastModified of
  705. LastModified when is_atom(LastModified) ->
  706. Req4 = Req3;
  707. LastModified ->
  708. LastModifiedStr = httpd_util:rfc1123_date(LastModified),
  709. {ok, Req4} = cowboy_req:set_resp_header(
  710. <<"Last-Modified">>, LastModifiedStr, Req3)
  711. end,
  712. {Req5, State4} = set_resp_expires(Req4, State3),
  713. case call(Req5, State4, Fun) of
  714. {halt, Req6, HandlerState} ->
  715. terminate(Req6, State4#state{handler_state=HandlerState});
  716. {Body, Req6, HandlerState} ->
  717. State5 = State4#state{handler_state=HandlerState},
  718. {ok, Req7} = case Body of
  719. {stream, Len, Fun1} ->
  720. cowboy_req:set_resp_body_fun(Len, Fun1, Req6);
  721. _Contents ->
  722. cowboy_req:set_resp_body(Body, Req6)
  723. end,
  724. multiple_choices(Req7, State5)
  725. end.
  726. multiple_choices(Req, State) ->
  727. expect(Req, State, multiple_choices, false, 200, 300).
  728. %% Response utility functions.
  729. set_resp_etag(Req, State) ->
  730. {Etag, Req2, State2} = generate_etag(Req, State),
  731. case Etag of
  732. undefined ->
  733. {Req2, State2};
  734. Etag ->
  735. {ok, Req3} = cowboy_req:set_resp_header(
  736. <<"ETag">>, encode_etag(Etag), Req2),
  737. {Req3, State2}
  738. end.
  739. -spec encode_etag({strong | weak, binary()}) -> iolist().
  740. encode_etag({strong, Etag}) -> [$",Etag,$"];
  741. encode_etag({weak, Etag}) -> ["W/\"",Etag,$"].
  742. set_resp_expires(Req, State) ->
  743. {Expires, Req2, State2} = expires(Req, State),
  744. case Expires of
  745. Expires when is_atom(Expires) ->
  746. {Req2, State2};
  747. Expires ->
  748. ExpiresStr = httpd_util:rfc1123_date(Expires),
  749. {ok, Req3} = cowboy_req:set_resp_header(
  750. <<"Expires">>, ExpiresStr, Req2),
  751. {Req3, State2}
  752. end.
  753. %% Info retrieval. No logic.
  754. generate_etag(Req, State=#state{etag=no_call}) ->
  755. {undefined, Req, State};
  756. generate_etag(Req, State=#state{etag=undefined}) ->
  757. case call(Req, State, generate_etag) of
  758. no_call ->
  759. {undefined, Req, State#state{etag=no_call}};
  760. %% Previously the return value from the generate_etag/2 callback was set
  761. %% as the value of the ETag header in the response. Therefore the only
  762. %% valid return type was `binary()'. If a handler returns a `binary()'
  763. %% it must be mapped to the expected type or it'll always fail to
  764. %% compare equal to any entity tags present in the request headers.
  765. %% @todo Remove support for binary return values after 0.6.
  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{handler=Handler, handler_state=HandlerState}) ->
  823. case erlang:function_exported(Handler, rest_terminate, 2) of
  824. true -> ok = Handler:rest_terminate(
  825. Req#http_req{resp_state=locked}, HandlerState);
  826. false -> ok
  827. end,
  828. {ok, Req}.