Merge 0.9->0.10
[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         local out = {};
60
61         local c = 0;
62         for component in path:gmatch("([^/]+)") do
63                 component = urldecode(component);
64                 if component:find(forbidden_chars_pattern) then
65                         return nil;
66                 elseif component == ".." then
67                         if c <= 0 then
68                                 return nil;
69                         end
70                         out[c] = nil;
71                         c = c - 1;
72                 elseif component ~= "." then
73                         c = c + 1;
74                         out[c] = component;
75                 end
76         end
77         return "/"..table.concat(out, "/");
78 end
79
80 local cache = setmetatable({}, { __mode = "kv" }); -- Let the garbage collector have it if it wants to.
81
82 function serve(opts)
83         if type(opts) ~= "table" then -- assume path string
84                 opts = { path = opts };
85         end
86         local base_path = opts.path;
87         local dir_indices = opts.index_files or dir_indices;
88         local directory_index = opts.directory_index;
89         local function serve_file(event, path)
90                 local request, response = event.request, event.response;
91                 path = sanitize_path(path);
92                 if not path then
93                         return 400;
94                 end
95                 local orig_path = sanitize_path(request.path);
96                 local full_path = base_path .. (path and "/"..path or ""):gsub("/", path_sep);
97                 local attr = stat(full_path:match("^.*[^\\/]")); -- Strip trailing path separator because Windows
98                 if not attr then
99                         return 404;
100                 end
101
102                 local request_headers, response_headers = request.headers, response.headers;
103
104                 local last_modified = os_date('!%a, %d %b %Y %H:%M:%S GMT', attr.modification);
105                 response_headers.last_modified = last_modified;
106
107                 local etag = ("%02x-%x-%x-%x"):format(attr.dev or 0, attr.ino or 0, attr.size or 0, attr.modification or 0);
108                 response_headers.etag = etag;
109
110                 local if_none_match = request_headers.if_none_match
111                 local if_modified_since = request_headers.if_modified_since;
112                 if etag == if_none_match
113                 or (not if_none_match and last_modified == if_modified_since) then
114                         return 304;
115                 end
116
117                 local data = cache[orig_path];
118                 if data and data.etag == etag then
119                         response_headers.content_type = data.content_type;
120                         data = data.data;
121                 elseif attr.mode == "directory" and path then
122                         if full_path:sub(-1) ~= "/" then
123                                 local path = { is_absolute = true, is_directory = true };
124                                 for dir in orig_path:gmatch("[^/]+") do path[#path+1]=dir; end
125                                 response_headers.location = build_path(path);
126                                 return 301;
127                         end
128                         for i=1,#dir_indices do
129                                 if stat(full_path..dir_indices[i], "mode") == "file" then
130                                         return serve_file(event, path..dir_indices[i]);
131                                 end
132                         end
133
134                         if directory_index then
135                                 data = server._events.fire_event("directory-index", { path = request.path, full_path = full_path });
136                         end
137                         if not data then
138                                 return 403;
139                         end
140                         cache[orig_path] = { data = data, content_type = mime_map.html; etag = etag; };
141                         response_headers.content_type = mime_map.html;
142
143                 else
144                         local f, err = open(full_path, "rb");
145                         if f then
146                                 data, err = f:read("*a");
147                                 f:close();
148                         end
149                         if not data then
150                                 module:log("debug", "Could not open or read %s. Error was %s", full_path, err);
151                                 return 403;
152                         end
153                         local ext = full_path:match("%.([^./]+)$");
154                         local content_type = ext and mime_map[ext];
155                         cache[orig_path] = { data = data; content_type = content_type; etag = etag };
156                         response_headers.content_type = content_type;
157                 end
158
159                 return response:send(data);
160         end
161
162         return serve_file;
163 end
164
165 function wrap_route(routes)
166         for route,handler in pairs(routes) do
167                 if type(handler) ~= "function" then
168                         routes[route] = serve(handler);
169                 end
170         end
171         return routes;
172 end
173
174 if base_path then
175         module:provides("http", {
176                 route = {
177                         ["GET /*"] = serve {
178                                 path = base_path;
179                                 directory_index = directory_index;
180                         }
181                 };
182         });
183 else
184         module:log("debug", "http_files_dir not set, assuming use by some other module");
185 end
186