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