cowboy_http_rest.erl 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. %% Copyright (c) 2011, Loïc Hoguin <essen@dev-extend.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_http_rest).
  21. -export([upgrade/4]).
  22. -record(state, {
  23. %% Handler.
  24. handler :: atom(),
  25. handler_state :: any(),
  26. %% Media type.
  27. content_types_p = [] ::
  28. [{{binary(), binary(), [{binary(), binary()}]}, atom()}],
  29. content_type_a :: undefined
  30. | {{binary(), binary(), [{binary(), binary()}]}, atom()},
  31. %% Language.
  32. languages_p = [] :: [binary()],
  33. language_a :: undefined | binary(),
  34. %% Charset.
  35. charsets_p = [] :: [binary()],
  36. charset_a :: undefined | binary(),
  37. %% Cached resource calls.
  38. etag :: undefined | no_call | binary(),
  39. last_modified :: undefined | no_call | cowboy_clock:datetime(),
  40. expires :: undefined | no_call | cowboy_clock:datetime()
  41. }).
  42. -include("include/http.hrl").
  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(), #http_req{}) -> {ok, #http_req{}}.
  49. upgrade(_ListenerPid, Handler, Opts, Req) ->
  50. try
  51. case erlang:function_exported(Handler, rest_init, 2) of
  52. true ->
  53. case Handler:rest_init(Req, Opts) of
  54. {ok, Req2, HandlerState} ->
  55. service_available(Req2, #state{handler=Handler,
  56. handler_state=HandlerState})
  57. end;
  58. false ->
  59. service_available(Req, #state{handler=Handler})
  60. end
  61. catch Class:Reason ->
  62. error_logger:error_msg(
  63. "** Handler ~p terminating in rest_init/3~n"
  64. " for the reason ~p:~p~n** Options were ~p~n"
  65. "** Request was ~p~n** Stacktrace: ~p~n~n",
  66. [Handler, Class, Reason, Opts, Req, erlang:get_stacktrace()]),
  67. {ok, _Req2} = cowboy_http_req:reply(500, Req),
  68. ok
  69. end.
  70. service_available(Req, State) ->
  71. expect(Req, State, service_available, true, fun known_methods/2, 503).
  72. known_methods(Req=#http_req{method=Method}, State) ->
  73. case call(Req, State, known_methods) of
  74. no_call ->
  75. next(Req, State, fun uri_too_long/2);
  76. {List, Req2, HandlerState2} ->
  77. State2 = State#state{handler_state=HandlerState2},
  78. case lists:member(Method, List) of
  79. true -> next(Req2, State2, fun uri_too_long/2);
  80. false -> next(Req2, State2, 501)
  81. end
  82. end.
  83. uri_too_long(Req, State) ->
  84. expect(Req, State, uri_too_long, false, fun allowed_methods/2, 414).
  85. allowed_methods(Req=#http_req{method=Method}, State) ->
  86. case call(Req, State, allowed_methods) of
  87. no_call ->
  88. next(Req, State, fun malformed_request/2);
  89. {List, Req2, HandlerState2} ->
  90. State2 = State#state{handler_state=HandlerState2},
  91. case lists:member(Method, List) of
  92. true -> next(Req2, State2, fun malformed_request/2);
  93. false -> method_not_allowed(Req2, State2, List)
  94. end
  95. end.
  96. method_not_allowed(Req, State, Methods) ->
  97. {ok, Req2} = cowboy_http_req:set_resp_header(
  98. <<"Allow">>, method_not_allowed_build(Methods, []), Req),
  99. respond(Req2, State, 405).
  100. method_not_allowed_build([], []) ->
  101. <<>>;
  102. method_not_allowed_build([], [_Ignore|Acc]) ->
  103. lists:reverse(Acc);
  104. method_not_allowed_build([Method|Tail], Acc) ->
  105. Method2 = list_to_binary(atom_to_list(Method)),
  106. method_not_allowed_build(Tail, [<<", ">>, Method2|Acc]).
  107. malformed_request(Req, State) ->
  108. expect(Req, State, malformed_request, false, fun is_authorized/2, 400).
  109. is_authorized(Req, State) ->
  110. case call(Req, State, is_authorized) of
  111. no_call ->
  112. forbidden(Req, State);
  113. {true, Req2, HandlerState2} ->
  114. forbidden(Req2, State#state{handler_state=HandlerState2});
  115. {{false, AuthHead}, Req2, HandlerState2} ->
  116. {ok, Req3} = cowboy_http_req:set_resp_header(
  117. <<"Www-Authenticate">>, AuthHead, Req2),
  118. respond(Req3, State#state{handler_state=HandlerState2}, 401)
  119. end.
  120. forbidden(Req, State) ->
  121. expect(Req, State, forbidden, false, fun valid_content_headers/2, 403).
  122. valid_content_headers(Req, State) ->
  123. expect(Req, State, valid_content_headers, true,
  124. fun known_content_type/2, 501).
  125. known_content_type(Req, State) ->
  126. expect(Req, State, known_content_type, true,
  127. fun valid_entity_length/2, 413).
  128. valid_entity_length(Req, State) ->
  129. expect(Req, State, valid_entity_length, true, fun options/2, 413).
  130. options(Req=#http_req{method='OPTIONS'}, State) ->
  131. {ok, Req2, HandlerState2} = call(Req, State, options),
  132. respond(Req2, State#state{handler_state=HandlerState2}, 200);
  133. options(Req, State) ->
  134. content_types_provided(Req, State).
  135. %% The content_types_provided function MUST be defined in the resource
  136. %% from this point onward.
  137. content_types_provided(Req, State) ->
  138. case call(Req, State, content_types_provided) of
  139. no_call ->
  140. not_acceptable(Req, State);
  141. {[], Req2, HandlerState2} ->
  142. not_acceptable(Req2, State#state{handler_state=HandlerState2});
  143. {CTP, Req2, HandlerState2} ->
  144. State2 = State#state{handler_state=HandlerState2, content_types_p=CTP},
  145. {Accept, Req3} = cowboy_http_req:parse_header('Accept', Req2),
  146. case Accept of
  147. undefined ->
  148. languages_provided(Req3,
  149. State2#state{content_type_a=hd(CTP)});
  150. Accept ->
  151. Accept2 = prioritize_accept(Accept),
  152. choose_media_type(Req3, State2, Accept2)
  153. end
  154. end.
  155. prioritize_accept(Accept) ->
  156. lists:sort(
  157. fun ({MediaTypeA, Quality, _AcceptParamsA},
  158. {MediaTypeB, Quality, _AcceptParamsB}) ->
  159. %% Same quality, check precedence in more details.
  160. prioritize_mediatype(MediaTypeA, MediaTypeB);
  161. ({_MediaTypeA, QualityA, _AcceptParamsA},
  162. {_MediaTypeB, QualityB, _AcceptParamsB}) ->
  163. %% Just compare the quality.
  164. QualityA > QualityB
  165. end, Accept).
  166. %% Media ranges can be overridden by more specific media ranges or
  167. %% specific media types. If more than one media range applies to a given
  168. %% type, the most specific reference has precedence.
  169. %%
  170. %% We always choose B over A when we can't decide between the two.
  171. prioritize_mediatype({TypeA, SubTypeA, ParamsA}, {TypeB, SubTypeB, ParamsB}) ->
  172. case TypeB of
  173. TypeA ->
  174. case SubTypeB of
  175. SubTypeA -> length(ParamsA) > length(ParamsB);
  176. <<"*">> -> true;
  177. _Any -> false
  178. end;
  179. <<"*">> -> true;
  180. _Any -> false
  181. end.
  182. %% Ignoring the rare AcceptParams. Not sure what should be done about them.
  183. choose_media_type(Req, State, []) ->
  184. not_acceptable(Req, State);
  185. choose_media_type(Req, State=#state{content_types_p=CTP},
  186. [MediaType|Tail]) ->
  187. match_media_type(Req, State, Tail, CTP, MediaType).
  188. match_media_type(Req, State, Accept, [], _MediaType) ->
  189. choose_media_type(Req, State, Accept);
  190. match_media_type(Req, State, Accept,
  191. [Provided = {{Type, SubType_P, Params_P}, _Fun}|Tail],
  192. MediaType = {{Type, SubType_A, Params_A}, _Quality, _AcceptParams})
  193. when SubType_P =:= SubType_A; SubType_A =:= <<"*">> ->
  194. case lists:sort(Params_P) =:= lists:sort(Params_A) of
  195. true ->
  196. languages_provided(Req, State#state{content_type_a=Provided});
  197. false ->
  198. match_media_type(Req, State, Accept, Tail, MediaType)
  199. end;
  200. match_media_type(Req, State, Accept, [_Any|Tail], MediaType) ->
  201. match_media_type(Req, State, Accept, Tail, MediaType).
  202. %% @todo I suppose we should also ask the resource if it wants to
  203. %% set a language itself or if it wants it to be automatically chosen.
  204. languages_provided(Req, State) ->
  205. case call(Req, State, languages_provided) of
  206. no_call ->
  207. charsets_provided(Req, State);
  208. {[], Req2, HandlerState2} ->
  209. not_acceptable(Req2, State#state{handler_state=HandlerState2});
  210. {LP, Req2, HandlerState2} ->
  211. State2 = State#state{handler_state=HandlerState2, languages_p=LP},
  212. {AcceptLanguage, Req3} =
  213. cowboy_http_req:parse_header('Accept-Language', Req2),
  214. case AcceptLanguage of
  215. undefined ->
  216. set_language(Req3, State2#state{language_a=hd(LP)});
  217. AcceptLanguage ->
  218. AcceptLanguage2 = prioritize_languages(AcceptLanguage),
  219. choose_language(Req3, State2, AcceptLanguage2)
  220. end
  221. end.
  222. %% A language-range matches a language-tag if it exactly equals the tag,
  223. %% or if it exactly equals a prefix of the tag such that the first tag
  224. %% character following the prefix is "-". The special range "*", if
  225. %% present in the Accept-Language field, matches every tag not matched
  226. %% by any other range present in the Accept-Language field.
  227. %%
  228. %% @todo The last sentence probably means we should always put '*'
  229. %% at the end of the list.
  230. prioritize_languages(AcceptLanguages) ->
  231. lists:sort(
  232. fun ({_TagA, QualityA}, {_TagB, QualityB}) ->
  233. QualityA > QualityB
  234. end, AcceptLanguages).
  235. choose_language(Req, State, []) ->
  236. not_acceptable(Req, State);
  237. choose_language(Req, State=#state{languages_p=LP}, [Language|Tail]) ->
  238. match_language(Req, State, Tail, LP, Language).
  239. match_language(Req, State, Accept, [], _Language) ->
  240. choose_language(Req, State, Accept);
  241. match_language(Req, State, _Accept, [Provided|_Tail], {'*', _Quality}) ->
  242. set_language(Req, State#state{language_a=Provided});
  243. match_language(Req, State, _Accept, [Provided|_Tail], {Provided, _Quality}) ->
  244. set_language(Req, State#state{language_a=Provided});
  245. match_language(Req, State, Accept, [Provided|Tail],
  246. Language = {Tag, _Quality}) ->
  247. Length = byte_size(Tag),
  248. case Provided of
  249. << Tag:Length/binary, $-, _Any/bits >> ->
  250. set_language(Req, State#state{language_a=Provided});
  251. _Any ->
  252. match_language(Req, State, Accept, Tail, Language)
  253. end.
  254. set_language(Req, State=#state{language_a=Language}) ->
  255. {ok, Req2} = cowboy_http_req:set_resp_header(
  256. <<"Content-Language">>, Language, Req),
  257. charsets_provided(Req2, State).
  258. charsets_provided(Req, State) ->
  259. case call(Req, State, charsets_provided) of
  260. no_call ->
  261. set_content_type(Req, State);
  262. {[], Req2, HandlerState2} ->
  263. not_acceptable(Req2, State#state{handler_state=HandlerState2});
  264. {CP, Req2, HandlerState2} ->
  265. State2 = State#state{handler_state=HandlerState2, charsets_p=CP},
  266. {AcceptCharset, Req3} =
  267. cowboy_http_req:parse_header('Accept-Charset', Req2),
  268. case AcceptCharset of
  269. undefined ->
  270. set_content_type(Req3, State2#state{charset_a=hd(CP)});
  271. AcceptCharset ->
  272. AcceptCharset2 = prioritize_charsets(AcceptCharset),
  273. choose_charset(Req3, State2, AcceptCharset2)
  274. end
  275. end.
  276. %% The special value "*", if present in the Accept-Charset field,
  277. %% matches every character set (including ISO-8859-1) which is not
  278. %% mentioned elsewhere in the Accept-Charset field. If no "*" is present
  279. %% in an Accept-Charset field, then all character sets not explicitly
  280. %% mentioned get a quality value of 0, except for ISO-8859-1, which gets
  281. %% a quality value of 1 if not explicitly mentioned.
  282. prioritize_charsets(AcceptCharsets) ->
  283. AcceptCharsets2 = lists:sort(
  284. fun ({_CharsetA, QualityA}, {_CharsetB, QualityB}) ->
  285. QualityA > QualityB
  286. end, AcceptCharsets),
  287. case lists:keymember(<<"*">>, 1, AcceptCharsets2) of
  288. true -> AcceptCharsets2;
  289. false -> [{<<"iso-8859-1">>, 1000}|AcceptCharsets2]
  290. end.
  291. choose_charset(Req, State, []) ->
  292. not_acceptable(Req, State);
  293. choose_charset(Req, State=#state{charsets_p=CP}, [Charset|Tail]) ->
  294. match_charset(Req, State, Tail, CP, Charset).
  295. match_charset(Req, State, Accept, [], _Charset) ->
  296. choose_charset(Req, State, Accept);
  297. match_charset(Req, State, _Accept, [Provided|_Tail],
  298. {Provided, _Quality}) ->
  299. set_content_type(Req, State#state{charset_a=Provided});
  300. match_charset(Req, State, Accept, [_Provided|Tail], Charset) ->
  301. match_charset(Req, State, Accept, Tail, Charset).
  302. set_content_type(Req, State=#state{
  303. content_type_a={{Type, SubType, Params}, _Fun},
  304. charset_a=Charset}) ->
  305. ParamsBin = set_content_type_build_params(Params, []),
  306. ContentType = [Type, <<"/">>, SubType, ParamsBin],
  307. ContentType2 = case Charset of
  308. undefined -> ContentType;
  309. Charset -> [ContentType, <<"; charset=">>, Charset]
  310. end,
  311. {ok, Req2} = cowboy_http_req:set_resp_header(
  312. <<"Content-Type">>, ContentType2, Req),
  313. encodings_provided(Req2, State).
  314. set_content_type_build_params([], []) ->
  315. <<>>;
  316. set_content_type_build_params([], Acc) ->
  317. lists:reverse(Acc);
  318. set_content_type_build_params([{Attr, Value}|Tail], Acc) ->
  319. set_content_type_build_params(Tail, [[Attr, <<"=">>, Value], <<";">>|Acc]).
  320. %% @todo Match for identity as we provide nothing else for now.
  321. %% @todo Don't forget to set the Content-Encoding header when we reply a body
  322. %% and the found encoding is something other than identity.
  323. encodings_provided(Req, State) ->
  324. variances(Req, State).
  325. not_acceptable(Req, State) ->
  326. respond(Req, State, 406).
  327. %% @todo Do Accept-Encoding too when we handle it.
  328. %% @todo Does the order matter?
  329. variances(Req, State=#state{content_types_p=CTP,
  330. languages_p=LP, charsets_p=CP}) ->
  331. Variances = case length(CTP) of
  332. 0 -> [];
  333. 1 -> [];
  334. _NCT -> [<<"Accept">>]
  335. end,
  336. Variances2 = case length(LP) of
  337. 0 -> Variances;
  338. 1 -> Variances;
  339. _NL -> [<<"Accept-Language">>|Variances]
  340. end,
  341. Variances3 = case length(CP) of
  342. 0 -> Variances2;
  343. 1 -> Variances2;
  344. _NC -> [<<"Accept-Charset">>|Variances2]
  345. end,
  346. {Variances4, Req3, State2} = case call(Req, State, variances) of
  347. no_call ->
  348. {Variances3, Req, State};
  349. {HandlerVariances, Req2, HandlerState} ->
  350. {Variances3 ++ HandlerVariances, Req2,
  351. State#state{handler_state=HandlerState}}
  352. end,
  353. case lists:flatten([[<<", ">>, V] || V <- Variances4]) of
  354. [] ->
  355. resource_exists(Req3, State2);
  356. [<<", ">>, Variances5] ->
  357. {ok, Req4} = cowboy_http_req:set_resp_header(
  358. <<"Variances">>, Variances5, Req3),
  359. resource_exists(Req4, State2)
  360. end.
  361. resource_exists(Req, State) ->
  362. expect(Req, State, resource_exists, true,
  363. fun if_match_exists/2, fun if_match_musnt_exist/2).
  364. if_match_exists(Req, State) ->
  365. case cowboy_http_req:parse_header('If-Match', Req) of
  366. {undefined, Req2} ->
  367. if_unmodified_since_exists(Req2, State);
  368. {'*', Req2} ->
  369. if_unmodified_since_exists(Req2, State);
  370. {ETagsList, Req2} ->
  371. if_match(Req2, State, ETagsList)
  372. end.
  373. if_match(Req, State, EtagsList) ->
  374. {Etag, Req2, State2} = generate_etag(Req, State),
  375. case Etag of
  376. no_call ->
  377. precondition_failed(Req2, State2);
  378. Etag ->
  379. case lists:member(Etag, EtagsList) of
  380. true -> if_unmodified_since_exists(Req2, State2);
  381. false -> precondition_failed(Req2, State2)
  382. end
  383. end.
  384. if_match_musnt_exist(Req, State) ->
  385. case cowboy_http_req:header('If-Match', Req) of
  386. {undefined, Req2} -> is_put_to_missing_resource(Req2, State);
  387. {_Any, Req2} -> precondition_failed(Req2, State)
  388. end.
  389. if_unmodified_since_exists(Req, State) ->
  390. case cowboy_http_req:parse_header('If-Unmodified-Since', Req) of
  391. {undefined, Req2} ->
  392. if_none_match_exists(Req2, State);
  393. {{error, badarg}, Req2} ->
  394. if_none_match_exists(Req2, State);
  395. {IfUnmodifiedSince, Req2} ->
  396. if_unmodified_since(Req2, State, IfUnmodifiedSince)
  397. end.
  398. %% If LastModified is the atom 'no_call', we continue.
  399. if_unmodified_since(Req, State, IfUnmodifiedSince) ->
  400. {LastModified, Req2, State2} = last_modified(Req, State),
  401. case LastModified > IfUnmodifiedSince of
  402. true -> precondition_failed(Req2, State2);
  403. false -> if_none_match_exists(Req2, State2)
  404. end.
  405. if_none_match_exists(Req, State) ->
  406. case cowboy_http_req:parse_header('If-None-Match', Req) of
  407. {undefined, Req2} ->
  408. if_modified_since_exists(Req2, State);
  409. {'*', Req2} ->
  410. precondition_is_head_get(Req2, State);
  411. {EtagsList, Req2} ->
  412. if_none_match(Req2, State, EtagsList)
  413. end.
  414. if_none_match(Req, State, EtagsList) ->
  415. {Etag, Req2, State2} = generate_etag(Req, State),
  416. case Etag of
  417. no_call ->
  418. precondition_failed(Req2, State2);
  419. Etag ->
  420. case lists:member(Etag, EtagsList) of
  421. true -> precondition_is_head_get(Req2, State2);
  422. false -> if_modified_since_exists(Req2, State2)
  423. end
  424. end.
  425. precondition_is_head_get(Req=#http_req{method=Method}, State)
  426. when Method =:= 'HEAD'; Method =:= 'GET' ->
  427. not_modified(Req, State);
  428. precondition_is_head_get(Req, State) ->
  429. precondition_failed(Req, State).
  430. if_modified_since_exists(Req, State) ->
  431. case cowboy_http_req:parse_header('If-Modified-Since', Req) of
  432. {undefined, Req2} ->
  433. method(Req2, State);
  434. {{error, badarg}, Req2} ->
  435. method(Req2, State);
  436. {IfModifiedSince, Req2} ->
  437. if_modified_since_now(Req2, State, IfModifiedSince)
  438. end.
  439. if_modified_since_now(Req, State, IfModifiedSince) ->
  440. case IfModifiedSince > erlang:universaltime() of
  441. true -> method(Req, State);
  442. false -> if_modified_since(Req, State, IfModifiedSince)
  443. end.
  444. if_modified_since(Req, State, IfModifiedSince) ->
  445. {LastModified, Req2, State2} = last_modified(Req, State),
  446. case LastModified of
  447. no_call ->
  448. method(Req2, State2);
  449. LastModified ->
  450. case LastModified > IfModifiedSince of
  451. true -> method(Req2, State2);
  452. false -> not_modified(Req2, State2)
  453. end
  454. end.
  455. not_modified(Req=#http_req{resp_headers=RespHeaders}, State) ->
  456. RespHeaders2 = lists:keydelete(<<"Content-Type">>, 1, RespHeaders),
  457. Req2 = Req#http_req{resp_headers=RespHeaders2},
  458. {Req3, State2} = set_resp_etag(Req2, State),
  459. {Req4, State3} = set_resp_expires(Req3, State2),
  460. respond(Req4, State3, 304).
  461. precondition_failed(Req, State) ->
  462. respond(Req, State, 412).
  463. is_put_to_missing_resource(Req=#http_req{method='PUT'}, State) ->
  464. moved_permanently(Req, State, fun is_conflict/2);
  465. is_put_to_missing_resource(Req, State) ->
  466. previously_existed(Req, State).
  467. moved_permanently(Req, State, OnFalse) ->
  468. case call(Req, State, moved_permanently) of
  469. {{true, Location}, Req2, HandlerState2} ->
  470. {ok, Req3} = cowboy_http_req:set_resp_header(
  471. <<"Location">>, Location, Req2),
  472. respond(Req3, State#state{handler_state=HandlerState2}, 301);
  473. {false, Req2, HandlerState2} ->
  474. OnFalse(Req2, State#state{handler_state=HandlerState2});
  475. no_call ->
  476. OnFalse(Req, State)
  477. end.
  478. previously_existed(Req, State) ->
  479. expect(Req, State, previously_existed, false,
  480. fun (R, S) -> is_post_to_missing_resource(R, S, 404) end,
  481. fun (R, S) -> moved_permanently(R, S, fun moved_temporarily/2) end).
  482. moved_temporarily(Req, State) ->
  483. case call(Req, State, moved_temporarily) of
  484. {{true, Location}, Req2, HandlerState2} ->
  485. {ok, Req3} = cowboy_http_req:set_resp_header(
  486. <<"Location">>, Location, Req2),
  487. respond(Req3, State#state{handler_state=HandlerState2}, 307);
  488. {false, Req2, HandlerState2} ->
  489. is_post_to_missing_resource(Req2, State#state{handler_state=HandlerState2}, 410);
  490. no_call ->
  491. is_post_to_missing_resource(Req, State, 410)
  492. end.
  493. is_post_to_missing_resource(Req=#http_req{method='POST'}, State, OnFalse) ->
  494. allow_missing_post(Req, State, OnFalse);
  495. is_post_to_missing_resource(Req, State, OnFalse) ->
  496. respond(Req, State, OnFalse).
  497. allow_missing_post(Req, State, OnFalse) ->
  498. expect(Req, State, allow_missing_post, true, fun post_is_create/2, OnFalse).
  499. method(Req=#http_req{method='DELETE'}, State) ->
  500. delete_resource(Req, State);
  501. method(Req=#http_req{method='POST'}, State) ->
  502. post_is_create(Req, State);
  503. method(Req=#http_req{method='PUT'}, State) ->
  504. is_conflict(Req, State);
  505. method(Req, State) ->
  506. set_resp_body(Req, State).
  507. delete_resource(Req, State) ->
  508. expect(Req, State, delete_resource, true, fun delete_completed/2, 500).
  509. delete_completed(Req, State) ->
  510. expect(Req, State, delete_completed, true, fun has_resp_body/2, 202).
  511. post_is_create(Req, State) ->
  512. expect(Req, State, post_is_create, false, fun process_post/2, fun create_path/2).
  513. create_path(Req, State) ->
  514. case call(Req, State, create_path) of
  515. {Location, Req2, HandlerState} ->
  516. State2 = State#state{handler_state=HandlerState},
  517. {ok, Req3} = cowboy_http_req:set_resp_header(
  518. <<"Location">>, Location, Req2),
  519. put_resource(Req3, State2, 303)
  520. end.
  521. process_post(Req, State) ->
  522. case call(Req, State, process_post) of
  523. {ok, _Req2, HandlerState} ->
  524. _ = _State2 = State#state{handler_state=HandlerState},
  525. todo %% @todo ???
  526. end.
  527. is_conflict(Req, State) ->
  528. expect(Req, State, is_conflict, false, fun put_resource/2, 409).
  529. put_resource(Req, State) ->
  530. put_resource(Req, State, fun is_new_resource/2).
  531. put_resource(Req, State, OnTrue) ->
  532. case call(Req, State, content_types_accepted) of
  533. no_call ->
  534. respond(Req, State, 415);
  535. {CTA, Req2, HandlerState2} ->
  536. State2 = State#state{handler_state=HandlerState2},
  537. {ContentType, Req3}
  538. = cowboy_http_req:parse_header('Content-Type', Req2),
  539. choose_content_type(Req3, State2, OnTrue, ContentType, CTA)
  540. end.
  541. choose_content_type(Req, State, _OnTrue, _ContentType, []) ->
  542. respond(Req, State, 415);
  543. choose_content_type(Req, State, OnTrue, ContentType,
  544. [{Accepted, Fun}|_Tail]) when ContentType =:= Accepted ->
  545. case call(Req, State, Fun) of
  546. {ok, Req2, HandlerState} ->
  547. State2 = State#state{handler_state=HandlerState},
  548. next(Req2, State2, OnTrue)
  549. end;
  550. choose_content_type(Req, State, OnTrue, ContentType, [_Any|Tail]) ->
  551. choose_content_type(Req, State, OnTrue, ContentType, Tail).
  552. is_new_resource(Req, State) ->
  553. case cowboy_http_req:has_resp_header(<<"Location">>, Req) of
  554. true -> respond(Req, State, 201);
  555. false -> has_resp_body(Req, State)
  556. end.
  557. has_resp_body(Req, State) ->
  558. case cowboy_http_req:has_resp_body(Req) of
  559. true -> multiple_choices(Req, State);
  560. false -> respond(Req, State, 204)
  561. end.
  562. set_resp_body(Req=#http_req{method=Method},
  563. State=#state{content_type_a={_Type, Fun}})
  564. when Method =:= 'GET'; Method =:= 'HEAD' ->
  565. {Req2, State2} = set_resp_etag(Req, State),
  566. {LastModified, Req3, State3} = last_modified(Req2, State2),
  567. case LastModified of
  568. LastModified when is_atom(LastModified) ->
  569. Req4 = Req3;
  570. LastModified ->
  571. LastModifiedStr = httpd_util:rfc1123_date(LastModified),
  572. {ok, Req4} = cowboy_http_req:set_resp_header(
  573. <<"Last-Modified">>, LastModifiedStr, Req3)
  574. end,
  575. {Req5, State4} = set_resp_expires(Req4, State3),
  576. case call(Req5, State4, Fun) of
  577. {Body, Req6, HandlerState} ->
  578. State5 = State4#state{handler_state=HandlerState},
  579. {ok, Req7} = cowboy_http_req:set_resp_body(Body, Req6),
  580. multiple_choices(Req7, State5)
  581. end;
  582. set_resp_body(Req, State) ->
  583. multiple_choices(Req, State).
  584. multiple_choices(Req, State) ->
  585. expect(Req, State, multiple_choices, false, 200, 300).
  586. %% Response utility functions.
  587. set_resp_etag(Req, State) ->
  588. {Etag, Req2, State2} = generate_etag(Req, State),
  589. case Etag of
  590. undefined ->
  591. {Req2, State2};
  592. Etag ->
  593. {ok, Req3} = cowboy_http_req:set_resp_header(
  594. <<"Etag">>, Etag, Req2),
  595. {Req3, State2}
  596. end.
  597. set_resp_expires(Req, State) ->
  598. {Expires, Req2, State2} = expires(Req, State),
  599. case Expires of
  600. Expires when is_atom(Expires) ->
  601. {Req2, State2};
  602. Expires ->
  603. ExpiresStr = httpd_util:rfc1123_date(Expires),
  604. {ok, Req3} = cowboy_http_req:set_resp_header(
  605. <<"Expires">>, ExpiresStr, Req2),
  606. {Req3, State2}
  607. end.
  608. %% Info retrieval. No logic.
  609. generate_etag(Req, State=#state{etag=no_call}) ->
  610. {undefined, Req, State};
  611. generate_etag(Req, State=#state{etag=undefined}) ->
  612. case call(Req, State, generate_etag) of
  613. no_call ->
  614. {undefined, Req, State#state{etag=no_call}};
  615. {Etag, Req2, HandlerState2} ->
  616. {Etag, Req2, State#state{handler_state=HandlerState2, etag=Etag}}
  617. end;
  618. generate_etag(Req, State=#state{etag=Etag}) ->
  619. {Etag, Req, State}.
  620. last_modified(Req, State=#state{last_modified=no_call}) ->
  621. {undefined, Req, State};
  622. last_modified(Req, State=#state{last_modified=undefined}) ->
  623. case call(Req, State, last_modified) of
  624. no_call ->
  625. {undefined, Req, State#state{last_modified=no_call}};
  626. {LastModified, Req2, HandlerState2} ->
  627. {LastModified, Req2, State#state{handler_state=HandlerState2,
  628. last_modified=LastModified}}
  629. end;
  630. last_modified(Req, State=#state{last_modified=LastModified}) ->
  631. {LastModified, Req, State}.
  632. expires(Req, State=#state{expires=no_call}) ->
  633. {undefined, Req, State};
  634. expires(Req, State=#state{expires=undefined}) ->
  635. case call(Req, State, expires) of
  636. no_call ->
  637. {undefined, Req, State#state{expires=no_call}};
  638. {Expires, Req2, HandlerState2} ->
  639. {Expires, Req2, State#state{handler_state=HandlerState2,
  640. expires=Expires}}
  641. end;
  642. expires(Req, State=#state{expires=Expires}) ->
  643. {Expires, Req, State}.
  644. %% REST primitives.
  645. expect(Req, State, Callback, Expected, OnTrue, OnFalse) ->
  646. case call(Req, State, Callback) of
  647. no_call ->
  648. next(Req, State, OnTrue);
  649. {Expected, Req2, HandlerState2} ->
  650. next(Req2, State#state{handler_state=HandlerState2}, OnTrue);
  651. {_Unexpected, Req2, HandlerState2} ->
  652. next(Req2, State#state{handler_state=HandlerState2}, OnFalse)
  653. end.
  654. call(Req, #state{handler=Handler, handler_state=HandlerState}, Fun) ->
  655. case erlang:function_exported(Handler, Fun, 2) of
  656. true -> Handler:Fun(Req, HandlerState);
  657. false -> no_call
  658. end.
  659. next(Req, State, Next) when is_function(Next) ->
  660. Next(Req, State);
  661. next(Req, State, StatusCode) when is_integer(StatusCode) ->
  662. respond(Req, State, StatusCode).
  663. %% @todo Allow some sort of callback for custom error pages.
  664. respond(Req, State, StatusCode) ->
  665. {ok, Req2} = cowboy_http_req:reply(StatusCode, Req),
  666. terminate(Req2, State).
  667. terminate(Req, #state{handler=Handler, handler_state=HandlerState}) ->
  668. case erlang:function_exported(Handler, rest_terminate, 2) of
  669. true -> ok = Handler:rest_terminate(
  670. Req#http_req{resp_state=locked}, HandlerState);
  671. false -> ok
  672. end,
  673. {ok, Req}.