cowboy_static.erl 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. %% Copyright (c) 2011, Magnus Klaar <magnus.klaar@gmail.com>
  2. %% Copyright (c) 2013-2014, Loïc Hoguin <essen@ninenines.eu>
  3. %%
  4. %% Permission to use, copy, modify, and/or distribute this software for any
  5. %% purpose with or without fee is hereby granted, provided that the above
  6. %% copyright notice and this permission notice appear in all copies.
  7. %%
  8. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  10. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  11. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  12. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  13. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  14. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. -module(cowboy_static).
  16. -export([init/3]).
  17. -export([rest_init/2]).
  18. -export([malformed_request/2]).
  19. -export([forbidden/2]).
  20. -export([content_types_provided/2]).
  21. -export([resource_exists/2]).
  22. -export([last_modified/2]).
  23. -export([generate_etag/2]).
  24. -export([get_file/2]).
  25. -type extra_etag() :: {etag, module(), function()} | {etag, false}.
  26. -type extra_mimetypes() :: {mimetypes, module(), function()}
  27. | {mimetypes, binary() | {binary(), binary(), [{binary(), binary()}]}}.
  28. -type extra() :: [extra_etag() | extra_mimetypes()].
  29. -type opts() :: {file | dir, string() | binary()}
  30. | {file | dir, string() | binary(), extra()}
  31. | {priv_file | priv_dir, atom(), string() | binary()}
  32. | {priv_file | priv_dir, atom(), string() | binary(), extra()}.
  33. -export_type([opts/0]).
  34. -include_lib("kernel/include/file.hrl").
  35. -type state() :: {binary(), {ok, #file_info{}} | {error, atom()}, extra()}.
  36. init(_, _, _) ->
  37. {upgrade, protocol, cowboy_rest}.
  38. %% @doc Resolve the file that will be sent and get its file information.
  39. %% If the handler is configured to manage a directory, check that the
  40. %% requested file is inside the configured directory.
  41. -spec rest_init(Req, opts())
  42. -> {ok, Req, error | state()}
  43. when Req::cowboy_req:req().
  44. rest_init(Req, {Name, Path}) ->
  45. rest_init_opts(Req, {Name, Path, []});
  46. rest_init(Req, {Name, App, Path})
  47. when Name =:= priv_file; Name =:= priv_dir ->
  48. rest_init_opts(Req, {Name, App, Path, []});
  49. rest_init(Req, Opts) ->
  50. rest_init_opts(Req, Opts).
  51. rest_init_opts(Req, {priv_file, App, Path, Extra}) ->
  52. rest_init_info(Req, absname(priv_path(App, Path)), Extra);
  53. rest_init_opts(Req, {file, Path, Extra}) ->
  54. rest_init_info(Req, absname(Path), Extra);
  55. rest_init_opts(Req, {priv_dir, App, Path, Extra}) ->
  56. rest_init_dir(Req, priv_path(App, Path), Extra);
  57. rest_init_opts(Req, {dir, Path, Extra}) ->
  58. rest_init_dir(Req, Path, Extra).
  59. priv_path(App, Path) ->
  60. case code:priv_dir(App) of
  61. {error, bad_name} ->
  62. error({badarg, "Can't resolve the priv_dir of application "
  63. ++ atom_to_list(App)});
  64. PrivDir when is_list(Path) ->
  65. PrivDir ++ "/" ++ Path;
  66. PrivDir when is_binary(Path) ->
  67. << (list_to_binary(PrivDir))/binary, $/, Path/binary >>
  68. end.
  69. absname(Path) when is_list(Path) ->
  70. filename:absname(list_to_binary(Path));
  71. absname(Path) when is_binary(Path) ->
  72. filename:absname(Path).
  73. rest_init_dir(Req, Path, Extra) when is_list(Path) ->
  74. rest_init_dir(Req, list_to_binary(Path), Extra);
  75. rest_init_dir(Req, Path, Extra) ->
  76. Dir = fullpath(filename:absname(Path)),
  77. {PathInfo, Req2} = cowboy_req:path_info(Req),
  78. Filepath = filename:join([Dir|PathInfo]),
  79. Len = byte_size(Dir),
  80. case fullpath(Filepath) of
  81. << Dir:Len/binary, $/, _/binary >> ->
  82. rest_init_info(Req2, Filepath, Extra);
  83. _ ->
  84. {ok, Req2, error}
  85. end.
  86. fullpath(Path) ->
  87. fullpath(filename:split(Path), []).
  88. fullpath([], Acc) ->
  89. filename:join(lists:reverse(Acc));
  90. fullpath([<<".">>|Tail], Acc) ->
  91. fullpath(Tail, Acc);
  92. fullpath([<<"..">>|Tail], Acc=[_]) ->
  93. fullpath(Tail, Acc);
  94. fullpath([<<"..">>|Tail], [_|Acc]) ->
  95. fullpath(Tail, Acc);
  96. fullpath([Segment|Tail], Acc) ->
  97. fullpath(Tail, [Segment|Acc]).
  98. rest_init_info(Req, Path, Extra) ->
  99. Info = file:read_file_info(Path, [{time, universal}]),
  100. {ok, Req, {Path, Info, Extra}}.
  101. -ifdef(TEST).
  102. fullpath_test_() ->
  103. Tests = [
  104. {<<"/home/cowboy">>, <<"/home/cowboy">>},
  105. {<<"/home/cowboy">>, <<"/home/cowboy/">>},
  106. {<<"/home/cowboy">>, <<"/home/cowboy/./">>},
  107. {<<"/home/cowboy">>, <<"/home/cowboy/./././././.">>},
  108. {<<"/home/cowboy">>, <<"/home/cowboy/abc/..">>},
  109. {<<"/home/cowboy">>, <<"/home/cowboy/abc/../">>},
  110. {<<"/home/cowboy">>, <<"/home/cowboy/abc/./../.">>},
  111. {<<"/">>, <<"/home/cowboy/../../../../../..">>},
  112. {<<"/etc/passwd">>, <<"/home/cowboy/../../etc/passwd">>}
  113. ],
  114. [{P, fun() -> R = fullpath(P) end} || {R, P} <- Tests].
  115. good_path_check_test_() ->
  116. Tests = [
  117. <<"/home/cowboy/file">>,
  118. <<"/home/cowboy/file/">>,
  119. <<"/home/cowboy/./file">>,
  120. <<"/home/cowboy/././././././file">>,
  121. <<"/home/cowboy/abc/../file">>,
  122. <<"/home/cowboy/abc/../file">>,
  123. <<"/home/cowboy/abc/./.././file">>
  124. ],
  125. [{P, fun() ->
  126. case fullpath(P) of
  127. << "/home/cowboy/", _/binary >> -> ok
  128. end
  129. end} || P <- Tests].
  130. bad_path_check_test_() ->
  131. Tests = [
  132. <<"/home/cowboy/../../../../../../file">>,
  133. <<"/home/cowboy/../../etc/passwd">>
  134. ],
  135. [{P, fun() ->
  136. error = case fullpath(P) of
  137. << "/home/cowboy/", _/binary >> -> ok;
  138. _ -> error
  139. end
  140. end} || P <- Tests].
  141. good_path_win32_check_test_() ->
  142. Tests = case os:type() of
  143. {unix, _} ->
  144. [];
  145. {win32, _} ->
  146. [
  147. <<"c:/home/cowboy/file">>,
  148. <<"c:/home/cowboy/file/">>,
  149. <<"c:/home/cowboy/./file">>,
  150. <<"c:/home/cowboy/././././././file">>,
  151. <<"c:/home/cowboy/abc/../file">>,
  152. <<"c:/home/cowboy/abc/../file">>,
  153. <<"c:/home/cowboy/abc/./.././file">>
  154. ]
  155. end,
  156. [{P, fun() ->
  157. case fullpath(P) of
  158. << "c:/home/cowboy/", _/binary >> -> ok
  159. end
  160. end} || P <- Tests].
  161. bad_path_win32_check_test_() ->
  162. Tests = case os:type() of
  163. {unix, _} ->
  164. [];
  165. {win32, _} ->
  166. [
  167. <<"c:/home/cowboy/../../secretfile.bat">>,
  168. <<"c:/home/cowboy/c:/secretfile.bat">>,
  169. <<"c:/home/cowboy/..\\..\\secretfile.bat">>,
  170. <<"c:/home/cowboy/c:\\secretfile.bat">>
  171. ]
  172. end,
  173. [{P, fun() ->
  174. error = case fullpath(P) of
  175. << "c:/home/cowboy/", _/binary >> -> ok;
  176. _ -> error
  177. end
  178. end} || P <- Tests].
  179. -endif.
  180. %% @doc Reject requests that tried to access a file outside
  181. %% the target directory.
  182. -spec malformed_request(Req, State)
  183. -> {boolean(), Req, State}.
  184. malformed_request(Req, State) ->
  185. {State =:= error, Req, State}.
  186. %% @doc Directories, files that can't be accessed at all and
  187. %% files with no read flag are forbidden.
  188. -spec forbidden(Req, State)
  189. -> {boolean(), Req, State}
  190. when State::state().
  191. forbidden(Req, State={_, {ok, #file_info{type=directory}}, _}) ->
  192. {true, Req, State};
  193. forbidden(Req, State={_, {error, eacces}, _}) ->
  194. {true, Req, State};
  195. forbidden(Req, State={_, {ok, #file_info{access=Access}}, _})
  196. when Access =:= write; Access =:= none ->
  197. {true, Req, State};
  198. forbidden(Req, State) ->
  199. {false, Req, State}.
  200. %% @doc Detect the mimetype of the file.
  201. -spec content_types_provided(Req, State)
  202. -> {[{binary(), get_file}], Req, State}
  203. when State::state().
  204. content_types_provided(Req, State={Path, _, Extra}) ->
  205. case lists:keyfind(mimetypes, 1, Extra) of
  206. false ->
  207. {[{cow_mimetypes:web(Path), get_file}], Req, State};
  208. {mimetypes, Module, Function} ->
  209. {[{Module:Function(Path), get_file}], Req, State};
  210. {mimetypes, Type} ->
  211. {[{Type, get_file}], Req, State}
  212. end.
  213. %% @doc Assume the resource doesn't exist if it's not a regular file.
  214. -spec resource_exists(Req, State)
  215. -> {boolean(), Req, State}
  216. when State::state().
  217. resource_exists(Req, State={_, {ok, #file_info{type=regular}}, _}) ->
  218. {true, Req, State};
  219. resource_exists(Req, State) ->
  220. {false, Req, State}.
  221. %% @doc Generate an etag for the file.
  222. -spec generate_etag(Req, State)
  223. -> {{strong | weak, binary()}, Req, State}
  224. when State::state().
  225. generate_etag(Req, State={Path, {ok, #file_info{size=Size, mtime=Mtime}},
  226. Extra}) ->
  227. case lists:keyfind(etag, 1, Extra) of
  228. false ->
  229. {generate_default_etag(Size, Mtime), Req, State};
  230. {etag, Module, Function} ->
  231. {Module:Function(Path, Size, Mtime), Req, State};
  232. {etag, false} ->
  233. {undefined, Req, State}
  234. end.
  235. generate_default_etag(Size, Mtime) ->
  236. {strong, list_to_binary(integer_to_list(
  237. erlang:phash2({Size, Mtime}, 16#ffffffff)))}.
  238. %% @doc Return the time of last modification of the file.
  239. -spec last_modified(Req, State)
  240. -> {calendar:datetime(), Req, State}
  241. when State::state().
  242. last_modified(Req, State={_, {ok, #file_info{mtime=Modified}}, _}) ->
  243. {Modified, Req, State}.
  244. %% @doc Stream the file.
  245. %% @todo Export cowboy_req:resp_body_fun()?
  246. -spec get_file(Req, State)
  247. -> {{stream, non_neg_integer(), fun()}, Req, State}
  248. when State::state().
  249. get_file(Req, State={Path, {ok, #file_info{size=Size}}, _}) ->
  250. Sendfile = fun (Socket, Transport) ->
  251. case Transport:sendfile(Socket, Path) of
  252. {ok, _} -> ok;
  253. {error, closed} -> ok;
  254. {error, etimedout} -> ok
  255. end
  256. end,
  257. {{stream, Size, Sendfile}, Req, State}.