2 -- This file is included with Prosody IM. It has modifications,
3 -- which are hereby placed in the public domain.
6 -- todo: quick (default) header generation
7 -- todo: nxdomain, error handling
8 -- todo: cache results of encodeName
11 -- reference: http://tools.ietf.org/html/rfc1035
12 -- reference: http://tools.ietf.org/html/rfc1876 (LOC)
15 local socket = require "socket";
16 local timer = require "util.timer";
18 local _, windows = pcall(require, "util.windows");
19 local is_windows = (_ and windows) or os.getenv("WINDIR");
21 local coroutine, io, math, string, table =
22 coroutine, io, math, string, table;
24 local ipairs, next, pairs, print, setmetatable, tostring, assert, error, unpack, select, type=
25 ipairs, next, pairs, print, setmetatable, tostring, assert, error, unpack, select, type;
27 local ztact = { -- public domain 20080404 lua@ztact.com
28 get = function(parent, ...)
29 local len = select('#', ...);
31 parent = parent[select(i, ...)];
32 if parent == nil then break; end
36 set = function(parent, ...)
37 local len = select('#', ...);
38 local key, value = select(len-1, ...);
39 local cutpoint, cutkey;
42 local key = select (i, ...)
43 local child = parent[key]
48 elseif next(child, next(child)) then
49 cutpoint = nil; cutkey = nil;
50 elseif cutpoint == nil then
51 cutpoint = parent; cutkey = key;
53 elseif child == nil then
60 if value == nil and cutpoint then
61 cutpoint[cutkey] = nil;
68 local get, set = ztact.get, ztact.set;
70 local default_timeout = 15;
72 -------------------------------------------------- module dns
77 -- dns type & class codes ------------------------------ dns type & class codes
80 local append = table.insert
83 local function highbyte(i) -- - - - - - - - - - - - - - - - - - - highbyte
84 return (i-(i%0x100))/0x100;
88 local function augment (t) -- - - - - - - - - - - - - - - - - - - - augment
90 for i,s in pairs(t) do
93 a[string.lower(s)] = s;
99 local function encode (t) -- - - - - - - - - - - - - - - - - - - - - encode
101 for i,s in pairs(t) do
102 local word = string.char(highbyte(i), i%0x100);
105 code[string.lower(s)] = word;
112 'A', 'NS', 'MD', 'MF', 'CNAME', 'SOA', 'MB', 'MG', 'MR', 'NULL', 'WKS',
113 'PTR', 'HINFO', 'MINFO', 'MX', 'TXT',
114 [ 28] = 'AAAA', [ 29] = 'LOC', [ 33] = 'SRV',
115 [252] = 'AXFR', [253] = 'MAILB', [254] = 'MAILA', [255] = '*' };
118 dns.classes = { 'IN', 'CS', 'CH', 'HS', [255] = '*' };
121 dns.type = augment (dns.types);
122 dns.class = augment (dns.classes);
123 dns.typecode = encode (dns.types);
124 dns.classcode = encode (dns.classes);
128 local function standardize(qname, qtype, qclass) -- - - - - - - standardize
129 if string.byte(qname, -1) ~= 0x2E then qname = qname..'.'; end
130 qname = string.lower(qname);
131 return qname, dns.type[qtype or 'A'], dns.class[qclass or 'IN'];
135 local function prune(rrs, time, soft) -- - - - - - - - - - - - - - - prune
136 time = time or socket.gettime();
137 for i,rr in ipairs(rrs) do
139 -- rr.tod = rr.tod - 50 -- accelerated decripitude
140 rr.ttl = math.floor(rr.tod - time);
142 rrs[rr[rr.type:lower()]] = nil;
143 table.remove(rrs, i);
144 return prune(rrs, time, soft); -- Re-iterate
146 elseif soft == 'soft' then -- What is this? I forget!
148 rrs[rr[rr.type:lower()]] = nil;
149 table.remove(rrs, i);
155 -- metatables & co. ------------------------------------------ metatables & co.
159 resolver.__index = resolver;
161 resolver.timeout = default_timeout;
163 local function default_rr_tostring(rr)
164 local rr_val = rr.type and rr[rr.type:lower()];
165 if type(rr_val) ~= "string" then
166 return "<UNKNOWN RDATA TYPE>";
171 local special_tostrings = {
172 LOC = resolver.LOC_tostring;
174 return string.format('%2i %s', rr.pref, rr.mx);
178 return string.format('%5d %5d %5d %s', s.priority, s.weight, s.port, s.target);
182 local rr_metatable = {}; -- - - - - - - - - - - - - - - - - - - rr_metatable
183 function rr_metatable.__tostring(rr)
184 local rr_string = (special_tostrings[rr.type] or default_rr_tostring)(rr);
185 return string.format('%2s %-5s %6i %-28s %s', rr.class, rr.type, rr.ttl, rr.name, rr_string);
189 local rrs_metatable = {}; -- - - - - - - - - - - - - - - - - - rrs_metatable
190 function rrs_metatable.__tostring(rrs)
192 for i,rr in ipairs(rrs) do
193 append(t, tostring(rr)..'\n');
195 return table.concat(t);
199 local cache_metatable = {}; -- - - - - - - - - - - - - - - - cache_metatable
200 function cache_metatable.__tostring(cache)
201 local time = socket.gettime();
203 for class,types in pairs(cache) do
204 for type,names in pairs(types) do
205 for name,rrs in pairs(names) do
207 append(t, tostring(rrs));
211 return table.concat(t);
215 function resolver:new() -- - - - - - - - - - - - - - - - - - - - - resolver
216 local r = { active = {}, cache = {}, unsorted = {} };
217 setmetatable(r, resolver);
218 setmetatable(r.cache, cache_metatable);
219 setmetatable(r.unsorted, { __mode = 'kv' });
224 -- packet layer -------------------------------------------------- packet layer
227 function dns.random(...) -- - - - - - - - - - - - - - - - - - - dns.random
228 math.randomseed(math.floor(10000*socket.gettime()) % 0x100000000);
229 dns.random = math.random;
230 return dns.random(...);
234 local function encodeHeader(o) -- - - - - - - - - - - - - - - encodeHeader
236 o.id = o.id or dns.random(0, 0xffff); -- 16b (random) id
238 o.rd = o.rd or 1; -- 1b 1 recursion desired
239 o.tc = o.tc or 0; -- 1b 1 truncated response
240 o.aa = o.aa or 0; -- 1b 1 authoritative response
241 o.opcode = o.opcode or 0; -- 4b 0 query
243 -- 2 server status request
245 o.qr = o.qr or 0; -- 1b 0 query, 1 response
247 o.rcode = o.rcode or 0; -- 4b 0 no error
254 o.z = o.z or 0; -- 3b 0 resvered
255 o.ra = o.ra or 0; -- 1b 1 recursion available
257 o.qdcount = o.qdcount or 1; -- 16b number of question RRs
258 o.ancount = o.ancount or 0; -- 16b number of answers RRs
259 o.nscount = o.nscount or 0; -- 16b number of nameservers RRs
260 o.arcount = o.arcount or 0; -- 16b number of additional RRs
262 -- string.char() rounds, so prevent roundup with -0.4999
263 local header = string.char(
264 highbyte(o.id), o.id %0x100,
265 o.rd + 2*o.tc + 4*o.aa + 8*o.opcode + 128*o.qr,
266 o.rcode + 16*o.z + 128*o.ra,
267 highbyte(o.qdcount), o.qdcount %0x100,
268 highbyte(o.ancount), o.ancount %0x100,
269 highbyte(o.nscount), o.nscount %0x100,
270 highbyte(o.arcount), o.arcount %0x100
277 local function encodeName(name) -- - - - - - - - - - - - - - - - encodeName
279 for part in string.gmatch(name, '[^.]+') do
280 append(t, string.char(string.len(part)));
283 append(t, string.char(0));
284 return table.concat(t);
288 local function encodeQuestion(qname, qtype, qclass) -- - - - encodeQuestion
289 qname = encodeName(qname);
290 qtype = dns.typecode[qtype or 'a'];
291 qclass = dns.classcode[qclass or 'in'];
292 return qname..qtype..qclass;
296 function resolver:byte(len) -- - - - - - - - - - - - - - - - - - - - - byte
298 local offset = self.offset;
299 local last = offset + len - 1;
300 if last > #self.packet then
301 error(string.format('out of bounds: %i>%i', last, #self.packet));
303 self.offset = offset + len;
304 return string.byte(self.packet, offset, last);
308 function resolver:word() -- - - - - - - - - - - - - - - - - - - - - - word
309 local b1, b2 = self:byte(2);
310 return 0x100*b1 + b2;
314 function resolver:dword () -- - - - - - - - - - - - - - - - - - - - - dword
315 local b1, b2, b3, b4 = self:byte(4);
316 --print('dword', b1, b2, b3, b4);
317 return 0x1000000*b1 + 0x10000*b2 + 0x100*b3 + b4;
321 function resolver:sub(len) -- - - - - - - - - - - - - - - - - - - - - - sub
323 local s = string.sub(self.packet, self.offset, self.offset + len - 1);
324 self.offset = self.offset + len;
329 function resolver:header(force) -- - - - - - - - - - - - - - - - - - header
330 local id = self:word();
331 --print(string.format(':header id %x', id));
332 if not self.active[id] and not force then return nil; end
334 local h = { id = id };
336 local b1, b2 = self:byte(2);
348 h.qdcount = self:word();
349 h.ancount = self:word();
350 h.nscount = self:word();
351 h.arcount = self:word();
353 for k,v in pairs(h) do h[k] = v-v%1; end
359 function resolver:name() -- - - - - - - - - - - - - - - - - - - - - - name
360 local remember, pointers = nil, 0;
361 local len = self:byte();
363 if len == 0 then return "." end -- Root label
365 if len >= 0xc0 then -- name is "compressed"
366 pointers = pointers + 1;
367 if pointers >= 20 then error('dns error: 20 pointers'); end;
368 local offset = ((len-0xc0)*0x100) + self:byte();
369 remember = remember or self.offset;
370 self.offset = offset + 1; -- +1 for lua
371 else -- name is not compressed
372 append(n, self:sub(len)..'.');
376 self.offset = remember or self.offset;
377 return table.concat(n);
381 function resolver:question() -- - - - - - - - - - - - - - - - - - question
383 q.name = self:name();
384 q.type = dns.type[self:word()];
385 q.class = dns.class[self:word()];
390 function resolver:A(rr) -- - - - - - - - - - - - - - - - - - - - - - - - A
391 local b1, b2, b3, b4 = self:byte(4);
392 rr.a = string.format('%i.%i.%i.%i', b1, b2, b3, b4);
395 function resolver:AAAA(rr)
397 for i = 1, rr.rdlength, 2 do
398 local b1, b2 = self:byte(2);
399 table.insert(addr, ("%02x%02x"):format(b1, b2));
401 addr = table.concat(addr, ":"):gsub("%f[%x]0+(%x)","%1");
403 for item in addr:gmatch(":[0:]+:") do
404 table.insert(zeros, item)
409 elseif #zeros > 1 then
410 table.sort(zeros, function(a, b) return #a > #b end);
412 rr.aaaa = addr:gsub(zeros[1], "::", 1):gsub("^0::", "::"):gsub("::0$", "::");
415 function resolver:CNAME(rr) -- - - - - - - - - - - - - - - - - - - - CNAME
416 rr.cname = self:name();
420 function resolver:MX(rr) -- - - - - - - - - - - - - - - - - - - - - - - MX
421 rr.pref = self:word();
426 function resolver:LOC_nibble_power() -- - - - - - - - - - LOC_nibble_power
427 local b = self:byte();
428 --print('nibbles', ((b-(b%0x10))/0x10), (b%0x10));
429 return ((b-(b%0x10))/0x10) * (10^(b%0x10));
433 function resolver:LOC(rr) -- - - - - - - - - - - - - - - - - - - - - - LOC
434 rr.version = self:byte();
435 if rr.version == 0 then
436 rr.loc = rr.loc or {};
437 rr.loc.size = self:LOC_nibble_power();
438 rr.loc.horiz_pre = self:LOC_nibble_power();
439 rr.loc.vert_pre = self:LOC_nibble_power();
440 rr.loc.latitude = self:dword();
441 rr.loc.longitude = self:dword();
442 rr.loc.altitude = self:dword();
447 local function LOC_tostring_degrees(f, pos, neg) -- - - - - - - - - - - - -
449 if f < 0 then pos = neg; f = -f; end
450 local deg, min, msec;
455 return string.format('%3d %2d %2.3f %s', deg, min, msec/1000, pos);
459 function resolver.LOC_tostring(rr) -- - - - - - - - - - - - - LOC_tostring
463 for k,name in pairs { 'size', 'horiz_pre', 'vert_pre', 'latitude', 'longitude', 'altitude' } do
464 append(t, string.format('%4s%-10s: %12.0f\n', '', name, rr.loc[name]));
468 append(t, string.format(
469 '%s %s %.2fm %.2fm %.2fm %.2fm',
470 LOC_tostring_degrees (rr.loc.latitude, 'N', 'S'),
471 LOC_tostring_degrees (rr.loc.longitude, 'E', 'W'),
472 (rr.loc.altitude - 10000000) / 100,
474 rr.loc.horiz_pre / 100,
475 rr.loc.vert_pre / 100
478 return table.concat(t);
482 function resolver:NS(rr) -- - - - - - - - - - - - - - - - - - - - - - - NS
487 function resolver:SOA(rr) -- - - - - - - - - - - - - - - - - - - - - - SOA
491 function resolver:SRV(rr) -- - - - - - - - - - - - - - - - - - - - - - SRV
493 rr.srv.priority = self:word();
494 rr.srv.weight = self:word();
495 rr.srv.port = self:word();
496 rr.srv.target = self:name();
499 function resolver:PTR(rr)
500 rr.ptr = self:name();
503 function resolver:TXT(rr) -- - - - - - - - - - - - - - - - - - - - - - TXT
504 rr.txt = self:sub (self:byte());
508 function resolver:rr() -- - - - - - - - - - - - - - - - - - - - - - - - rr
510 setmetatable(rr, rr_metatable);
511 rr.name = self:name(self);
512 rr.type = dns.type[self:word()] or rr.type;
513 rr.class = dns.class[self:word()] or rr.class;
514 rr.ttl = 0x10000*self:word() + self:word();
515 rr.rdlength = self:word();
518 rr.tod = self.time + 30;
520 rr.tod = self.time + rr.ttl;
523 local remember = self.offset;
524 local rr_parser = self[dns.type[rr.type]];
525 if rr_parser then rr_parser(self, rr); end
526 self.offset = remember;
527 rr.rdata = self:sub(rr.rdlength);
532 function resolver:rrs (count) -- - - - - - - - - - - - - - - - - - - - - rrs
534 for i = 1,count do append(rrs, self:rr()); end
539 function resolver:decode(packet, force) -- - - - - - - - - - - - - - decode
540 self.packet, self.offset = packet, 1;
541 local header = self:header(force);
542 if not header then return nil; end
543 local response = { header = header };
545 response.question = {};
546 local offset = self.offset;
547 for i = 1,response.header.qdcount do
548 append(response.question, self:question());
550 response.question.raw = string.sub(self.packet, offset, self.offset - 1);
553 if not self.active[response.header.id] or not self.active[response.header.id][response.question.raw] then
554 self.active[response.header.id] = nil;
559 response.answer = self:rrs(response.header.ancount);
560 response.authority = self:rrs(response.header.nscount);
561 response.additional = self:rrs(response.header.arcount);
567 -- socket layer -------------------------------------------------- socket layer
570 resolver.delays = { 1, 3 };
573 function resolver:addnameserver(address) -- - - - - - - - - - addnameserver
574 self.server = self.server or {};
575 append(self.server, address);
579 function resolver:setnameserver(address) -- - - - - - - - - - setnameserver
581 self:addnameserver(address);
585 function resolver:adddefaultnameservers() -- - - - - adddefaultnameservers
587 if windows and windows.get_nameservers then
588 for _, server in ipairs(windows.get_nameservers()) do
589 self:addnameserver(server);
592 if not self.server or #self.server == 0 then
593 -- TODO log warning about no nameservers, adding opendns servers as fallback
594 self:addnameserver("208.67.222.222");
595 self:addnameserver("208.67.220.220");
598 local resolv_conf = io.open("/etc/resolv.conf");
600 for line in resolv_conf:lines() do
601 line = line:gsub("#.*$", "")
602 :match('^%s*nameserver%s+(.*)%s*$');
604 line:gsub("%f[%d.](%d+%.%d+%.%d+%.%d+)%f[^%d.]", function (address)
605 self:addnameserver(address)
610 if not self.server or #self.server == 0 then
611 -- TODO log warning about no nameservers, adding localhost as the default nameserver
612 self:addnameserver("127.0.0.1");
618 function resolver:getsocket(servernum) -- - - - - - - - - - - - - getsocket
619 self.socket = self.socket or {};
620 self.socketset = self.socketset or {};
622 local sock = self.socket[servernum];
623 if sock then return sock; end
626 sock, err = socket.udp();
627 if sock and self.socket_wrapper then sock, err = self.socket_wrapper(sock, self); end
632 -- todo: attempt to use a random port, fallback to 0
633 sock:setsockname('*', 0);
634 sock:setpeername(self.server[servernum], 53);
635 self.socket[servernum] = sock;
636 self.socketset[sock] = servernum;
640 function resolver:voidsocket(sock)
641 if self.socket[sock] then
642 self.socketset[self.socket[sock]] = nil;
643 self.socket[sock] = nil;
644 elseif self.socketset[sock] then
645 self.socket[self.socketset[sock]] = nil;
646 self.socketset[sock] = nil;
651 function resolver:socket_wrapper_set(func) -- - - - - - - socket_wrapper_set
652 self.socket_wrapper = func;
656 function resolver:closeall () -- - - - - - - - - - - - - - - - - - closeall
657 for i,sock in ipairs(self.socket) do
658 self.socket[i] = nil;
659 self.socketset[sock] = nil;
665 function resolver:remember(rr, type) -- - - - - - - - - - - - - - remember
666 --print ('remember', type, rr.class, rr.type, rr.name)
667 local qname, qtype, qclass = standardize(rr.name, rr.type, rr.class);
671 local all = get(self.cache, qclass, '*', qname);
672 --print('remember all', all);
673 if all then append(all, rr); end
676 self.cache = self.cache or setmetatable({}, cache_metatable);
677 local rrs = get(self.cache, qclass, type, qname) or
678 set(self.cache, qclass, type, qname, setmetatable({}, rrs_metatable));
679 if not rrs[rr[qtype:lower()]] then
680 rrs[rr[qtype:lower()]] = true;
684 if type == 'MX' then self.unsorted[rrs] = true; end
688 local function comp_mx(a, b) -- - - - - - - - - - - - - - - - - - - comp_mx
689 return (a.pref == b.pref) and (a.mx < b.mx) or (a.pref < b.pref);
693 function resolver:peek (qname, qtype, qclass) -- - - - - - - - - - - - peek
694 qname, qtype, qclass = standardize(qname, qtype, qclass);
695 local rrs = get(self.cache, qclass, qtype, qname);
696 if not rrs then return nil; end
697 if prune(rrs, socket.gettime()) and qtype == '*' or not next(rrs) then
698 set(self.cache, qclass, qtype, qname, nil);
701 if self.unsorted[rrs] then table.sort (rrs, comp_mx); end
706 function resolver:purge(soft) -- - - - - - - - - - - - - - - - - - - purge
707 if soft == 'soft' then
708 self.time = socket.gettime();
709 for class,types in pairs(self.cache or {}) do
710 for type,names in pairs(types) do
711 for name,rrs in pairs(names) do
712 prune(rrs, self.time, 'soft')
716 else self.cache = setmetatable({}, cache_metatable); end
720 function resolver:query(qname, qtype, qclass) -- - - - - - - - - - -- query
721 qname, qtype, qclass = standardize(qname, qtype, qclass)
723 local co = coroutine.running();
724 local q = get(self.wanted, qclass, qtype, qname);
726 -- We are already waiting for a reply to an identical query.
727 set(self.wanted, qclass, qtype, qname, co, true);
731 if not self.server then self:adddefaultnameservers(); end
733 local question = encodeQuestion(qname, qtype, qclass);
734 local peek = self:peek (qname, qtype, qclass);
735 if peek then return peek; end
737 local header, id = encodeHeader();
738 --print ('query id', id, qclass, qtype, qname)
740 packet = header..question,
741 server = self.best_server,
743 retry = socket.gettime() + self.delays[1]
746 -- remember the query
747 self.active[id] = self.active[id] or {};
748 self.active[id][question] = o;
750 -- remember which coroutine wants the answer
752 set(self.wanted, qclass, qtype, qname, co, true);
755 local conn, err = self:getsocket(o.server)
761 if timer and self.timeout then
762 local num_servers = #self.server;
764 timer.add_task(self.timeout, function ()
765 if get(self.wanted, qclass, qtype, qname, co) then
766 if i < num_servers then
769 o.server = self.best_server;
770 conn, err = self:getsocket(o.server);
776 -- Tried everything, failed
777 self:cancel(qclass, qtype, qname);
784 function resolver:servfail(sock)
785 -- Resend all queries for this server
787 local num = self.socketset[sock]
789 -- Socket is dead now
790 self:voidsocket(sock);
792 -- Find all requests to the down server, and retry on the next server
793 self.time = socket.gettime();
794 for id,queries in pairs(self.active) do
795 for question,o in pairs(queries) do
796 if o.server == num then -- This request was to the broken server
797 o.server = o.server + 1 -- Use next server
798 if o.server > #self.server then
802 o.retries = (o.retries or 0) + 1;
803 if o.retries >= #self.server then
805 queries[question] = nil;
807 local _a = self:getsocket(o.server);
808 if _a then _a:send(o.packet); end
812 if next(queries) == nil then
813 self.active[id] = nil;
817 if num == self.best_server then
818 self.best_server = self.best_server + 1;
819 if self.best_server > #self.server then
820 -- Exhausted all servers, try first again
821 self.best_server = 1;
826 function resolver:settimeout(seconds)
827 self.timeout = seconds;
830 function resolver:receive(rset) -- - - - - - - - - - - - - - - - - receive
831 --print('receive'); print(self.socket);
832 self.time = socket.gettime();
833 rset = rset or self.socket;
836 for i,sock in pairs(rset) do
838 if self.socketset[sock] then
839 local packet = sock:receive();
841 response = self:decode(packet);
842 if response and self.active[response.header.id]
843 and self.active[response.header.id][response.question.raw] then
844 --print('received response');
845 --self.print(response);
847 for j,rr in pairs(response.answer) do
848 if rr.name:sub(-#response.question[1].name, -1) == response.question[1].name then
849 self:remember(rr, response.question[1].type)
854 local queries = self.active[response.header.id];
855 queries[response.question.raw] = nil;
857 if not next(queries) then self.active[response.header.id] = nil; end
858 if not next(self.active) then self:closeall(); end
860 -- was the query on the wanted list?
861 local q = response.question[1];
862 local cos = get(self.wanted, q.class, q.type, q.name);
864 for co in pairs(cos) do
865 if coroutine.status(co) == "suspended" then coroutine.resume(co); end
867 set(self.wanted, q.class, q.type, q.name, nil);
879 function resolver:feed(sock, packet, force)
880 --print('receive'); print(self.socket);
881 self.time = socket.gettime();
883 local response = self:decode(packet, force);
884 if response and self.active[response.header.id]
885 and self.active[response.header.id][response.question.raw] then
886 --print('received response');
887 --self.print(response);
889 for j,rr in pairs(response.answer) do
890 self:remember(rr, response.question[1].type);
894 local queries = self.active[response.header.id];
895 queries[response.question.raw] = nil;
896 if not next(queries) then self.active[response.header.id] = nil; end
897 if not next(self.active) then self:closeall(); end
899 -- was the query on the wanted list?
900 local q = response.question[1];
902 local cos = get(self.wanted, q.class, q.type, q.name);
904 for co in pairs(cos) do
905 if coroutine.status(co) == "suspended" then coroutine.resume(co); end
907 set(self.wanted, q.class, q.type, q.name, nil);
915 function resolver:cancel(qclass, qtype, qname)
916 local cos = get(self.wanted, qclass, qtype, qname);
918 for co in pairs(cos) do
919 if coroutine.status(co) == "suspended" then coroutine.resume(co); end
921 set(self.wanted, qclass, qtype, qname, nil);
925 function resolver:pulse() -- - - - - - - - - - - - - - - - - - - - - pulse
927 while self:receive() do end
928 if not next(self.active) then return nil; end
930 self.time = socket.gettime();
931 for id,queries in pairs(self.active) do
932 for question,o in pairs(queries) do
933 if self.time >= o.retry then
935 o.server = o.server + 1;
936 if o.server > #self.server then
938 o.delay = o.delay + 1;
941 if o.delay > #self.delays then
943 queries[question] = nil;
944 if not next(queries) then self.active[id] = nil; end
945 if not next(self.active) then return nil; end
947 --print('retry', o.server, o.delay);
948 local _a = self.socket[o.server];
949 if _a then _a:send(o.packet); end
950 o.retry = self.time + self.delays[o.delay];
956 if next(self.active) then return true; end
961 function resolver:lookup(qname, qtype, qclass) -- - - - - - - - - - lookup
962 self:query (qname, qtype, qclass)
963 while self:pulse() do
965 for i, s in ipairs(self.socket) do
968 socket.select(recvt, nil, 4)
971 return self:peek(qname, qtype, qclass);
974 function resolver:lookupex(handler, qname, qtype, qclass) -- - - - - - - - - - lookup
975 return self:peek(qname, qtype, qclass) or self:query(qname, qtype, qclass);
978 function resolver:tohostname(ip)
979 return dns.lookup(ip:gsub("(%d+)%.(%d+)%.(%d+)%.(%d+)", "%4.%3.%2.%1.in-addr.arpa."), "PTR");
982 --print ---------------------------------------------------------------- print
985 local hints = { -- - - - - - - - - - - - - - - - - - - - - - - - - - - hints
986 qr = { [0]='query', 'response' },
987 opcode = { [0]='query', 'inverse query', 'server status request' },
988 aa = { [0]='non-authoritative', 'authoritative' },
989 tc = { [0]='complete', 'truncated' },
990 rd = { [0]='recursion not desired', 'recursion desired' },
991 ra = { [0]='recursion not available', 'recursion available' },
992 z = { [0]='(reserved)' },
993 rcode = { [0]='no error', 'format error', 'server failure', 'name error', 'not implemented' },
1000 local function hint(p, s) -- - - - - - - - - - - - - - - - - - - - - - hint
1001 return (hints[s] and hints[s][p[s]]) or '';
1005 function resolver.print(response) -- - - - - - - - - - - - - resolver.print
1006 for s,s in pairs { 'id', 'qr', 'opcode', 'aa', 'tc', 'rd', 'ra', 'z',
1007 'rcode', 'qdcount', 'ancount', 'nscount', 'arcount' } do
1008 print( string.format('%-30s', 'header.'..s), response.header[s], hint(response.header, s) );
1011 for i,question in ipairs(response.question) do
1012 print(string.format ('question[%i].name ', i), question.name);
1013 print(string.format ('question[%i].type ', i), question.type);
1014 print(string.format ('question[%i].class ', i), question.class);
1017 local common = { name=1, type=1, class=1, ttl=1, rdlength=1, rdata=1 };
1019 for s,s in pairs({'answer', 'authority', 'additional'}) do
1020 for i,rr in pairs(response[s]) do
1021 for j,t in pairs({ 'name', 'type', 'class', 'ttl', 'rdlength' }) do
1022 tmp = string.format('%s[%i].%s', s, i, t);
1023 print(string.format('%-30s', tmp), rr[t], hint(rr, t));
1025 for j,t in pairs(rr) do
1026 if not common[j] then
1027 tmp = string.format('%s[%i].%s', s, i, j);
1028 print(string.format('%-30s %s', tostring(tmp), tostring(t)));
1036 -- module api ------------------------------------------------------ module api
1039 function dns.resolver () -- - - - - - - - - - - - - - - - - - - - - resolver
1040 -- this function seems to be redundant with resolver.new ()
1042 local r = { active = {}, cache = {}, unsorted = {}, wanted = {}, best_server = 1 };
1043 setmetatable (r, resolver);
1044 setmetatable (r.cache, cache_metatable);
1045 setmetatable (r.unsorted, { __mode = 'kv' });
1049 local _resolver = dns.resolver();
1050 dns._resolver = _resolver;
1052 function dns.lookup(...) -- - - - - - - - - - - - - - - - - - - - - lookup
1053 return _resolver:lookup(...);
1056 function dns.tohostname(...)
1057 return _resolver:tohostname(...);
1060 function dns.purge(...) -- - - - - - - - - - - - - - - - - - - - - - purge
1061 return _resolver:purge(...);
1064 function dns.peek(...) -- - - - - - - - - - - - - - - - - - - - - - - peek
1065 return _resolver:peek(...);
1068 function dns.query(...) -- - - - - - - - - - - - - - - - - - - - - - query
1069 return _resolver:query(...);
1072 function dns.feed(...) -- - - - - - - - - - - - - - - - - - - - - - - feed
1073 return _resolver:feed(...);
1076 function dns.cancel(...) -- - - - - - - - - - - - - - - - - - - - - - cancel
1077 return _resolver:cancel(...);
1080 function dns.settimeout(...)
1081 return _resolver:settimeout(...);
1084 function dns.cache()
1085 return _resolver.cache;
1088 function dns.socket_wrapper_set(...) -- - - - - - - - - socket_wrapper_set
1089 return _resolver:socket_wrapper_set(...);