ejabberdsql2prosody: Allow for multiple INSERTs to the same table
[prosody.git] / net / adns.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 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 server = require "net.server";
10 local dns = require "net.dns";
11
12 local log = require "util.logger".init("adns");
13
14 local coroutine, tostring, pcall = coroutine, tostring, pcall;
15
16 module "adns"
17
18 function lookup(handler, qname, qtype, qclass)
19         return coroutine.wrap(function (peek)
20                                 if peek then
21                                         log("debug", "Records for %s already cached, using those...", qname);
22                                         handler(peek);
23                                         return;
24                                 end
25                                 log("debug", "Records for %s not in cache, sending query (%s)...", qname, tostring(coroutine.running()));
26                                 dns.query(qname, qtype, qclass);
27                                 coroutine.yield({ qclass or "IN", qtype or "A", qname, coroutine.running()}); -- Wait for reply
28                                 log("debug", "Reply for %s (%s)", qname, tostring(coroutine.running()));
29                                 local ok, err = pcall(handler, dns.peek(qname, qtype, qclass));
30                                 if not ok then
31                                         log("debug", "Error in DNS response handler: %s", tostring(err));
32                                 end
33                         end)(dns.peek(qname, qtype, qclass));
34 end
35
36 function cancel(handle, call_handler)
37         log("warn", "Cancelling DNS lookup for %s", tostring(handle[3]));
38         dns.cancel(handle);
39         if call_handler then
40                 coroutine.resume(handle[4]);
41         end
42 end
43
44 function new_async_socket(sock)
45         local newconn = {};
46         local listener = {};
47         function listener.incoming(conn, data)
48                 dns.feed(sock, data);
49         end
50         function listener.disconnect()
51         end
52         newconn.handler, newconn._socket = server.wrapclient(sock, "dns", 53, listener);
53         newconn.handler.settimeout = function () end
54         newconn.handler.setsockname = function (_, ...) return sock:setsockname(...); end
55         newconn.handler.setpeername = function (_, ...) local ret = sock:setpeername(...); _.setsend(sock.send); return ret; end
56         newconn.handler.connect = function (_, ...) return sock:connect(...) end        
57         newconn.handler.send = function (_, data) _.write(data); return _.sendbuffer(); end     
58         return newconn.handler;
59 end
60
61 dns:socket_wrapper_set(new_async_socket);
62
63 return _M;