b78f84382b40137484b3261ce541ded64c153d27
[prosody.git] / net / http.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 local b64 = require "util.encodings".base64.encode;
10 local url = require "socket.url"
11 local httpstream_new = require "net.http.parser".new;
12 local util_http = require "util.http";
13
14 local ssl_available = pcall(require, "ssl");
15
16 local server = require "net.server"
17
18 local t_insert, t_concat = table.insert, table.concat;
19 local pairs = pairs;
20 local tonumber, tostring, xpcall, select, traceback =
21       tonumber, tostring, xpcall, select, debug.traceback;
22 local assert, error = assert, error
23
24 local log = require "util.logger".init("http");
25
26 local _ENV = nil;
27
28 local requests = {}; -- Open requests
29
30 local listener = { default_port = 80, default_mode = "*a" };
31
32 function listener.onconnect(conn)
33         local req = requests[conn];
34         -- Send the request
35         local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" };
36         if req.query then
37                 t_insert(request_line, 4, "?"..req.query);
38         end
39
40         conn:write(t_concat(request_line));
41         local t = { [2] = ": ", [4] = "\r\n" };
42         for k, v in pairs(req.headers) do
43                 t[1], t[3] = k, v;
44                 conn:write(t_concat(t));
45         end
46         conn:write("\r\n");
47
48         if req.body then
49                 conn:write(req.body);
50         end
51 end
52
53 function listener.onincoming(conn, data)
54         local request = requests[conn];
55
56         if not request then
57                 log("warn", "Received response from connection %s with no request attached!", tostring(conn));
58                 return;
59         end
60
61         if data and request.reader then
62                 request:reader(data);
63         end
64 end
65
66 function listener.ondisconnect(conn, err)
67         local request = requests[conn];
68         if request and request.conn then
69                 request:reader(nil, err);
70         end
71         requests[conn] = nil;
72 end
73
74 function listener.ondetach(conn)
75         requests[conn] = nil;
76 end
77
78 local function destroy_request(request)
79         if request.conn then
80                 request.conn = nil;
81                 request.handler:close()
82         end
83 end
84
85 local function request_reader(request, data, err)
86         if not request.parser then
87                 local function error_cb(reason)
88                         if request.callback then
89                                 request.callback(reason or "connection-closed", 0, request);
90                                 request.callback = nil;
91                         end
92                         destroy_request(request);
93                 end
94
95                 if not data then
96                         error_cb(err);
97                         return;
98                 end
99
100                 local function success_cb(r)
101                         if request.callback then
102                                 request.callback(r.body, r.code, r, request);
103                                 request.callback = nil;
104                         end
105                         destroy_request(request);
106                 end
107                 local function options_cb()
108                         return request;
109                 end
110                 request.parser = httpstream_new(success_cb, error_cb, "client", options_cb);
111         end
112         request.parser:feed(data);
113 end
114
115 local function handleerr(err) log("error", "Traceback[http]: %s", traceback(tostring(err), 2)); end
116 local function request(u, ex, callback)
117         local req = url.parse(u);
118
119         if not (req and req.host) then
120                 callback(nil, 0, req);
121                 return nil, "invalid-url";
122         end
123
124         if not req.path then
125                 req.path = "/";
126         end
127
128         local method, headers, body;
129
130         local host, port = req.host, req.port;
131         local host_header = host;
132         if (port == "80" and req.scheme == "http")
133         or (port == "443" and req.scheme == "https") then
134                 port = nil;
135         elseif port then
136                 host_header = host_header..":"..port;
137         end
138
139         headers = {
140                 ["Host"] = host_header;
141                 ["User-Agent"] = "Prosody XMPP Server";
142         };
143
144         if req.userinfo then
145                 headers["Authorization"] = "Basic "..b64(req.userinfo);
146         end
147
148         if ex then
149                 req.onlystatus = ex.onlystatus;
150                 body = ex.body;
151                 if body then
152                         method = "POST";
153                         headers["Content-Length"] = tostring(#body);
154                         headers["Content-Type"] = "application/x-www-form-urlencoded";
155                 end
156                 if ex.method then method = ex.method; end
157                 if ex.headers then
158                         for k, v in pairs(ex.headers) do
159                                 headers[k] = v;
160                         end
161                 end
162         end
163
164         -- Attach to request object
165         req.method, req.headers, req.body = method, headers, body;
166
167         local using_https = req.scheme == "https";
168         if using_https and not ssl_available then
169                 error("SSL not available, unable to contact https URL");
170         end
171         local port_number = port and tonumber(port) or (using_https and 443 or 80);
172
173         local sslctx = false;
174         if using_https then
175                 sslctx = ex and ex.sslctx or { mode = "client", protocol = "sslv23", options = { "no_sslv2", "no_sslv3" } };
176         end
177
178         local handler, conn = server.addclient(host, port_number, listener, "*a", sslctx)
179         if not handler then
180                 callback(nil, 0, req);
181                 return nil, conn;
182         end
183         req.handler, req.conn = handler, conn
184         req.write = function (...) return req.handler:write(...); end
185
186         req.callback = function (content, code, request, response) log("debug", "Calling callback, status %s", code or "---"); return select(2, xpcall(function () return callback(content, code, request, response) end, handleerr)); end
187         req.reader = request_reader;
188         req.state = "status";
189
190         requests[req.handler] = req;
191         return req;
192 end
193
194 return {
195         request = request;
196         
197         -- COMPAT
198         urlencode = util_http.urlencode;
199         urldecode = util_http.urldecode;
200         formencode = util_http.formencode;
201         formdecode = util_http.formdecode;
202 };