mod_console: s2s:close: Use session:close() if that exists, otherwise just destroy...
[prosody.git] / plugins / mod_httpserver.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 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
10 local httpserver = require "net.httpserver";
11
12 local open = io.open;
13 local t_concat = table.concat;
14 local check_http_path;
15
16 local http_base = config.get("*", "core", "http_path") or "www_files";
17
18 local response_403 = { status = "403 Forbidden", body = "<h1>Invalid URL</h1>Sorry, we couldn't find what you were looking for :(" };
19 local response_404 = { status = "404 Not Found", body = "<h1>Page Not Found</h1>Sorry, we couldn't find what you were looking for :(" };
20
21 local http_path = { http_base };
22 local function handle_request(method, body, request)
23         local path = check_http_path(request.url.path:gsub("^/[^/]+%.*", ""));
24         if not path then
25                 return response_403;
26         end
27         http_path[2] = path;
28         local f, err = open(t_concat(http_path), "r");
29         if not f then return response_404; end
30         local data = f:read("*a");
31         f:close();
32         return data;
33 end
34
35 local ports = config.get(module.host, "core", "http_ports") or { 5280 };
36 httpserver.new_from_config(ports, "files", handle_request);
37
38 function check_http_path(url)
39         if url:sub(1,1) ~= "/" then
40                 url = "/"..url;
41         end
42         
43         local level = 0;
44         for part in url:gmatch("%/([^/]+)") do
45                 if part == ".." then
46                         level = level - 1;
47                 elseif part ~= "." then
48                         level = level + 1;
49                 end
50                 if level < 0 then
51                         return nil;
52                 end
53         end
54         return url;
55 end