38db0c0df2f6ebce0130301fc017465182fba7d2
[prosody.git] / net / http.lua
1
2 local socket = require "socket"
3 local mime = require "mime"
4 local url = require "socket.url"
5
6 local server = require "net.server"
7
8 local connlisteners_get = require "net.connlisteners".get;
9 local listener = connlisteners_get("httpclient") or error("No httpclient listener!");
10
11 local t_insert, t_concat = table.insert, table.concat;
12 local tonumber, tostring, pairs = tonumber, tostring, pairs;
13 local print = function () end
14
15 local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
16 local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end
17
18 module "http"
19
20 local function expectbody(reqt, code)
21     if reqt.method == "HEAD" then return nil end
22     if code == 204 or code == 304 then return nil end
23     if code >= 100 and code < 200 then return nil end
24     return 1
25 end
26
27 local function request_reader(request, data, startpos)
28         if not data then
29                 if request.body then
30                         request.callback(t_concat(request.body), request.code, request);
31                 else
32                         -- Error.. connection was closed prematurely
33                         request.callback("connection-closed", 0, request);
34                 end
35                 destroy_request(request);
36                 return;
37         end
38         if request.state == "body" then
39                 print("Reading body...")
40                 if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end
41                 if startpos then
42                         data = data:sub(startpos, -1)
43                 end
44                 t_insert(request.body, data);
45                 if request.bodylength then
46                         request.havebodylength = request.havebodylength + #data;
47                         if request.havebodylength >= request.bodylength then
48                                 -- We have the body
49                                 if request.callback then
50                                         request.callback(t_concat(request.body), request.code, request);
51                                 end
52                         end
53                         print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength);
54                 end
55         elseif request.state == "headers" then
56                 print("Reading headers...")
57                 local pos = startpos;
58                 local headers = request.responseheaders or {};
59                 for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do
60                         startpos = startpos + #line + 2;
61                         local k, v = line:match("(%S+): (.+)");
62                         if k and v then
63                                 headers[k:lower()] = v;
64                                 print("Header: "..k:lower().." = "..v);
65                         elseif #line == 0 then
66                                 request.responseheaders = headers;
67                                 break;
68                         else
69                                 print("Unhandled header line: "..line);
70                         end
71                 end
72                 -- Reached the end of the headers
73                 request.state = "body";
74                 if #data > startpos then
75                         return request_reader(request, data, startpos);
76                 end
77         elseif request.state == "status" then
78                 print("Reading status...")
79                 local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos);
80                 code = tonumber(code);
81                 if not code then
82                         return request.callback("invalid-status-line", 0, request);
83                 end
84                 
85                 request.code, request.responseversion = code, http;
86                 
87                 if request.onlystatus or not expectbody(request, code) then
88                         if request.callback then
89                                 request.callback(nil, code, request);
90                         end
91                         destroy_request(request);
92                         return;
93                 end
94                 
95                 request.state = "headers";
96                 
97                 if #data > linelen then
98                         return request_reader(request, data, linelen);
99                 end
100         end
101 end
102
103 function request(u, ex, callback)
104         local req = url.parse(u);
105         
106         local custom_headers, body;
107         local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" }
108         
109         
110         if req.userinfo then
111                 default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo);
112         end
113         
114         if ex then
115                 custom_headers = ex.custom_headers;
116                 req.onlystatus = ex.onlystatus;
117                 body = ex.body;
118                 if body then
119                         req.method = "POST ";
120                         default_headers["Content-Length"] = tostring(#body);
121                         default_headers["Content-Type"] = "application/x-www-form-urlencoded";
122                 end
123                 if ex.method then req.method = ex.method; end
124         end
125         
126         req.handler, req.conn = server.wraptcpclient(listener, socket.tcp(), req.host, req.port or 80, 0, "*a");
127         req.write = req.handler.write;
128         req.conn:settimeout(0);
129         local ok, err = req.conn:connect(req.host, req.port or 80);
130         if not ok and err ~= "timeout" then
131                 return nil, err;
132         end
133         
134         req.write((req.method or "GET ")..req.path.." HTTP/1.0\r\n");
135         local t = { [2] = ": ", [4] = "\r\n" };
136         if custom_headers then
137                 for k, v in pairs(custom_headers) do
138                         t[1], t[3] = k, v;
139                         req.write(t_concat(t));
140                         default_headers[k] = nil;
141                 end
142         end
143         
144         for k, v in pairs(default_headers) do
145                 t[1], t[3] = k, v;
146                 req.write(t_concat(t));
147                 default_headers[k] = nil;
148         end
149         req.write("\r\n");
150         
151         if body then
152                 req.write(body);
153         end
154         
155         req.callback = callback;
156         req.reader = request_reader;
157         req.state = "status"
158         
159         listener.register_request(req.handler, req);
160
161         return req;
162 end
163
164 function destroy_request(request)
165         if request.conn then
166                 request.handler.close()
167                 listener.disconnect(request.conn, "closed");
168         end
169 end
170
171 _M.urlencode = urlencode;
172
173 return _M;