cowboy_static.erl 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. %% Copyright (c) 2011, Magnus Klaar <magnus.klaar@gmail.com>
  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 Static resource handler.
  15. %%
  16. %% This built in HTTP handler provides a simple file serving capability for
  17. %% cowboy applications. It should be considered an experimental feature because
  18. %% of it's dependency on the experimental REST handler. It's recommended to be
  19. %% used for small or temporary environments where it is not preferrable to set
  20. %% up a second server just to serve files.
  21. %%
  22. %% If this handler is used the Erlang node running the cowboy application must
  23. %% be configured to use an async thread pool. This is configured by adding the
  24. %% `+A $POOL_SIZE' argument to the `erl' command used to start the node. See
  25. %% <a href="http://erlang.org/pipermail/erlang-bugs/2012-January/002720.html">
  26. %% this reply</a> from the OTP team to erlang-bugs
  27. %%
  28. %% == Base configuration ==
  29. %%
  30. %% The handler must be configured with a request path prefix to serve files
  31. %% under and the path to a directory to read files from. The request path prefix
  32. %% is defined in the path pattern of the cowboy dispatch rule for the handler.
  33. %% The request path pattern must end with a `...' token.
  34. %%
  35. %% The directory path can be set to either an absolute or relative path in the
  36. %% form of a list or binary string representation of a file system path. A list
  37. %% of binary path segments is also a valid directory path.
  38. %%
  39. %% The directory path can also be set to a relative path within the `priv/'
  40. %% directory of an application. This is configured by setting the value of the
  41. %% directory option to a tuple of the form `{priv_dir, Application, Relpath}'.
  42. %%
  43. %% ==== Examples ====
  44. %% ```
  45. %% %% Serve files from /var/www/ under http://example.com/static/
  46. %% {"/static/[...]", cowboy_static,
  47. %% [{directory, "/var/www"}]}
  48. %%
  49. %% %% Serve files from the current working directory under http://example.com/static/
  50. %% {"/static/[...]", cowboy_static,
  51. %% [{directory, <<"./">>}]}
  52. %%
  53. %% %% Serve files from cowboy/priv/www under http://example.com/
  54. %% {"/[...]", cowboy_static,
  55. %% [{directory, {priv_dir, cowboy, [<<"www">>]}}]}
  56. %% '''
  57. %%
  58. %% == Content type configuration ==
  59. %%
  60. %% By default the content type of all static resources will be set to
  61. %% `application/octet-stream'. This can be overriden by supplying a list
  62. %% of filename extension to mimetypes pairs in the `mimetypes' option.
  63. %% The filename extension should be a binary string including the leading dot.
  64. %% The mimetypes must be of a type that the `cowboy_rest' protocol can
  65. %% handle.
  66. %%
  67. %% The <a href="https://github.com/spawngrid/mimetypes">spawngrid/mimetypes</a>
  68. %% application, or an arbitrary function accepting the path to the file being
  69. %% served, can also be used to generate the list of content types for a static
  70. %% file resource. The function used must accept an additional argument after
  71. %% the file path argument.
  72. %%
  73. %% ==== Example ====
  74. %% ```
  75. %% %% Use a static list of content types.
  76. %% {"/static/[...]", cowboy_static,
  77. %% [{directory, {priv_dir, cowboy, []}},
  78. %% {mimetypes, [
  79. %% {<<".css">>, [<<"text/css">>]},
  80. %% {<<".js">>, [<<"application/javascript">>]}]}]}
  81. %%
  82. %% %% Use the default database in the mimetypes application.
  83. %% {"/static/[...]", cowboy_static,
  84. %% [{directory, {priv_dir, cowboy, []}},
  85. %% {mimetypes, {fun mimetypes:path_to_mimes/2, default}}]}
  86. %% '''
  87. %%
  88. %% == ETag Header Function ==
  89. %%
  90. %% The default behaviour of the static file handler is to not generate ETag
  91. %% headers. This is because generating ETag headers based on file metadata
  92. %% causes different servers in a cluster to generate different ETag values for
  93. %% the same file unless the metadata is also synced. Generating strong ETags
  94. %% based on the contents of a file is currently out of scope for this module.
  95. %%
  96. %% The default behaviour can be overridden to generate an ETag header based on
  97. %% a combination of the file path, file size, inode and mtime values. If the
  98. %% option value is a non-empty list of attribute names tagged with `attributes'
  99. %% a hex encoded checksum of each attribute specified is included in the value
  100. %% of the the ETag header. If the list of attribute names is empty no ETag
  101. %% header is generated.
  102. %%
  103. %% If a strong ETag is required a user defined function for generating the
  104. %% header value can be supplied. The function must accept a list of key/values
  105. %% of the file attributes as the first argument and a second argument
  106. %% containing any additional data that the function requires. The function
  107. %% must return a term of the type `{weak | strong, binary()}' or `undefined'.
  108. %%
  109. %% ==== Examples ====
  110. %% ```
  111. %% %% A value of default is equal to not specifying the option.
  112. %% {"static/[...]", cowboy_static,
  113. %% [{directory, {priv_dir, cowboy, []}},
  114. %% {etag, default}]}
  115. %%
  116. %% %% Use all avaliable ETag function arguments to generate a header value.
  117. %% {"static/[...]", cowboy_static,
  118. %% [{directory, {priv_dir, cowboy, []}},
  119. %% {etag, {attributes, [filepath, filesize, inode, mtime]}}]}
  120. %%
  121. %% %% Use a user defined function to generate a strong ETag header value.
  122. %% {"static/[...]", cowboy_static,
  123. %% [{directory, {priv_dir, cowboy, []}},
  124. %% {etag, {fun generate_strong_etag/2, strong_etag_extra}}]}
  125. %%
  126. %% generate_strong_etag(Arguments, strong_etag_extra) ->
  127. %% {_, Filepath} = lists:keyfind(filepath, 1, Arguments),
  128. %% {_, _Filesize} = lists:keyfind(filesize, 1, Arguments),
  129. %% {_, _INode} = lists:keyfind(inode, 1, Arguments),
  130. %% {_, _Modified} = lists:keyfind(mtime, 1, Arguments),
  131. %% ChecksumCommand = lists:flatten(io_lib:format("sha1sum ~s", [Filepath])),
  132. %% [Checksum|_] = string:tokens(os:cmd(ChecksumCommand), " "),
  133. %% {strong, iolist_to_binary(Checksum)}.
  134. %% '''
  135. %%
  136. %% == File configuration ==
  137. %%
  138. %% If the file system path being served does not share a common suffix with
  139. %% the request path it is possible to override the file path using the `file'
  140. %% option. The value of this option is expected to be a relative path within
  141. %% the static file directory specified using the `directory' option.
  142. %% The path must be in the form of a list or binary string representation of a
  143. %% file system path. A list of binary path segments, as is used throughout
  144. %% cowboy, is also a valid.
  145. %%
  146. %% When the `file' option is used the same file will be served for all requests
  147. %% matching the cowboy dispatch fule for the handler. It is not necessary to
  148. %% end the request path pattern with a `...' token because the request path
  149. %% will not be used to determine which file to serve from the static directory.
  150. %%
  151. %% === Examples ===
  152. %%
  153. %% ```
  154. %% %% Serve cowboy/priv/www/index.html as http://example.com/
  155. %% {"/", cowboy_static,
  156. %% [{directory, {priv_dir, cowboy, [<<"www">>]}}
  157. %% {file, <<"index.html">>}]}
  158. %%
  159. %% %% Serve cowboy/priv/www/page.html under http://example.com/*/page
  160. %% {"/:_/page", cowboy_static,
  161. %% [{directory, {priv_dir, cowboy, [<<"www">>]}}
  162. %% {file, <<"page.html">>}]}.
  163. %%
  164. %% %% Always serve cowboy/priv/www/other.html under http://example.com/other
  165. %% {"/other/[...]", cowboy_static,
  166. %% [{directory, {priv_dir, cowboy, [<<"www">>]}}
  167. %% {file, "other.html"}]}
  168. %% '''
  169. -module(cowboy_static).
  170. %% include files
  171. -include_lib("kernel/include/file.hrl").
  172. %% cowboy_protocol callbacks
  173. -export([init/3]).
  174. %% cowboy_rest callbacks
  175. -export([rest_init/2]).
  176. -export([allowed_methods/2]).
  177. -export([malformed_request/2]).
  178. -export([resource_exists/2]).
  179. -export([forbidden/2]).
  180. -export([last_modified/2]).
  181. -export([generate_etag/2]).
  182. -export([content_types_provided/2]).
  183. -export([file_contents/2]).
  184. %% internal
  185. -export([path_to_mimetypes/2]).
  186. %% types
  187. -type dirpath() :: string() | binary() | [binary()].
  188. -type dirspec() :: dirpath() | {priv, atom(), dirpath()}.
  189. -type mimedef() :: {binary(), binary(), [{binary(), binary()}]}.
  190. -type etagarg() :: {filepath, binary()} | {mtime, calendar:datetime()}
  191. | {inode, non_neg_integer()} | {filesize, non_neg_integer()}.
  192. %% handler state
  193. -record(state, {
  194. filepath :: binary() | error,
  195. fileinfo :: {ok, #file_info{}} | {error, _} | error,
  196. mimetypes :: {fun((binary(), T) -> [mimedef()]), T} | undefined,
  197. etag_fun :: {fun(([etagarg()], T) ->
  198. undefined | {strong | weak, binary()}), T}
  199. }).
  200. %% @private Upgrade from HTTP handler to REST handler.
  201. init({_Transport, http}, _Req, _Opts) ->
  202. {upgrade, protocol, cowboy_rest}.
  203. %% @private Set up initial state of REST handler.
  204. -spec rest_init(Req, list()) -> {ok, Req, #state{}} when Req::cowboy_req:req().
  205. rest_init(Req, Opts) ->
  206. {_, DirectoryOpt} = lists:keyfind(directory, 1, Opts),
  207. Directory = fullpath(filename:absname(directory_path(DirectoryOpt))),
  208. case lists:keyfind(file, 1, Opts) of
  209. false ->
  210. {PathInfo, Req2} = cowboy_req:path_info(Req),
  211. Filepath = filename:join([Directory|PathInfo]),
  212. Len = byte_size(Directory),
  213. case fullpath(Filepath) of
  214. << Directory:Len/binary, $/, _/binary >> ->
  215. rest_init(Req2, Opts, Filepath);
  216. _ ->
  217. {ok, Req2, #state{filepath=error, fileinfo=error,
  218. mimetypes=undefined, etag_fun=undefined}}
  219. end;
  220. {_, FileOpt} ->
  221. Filepath = filepath_path(FileOpt),
  222. Filepath2 = << Directory/binary, $/, Filepath/binary >>,
  223. rest_init(Req, Opts, Filepath2)
  224. end.
  225. rest_init(Req, Opts, Filepath) ->
  226. Fileinfo = file:read_file_info(Filepath),
  227. Mimetypes = case lists:keyfind(mimetypes, 1, Opts) of
  228. false -> {fun path_to_mimetypes/2, []};
  229. {_, {{M, F}, E}} -> {fun M:F/2, E};
  230. {_, Mtypes} when is_tuple(Mtypes) -> Mtypes;
  231. {_, Mtypes} when is_list(Mtypes) -> {fun path_to_mimetypes/2, Mtypes}
  232. end,
  233. EtagFun = case lists:keyfind(etag, 1, Opts) of
  234. false -> {fun no_etag_function/2, undefined};
  235. {_, default} -> {fun no_etag_function/2, undefined};
  236. {_, {attributes, []}} -> {fun no_etag_function/2, undefined};
  237. {_, {attributes, Attrs}} -> {fun attr_etag_function/2, Attrs};
  238. {_, EtagOpt} -> EtagOpt
  239. end,
  240. {ok, Req, #state{filepath=Filepath, fileinfo=Fileinfo,
  241. mimetypes=Mimetypes, etag_fun=EtagFun}}.
  242. %% @private Only allow GET and HEAD requests on files.
  243. -spec allowed_methods(Req, #state{})
  244. -> {[binary()], Req, #state{}} when Req::cowboy_req:req().
  245. allowed_methods(Req, State) ->
  246. {[<<"GET">>, <<"HEAD">>], Req, State}.
  247. %% @private
  248. -spec malformed_request(Req, #state{})
  249. -> {boolean(), Req, #state{}} when Req::cowboy_req:req().
  250. malformed_request(Req, #state{filepath=error}=State) ->
  251. {true, Req, State};
  252. malformed_request(Req, State) ->
  253. {false, Req, State}.
  254. %% @private Check if the resource exists under the document root.
  255. -spec resource_exists(Req, #state{})
  256. -> {boolean(), Req, #state{}} when Req::cowboy_req:req().
  257. resource_exists(Req, #state{fileinfo={error, _}}=State) ->
  258. {false, Req, State};
  259. resource_exists(Req, #state{fileinfo={ok, Fileinfo}}=State) ->
  260. {Fileinfo#file_info.type =:= regular, Req, State}.
  261. %% @private
  262. %% Access to a file resource is forbidden if it exists and the local node does
  263. %% not have permission to read it. Directory listings are always forbidden.
  264. -spec forbidden(Req, #state{})
  265. -> {boolean(), Req, #state{}} when Req::cowboy_req:req().
  266. forbidden(Req, #state{fileinfo={_, #file_info{type=directory}}}=State) ->
  267. {true, Req, State};
  268. forbidden(Req, #state{fileinfo={error, eacces}}=State) ->
  269. {true, Req, State};
  270. forbidden(Req, #state{fileinfo={error, _}}=State) ->
  271. {false, Req, State};
  272. forbidden(Req, #state{fileinfo={ok, #file_info{access=Access}}}=State) ->
  273. {not (Access =:= read orelse Access =:= read_write), Req, State}.
  274. %% @private Read the time a file system system object was last modified.
  275. -spec last_modified(Req, #state{})
  276. -> {calendar:datetime(), Req, #state{}} when Req::cowboy_req:req().
  277. last_modified(Req, #state{fileinfo={ok, #file_info{mtime=Modified}}}=State) ->
  278. {erlang:localtime_to_universaltime(Modified), Req, State}.
  279. %% @private Generate the ETag header value for this file.
  280. %% The ETag header value is only generated if the resource is a file that
  281. %% exists in document root.
  282. -spec generate_etag(Req, #state{})
  283. -> {undefined | binary(), Req, #state{}} when Req::cowboy_req:req().
  284. generate_etag(Req, #state{fileinfo={_, #file_info{type=regular, inode=INode,
  285. mtime=Modified, size=Filesize}}, filepath=Filepath,
  286. etag_fun={ETagFun, ETagData}}=State) ->
  287. ETagArgs = [
  288. {filepath, Filepath}, {filesize, Filesize},
  289. {inode, INode}, {mtime, Modified}],
  290. {ETagFun(ETagArgs, ETagData), Req, State};
  291. generate_etag(Req, State) ->
  292. {undefined, Req, State}.
  293. %% @private Return the content type of a file.
  294. -spec content_types_provided(cowboy_req:req(), #state{}) -> tuple().
  295. content_types_provided(Req, #state{filepath=Filepath,
  296. mimetypes={MimetypesFun, MimetypesData}}=State) ->
  297. Mimetypes = [{T, file_contents}
  298. || T <- MimetypesFun(Filepath, MimetypesData)],
  299. {Mimetypes, Req, State}.
  300. %% @private Return a function that writes a file directly to the socket.
  301. -spec file_contents(cowboy_req:req(), #state{}) -> tuple().
  302. file_contents(Req, #state{filepath=Filepath,
  303. fileinfo={ok, #file_info{size=Filesize}}}=State) ->
  304. Writefile = fun(Socket, Transport) ->
  305. %% Transport:sendfile/2 may return {error, closed}
  306. %% if the connection is closed while sending the file.
  307. case Transport:sendfile(Socket, Filepath) of
  308. {ok, _} -> ok;
  309. {error, closed} -> ok;
  310. {error, etimedout} -> ok
  311. end
  312. end,
  313. {{stream, Filesize, Writefile}, Req, State}.
  314. %% Internal.
  315. -spec directory_path(dirspec()) -> dirpath().
  316. directory_path({priv_dir, App, []}) ->
  317. priv_dir_path(App);
  318. directory_path({priv_dir, App, [H|_]=Path}) when is_binary(H) ->
  319. filename:join(priv_dir_path(App), filename:join(Path));
  320. directory_path({priv_dir, App, Path}) ->
  321. filename:join(priv_dir_path(App), Path);
  322. directory_path([H|_]=Path) when is_binary(H) ->
  323. filename:join(Path);
  324. directory_path([H|_]=Path) when is_integer(H) ->
  325. list_to_binary(Path);
  326. directory_path(Path) when is_binary(Path) ->
  327. Path.
  328. %% @private Return the path to the priv/ directory of an application.
  329. -spec priv_dir_path(atom()) -> string().
  330. priv_dir_path(App) ->
  331. case code:priv_dir(App) of
  332. {error, bad_name} -> priv_dir_mod(App);
  333. Dir -> list_to_binary(Dir)
  334. end.
  335. -spec priv_dir_mod(atom()) -> string().
  336. priv_dir_mod(Mod) ->
  337. case code:which(Mod) of
  338. File when not is_list(File) -> <<"../priv">>;
  339. File -> filename:join(filename:dirname(File), <<"../priv">>)
  340. end.
  341. %% @private Ensure that a file path is of the same type as a request path.
  342. filepath_path(Path) when is_binary(Path) ->
  343. Path;
  344. filepath_path([H|_]=Path) when is_binary(H) ->
  345. filename:join(Path);
  346. filepath_path([H|_]=Path) when is_integer(H) ->
  347. list_to_binary(Path).
  348. fullpath(Path) when is_binary(Path) ->
  349. fullpath(filename:split(Path), []).
  350. fullpath([], Acc) ->
  351. filename:join(lists:reverse(Acc));
  352. fullpath([<<".">>|Tail], Acc) ->
  353. fullpath(Tail, Acc);
  354. fullpath([<<"..">>|Tail], Acc=[_]) ->
  355. fullpath(Tail, Acc);
  356. fullpath([<<"..">>|Tail], [_|Acc]) ->
  357. fullpath(Tail, Acc);
  358. fullpath([Segment|Tail], Acc) ->
  359. fullpath(Tail, [Segment|Acc]).
  360. %% @private Use application/octet-stream as the default mimetype.
  361. %% If a list of extension - mimetype pairs are provided as the mimetypes
  362. %% an attempt to find the mimetype using the file extension. If no match
  363. %% is found the default mimetype is returned.
  364. -spec path_to_mimetypes(binary(), [{binary(), [mimedef()]}]) ->
  365. [mimedef()].
  366. path_to_mimetypes(Filepath, Extensions) when is_binary(Filepath) ->
  367. Ext = filename:extension(Filepath),
  368. case Ext of
  369. <<>> -> default_mimetype();
  370. _Ext -> path_to_mimetypes_(Ext, Extensions)
  371. end.
  372. -spec path_to_mimetypes_(binary(), [{binary(), [mimedef()]}]) -> [mimedef()].
  373. path_to_mimetypes_(Ext, Extensions) ->
  374. case lists:keyfind(cowboy_bstr:to_lower(Ext), 1, Extensions) of
  375. {_, MTs} -> MTs;
  376. _Unknown -> default_mimetype()
  377. end.
  378. -spec default_mimetype() -> [mimedef()].
  379. default_mimetype() ->
  380. [{<<"application">>, <<"octet-stream">>, []}].
  381. %% @private Do not send ETag headers in the default configuration.
  382. -spec no_etag_function([etagarg()], undefined) -> undefined.
  383. no_etag_function(_Args, undefined) ->
  384. undefined.
  385. %% @private A simple alternative is to send an ETag based on file attributes.
  386. -type fileattr() :: filepath | filesize | mtime | inode.
  387. -spec attr_etag_function([etagarg()], [fileattr()]) -> {strong, binary()}.
  388. attr_etag_function(Args, Attrs) ->
  389. [[_|H]|T] = [begin
  390. {_,Pair} = {_,{_,_}} = {Attr,lists:keyfind(Attr, 1, Args)},
  391. [$-|integer_to_list(erlang:phash2(Pair, 1 bsl 32), 16)]
  392. end || Attr <- Attrs],
  393. {strong, list_to_binary([H|T])}.
  394. -ifdef(TEST).
  395. -include_lib("eunit/include/eunit.hrl").
  396. -define(_eq(E, I), ?_assertEqual(E, I)).
  397. directory_path_test_() ->
  398. PL = fun(D) -> length(filename:split(directory_path(D))) end,
  399. Base = PL({priv_dir, cowboy, []}),
  400. LengthTests = [
  401. Base + 1, {priv_dir, cowboy, "a"},
  402. Base + 1, {priv_dir, cowboy, <<"a">>},
  403. Base + 1, {priv_dir, cowboy, [<<"a">>]},
  404. Base + 2, {priv_dir, cowboy, "a/b"},
  405. Base + 2, {priv_dir, cowboy, <<"a/b">>},
  406. Base + 2, {priv_dir, cowboy, [<<"a">>, <<"b">>]}
  407. ],
  408. TypeTests = [
  409. {priv_dir, cowboy, []},
  410. {priv_dir, cowboy, "a"},
  411. {priv_dir, cowboy, <<"a">>},
  412. {priv_dir, cowboy, [<<"a">>]},
  413. "a",
  414. <<"a">>,
  415. [<<"a">>]
  416. ],
  417. [{lists:flatten(io_lib:format("~p", [D])),
  418. fun() -> R = PL(D) end} || {R, D} <- LengthTests]
  419. ++ [{lists:flatten(io_lib:format("~p", [D])),
  420. fun() -> is_binary(directory_path(D)) end} || D <- TypeTests].
  421. filepath_path_test_() ->
  422. Tests = [
  423. {<<"a">>, "a"},
  424. {<<"a">>, <<"a">>},
  425. {<<"a">>, [<<"a">>]},
  426. {<<"a/b">>, "a/b"},
  427. {<<"a/b">>, <<"a/b">>},
  428. {<<"a/b">>, [<<"a">>, <<"b">>]}
  429. ],
  430. [{lists:flatten(io_lib:format("~p", [F])),
  431. fun() -> R = filepath_path(F) end} || {R, F} <- Tests].
  432. fullpath_test_() ->
  433. Tests = [
  434. {<<"/home/cowboy">>, <<"/home/cowboy">>},
  435. {<<"/home/cowboy">>, <<"/home/cowboy/">>},
  436. {<<"/home/cowboy">>, <<"/home/cowboy/./">>},
  437. {<<"/home/cowboy">>, <<"/home/cowboy/./././././.">>},
  438. {<<"/home/cowboy">>, <<"/home/cowboy/abc/..">>},
  439. {<<"/home/cowboy">>, <<"/home/cowboy/abc/../">>},
  440. {<<"/home/cowboy">>, <<"/home/cowboy/abc/./../.">>},
  441. {<<"/">>, <<"/home/cowboy/../../../../../..">>},
  442. {<<"/etc/passwd">>, <<"/home/cowboy/../../etc/passwd">>}
  443. ],
  444. [{P, fun() -> R = fullpath(P) end} || {R, P} <- Tests].
  445. good_path_check_test_() ->
  446. Tests = [
  447. <<"/home/cowboy/file">>,
  448. <<"/home/cowboy/file/">>,
  449. <<"/home/cowboy/./file">>,
  450. <<"/home/cowboy/././././././file">>,
  451. <<"/home/cowboy/abc/../file">>,
  452. <<"/home/cowboy/abc/../file">>,
  453. <<"/home/cowboy/abc/./.././file">>
  454. ],
  455. [{P, fun() ->
  456. case fullpath(P) of
  457. << "/home/cowboy/", _/binary >> -> ok
  458. end
  459. end} || P <- Tests].
  460. bad_path_check_test_() ->
  461. Tests = [
  462. <<"/home/cowboy/../../../../../../file">>,
  463. <<"/home/cowboy/../../etc/passwd">>
  464. ],
  465. [{P, fun() ->
  466. error = case fullpath(P) of
  467. << "/home/cowboy/", _/binary >> -> ok;
  468. _ -> error
  469. end
  470. end} || P <- Tests].
  471. good_path_win32_check_test_() ->
  472. Tests = case os:type() of
  473. {unix, _} ->
  474. [];
  475. {win32, _} ->
  476. [
  477. <<"c:/home/cowboy/file">>,
  478. <<"c:/home/cowboy/file/">>,
  479. <<"c:/home/cowboy/./file">>,
  480. <<"c:/home/cowboy/././././././file">>,
  481. <<"c:/home/cowboy/abc/../file">>,
  482. <<"c:/home/cowboy/abc/../file">>,
  483. <<"c:/home/cowboy/abc/./.././file">>
  484. ]
  485. end,
  486. [{P, fun() ->
  487. case fullpath(P) of
  488. << "c:/home/cowboy/", _/binary >> -> ok
  489. end
  490. end} || P <- Tests].
  491. bad_path_win32_check_test_() ->
  492. Tests = case os:type() of
  493. {unix, _} ->
  494. [];
  495. {win32, _} ->
  496. [
  497. <<"c:/home/cowboy/../../secretfile.bat">>,
  498. <<"c:/home/cowboy/c:/secretfile.bat">>,
  499. <<"c:/home/cowboy/..\\..\\secretfile.bat">>,
  500. <<"c:/home/cowboy/c:\\secretfile.bat">>
  501. ]
  502. end,
  503. [{P, fun() ->
  504. error = case fullpath(P) of
  505. << "c:/home/cowboy/", _/binary >> -> ok;
  506. _ -> error
  507. end
  508. end} || P <- Tests].
  509. -endif.