net.http, httpclient_listener: Move request sending from net.http to onconnect()...
[prosody.git] / net / httpclient_listener.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 log = require "util.logger".init("httpclient_listener");
10 local t_concat = table.concat;
11
12 local connlisteners_register = require "net.connlisteners".register;
13
14 local requests = {}; -- Open requests
15 local buffers = {}; -- Buffers of partial lines
16
17 local httpclient = { default_port = 80, default_mode = "*a" };
18
19 function httpclient.onconnect(conn)
20         local req = requests[conn];
21         -- Send the request
22         local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" };
23         if req.query then
24                 t_insert(request_line, 4, "?"..req.query);
25         end
26         
27         conn:write(t_concat(request_line));
28         local t = { [2] = ": ", [4] = "\r\n" };
29         for k, v in pairs(req.headers) do
30                 t[1], t[3] = k, v;
31                 conn:write(t_concat(t));
32         end
33         conn:write("\r\n");
34         
35         if body then
36                 conn:write(body);
37         end
38 end
39
40 function httpclient.onincoming(conn, data)
41         local request = requests[conn];
42
43         if not request then
44                 log("warn", "Received response from connection %s with no request attached!", tostring(conn));
45                 return;
46         end
47
48         if data and request.reader then
49                 request:reader(data);
50         end
51 end
52
53 function httpclient.ondisconnect(conn, err)
54         local request = requests[conn];
55         if request and err ~= "closed" then
56                 request:reader(nil);
57         end
58         requests[conn] = nil;
59 end
60
61 function httpclient.register_request(conn, req)
62         log("debug", "Attaching request %s to connection %s", tostring(req.id or req), tostring(conn));
63         requests[conn] = req;
64 end
65
66 connlisteners_register("httpclient", httpclient);