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";
17 local new_ip = require "util.ip".new_ip;
19 local _, windows = pcall(require, "util.windows");
20 local is_windows = (_ and windows) or os.getenv("WINDIR");
22 local coroutine, io, math, string, table =
23 coroutine, io, math, string, table;
25 local ipairs, next, pairs, print, setmetatable, tostring, assert, error, unpack, select, type=
26 ipairs, next, pairs, print, setmetatable, tostring, assert, error, unpack, select, type;
28 local ztact = { -- public domain 20080404 lua@ztact.com
29 get = function(parent, ...)
30 local len = select('#', ...);
32 parent = parent[select(i, ...)];
33 if parent == nil then break; end
37 set = function(parent, ...)
38 local len = select('#', ...);
39 local key, value = select(len-1, ...);
40 local cutpoint, cutkey;
43 local key = select (i, ...)
44 local child = parent[key]
49 elseif next(child, next(child)) then
50 cutpoint = nil; cutkey = nil;
51 elseif cutpoint == nil then
52 cutpoint = parent; cutkey = key;
54 elseif child == nil then
61 if value == nil and cutpoint then
62 cutpoint[cutkey] = nil;
69 local get, set = ztact.get, ztact.set;
71 local default_timeout = 15;
73 -------------------------------------------------- module dns
78 -- dns type & class codes ------------------------------ dns type & class codes
81 local append = table.insert
84 local function highbyte(i) -- - - - - - - - - - - - - - - - - - - highbyte
85 return (i-(i%0x100))/0x100;
89 local function augment (t) -- - - - - - - - - - - - - - - - - - - - augment
91 for i,s in pairs(t) do
94 a[string.lower(s)] = s;
100 local function encode (t) -- - - - - - - - - - - - - - - - - - - - - encode
102 for i,s in pairs(t) do
103 local word = string.char(highbyte(i), i%0x100);
106 code[string.lower(s)] = word;
113 'A', 'NS', 'MD', 'MF', 'CNAME', 'SOA', 'MB', 'MG', 'MR', 'NULL', 'WKS',
114 'PTR', 'HINFO', 'MINFO', 'MX', 'TXT',
115 [ 28] = 'AAAA', [ 29] = 'LOC', [ 33] = 'SRV',
116 [252] = 'AXFR', [253] = 'MAILB', [254] = 'MAILA', [255] = '*' };
119 dns.classes = { 'IN', 'CS', 'CH', 'HS', [255] = '*' };
122 dns.type = augment (dns.types);
123 dns.class = augment (dns.classes);
124 dns.typecode = encode (dns.types);
125 dns.classcode = encode (dns.classes);
129 local function standardize(qname, qtype, qclass) -- - - - - - - standardize
130 if string.byte(qname, -1) ~= 0x2E then qname = qname..'.'; end
131 qname = string.lower(qname);
132 return qname, dns.type[qtype or 'A'], dns.class[qclass or 'IN'];
136 local function prune(rrs, time, soft) -- - - - - - - - - - - - - - - prune
137 time = time or socket.gettime();
138 for i,rr in ipairs(rrs) do
140 -- rr.tod = rr.tod - 50 -- accelerated decripitude
141 rr.ttl = math.floor(rr.tod - time);
143 rrs[rr[rr.type:lower()]] = nil;
144 table.remove(rrs, i);
145 return prune(rrs, time, soft); -- Re-iterate
147 elseif soft == 'soft' then -- What is this? I forget!
149 rrs[rr[rr.type:lower()]] = nil;
150 table.remove(rrs, i);
156 -- metatables & co. ------------------------------------------ metatables & co.
160 resolver.__index = resolver;
162 resolver.timeout = default_timeout;
164 local function default_rr_tostring(rr)
165 local rr_val = rr.type and rr[rr.type:lower()];
166 if type(rr_val) ~= "string" then
167 return "<UNKNOWN RDATA TYPE>";
172 local special_tostrings = {
173 LOC = resolver.LOC_tostring;
175 return string.format('%2i %s', rr.pref, rr.mx);
179 return string.format('%5d %5d %5d %s', s.priority, s.weight, s.port, s.target);
183 local rr_metatable = {}; -- - - - - - - - - - - - - - - - - - - rr_metatable
184 function rr_metatable.__tostring(rr)
185 local rr_string = (special_tostrings[rr.type] or default_rr_tostring)(rr);
186 return string.format('%2s %-5s %6i %-28s %s', rr.class, rr.type, rr.ttl, rr.name, rr_string);
190 local rrs_metatable = {}; -- - - - - - - - - - - - - - - - - - rrs_metatable
191 function rrs_metatable.__tostring(rrs)
193 for i,rr in ipairs(rrs) do
194 append(t, tostring(rr)..'\n');
196 return table.concat(t);
200 local cache_metatable = {}; -- - - - - - - - - - - - - - - - cache_metatable
201 function cache_metatable.__tostring(cache)
202 local time = socket.gettime();
204 for class,types in pairs(cache) do
205 for type,names in pairs(types) do
206 for name,rrs in pairs(names) do
208 append(t, tostring(rrs));
212 return table.concat(t);
216 -- packet layer -------------------------------------------------- packet layer
219 function dns.random(...) -- - - - - - - - - - - - - - - - - - - dns.random
220 math.randomseed(math.floor(10000*socket.gettime()) % 0x80000000);
221 dns.random = math.random;
222 return dns.random(...);
226 local function encodeHeader(o) -- - - - - - - - - - - - - - - encodeHeader
228 o.id = o.id or dns.random(0, 0xffff); -- 16b (random) id
230 o.rd = o.rd or 1; -- 1b 1 recursion desired
231 o.tc = o.tc or 0; -- 1b 1 truncated response
232 o.aa = o.aa or 0; -- 1b 1 authoritative response
233 o.opcode = o.opcode or 0; -- 4b 0 query
235 -- 2 server status request
237 o.qr = o.qr or 0; -- 1b 0 query, 1 response
239 o.rcode = o.rcode or 0; -- 4b 0 no error
246 o.z = o.z or 0; -- 3b 0 resvered
247 o.ra = o.ra or 0; -- 1b 1 recursion available
249 o.qdcount = o.qdcount or 1; -- 16b number of question RRs
250 o.ancount = o.ancount or 0; -- 16b number of answers RRs
251 o.nscount = o.nscount or 0; -- 16b number of nameservers RRs
252 o.arcount = o.arcount or 0; -- 16b number of additional RRs
254 -- string.char() rounds, so prevent roundup with -0.4999
255 local header = string.char(
256 highbyte(o.id), o.id %0x100,
257 o.rd + 2*o.tc + 4*o.aa + 8*o.opcode + 128*o.qr,
258 o.rcode + 16*o.z + 128*o.ra,
259 highbyte(o.qdcount), o.qdcount %0x100,
260 highbyte(o.ancount), o.ancount %0x100,
261 highbyte(o.nscount), o.nscount %0x100,
262 highbyte(o.arcount), o.arcount %0x100
269 local function encodeName(name) -- - - - - - - - - - - - - - - - encodeName
271 for part in string.gmatch(name, '[^.]+') do
272 append(t, string.char(string.len(part)));
275 append(t, string.char(0));
276 return table.concat(t);
280 local function encodeQuestion(qname, qtype, qclass) -- - - - encodeQuestion
281 qname = encodeName(qname);
282 qtype = dns.typecode[qtype or 'a'];
283 qclass = dns.classcode[qclass or 'in'];
284 return qname..qtype..qclass;
288 function resolver:byte(len) -- - - - - - - - - - - - - - - - - - - - - byte
290 local offset = self.offset;
291 local last = offset + len - 1;
292 if last > #self.packet then
293 error(string.format('out of bounds: %i>%i', last, #self.packet));
295 self.offset = offset + len;
296 return string.byte(self.packet, offset, last);
300 function resolver:word() -- - - - - - - - - - - - - - - - - - - - - - word
301 local b1, b2 = self:byte(2);
302 return 0x100*b1 + b2;
306 function resolver:dword () -- - - - - - - - - - - - - - - - - - - - - dword
307 local b1, b2, b3, b4 = self:byte(4);
308 --print('dword', b1, b2, b3, b4);
309 return 0x1000000*b1 + 0x10000*b2 + 0x100*b3 + b4;
313 function resolver:sub(len) -- - - - - - - - - - - - - - - - - - - - - - sub
315 local s = string.sub(self.packet, self.offset, self.offset + len - 1);
316 self.offset = self.offset + len;
321 function resolver:header(force) -- - - - - - - - - - - - - - - - - - header
322 local id = self:word();
323 --print(string.format(':header id %x', id));
324 if not self.active[id] and not force then return nil; end
326 local h = { id = id };
328 local b1, b2 = self:byte(2);
340 h.qdcount = self:word();
341 h.ancount = self:word();
342 h.nscount = self:word();
343 h.arcount = self:word();
345 for k,v in pairs(h) do h[k] = v-v%1; end
351 function resolver:name() -- - - - - - - - - - - - - - - - - - - - - - name
352 local remember, pointers = nil, 0;
353 local len = self:byte();
355 if len == 0 then return "." end -- Root label
357 if len >= 0xc0 then -- name is "compressed"
358 pointers = pointers + 1;
359 if pointers >= 20 then error('dns error: 20 pointers'); end;
360 local offset = ((len-0xc0)*0x100) + self:byte();
361 remember = remember or self.offset;
362 self.offset = offset + 1; -- +1 for lua
363 else -- name is not compressed
364 append(n, self:sub(len)..'.');
368 self.offset = remember or self.offset;
369 return table.concat(n);
373 function resolver:question() -- - - - - - - - - - - - - - - - - - question
375 q.name = self:name();
376 q.type = dns.type[self:word()];
377 q.class = dns.class[self:word()];
382 function resolver:A(rr) -- - - - - - - - - - - - - - - - - - - - - - - - A
383 local b1, b2, b3, b4 = self:byte(4);
384 rr.a = string.format('%i.%i.%i.%i', b1, b2, b3, b4);
387 function resolver:AAAA(rr)
389 for i = 1, rr.rdlength, 2 do
390 local b1, b2 = self:byte(2);
391 table.insert(addr, ("%02x%02x"):format(b1, b2));
393 addr = table.concat(addr, ":"):gsub("%f[%x]0+(%x)","%1");
395 for item in addr:gmatch(":[0:]+:") do
396 table.insert(zeros, item)
401 elseif #zeros > 1 then
402 table.sort(zeros, function(a, b) return #a > #b end);
404 rr.aaaa = addr:gsub(zeros[1], "::", 1):gsub("^0::", "::"):gsub("::0$", "::");
407 function resolver:CNAME(rr) -- - - - - - - - - - - - - - - - - - - - CNAME
408 rr.cname = self:name();
412 function resolver:MX(rr) -- - - - - - - - - - - - - - - - - - - - - - - MX
413 rr.pref = self:word();
418 function resolver:LOC_nibble_power() -- - - - - - - - - - LOC_nibble_power
419 local b = self:byte();
420 --print('nibbles', ((b-(b%0x10))/0x10), (b%0x10));
421 return ((b-(b%0x10))/0x10) * (10^(b%0x10));
425 function resolver:LOC(rr) -- - - - - - - - - - - - - - - - - - - - - - LOC
426 rr.version = self:byte();
427 if rr.version == 0 then
428 rr.loc = rr.loc or {};
429 rr.loc.size = self:LOC_nibble_power();
430 rr.loc.horiz_pre = self:LOC_nibble_power();
431 rr.loc.vert_pre = self:LOC_nibble_power();
432 rr.loc.latitude = self:dword();
433 rr.loc.longitude = self:dword();
434 rr.loc.altitude = self:dword();
439 local function LOC_tostring_degrees(f, pos, neg) -- - - - - - - - - - - - -
441 if f < 0 then pos = neg; f = -f; end
442 local deg, min, msec;
447 return string.format('%3d %2d %2.3f %s', deg, min, msec/1000, pos);
451 function resolver.LOC_tostring(rr) -- - - - - - - - - - - - - LOC_tostring
455 for k,name in pairs { 'size', 'horiz_pre', 'vert_pre', 'latitude', 'longitude', 'altitude' } do
456 append(t, string.format('%4s%-10s: %12.0f\n', '', name, rr.loc[name]));
460 append(t, string.format(
461 '%s %s %.2fm %.2fm %.2fm %.2fm',
462 LOC_tostring_degrees (rr.loc.latitude, 'N', 'S'),
463 LOC_tostring_degrees (rr.loc.longitude, 'E', 'W'),
464 (rr.loc.altitude - 10000000) / 100,
466 rr.loc.horiz_pre / 100,
467 rr.loc.vert_pre / 100
470 return table.concat(t);
474 function resolver:NS(rr) -- - - - - - - - - - - - - - - - - - - - - - - NS
479 function resolver:SOA(rr) -- - - - - - - - - - - - - - - - - - - - - - SOA
483 function resolver:SRV(rr) -- - - - - - - - - - - - - - - - - - - - - - SRV
485 rr.srv.priority = self:word();
486 rr.srv.weight = self:word();
487 rr.srv.port = self:word();
488 rr.srv.target = self:name();
491 function resolver:PTR(rr)
492 rr.ptr = self:name();
495 function resolver:TXT(rr) -- - - - - - - - - - - - - - - - - - - - - - TXT
496 rr.txt = self:sub (self:byte());
500 function resolver:rr() -- - - - - - - - - - - - - - - - - - - - - - - - rr
502 setmetatable(rr, rr_metatable);
503 rr.name = self:name(self);
504 rr.type = dns.type[self:word()] or rr.type;
505 rr.class = dns.class[self:word()] or rr.class;
506 rr.ttl = 0x10000*self:word() + self:word();
507 rr.rdlength = self:word();
510 rr.tod = self.time + 30;
512 rr.tod = self.time + rr.ttl;
515 local remember = self.offset;
516 local rr_parser = self[dns.type[rr.type]];
517 if rr_parser then rr_parser(self, rr); end
518 self.offset = remember;
519 rr.rdata = self:sub(rr.rdlength);
524 function resolver:rrs (count) -- - - - - - - - - - - - - - - - - - - - - rrs
526 for i = 1,count do append(rrs, self:rr()); end
531 function resolver:decode(packet, force) -- - - - - - - - - - - - - - decode
532 self.packet, self.offset = packet, 1;
533 local header = self:header(force);
534 if not header then return nil; end
535 local response = { header = header };
537 response.question = {};
538 local offset = self.offset;
539 for i = 1,response.header.qdcount do
540 append(response.question, self:question());
542 response.question.raw = string.sub(self.packet, offset, self.offset - 1);
545 if not self.active[response.header.id] or not self.active[response.header.id][response.question.raw] then
546 self.active[response.header.id] = nil;
551 response.answer = self:rrs(response.header.ancount);
552 response.authority = self:rrs(response.header.nscount);
553 response.additional = self:rrs(response.header.arcount);
559 -- socket layer -------------------------------------------------- socket layer
562 resolver.delays = { 1, 3 };
565 function resolver:addnameserver(address) -- - - - - - - - - - addnameserver
566 self.server = self.server or {};
567 append(self.server, address);
571 function resolver:setnameserver(address) -- - - - - - - - - - setnameserver
573 self:addnameserver(address);
577 function resolver:adddefaultnameservers() -- - - - - adddefaultnameservers
579 if windows and windows.get_nameservers then
580 for _, server in ipairs(windows.get_nameservers()) do
581 self:addnameserver(server);
584 if not self.server or #self.server == 0 then
585 -- TODO log warning about no nameservers, adding opendns servers as fallback
586 self:addnameserver("208.67.222.222");
587 self:addnameserver("208.67.220.220");
590 local resolv_conf = io.open("/etc/resolv.conf");
592 for line in resolv_conf:lines() do
593 line = line:gsub("#.*$", "")
594 :match('^%s*nameserver%s+([%x:%.]*)%s*$');
596 local ip = new_ip(line);
598 self:addnameserver(ip.addr);
603 if not self.server or #self.server == 0 then
604 -- TODO log warning about no nameservers, adding localhost as the default nameserver
605 self:addnameserver("127.0.0.1");
611 function resolver:getsocket(servernum) -- - - - - - - - - - - - - getsocket
612 self.socket = self.socket or {};
613 self.socketset = self.socketset or {};
615 local sock = self.socket[servernum];
616 if sock then return sock; end
619 local peer = self.server[servernum];
620 if peer:find(":") then
621 sock, err = socket.udp6();
623 sock, err = socket.udp();
625 if sock and self.socket_wrapper then sock, err = self.socket_wrapper(sock, self); end
630 -- todo: attempt to use a random port, fallback to 0
631 self.socket[servernum] = sock;
632 self.socketset[sock] = servernum;
633 -- set{sock,peer}name can fail, eg because of local routing table
634 -- if so, try the next server
635 ok, err = sock:setsockname('*', 0);
636 if not ok then return self:servfail(sock, err); end
637 ok, err = sock:setpeername(peer, 53);
638 if not ok then return self:servfail(sock, err); end
642 function resolver:voidsocket(sock)
643 if self.socket[sock] then
644 self.socketset[self.socket[sock]] = nil;
645 self.socket[sock] = nil;
646 elseif self.socketset[sock] then
647 self.socket[self.socketset[sock]] = nil;
648 self.socketset[sock] = nil;
653 function resolver:socket_wrapper_set(func) -- - - - - - - socket_wrapper_set
654 self.socket_wrapper = func;
658 function resolver:closeall () -- - - - - - - - - - - - - - - - - - closeall
659 for i,sock in ipairs(self.socket) do
660 self.socket[i] = nil;
661 self.socketset[sock] = nil;
667 function resolver:remember(rr, type) -- - - - - - - - - - - - - - remember
668 --print ('remember', type, rr.class, rr.type, rr.name)
669 local qname, qtype, qclass = standardize(rr.name, rr.type, rr.class);
673 local all = get(self.cache, qclass, '*', qname);
674 --print('remember all', all);
675 if all then append(all, rr); end
678 self.cache = self.cache or setmetatable({}, cache_metatable);
679 local rrs = get(self.cache, qclass, type, qname) or
680 set(self.cache, qclass, type, qname, setmetatable({}, rrs_metatable));
681 if not rrs[rr[qtype:lower()]] then
682 rrs[rr[qtype:lower()]] = true;
686 if type == 'MX' then self.unsorted[rrs] = true; end
690 local function comp_mx(a, b) -- - - - - - - - - - - - - - - - - - - comp_mx
691 return (a.pref == b.pref) and (a.mx < b.mx) or (a.pref < b.pref);
695 function resolver:peek (qname, qtype, qclass, n) -- - - - - - - - - - - - peek
696 qname, qtype, qclass = standardize(qname, qtype, qclass);
697 local rrs = get(self.cache, qclass, qtype, qname);
699 if n then if n <= 0 then return end else n = 3 end
700 rrs = get(self.cache, qclass, "CNAME", qname);
701 if not (rrs and rrs[1]) then return end
702 return self:peek(rrs[1].cname, qtype, qclass, n - 1);
704 if prune(rrs, socket.gettime()) and qtype == '*' or not next(rrs) then
705 set(self.cache, qclass, qtype, qname, nil);
708 if self.unsorted[rrs] then table.sort (rrs, comp_mx); self.unsorted[rrs] = nil; end
713 function resolver:purge(soft) -- - - - - - - - - - - - - - - - - - - purge
714 if soft == 'soft' then
715 self.time = socket.gettime();
716 for class,types in pairs(self.cache or {}) do
717 for type,names in pairs(types) do
718 for name,rrs in pairs(names) do
719 prune(rrs, self.time, 'soft')
723 else self.cache = setmetatable({}, cache_metatable); end
727 function resolver:query(qname, qtype, qclass) -- - - - - - - - - - -- query
728 qname, qtype, qclass = standardize(qname, qtype, qclass)
730 local co = coroutine.running();
731 local q = get(self.wanted, qclass, qtype, qname);
733 -- We are already waiting for a reply to an identical query.
734 set(self.wanted, qclass, qtype, qname, co, true);
738 if not self.server then self:adddefaultnameservers(); end
740 local question = encodeQuestion(qname, qtype, qclass);
741 local peek = self:peek (qname, qtype, qclass);
742 if peek then return peek; end
744 local header, id = encodeHeader();
745 --print ('query id', id, qclass, qtype, qname)
747 packet = header..question,
748 server = self.best_server,
750 retry = socket.gettime() + self.delays[1]
753 -- remember the query
754 self.active[id] = self.active[id] or {};
755 self.active[id][question] = o;
757 -- remember which coroutine wants the answer
759 set(self.wanted, qclass, qtype, qname, co, true);
762 local conn, err = self:getsocket(o.server)
768 if timer and self.timeout then
769 local num_servers = #self.server;
771 timer.add_task(self.timeout, function ()
772 if get(self.wanted, qclass, qtype, qname, co) then
773 if i < num_servers then
776 o.server = self.best_server;
777 conn, err = self:getsocket(o.server);
783 -- Tried everything, failed
784 self:cancel(qclass, qtype, qname);
791 function resolver:servfail(sock, err)
792 -- Resend all queries for this server
794 local num = self.socketset[sock]
796 -- Socket is dead now
797 sock = self:voidsocket(sock);
799 -- Find all requests to the down server, and retry on the next server
800 self.time = socket.gettime();
801 for id,queries in pairs(self.active) do
802 for question,o in pairs(queries) do
803 if o.server == num then -- This request was to the broken server
804 o.server = o.server + 1 -- Use next server
805 if o.server > #self.server then
809 o.retries = (o.retries or 0) + 1;
810 if o.retries >= #self.server then
812 queries[question] = nil;
814 sock, err = self:getsocket(o.server);
815 if sock then sock:send(o.packet); end
819 if next(queries) == nil then
820 self.active[id] = nil;
824 if num == self.best_server then
825 self.best_server = self.best_server + 1;
826 if self.best_server > #self.server then
827 -- Exhausted all servers, try first again
828 self.best_server = 1;
834 function resolver:settimeout(seconds)
835 self.timeout = seconds;
838 function resolver:receive(rset) -- - - - - - - - - - - - - - - - - receive
839 --print('receive'); print(self.socket);
840 self.time = socket.gettime();
841 rset = rset or self.socket;
844 for i,sock in pairs(rset) do
846 if self.socketset[sock] then
847 local packet = sock:receive();
849 response = self:decode(packet);
850 if response and self.active[response.header.id]
851 and self.active[response.header.id][response.question.raw] then
852 --print('received response');
853 --self.print(response);
855 for j,rr in pairs(response.answer) do
856 if rr.name:sub(-#response.question[1].name, -1) == response.question[1].name then
857 self:remember(rr, response.question[1].type)
862 local queries = self.active[response.header.id];
863 queries[response.question.raw] = nil;
865 if not next(queries) then self.active[response.header.id] = nil; end
866 if not next(self.active) then self:closeall(); end
868 -- was the query on the wanted list?
869 local q = response.question[1];
870 local cos = get(self.wanted, q.class, q.type, q.name);
872 for co in pairs(cos) do
873 if coroutine.status(co) == "suspended" then coroutine.resume(co); end
875 set(self.wanted, q.class, q.type, q.name, nil);
887 function resolver:feed(sock, packet, force)
888 --print('receive'); print(self.socket);
889 self.time = socket.gettime();
891 local response = self:decode(packet, force);
892 if response and self.active[response.header.id]
893 and self.active[response.header.id][response.question.raw] then
894 --print('received response');
895 --self.print(response);
897 for j,rr in pairs(response.answer) do
898 self:remember(rr, response.question[1].type);
902 local queries = self.active[response.header.id];
903 queries[response.question.raw] = nil;
904 if not next(queries) then self.active[response.header.id] = nil; end
905 if not next(self.active) then self:closeall(); end
907 -- was the query on the wanted list?
908 local q = response.question[1];
910 local cos = get(self.wanted, q.class, q.type, q.name);
912 for co in pairs(cos) do
913 if coroutine.status(co) == "suspended" then coroutine.resume(co); end
915 set(self.wanted, q.class, q.type, q.name, nil);
923 function resolver:cancel(qclass, qtype, qname)
924 local cos = get(self.wanted, qclass, qtype, qname);
926 for co in pairs(cos) do
927 if coroutine.status(co) == "suspended" then coroutine.resume(co); end
929 set(self.wanted, qclass, qtype, qname, nil);
933 function resolver:pulse() -- - - - - - - - - - - - - - - - - - - - - pulse
935 while self:receive() do end
936 if not next(self.active) then return nil; end
938 self.time = socket.gettime();
939 for id,queries in pairs(self.active) do
940 for question,o in pairs(queries) do
941 if self.time >= o.retry then
943 o.server = o.server + 1;
944 if o.server > #self.server then
946 o.delay = o.delay + 1;
949 if o.delay > #self.delays then
951 queries[question] = nil;
952 if not next(queries) then self.active[id] = nil; end
953 if not next(self.active) then return nil; end
955 --print('retry', o.server, o.delay);
956 local _a = self.socket[o.server];
957 if _a then _a:send(o.packet); end
958 o.retry = self.time + self.delays[o.delay];
964 if next(self.active) then return true; end
969 function resolver:lookup(qname, qtype, qclass) -- - - - - - - - - - lookup
970 self:query (qname, qtype, qclass)
971 while self:pulse() do
973 for i, s in ipairs(self.socket) do
976 socket.select(recvt, nil, 4)
979 return self:peek(qname, qtype, qclass);
982 function resolver:lookupex(handler, qname, qtype, qclass) -- - - - - - - - - - lookup
983 return self:peek(qname, qtype, qclass) or self:query(qname, qtype, qclass);
986 function resolver:tohostname(ip)
987 return dns.lookup(ip:gsub("(%d+)%.(%d+)%.(%d+)%.(%d+)", "%4.%3.%2.%1.in-addr.arpa."), "PTR");
990 --print ---------------------------------------------------------------- print
993 local hints = { -- - - - - - - - - - - - - - - - - - - - - - - - - - - hints
994 qr = { [0]='query', 'response' },
995 opcode = { [0]='query', 'inverse query', 'server status request' },
996 aa = { [0]='non-authoritative', 'authoritative' },
997 tc = { [0]='complete', 'truncated' },
998 rd = { [0]='recursion not desired', 'recursion desired' },
999 ra = { [0]='recursion not available', 'recursion available' },
1000 z = { [0]='(reserved)' },
1001 rcode = { [0]='no error', 'format error', 'server failure', 'name error', 'not implemented' },
1008 local function hint(p, s) -- - - - - - - - - - - - - - - - - - - - - - hint
1009 return (hints[s] and hints[s][p[s]]) or '';
1013 function resolver.print(response) -- - - - - - - - - - - - - resolver.print
1014 for s,s in pairs { 'id', 'qr', 'opcode', 'aa', 'tc', 'rd', 'ra', 'z',
1015 'rcode', 'qdcount', 'ancount', 'nscount', 'arcount' } do
1016 print( string.format('%-30s', 'header.'..s), response.header[s], hint(response.header, s) );
1019 for i,question in ipairs(response.question) do
1020 print(string.format ('question[%i].name ', i), question.name);
1021 print(string.format ('question[%i].type ', i), question.type);
1022 print(string.format ('question[%i].class ', i), question.class);
1025 local common = { name=1, type=1, class=1, ttl=1, rdlength=1, rdata=1 };
1027 for s,s in pairs({'answer', 'authority', 'additional'}) do
1028 for i,rr in pairs(response[s]) do
1029 for j,t in pairs({ 'name', 'type', 'class', 'ttl', 'rdlength' }) do
1030 tmp = string.format('%s[%i].%s', s, i, t);
1031 print(string.format('%-30s', tmp), rr[t], hint(rr, t));
1033 for j,t in pairs(rr) do
1034 if not common[j] then
1035 tmp = string.format('%s[%i].%s', s, i, j);
1036 print(string.format('%-30s %s', tostring(tmp), tostring(t)));
1044 -- module api ------------------------------------------------------ module api
1047 function dns.resolver () -- - - - - - - - - - - - - - - - - - - - - resolver
1048 local r = { active = {}, cache = {}, unsorted = {}, wanted = {}, best_server = 1 };
1049 setmetatable (r, resolver);
1050 setmetatable (r.cache, cache_metatable);
1051 setmetatable (r.unsorted, { __mode = 'kv' });
1055 local _resolver = dns.resolver();
1056 dns._resolver = _resolver;
1058 function dns.lookup(...) -- - - - - - - - - - - - - - - - - - - - - lookup
1059 return _resolver:lookup(...);
1062 function dns.tohostname(...)
1063 return _resolver:tohostname(...);
1066 function dns.purge(...) -- - - - - - - - - - - - - - - - - - - - - - purge
1067 return _resolver:purge(...);
1070 function dns.peek(...) -- - - - - - - - - - - - - - - - - - - - - - - peek
1071 return _resolver:peek(...);
1074 function dns.query(...) -- - - - - - - - - - - - - - - - - - - - - - query
1075 return _resolver:query(...);
1078 function dns.feed(...) -- - - - - - - - - - - - - - - - - - - - - - - feed
1079 return _resolver:feed(...);
1082 function dns.cancel(...) -- - - - - - - - - - - - - - - - - - - - - - cancel
1083 return _resolver:cancel(...);
1086 function dns.settimeout(...)
1087 return _resolver:settimeout(...);
1090 function dns.cache()
1091 return _resolver.cache;
1094 function dns.socket_wrapper_set(...) -- - - - - - - - - socket_wrapper_set
1095 return _resolver:socket_wrapper_set(...);