2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 local server = require "net.server";
10 local dns = require "net.dns";
12 local log = require "util.logger".init("adns");
14 local t_insert, t_remove = table.insert, table.remove;
15 local coroutine, tostring, pcall = coroutine, tostring, pcall;
19 function lookup(handler, qname, qtype, qclass)
20 return coroutine.wrap(function (peek)
22 log("debug", "Records for %s already cached, using those...", qname);
26 log("debug", "Records for %s not in cache, sending query (%s)...", qname, tostring(coroutine.running()));
27 dns.query(qname, qtype, qclass);
28 coroutine.yield({ qclass or "IN", qtype or "A", qname, coroutine.running()}); -- Wait for reply
29 log("debug", "Reply for %s (%s)", qname, tostring(coroutine.running()));
30 local ok, err = pcall(handler, dns.peek(qname, qtype, qclass));
32 log("error", "Error in DNS response handler: %s", tostring(err));
34 end)(dns.peek(qname, qtype, qclass));
37 function cancel(handle, call_handler)
38 log("warn", "Cancelling DNS lookup for %s", tostring(handle[3]));
41 coroutine.resume(handle[4]);
45 function new_async_socket(sock, resolver)
46 local newconn, peername = {}, "<unknown>";
48 function listener.onincoming(conn, data)
51 function listener.ondisconnect(conn, err)
52 log("warn", "DNS socket for %s disconnected: %s", peername, err);
53 local servers = resolver.server;
54 if resolver.socketset[newconn.handler] == resolver.best_server and resolver.best_server == #servers then
55 log("error", "Exhausted all %d configured DNS servers, next lookup will try %s again", #servers, servers[1]);
58 resolver:servfail(conn); -- Let the magic commence
60 newconn.handler, newconn._socket = server.wrapclient(sock, "dns", 53, listener);
61 if not newconn.handler then
62 log("warn", "handler is nil");
64 if not newconn._socket then
65 log("warn", "socket is nil");
67 newconn.handler.settimeout = function () end
68 newconn.handler.setsockname = function (_, ...) return sock:setsockname(...); end
69 newconn.handler.setpeername = function (_, ...) peername = (...); local ret = sock:setpeername(...); _.setsend(sock.send); return ret; end
70 newconn.handler.connect = function (_, ...) return sock:connect(...) end
71 newconn.handler.send = function (_, data) _.write(_, data); return _.sendbuffer(); end
72 return newconn.handler;
75 dns:socket_wrapper_set(new_async_socket);