cowboy_static.erl 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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/2]).
  17. -export([malformed_request/2]).
  18. -export([forbidden/2]).
  19. -export([content_types_provided/2]).
  20. -export([resource_exists/2]).
  21. -export([last_modified/2]).
  22. -export([generate_etag/2]).
  23. -export([get_file/2]).
  24. -type extra_etag() :: {etag, module(), function()} | {etag, false}.
  25. -type extra_mimetypes() :: {mimetypes, module(), function()}
  26. | {mimetypes, binary() | {binary(), binary(), [{binary(), binary()}]}}.
  27. -type extra() :: [extra_etag() | extra_mimetypes()].
  28. -type opts() :: {file | dir, string() | binary()}
  29. | {file | dir, string() | binary(), extra()}
  30. | {priv_file | priv_dir, atom(), string() | binary()}
  31. | {priv_file | priv_dir, atom(), string() | binary(), extra()}.
  32. -export_type([opts/0]).
  33. -include_lib("kernel/include/file.hrl").
  34. -type state() :: {binary(), {ok, #file_info{}} | {error, atom()}, extra()}.
  35. %% Resolve the file that will be sent and get its file information.
  36. %% If the handler is configured to manage a directory, check that the
  37. %% requested file is inside the configured directory.
  38. -spec init(Req, opts()) -> {cowboy_rest, Req, error | state()} when Req::cowboy_req:req().
  39. init(Req, {Name, Path}) ->
  40. init_opts(Req, {Name, Path, []});
  41. init(Req, {Name, App, Path})
  42. when Name =:= priv_file; Name =:= priv_dir ->
  43. init_opts(Req, {Name, App, Path, []});
  44. init(Req, Opts) ->
  45. init_opts(Req, Opts).
  46. init_opts(Req, {priv_file, App, Path, Extra}) ->
  47. init_info(Req, absname(priv_path(App, Path)), Extra);
  48. init_opts(Req, {file, Path, Extra}) ->
  49. init_info(Req, absname(Path), Extra);
  50. init_opts(Req, {priv_dir, App, Path, Extra}) ->
  51. init_dir(Req, priv_path(App, Path), Extra);
  52. init_opts(Req, {dir, Path, Extra}) ->
  53. init_dir(Req, Path, Extra).
  54. priv_path(App, Path) ->
  55. case code:priv_dir(App) of
  56. {error, bad_name} ->
  57. error({badarg, "Can't resolve the priv_dir of application "
  58. ++ atom_to_list(App)});
  59. PrivDir when is_list(Path) ->
  60. PrivDir ++ "/" ++ Path;
  61. PrivDir when is_binary(Path) ->
  62. << (list_to_binary(PrivDir))/binary, $/, Path/binary >>
  63. end.
  64. absname(Path) when is_list(Path) ->
  65. filename:absname(list_to_binary(Path));
  66. absname(Path) when is_binary(Path) ->
  67. filename:absname(Path).
  68. init_dir(Req, Path, Extra) when is_list(Path) ->
  69. init_dir(Req, list_to_binary(Path), Extra);
  70. init_dir(Req, Path, Extra) ->
  71. Dir = fullpath(filename:absname(Path)),
  72. PathInfo = cowboy_req:path_info(Req),
  73. Filepath = filename:join([Dir|PathInfo]),
  74. Len = byte_size(Dir),
  75. case fullpath(Filepath) of
  76. << Dir:Len/binary, $/, _/binary >> ->
  77. init_info(Req, Filepath, Extra);
  78. _ ->
  79. {cowboy_rest, Req, error}
  80. end.
  81. fullpath(Path) ->
  82. fullpath(filename:split(Path), []).
  83. fullpath([], Acc) ->
  84. filename:join(lists:reverse(Acc));
  85. fullpath([<<".">>|Tail], Acc) ->
  86. fullpath(Tail, Acc);
  87. fullpath([<<"..">>|Tail], Acc=[_]) ->
  88. fullpath(Tail, Acc);
  89. fullpath([<<"..">>|Tail], [_|Acc]) ->
  90. fullpath(Tail, Acc);
  91. fullpath([Segment|Tail], Acc) ->
  92. fullpath(Tail, [Segment|Acc]).
  93. init_info(Req, Path, Extra) ->
  94. Info = file:read_file_info(Path, [{time, universal}]),
  95. {cowboy_rest, Req, {Path, Info, Extra}}.
  96. -ifdef(TEST).
  97. fullpath_test_() ->
  98. Tests = [
  99. {<<"/home/cowboy">>, <<"/home/cowboy">>},
  100. {<<"/home/cowboy">>, <<"/home/cowboy/">>},
  101. {<<"/home/cowboy">>, <<"/home/cowboy/./">>},
  102. {<<"/home/cowboy">>, <<"/home/cowboy/./././././.">>},
  103. {<<"/home/cowboy">>, <<"/home/cowboy/abc/..">>},
  104. {<<"/home/cowboy">>, <<"/home/cowboy/abc/../">>},
  105. {<<"/home/cowboy">>, <<"/home/cowboy/abc/./../.">>},
  106. {<<"/">>, <<"/home/cowboy/../../../../../..">>},
  107. {<<"/etc/passwd">>, <<"/home/cowboy/../../etc/passwd">>}
  108. ],
  109. [{P, fun() -> R = fullpath(P) end} || {R, P} <- Tests].
  110. good_path_check_test_() ->
  111. Tests = [
  112. <<"/home/cowboy/file">>,
  113. <<"/home/cowboy/file/">>,
  114. <<"/home/cowboy/./file">>,
  115. <<"/home/cowboy/././././././file">>,
  116. <<"/home/cowboy/abc/../file">>,
  117. <<"/home/cowboy/abc/../file">>,
  118. <<"/home/cowboy/abc/./.././file">>
  119. ],
  120. [{P, fun() ->
  121. case fullpath(P) of
  122. << "/home/cowboy/", _/bits >> -> ok
  123. end
  124. end} || P <- Tests].
  125. bad_path_check_test_() ->
  126. Tests = [
  127. <<"/home/cowboy/../../../../../../file">>,
  128. <<"/home/cowboy/../../etc/passwd">>
  129. ],
  130. [{P, fun() ->
  131. error = case fullpath(P) of
  132. << "/home/cowboy/", _/bits >> -> ok;
  133. _ -> error
  134. end
  135. end} || P <- Tests].
  136. good_path_win32_check_test_() ->
  137. Tests = case os:type() of
  138. {unix, _} ->
  139. [];
  140. {win32, _} ->
  141. [
  142. <<"c:/home/cowboy/file">>,
  143. <<"c:/home/cowboy/file/">>,
  144. <<"c:/home/cowboy/./file">>,
  145. <<"c:/home/cowboy/././././././file">>,
  146. <<"c:/home/cowboy/abc/../file">>,
  147. <<"c:/home/cowboy/abc/../file">>,
  148. <<"c:/home/cowboy/abc/./.././file">>
  149. ]
  150. end,
  151. [{P, fun() ->
  152. case fullpath(P) of
  153. << "c:/home/cowboy/", _/bits >> -> ok
  154. end
  155. end} || P <- Tests].
  156. bad_path_win32_check_test_() ->
  157. Tests = case os:type() of
  158. {unix, _} ->
  159. [];
  160. {win32, _} ->
  161. [
  162. <<"c:/home/cowboy/../../secretfile.bat">>,
  163. <<"c:/home/cowboy/c:/secretfile.bat">>,
  164. <<"c:/home/cowboy/..\\..\\secretfile.bat">>,
  165. <<"c:/home/cowboy/c:\\secretfile.bat">>
  166. ]
  167. end,
  168. [{P, fun() ->
  169. error = case fullpath(P) of
  170. << "c:/home/cowboy/", _/bits >> -> ok;
  171. _ -> error
  172. end
  173. end} || P <- Tests].
  174. -endif.
  175. %% Reject requests that tried to access a file outside
  176. %% the target directory.
  177. -spec malformed_request(Req, State)
  178. -> {boolean(), Req, State}.
  179. malformed_request(Req, State) ->
  180. {State =:= error, Req, State}.
  181. %% Directories, files that can't be accessed at all and
  182. %% files with no read flag are forbidden.
  183. -spec forbidden(Req, State)
  184. -> {boolean(), Req, State}
  185. when State::state().
  186. forbidden(Req, State={_, {ok, #file_info{type=directory}}, _}) ->
  187. {true, Req, State};
  188. forbidden(Req, State={_, {error, eacces}, _}) ->
  189. {true, Req, State};
  190. forbidden(Req, State={_, {ok, #file_info{access=Access}}, _})
  191. when Access =:= write; Access =:= none ->
  192. {true, Req, State};
  193. forbidden(Req, State) ->
  194. {false, Req, State}.
  195. %% Detect the mimetype of the file.
  196. -spec content_types_provided(Req, State)
  197. -> {[{binary(), get_file}], Req, State}
  198. when State::state().
  199. content_types_provided(Req, State={Path, _, Extra}) ->
  200. case lists:keyfind(mimetypes, 1, Extra) of
  201. false ->
  202. {[{cow_mimetypes:web(Path), get_file}], Req, State};
  203. {mimetypes, Module, Function} ->
  204. {[{Module:Function(Path), get_file}], Req, State};
  205. {mimetypes, Type} ->
  206. {[{Type, get_file}], Req, State}
  207. end.
  208. %% Assume the resource doesn't exist if it's not a regular file.
  209. -spec resource_exists(Req, State)
  210. -> {boolean(), Req, State}
  211. when State::state().
  212. resource_exists(Req, State={_, {ok, #file_info{type=regular}}, _}) ->
  213. {true, Req, State};
  214. resource_exists(Req, State) ->
  215. {false, Req, State}.
  216. %% Generate an etag for the file.
  217. -spec generate_etag(Req, State)
  218. -> {{strong | weak, binary()}, Req, State}
  219. when State::state().
  220. generate_etag(Req, State={Path, {ok, #file_info{size=Size, mtime=Mtime}},
  221. Extra}) ->
  222. case lists:keyfind(etag, 1, Extra) of
  223. false ->
  224. {generate_default_etag(Size, Mtime), Req, State};
  225. {etag, Module, Function} ->
  226. {Module:Function(Path, Size, Mtime), Req, State};
  227. {etag, false} ->
  228. {undefined, Req, State}
  229. end.
  230. generate_default_etag(Size, Mtime) ->
  231. {strong, integer_to_binary(erlang:phash2({Size, Mtime}, 16#ffffffff))}.
  232. %% Return the time of last modification of the file.
  233. -spec last_modified(Req, State)
  234. -> {calendar:datetime(), Req, State}
  235. when State::state().
  236. last_modified(Req, State={_, {ok, #file_info{mtime=Modified}}, _}) ->
  237. {Modified, Req, State}.
  238. %% Stream the file.
  239. %% @todo Export cowboy_req:resp_body_fun()?
  240. -spec get_file(Req, State)
  241. -> {{stream, non_neg_integer(), fun()}, Req, State}
  242. when State::state().
  243. get_file(Req, State={Path, {ok, #file_info{size=Size}}, _}) ->
  244. Sendfile = fun (Socket, Transport) ->
  245. case Transport:sendfile(Socket, Path) of
  246. {ok, _} -> ok;
  247. {error, closed} -> ok;
  248. {error, etimedout} -> ok
  249. end
  250. end,
  251. {{stream, Size, Sendfile}, Req, State}.