cowboy_static.erl 8.8 KB

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