mod_http_files: Export function can be used by other modules to serve files. Don...
[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 lfs = require "lfs";
11
12 local os_date = os.date;
13 local open = io.open;
14 local stat = lfs.attributes;
15 local build_path = require"socket.url".build_path;
16
17 local base_path = module:get_option_string("http_files_dir", module:get_option_string("http_path"));
18 local dir_indices = module:get_option("http_index_files", { "index.html", "index.htm" });
19 local directory_index = module:get_option_boolean("http_dir_listing");
20
21 local mime_map = module:shared("mime").types;
22 if not mime_map then
23         mime_map = {
24                 html = "text/html", htm = "text/html",
25                 xml = "application/xml",
26                 txt = "text/plain",
27                 css = "text/css",
28                 js = "application/javascript",
29                 png = "image/png",
30                 gif = "image/gif",
31                 jpeg = "image/jpeg", jpg = "image/jpeg",
32                 svg = "image/svg+xml",
33         };
34         module:shared("mime").types = mime_map;
35
36         local mime_types, err = open(module:get_option_string("mime_types_file", "/etc/mime.types"),"r");
37         if mime_types then
38                 local mime_data = mime_types:read("*a");
39                 mime_types:close();
40                 setmetatable(mime_map, {
41                         __index = function(t, ext)
42                                 local typ = mime_data:match("\n(%S+)[^\n]*%s"..(ext:lower()).."%s") or "application/octet-stream";
43                                 t[ext] = typ;
44                                 return typ;
45                         end
46                 });
47         end
48 end
49
50 local cache = setmetatable({}, { __mode = "kv" }); -- Let the garbage collector have it if it wants to.
51
52 function serve(opts)
53         local base_path = opts.path;
54         local dir_indices = opts.index_files or dir_indices;
55         local directory_index = opts.directory_index;
56         local function serve_file(event, path)
57                 local request, response = event.request, event.response;
58                 local orig_path = request.path;
59                 local full_path = base_path .. (path and "/"..path or "");
60                 local attr = stat(full_path);
61                 if not attr then
62                         return 404;
63                 end
64
65                 local request_headers, response_headers = request.headers, response.headers;
66
67                 local last_modified = os_date('!%a, %d %b %Y %H:%M:%S GMT', attr.modification);
68                 response_headers.last_modified = last_modified;
69
70                 local etag = ("%02x-%x-%x-%x"):format(attr.dev or 0, attr.ino or 0, attr.size or 0, attr.modification or 0);
71                 response_headers.etag = etag;
72
73                 local if_none_match = request_headers.if_none_match
74                 local if_modified_since = request_headers.if_modified_since;
75                 if etag == if_none_match
76                 or (not if_none_match and last_modified == if_modified_since) then
77                         return 304;
78                 end
79
80                 local data = cache[path];
81                 if data and data.etag == etag then
82                         response_headers.content_type = data.content_type;
83                         data = data.data;
84                 elseif attr.mode == "directory" then
85                         if full_path:sub(-1) ~= "/" then
86                                 local path = { is_absolute = true, is_directory = true };
87                                 for dir in orig_path:gmatch("[^/]+") do path[#path+1]=dir; end
88                                 response_headers.location = build_path(path);
89                                 return 301;
90                         end
91                         for i=1,#dir_indices do
92                                 if stat(full_path..dir_indices[i], "mode") == "file" then
93                                         return serve_file(event, path..dir_indices[i]);
94                                 end
95                         end
96
97                         if not directory_index then
98                                 return 403;
99                         else
100                                 local html = require"util.stanza".stanza("html")
101                                         :tag("head"):tag("title"):text(path):up()
102                                                 :tag("meta", { charset="utf-8" }):up()
103                                         :up()
104                                         :tag("body"):tag("h1"):text(path):up()
105                                                 :tag("ul");
106                                 for file in lfs.dir(full_path) do
107                                         if file:sub(1,1) ~= "." then
108                                                 local attr = stat(full_path..file) or {};
109                                                 html:tag("li", { class = attr.mode })
110                                                         :tag("a", { href = file }):text(file)
111                                                 :up():up();
112                                         end
113                                 end
114                                 data = "<!DOCTYPE html>\n"..tostring(html);
115                                 cache[path] = { data = data, content_type = mime_map.html; etag = etag; };
116                                 response_headers.content_type = mime_map.html;
117                         end
118
119                 else
120                         local f, err = open(full_path, "rb");
121                         if f then
122                                 data, err = f:read("*a");
123                                 f:close();
124                         end
125                         if not data then
126                                 module:log("debug", "Could not open or read %s. Error was %s", full_path, err);
127                                 return 403;
128                         end
129                         local ext = path:match("%.([^./]+)$");
130                         local content_type = ext and mime_map[ext];
131                         cache[path] = { data = data; content_type = content_type; etag = etag };
132                         response_headers.content_type = content_type;
133                 end
134
135                 return response:send(data);
136         end
137
138         return serve_file;
139 end
140
141
142 if base_path then
143         module:provides("http", {
144                 route = {
145                         ["GET /*"] = serve {
146                                 path = base_path;
147                                 directory_index = directory_index;
148                         }
149                 };
150         });
151 else
152         module:log("debug", "http_files_dir not set, assuming use by some other module");
153 end
154