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