mod_http_files: Don't prepend / to path twice, sanitize path does this already
[prosody.git] / plugins / mod_http_files.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 module:depends("http");
10 local server = require"net.http.server";
11 local lfs = require "lfs";
12
13 local os_date = os.date;
14 local open = io.open;
15 local stat = lfs.attributes;
16 local build_path = require"socket.url".build_path;
17 local path_sep = package.config:sub(1,1);
18
19 local base_path = module:get_option_string("http_files_dir", module:get_option_string("http_path"));
20 local dir_indices = module:get_option("http_index_files", { "index.html", "index.htm" });
21 local directory_index = module:get_option_boolean("http_dir_listing");
22
23 local mime_map = module:shared("/*/http_files/mime").types;
24 if not mime_map then
25         mime_map = {
26                 html = "text/html", htm = "text/html",
27                 xml = "application/xml",
28                 txt = "text/plain",
29                 css = "text/css",
30                 js = "application/javascript",
31                 png = "image/png",
32                 gif = "image/gif",
33                 jpeg = "image/jpeg", jpg = "image/jpeg",
34                 svg = "image/svg+xml",
35         };
36         module:shared("/*/http_files/mime").types = mime_map;
37
38         local mime_types, err = open(module:get_option_string("mime_types_file", "/etc/mime.types"),"r");
39         if mime_types then
40                 local mime_data = mime_types:read("*a");
41                 mime_types:close();
42                 setmetatable(mime_map, {
43                         __index = function(t, ext)
44                                 local typ = mime_data:match("\n(%S+)[^\n]*%s"..(ext:lower()).."%s") or "application/octet-stream";
45                                 t[ext] = typ;
46                                 return typ;
47                         end
48                 });
49         end
50 end
51
52 local forbidden_chars_pattern = "[/%z]";
53 if prosody.platform == "windows" then
54         forbidden_chars_pattern = "[/%z\001-\031\127\"*:<>?|]"
55 end
56
57 local urldecode = require "util.http".urldecode;
58 function sanitize_path(path)
59         if not path then return end
60         local out = {};
61
62         local c = 0;
63         for component in path:gmatch("([^/]+)") do
64                 component = urldecode(component);
65                 if component:find(forbidden_chars_pattern) then
66                         return nil;
67                 elseif component == ".." then
68                         if c <= 0 then
69                                 return nil;
70                         end
71                         out[c] = nil;
72                         c = c - 1;
73                 elseif component ~= "." then
74                         c = c + 1;
75                         out[c] = component;
76                 end
77         end
78         return "/"..table.concat(out, "/");
79 end
80
81 local cache = setmetatable({}, { __mode = "kv" }); -- Let the garbage collector have it if it wants to.
82
83 function serve(opts)
84         if type(opts) ~= "table" then -- assume path string
85                 opts = { path = opts };
86         end
87         local base_path = opts.path;
88         local dir_indices = opts.index_files or dir_indices;
89         local directory_index = opts.directory_index;
90         local function serve_file(event, path)
91                 local request, response = event.request, event.response;
92                 local sanitized_path = sanitize_path(path);
93                 if path and not sanitized_path then
94                         return 400;
95                 end
96                 path = sanitized_path;
97                 local orig_path = sanitize_path(request.path);
98                 local full_path = base_path .. (path or ""):gsub("/", path_sep);
99                 local attr = stat(full_path:match("^.*[^\\/]")); -- Strip trailing path separator because Windows
100                 if not attr then
101                         return 404;
102                 end
103
104                 local request_headers, response_headers = request.headers, response.headers;
105
106                 local last_modified = os_date('!%a, %d %b %Y %H:%M:%S GMT', attr.modification);
107                 response_headers.last_modified = last_modified;
108
109                 local etag = ("%02x-%x-%x-%x"):format(attr.dev or 0, attr.ino or 0, attr.size or 0, attr.modification or 0);
110                 response_headers.etag = etag;
111
112                 local if_none_match = request_headers.if_none_match
113                 local if_modified_since = request_headers.if_modified_since;
114                 if etag == if_none_match
115                 or (not if_none_match and last_modified == if_modified_since) then
116                         return 304;
117                 end
118
119                 local data = cache[orig_path];
120                 if data and data.etag == etag then
121                         response_headers.content_type = data.content_type;
122                         data = data.data;
123                 elseif attr.mode == "directory" and path then
124                         if full_path:sub(-1) ~= "/" then
125                                 local path = { is_absolute = true, is_directory = true };
126                                 for dir in orig_path:gmatch("[^/]+") do path[#path+1]=dir; end
127                                 response_headers.location = build_path(path);
128                                 return 301;
129                         end
130                         for i=1,#dir_indices do
131                                 if stat(full_path..dir_indices[i], "mode") == "file" then
132                                         return serve_file(event, path..dir_indices[i]);
133                                 end
134                         end
135
136                         if directory_index then
137                                 data = server._events.fire_event("directory-index", { path = request.path, full_path = full_path });
138                         end
139                         if not data then
140                                 return 403;
141                         end
142                         cache[orig_path] = { data = data, content_type = mime_map.html; etag = etag; };
143                         response_headers.content_type = mime_map.html;
144
145                 else
146                         local f, err = open(full_path, "rb");
147                         if f then
148                                 data, err = f:read("*a");
149                                 f:close();
150                         end
151                         if not data then
152                                 module:log("debug", "Could not open or read %s. Error was %s", full_path, err);
153                                 return 403;
154                         end
155                         local ext = full_path:match("%.([^./]+)$");
156                         local content_type = ext and mime_map[ext];
157                         cache[orig_path] = { data = data; content_type = content_type; etag = etag };
158                         response_headers.content_type = content_type;
159                 end
160
161                 return response:send(data);
162         end
163
164         return serve_file;
165 end
166
167 function wrap_route(routes)
168         for route,handler in pairs(routes) do
169                 if type(handler) ~= "function" then
170                         routes[route] = serve(handler);
171                 end
172         end
173         return routes;
174 end
175
176 if base_path then
177         module:provides("http", {
178                 route = {
179                         ["GET /*"] = serve {
180                                 path = base_path;
181                                 directory_index = directory_index;
182                         }
183                 };
184         });
185 else
186         module:log("debug", "http_files_dir not set, assuming use by some other module");
187 end
188