net.httpserver: Removed unused import and variables.
[prosody.git] / net / httpserver.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
10 local server = require "net.server"
11 local url_parse = require "socket.url".parse;
12 local httpstream_new = require "util.httpstream".new;
13
14 local connlisteners_start = require "net.connlisteners".start;
15 local connlisteners_get = require "net.connlisteners".get;
16 local listener;
17
18 local t_insert, t_concat = table.insert, table.concat;
19 local tonumber, tostring, pairs, ipairs, type = tonumber, tostring, pairs, ipairs, type;
20
21 local urlencode = function (s) return s and (s:gsub("%W", function (c) return ("%%%02x"):format(c:byte()); end)); end
22
23 local log = require "util.logger".init("httpserver");
24
25 local http_servers = {};
26
27 module "httpserver"
28
29 local default_handler;
30
31 local function expectbody(reqt)
32         return reqt.method == "POST";
33 end
34
35 local function send_response(request, response)
36         -- Write status line
37         local resp;
38         if response.body or response.headers then
39                 local body = response.body and tostring(response.body);
40                 log("debug", "Sending response to %s", request.id);
41                 resp = { "HTTP/1.0 "..(response.status or "200 OK").."\r\n" };
42                 local h = response.headers;
43                 if h then
44                         for k, v in pairs(h) do
45                                 t_insert(resp, k..": "..v.."\r\n");
46                         end
47                 end
48                 if body and not (h and h["Content-Length"]) then
49                         t_insert(resp, "Content-Length: "..#body.."\r\n");
50                 end
51                 t_insert(resp, "\r\n");
52                 
53                 if body and request.method ~= "HEAD" then
54                         t_insert(resp, body);
55                 end
56                 request.write(t_concat(resp));
57         else
58                 -- Response we have is just a string (the body)
59                 log("debug", "Sending 200 response to %s", request.id or "<none>");
60                 
61                 local resp = "HTTP/1.0 200 OK\r\n"
62                         .. "Connection: close\r\n"
63                         .. "Content-Type: text/html\r\n"
64                         .. "Content-Length: "..#response.."\r\n"
65                         .. "\r\n"
66                         .. response;
67                 
68                 request.write(resp);
69         end
70         if not request.stayopen then
71                 request:destroy();
72         end
73 end
74
75 local function call_callback(request, err)
76         if request.handled then return; end
77         request.handled = true;
78         local callback = request.callback;
79         if not callback and request.path then
80                 local path = request.url.path;
81                 local base = path:match("^/([^/?]+)");
82                 if not base then
83                         base = path:match("^http://[^/?]+/([^/?]+)");
84                 end
85                 
86                 callback = (request.server and request.server.handlers[base]) or default_handler;
87         end
88         if callback then
89                 if err then
90                         log("debug", "Request error: "..err);
91                         if not callback(nil, err, request) then
92                                 destroy_request(request);
93                         end
94                         return;
95                 end
96                 
97                 local response = callback(request.method, request.body and t_concat(request.body), request);
98                 if response then
99                         if response == true and not request.destroyed then
100                                 -- Keep connection open, we will reply later
101                                 log("debug", "Request %s left open, on_destroy is %s", request.id, tostring(request.on_destroy));
102                         elseif response ~= true then
103                                 -- Assume response
104                                 send_response(request, response);
105                                 destroy_request(request);
106                         end
107                 else
108                         log("debug", "Request handler provided no response, destroying request...");
109                         -- No response, close connection
110                         destroy_request(request);
111                 end
112         end
113 end
114
115 local function request_reader(request, data, startpos)
116         if not request.parser then
117                 local function success_cb(r)
118                         for k,v in pairs(r) do request[k] = v; end
119                         request.url = url_parse(request.path);
120                         request.url.path = request.url.path and request.url.path:gsub("%%(%x%x)", function(x) return x.char(tonumber(x, 16)) end);
121                         request.body = { request.body };
122                         call_callback(request);
123                 end
124                 local function error_cb(r)
125                         call_callback(request, r or "connection-closed");
126                         destroy_request(request);
127                 end
128                 request.parser = httpstream_new(success_cb, error_cb);
129         end
130         request.parser:feed(data);
131 end
132
133 -- The default handler for requests
134 default_handler = function (method, body, request)
135         log("debug", method.." request for "..tostring(request.path) .. " on port "..request.handler:serverport());
136         return { status = "404 Not Found",
137                         headers = { ["Content-Type"] = "text/html" },
138                         body = "<html><head><title>Page Not Found</title></head><body>Not here :(</body></html>" };
139 end
140
141
142 function new_request(handler)
143         return { handler = handler, conn = handler,
144                         write = function (...) return handler:write(...); end, state = "request",
145                         server = http_servers[handler:serverport()],
146                         send = send_response,
147                         destroy = destroy_request,
148                         id = tostring{}:match("%x+$")
149                          };
150 end
151
152 function destroy_request(request)
153         log("debug", "Destroying request %s", request.id);
154         listener = listener or connlisteners_get("httpserver");
155         if not request.destroyed then
156                 request.destroyed = true;
157                 if request.on_destroy then
158                         log("debug", "Request has destroy callback");
159                         request.on_destroy(request);
160                 else
161                         log("debug", "Request has no destroy callback");
162                 end
163                 request.handler:close()
164                 if request.conn then
165                         listener.ondisconnect(request.conn, "closed");
166                 end
167         end
168 end
169
170 function new(params)
171         local http_server = http_servers[params.port];
172         if not http_server then
173                 http_server = { handlers = {} };
174                 http_servers[params.port] = http_server;
175                 -- We weren't already listening on this port, so start now
176                 connlisteners_start("httpserver", params);
177         end
178         if params.base then
179                 http_server.handlers[params.base] = params.handler;
180         end
181 end
182
183 function set_default_handler(handler)
184         default_handler = handler;
185 end
186
187 function new_from_config(ports, handle_request, default_options)
188         if type(handle_request) == "string" then -- COMPAT with old plugins
189                 log("warn", "Old syntax of httpserver.new_from_config being used to register %s", handle_request);
190                 handle_request, default_options = default_options, { base = handle_request };
191         end
192         ports = ports or {5280};
193         for _, options in ipairs(ports) do
194                 local port = default_options.port or 5280;
195                 local base = default_options.base;
196                 local ssl = default_options.ssl or false;
197                 local interface = default_options.interface;
198                 if type(options) == "number" then
199                         port = options;
200                 elseif type(options) == "table" then
201                         port = options.port or port;
202                         base = options.path or base;
203                         ssl = options.ssl or ssl;
204                         interface = options.interface or interface;
205                 elseif type(options) == "string" then
206                         base = options;
207                 end
208                 
209                 if ssl then
210                         ssl.mode = "server";
211                         ssl.protocol = "sslv23";
212                         ssl.options = "no_sslv2";
213                 end
214                 
215                 new{ port = port, interface = interface,
216                         base = base, handler = handle_request,
217                         ssl = ssl, type = (ssl and "ssl") or "tcp" };
218         end
219 end
220
221 _M.request_reader = request_reader;
222 _M.send_response = send_response;
223 _M.urlencode = urlencode;
224
225 return _M;