2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
10 local httpserver = require "net.httpserver";
13 local t_concat = table.concat;
15 local http_base = config.get("*", "core", "http_path") or "www_files";
17 local response_400 = { status = "400 Bad Request", body = "<h1>Bad Request</h1>Sorry, we didn't understand your request :(" };
18 local response_404 = { status = "404 Not Found", body = "<h1>Page Not Found</h1>Sorry, we couldn't find what you were looking for :(" };
20 -- TODO: Should we read this from /etc/mime.types if it exists? (startup time...?)
26 txt = "plain/text; charset=utf-8";
27 js = "text/javascript";
31 local function preprocess_path(path)
32 if path:sub(1,1) ~= "/" then
36 for component in path:gmatch("([^/]+)/") do
37 if component == ".." then
39 elseif component ~= "." then
49 function serve_file(path)
50 local f, err = open(http_base..path, "r");
51 if not f then return response_404; end
52 local data = f:read("*a");
54 local ext = path:match("%.([^.]*)$");
55 local mime = mime_map[ext];
57 mime = ext and "application/octet-stream" or "text/html";
59 module:log("warn", "ext: %s, mime: %s", ext, mime);
61 headers = { ["Content-Type"] = mime; };
66 local function handle_file_request(method, body, request)
67 local path = preprocess_path(request.url.path);
68 if not path then return response_400; end
69 path = path:gsub("^/[^/]+", ""); -- Strip /files/
70 return serve_file(path);
73 local function handle_default_request(method, body, request)
74 local path = preprocess_path(request.url.path);
75 if not path then return response_400; end
76 return serve_file(path);
79 local ports = config.get(module.host, "core", "http_ports") or { 5280 };
80 httpserver.set_default_handler(handle_default_request);
81 httpserver.new_from_config(ports, handle_file_request, { base = "files" });