net.dns: Support for resolving AAAA records
[prosody.git] / net / dns.lua
1 -- Prosody IM
2 -- This file is included with Prosody IM. It has modifications,
3 -- which are hereby placed in the public domain.
4
5
6 -- todo: quick (default) header generation
7 -- todo: nxdomain, error handling
8 -- todo: cache results of encodeName
9
10
11 -- reference: http://tools.ietf.org/html/rfc1035
12 -- reference: http://tools.ietf.org/html/rfc1876 (LOC)
13
14
15 local socket = require "socket";
16 local timer = require "util.timer";
17
18 local _, windows = pcall(require, "util.windows");
19 local is_windows = (_ and windows) or os.getenv("WINDIR");
20
21 local coroutine, io, math, string, table =
22       coroutine, io, math, string, table;
23
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;
26
27 local ztact = { -- public domain 20080404 lua@ztact.com
28         get = function(parent, ...)
29                 local len = select('#', ...);
30                 for i=1,len do
31                         parent = parent[select(i, ...)];
32                         if parent == nil then break; end
33                 end
34                 return parent;
35         end;
36         set = function(parent, ...)
37                 local len = select('#', ...);
38                 local key, value = select(len-1, ...);
39                 local cutpoint, cutkey;
40
41                 for i=1,len-2 do
42                         local key = select (i, ...)
43                         local child = parent[key]
44
45                         if value == nil then
46                                 if child == nil then
47                                         return;
48                                 elseif next(child, next(child)) then
49                                         cutpoint = nil; cutkey = nil;
50                                 elseif cutpoint == nil then
51                                         cutpoint = parent; cutkey = key;
52                                 end
53                         elseif child == nil then
54                                 child = {};
55                                 parent[key] = child;
56                         end
57                         parent = child
58                 end
59
60                 if value == nil and cutpoint then
61                         cutpoint[cutkey] = nil;
62                 else
63                         parent[key] = value;
64                         return value;
65                 end
66         end;
67 };
68 local get, set = ztact.get, ztact.set;
69
70 local default_timeout = 15;
71
72 -------------------------------------------------- module dns
73 module('dns')
74 local dns = _M;
75
76
77 -- dns type & class codes ------------------------------ dns type & class codes
78
79
80 local append = table.insert
81
82
83 local function highbyte(i)    -- - - - - - - - - - - - - - - - - - -  highbyte
84         return (i-(i%0x100))/0x100;
85 end
86
87
88 local function augment (t)    -- - - - - - - - - - - - - - - - - - - -  augment
89         local a = {};
90         for i,s in pairs(t) do
91                 a[i] = s;
92                 a[s] = s;
93                 a[string.lower(s)] = s;
94         end
95         return a;
96 end
97
98
99 local function encode (t)    -- - - - - - - - - - - - - - - - - - - - -  encode
100         local code = {};
101         for i,s in pairs(t) do
102                 local word = string.char(highbyte(i), i%0x100);
103                 code[i] = word;
104                 code[s] = word;
105                 code[string.lower(s)] = word;
106         end
107         return code;
108 end
109
110
111 dns.types = {
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] = '*' };
116
117
118 dns.classes = { 'IN', 'CS', 'CH', 'HS', [255] = '*' };
119
120
121 dns.type      = augment (dns.types);
122 dns.class     = augment (dns.classes);
123 dns.typecode  = encode  (dns.types);
124 dns.classcode = encode  (dns.classes);
125
126
127
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'];
132 end
133
134
135 local function prune(rrs, time, soft)    -- - - - - - - - - - - - - - -  prune
136         time = time or socket.gettime();
137         for i,rr in pairs(rrs) do
138                 if rr.tod then
139                         -- rr.tod = rr.tod - 50    -- accelerated decripitude
140                         rr.ttl = math.floor(rr.tod - time);
141                         if rr.ttl <= 0 then
142                                 table.remove(rrs, i);
143                                 return prune(rrs, time, soft); -- Re-iterate
144                         end
145                 elseif soft == 'soft' then    -- What is this?  I forget!
146                         assert(rr.ttl == 0);
147                         rrs[i] = nil;
148                 end
149         end
150 end
151
152
153 -- metatables & co. ------------------------------------------ metatables & co.
154
155
156 local resolver = {};
157 resolver.__index = resolver;
158
159 resolver.timeout = default_timeout;
160
161 local function default_rr_tostring(rr)
162         local rr_val = rr.type and rr[rr.type:lower()];
163         if type(rr_val) ~= "string" then
164                 return "<UNKNOWN RDATA TYPE>";
165         end
166         return rr_val;
167 end
168
169 local special_tostrings = {
170         LOC = resolver.LOC_tostring;
171         MX  = function (rr)
172                 return string.format('%2i %s', rr.pref, rr.mx);
173         end;
174         SRV = function (rr)
175                 local s = rr.srv;
176                 return string.format('%5d %5d %5d %s', s.priority, s.weight, s.port, s.target);
177         end;
178 };
179
180 local rr_metatable = {};   -- - - - - - - - - - - - - - - - - - -  rr_metatable
181 function rr_metatable.__tostring(rr)
182         local rr_string = (special_tostrings[rr.type] or default_rr_tostring)(rr);
183         return string.format('%2s %-5s %6i %-28s %s', rr.class, rr.type, rr.ttl, rr.name, rr_string);
184 end
185
186
187 local rrs_metatable = {};    -- - - - - - - - - - - - - - - - - -  rrs_metatable
188 function rrs_metatable.__tostring(rrs)
189         local t = {};
190         for i,rr in pairs(rrs) do
191                 append(t, tostring(rr)..'\n');
192         end
193         return table.concat(t);
194 end
195
196
197 local cache_metatable = {};    -- - - - - - - - - - - - - - - -  cache_metatable
198 function cache_metatable.__tostring(cache)
199         local time = socket.gettime();
200         local t = {};
201         for class,types in pairs(cache) do
202                 for type,names in pairs(types) do
203                         for name,rrs in pairs(names) do
204                                 prune(rrs, time);
205                                 append(t, tostring(rrs));
206                         end
207                 end
208         end
209         return table.concat(t);
210 end
211
212
213 function resolver:new()    -- - - - - - - - - - - - - - - - - - - - - resolver
214         local r = { active = {}, cache = {}, unsorted = {} };
215         setmetatable(r, resolver);
216         setmetatable(r.cache, cache_metatable);
217         setmetatable(r.unsorted, { __mode = 'kv' });
218         return r;
219 end
220
221
222 -- packet layer -------------------------------------------------- packet layer
223
224
225 function dns.random(...)    -- - - - - - - - - - - - - - - - - - -  dns.random
226         math.randomseed(math.floor(10000*socket.gettime()));
227         dns.random = math.random;
228         return dns.random(...);
229 end
230
231
232 local function encodeHeader(o)    -- - - - - - - - - - - - - - -  encodeHeader
233         o = o or {};
234         o.id = o.id or dns.random(0, 0xffff); -- 16b    (random) id
235
236         o.rd = o.rd or 1;               --  1b  1 recursion desired
237         o.tc = o.tc or 0;               --  1b  1 truncated response
238         o.aa = o.aa or 0;               --  1b  1 authoritative response
239         o.opcode = o.opcode or 0;       --  4b  0 query
240                                 --  1 inverse query
241                                 --      2 server status request
242                                 --      3-15 reserved
243         o.qr = o.qr or 0;               --  1b  0 query, 1 response
244
245         o.rcode = o.rcode or 0; --  4b  0 no error
246                                 --      1 format error
247                                 --      2 server failure
248                                 --      3 name error
249                                 --      4 not implemented
250                                 --      5 refused
251                                 --      6-15 reserved
252         o.z = o.z  or 0;                --  3b  0 resvered
253         o.ra = o.ra or 0;               --  1b  1 recursion available
254
255         o.qdcount = o.qdcount or 1;     -- 16b  number of question RRs
256         o.ancount = o.ancount or 0;     -- 16b  number of answers RRs
257         o.nscount = o.nscount or 0;     -- 16b  number of nameservers RRs
258         o.arcount = o.arcount or 0;     -- 16b  number of additional RRs
259
260         -- string.char() rounds, so prevent roundup with -0.4999
261         local header = string.char(
262                 highbyte(o.id), o.id %0x100,
263                 o.rd + 2*o.tc + 4*o.aa + 8*o.opcode + 128*o.qr,
264                 o.rcode + 16*o.z + 128*o.ra,
265                 highbyte(o.qdcount),  o.qdcount %0x100,
266                 highbyte(o.ancount),  o.ancount %0x100,
267                 highbyte(o.nscount),  o.nscount %0x100,
268                 highbyte(o.arcount),  o.arcount %0x100
269         );
270
271         return header, o.id;
272 end
273
274
275 local function encodeName(name)    -- - - - - - - - - - - - - - - - encodeName
276         local t = {};
277         for part in string.gmatch(name, '[^.]+') do
278                 append(t, string.char(string.len(part)));
279                 append(t, part);
280         end
281         append(t, string.char(0));
282         return table.concat(t);
283 end
284
285
286 local function encodeQuestion(qname, qtype, qclass)    -- - - - encodeQuestion
287         qname  = encodeName(qname);
288         qtype  = dns.typecode[qtype or 'a'];
289         qclass = dns.classcode[qclass or 'in'];
290         return qname..qtype..qclass;
291 end
292
293
294 function resolver:byte(len)    -- - - - - - - - - - - - - - - - - - - - - byte
295         len = len or 1;
296         local offset = self.offset;
297         local last = offset + len - 1;
298         if last > #self.packet then
299                 error(string.format('out of bounds: %i>%i', last, #self.packet));
300         end
301         self.offset = offset + len;
302         return string.byte(self.packet, offset, last);
303 end
304
305
306 function resolver:word()    -- - - - - - - - - - - - - - - - - - - - - -  word
307         local b1, b2 = self:byte(2);
308         return 0x100*b1 + b2;
309 end
310
311
312 function resolver:dword ()    -- - - - - - - - - - - - - - - - - - - - -  dword
313         local b1, b2, b3, b4 = self:byte(4);
314         --print('dword', b1, b2, b3, b4);
315         return 0x1000000*b1 + 0x10000*b2 + 0x100*b3 + b4;
316 end
317
318
319 function resolver:sub(len)    -- - - - - - - - - - - - - - - - - - - - - - sub
320         len = len or 1;
321         local s = string.sub(self.packet, self.offset, self.offset + len - 1);
322         self.offset = self.offset + len;
323         return s;
324 end
325
326
327 function resolver:header(force)    -- - - - - - - - - - - - - - - - - - header
328         local id = self:word();
329         --print(string.format(':header  id  %x', id));
330         if not self.active[id] and not force then return nil; end
331
332         local h = { id = id };
333
334         local b1, b2 = self:byte(2);
335
336         h.rd      = b1 %2;
337         h.tc      = b1 /2%2;
338         h.aa      = b1 /4%2;
339         h.opcode  = b1 /8%16;
340         h.qr      = b1 /128;
341
342         h.rcode   = b2 %16;
343         h.z       = b2 /16%8;
344         h.ra      = b2 /128;
345
346         h.qdcount = self:word();
347         h.ancount = self:word();
348         h.nscount = self:word();
349         h.arcount = self:word();
350
351         for k,v in pairs(h) do h[k] = v-v%1; end
352
353         return h;
354 end
355
356
357 function resolver:name()    -- - - - - - - - - - - - - - - - - - - - - -  name
358         local remember, pointers = nil, 0;
359         local len = self:byte();
360         local n = {};
361         while len > 0 do
362                 if len >= 0xc0 then    -- name is "compressed"
363                         pointers = pointers + 1;
364                         if pointers >= 20 then error('dns error: 20 pointers'); end;
365                         local offset = ((len-0xc0)*0x100) + self:byte();
366                         remember = remember or self.offset;
367                         self.offset = offset + 1;    -- +1 for lua
368                 else    -- name is not compressed
369                         append(n, self:sub(len)..'.');
370                 end
371                 len = self:byte();
372         end
373         self.offset = remember or self.offset;
374         return table.concat(n);
375 end
376
377
378 function resolver:question()    -- - - - - - - - - - - - - - - - - -  question
379         local q = {};
380         q.name  = self:name();
381         q.type  = dns.type[self:word()];
382         q.class = dns.class[self:word()];
383         return q;
384 end
385
386
387 function resolver:A(rr)    -- - - - - - - - - - - - - - - - - - - - - - - -  A
388         local b1, b2, b3, b4 = self:byte(4);
389         rr.a = string.format('%i.%i.%i.%i', b1, b2, b3, b4);
390 end
391
392 function resolver:AAAA(rr)
393         local addr = {};
394         for i = 1, rr.rdlength, 2 do
395                 local b1, b2 = self:byte(2);
396                 table.insert(addr, ("%02x%02x"):format(b1, b2));
397         end
398         rr.aaaa = table.concat(addr, ":");
399 end
400
401 function resolver:CNAME(rr)    -- - - - - - - - - - - - - - - - - - - -  CNAME
402         rr.cname = self:name();
403 end
404
405
406 function resolver:MX(rr)    -- - - - - - - - - - - - - - - - - - - - - - -  MX
407         rr.pref = self:word();
408         rr.mx   = self:name();
409 end
410
411
412 function resolver:LOC_nibble_power()    -- - - - - - - - - -  LOC_nibble_power
413         local b = self:byte();
414         --print('nibbles', ((b-(b%0x10))/0x10), (b%0x10));
415         return ((b-(b%0x10))/0x10) * (10^(b%0x10));
416 end
417
418
419 function resolver:LOC(rr)    -- - - - - - - - - - - - - - - - - - - - - -  LOC
420         rr.version = self:byte();
421         if rr.version == 0 then
422                 rr.loc           = rr.loc or {};
423                 rr.loc.size      = self:LOC_nibble_power();
424                 rr.loc.horiz_pre = self:LOC_nibble_power();
425                 rr.loc.vert_pre  = self:LOC_nibble_power();
426                 rr.loc.latitude  = self:dword();
427                 rr.loc.longitude = self:dword();
428                 rr.loc.altitude  = self:dword();
429         end
430 end
431
432
433 local function LOC_tostring_degrees(f, pos, neg)    -- - - - - - - - - - - - -
434         f = f - 0x80000000;
435         if f < 0 then pos = neg; f = -f; end
436         local deg, min, msec;
437         msec = f%60000;
438         f    = (f-msec)/60000;
439         min  = f%60;
440         deg = (f-min)/60;
441         return string.format('%3d %2d %2.3f %s', deg, min, msec/1000, pos);
442 end
443
444
445 function resolver.LOC_tostring(rr)    -- - - - - - - - - - - - -  LOC_tostring
446         local t = {};
447
448         --[[
449         for k,name in pairs { 'size', 'horiz_pre', 'vert_pre', 'latitude', 'longitude', 'altitude' } do
450                 append(t, string.format('%4s%-10s: %12.0f\n', '', name, rr.loc[name]));
451         end
452         --]]
453
454         append(t, string.format(
455                 '%s    %s    %.2fm %.2fm %.2fm %.2fm',
456                 LOC_tostring_degrees (rr.loc.latitude, 'N', 'S'),
457                 LOC_tostring_degrees (rr.loc.longitude, 'E', 'W'),
458                 (rr.loc.altitude - 10000000) / 100,
459                 rr.loc.size / 100,
460                 rr.loc.horiz_pre / 100,
461                 rr.loc.vert_pre / 100
462         ));
463
464         return table.concat(t);
465 end
466
467
468 function resolver:NS(rr)    -- - - - - - - - - - - - - - - - - - - - - - -  NS
469         rr.ns = self:name();
470 end
471
472
473 function resolver:SOA(rr)    -- - - - - - - - - - - - - - - - - - - - - -  SOA
474 end
475
476
477 function resolver:SRV(rr)    -- - - - - - - - - - - - - - - - - - - - - -  SRV
478           rr.srv = {};
479           rr.srv.priority = self:word();
480           rr.srv.weight   = self:word();
481           rr.srv.port     = self:word();
482           rr.srv.target   = self:name();
483 end
484
485 function resolver:PTR(rr)
486         rr.ptr = self:name();
487 end
488
489 function resolver:TXT(rr)    -- - - - - - - - - - - - - - - - - - - - - -  TXT
490         rr.txt = self:sub (self:byte());
491 end
492
493
494 function resolver:rr()    -- - - - - - - - - - - - - - - - - - - - - - - -  rr
495         local rr = {};
496         setmetatable(rr, rr_metatable);
497         rr.name     = self:name(self);
498         rr.type     = dns.type[self:word()] or rr.type;
499         rr.class    = dns.class[self:word()] or rr.class;
500         rr.ttl      = 0x10000*self:word() + self:word();
501         rr.rdlength = self:word();
502
503         if rr.ttl <= 0 then
504                 rr.tod = self.time + 30;
505         else
506                 rr.tod = self.time + rr.ttl;
507         end
508
509         local remember = self.offset;
510         local rr_parser = self[dns.type[rr.type]];
511         if rr_parser then rr_parser(self, rr); end
512         self.offset = remember;
513         rr.rdata = self:sub(rr.rdlength);
514         return rr;
515 end
516
517
518 function resolver:rrs (count)    -- - - - - - - - - - - - - - - - - - - - - rrs
519         local rrs = {};
520         for i = 1,count do append(rrs, self:rr()); end
521         return rrs;
522 end
523
524
525 function resolver:decode(packet, force)    -- - - - - - - - - - - - - - decode
526         self.packet, self.offset = packet, 1;
527         local header = self:header(force);
528         if not header then return nil; end
529         local response = { header = header };
530
531         response.question = {};
532         local offset = self.offset;
533         for i = 1,response.header.qdcount do
534                 append(response.question, self:question());
535         end
536         response.question.raw = string.sub(self.packet, offset, self.offset - 1);
537
538         if not force then
539                 if not self.active[response.header.id] or not self.active[response.header.id][response.question.raw] then
540                         return nil;
541                 end
542         end
543
544         response.answer     = self:rrs(response.header.ancount);
545         response.authority  = self:rrs(response.header.nscount);
546         response.additional = self:rrs(response.header.arcount);
547
548         return response;
549 end
550
551
552 -- socket layer -------------------------------------------------- socket layer
553
554
555 resolver.delays = { 1, 3 };
556
557
558 function resolver:addnameserver(address)    -- - - - - - - - - - addnameserver
559         self.server = self.server or {};
560         append(self.server, address);
561 end
562
563
564 function resolver:setnameserver(address)    -- - - - - - - - - - setnameserver
565         self.server = {};
566         self:addnameserver(address);
567 end
568
569
570 function resolver:adddefaultnameservers()    -- - - - -  adddefaultnameservers
571         if is_windows then
572                 if windows and windows.get_nameservers then
573                         for _, server in ipairs(windows.get_nameservers()) do
574                                 self:addnameserver(server);
575                         end
576                 end
577                 if not self.server or #self.server == 0 then
578                         -- TODO log warning about no nameservers, adding opendns servers as fallback
579                         self:addnameserver("208.67.222.222");
580                         self:addnameserver("208.67.220.220");
581                 end
582         else -- posix
583                 local resolv_conf = io.open("/etc/resolv.conf");
584                 if resolv_conf then
585                         for line in resolv_conf:lines() do
586                                 line = line:gsub("#.*$", "")
587                                         :match('^%s*nameserver%s+(.*)%s*$');
588                                 if line then
589                                         line:gsub("%f[%d.](%d+%.%d+%.%d+%.%d+)%f[^%d.]", function (address)
590                                                 self:addnameserver(address)
591                                         end);
592                                 end
593                         end
594                 end
595                 if not self.server or #self.server == 0 then
596                         -- TODO log warning about no nameservers, adding localhost as the default nameserver
597                         self:addnameserver("127.0.0.1");
598                 end
599         end
600 end
601
602
603 function resolver:getsocket(servernum)    -- - - - - - - - - - - - - getsocket
604         self.socket = self.socket or {};
605         self.socketset = self.socketset or {};
606
607         local sock = self.socket[servernum];
608         if sock then return sock; end
609
610         local err;
611         sock, err = socket.udp();
612         if not sock then
613                 return nil, err;
614         end
615         if self.socket_wrapper then sock = self.socket_wrapper(sock, self); end
616         sock:settimeout(0);
617         -- todo: attempt to use a random port, fallback to 0
618         sock:setsockname('*', 0);
619         sock:setpeername(self.server[servernum], 53);
620         self.socket[servernum] = sock;
621         self.socketset[sock] = servernum;
622         return sock;
623 end
624
625 function resolver:voidsocket(sock)
626         if self.socket[sock] then
627                 self.socketset[self.socket[sock]] = nil;
628                 self.socket[sock] = nil;
629         elseif self.socketset[sock] then
630                 self.socket[self.socketset[sock]] = nil;
631                 self.socketset[sock] = nil;
632         end
633 end
634
635 function resolver:socket_wrapper_set(func)  -- - - - - - - socket_wrapper_set
636         self.socket_wrapper = func;
637 end
638
639
640 function resolver:closeall ()    -- - - - - - - - - - - - - - - - - -  closeall
641         for i,sock in ipairs(self.socket) do
642                 self.socket[i] = nil;
643                 self.socketset[sock] = nil;
644                 sock:close();
645         end
646 end
647
648
649 function resolver:remember(rr, type)    -- - - - - - - - - - - - - -  remember
650         --print ('remember', type, rr.class, rr.type, rr.name)
651         local qname, qtype, qclass = standardize(rr.name, rr.type, rr.class);
652
653         if type ~= '*' then
654                 type = qtype;
655                 local all = get(self.cache, qclass, '*', qname);
656                 --print('remember all', all);
657                 if all then append(all, rr); end
658         end
659
660         self.cache = self.cache or setmetatable({}, cache_metatable);
661         local rrs = get(self.cache, qclass, type, qname) or
662                 set(self.cache, qclass, type, qname, setmetatable({}, rrs_metatable));
663         append(rrs, rr);
664
665         if type == 'MX' then self.unsorted[rrs] = true; end
666 end
667
668
669 local function comp_mx(a, b)    -- - - - - - - - - - - - - - - - - - - comp_mx
670         return (a.pref == b.pref) and (a.mx < b.mx) or (a.pref < b.pref);
671 end
672
673
674 function resolver:peek (qname, qtype, qclass)    -- - - - - - - - - - - -  peek
675         qname, qtype, qclass = standardize(qname, qtype, qclass);
676         local rrs = get(self.cache, qclass, qtype, qname);
677         if not rrs then return nil; end
678         if prune(rrs, socket.gettime()) and qtype == '*' or not next(rrs) then
679                 set(self.cache, qclass, qtype, qname, nil);
680                 return nil;
681         end
682         if self.unsorted[rrs] then table.sort (rrs, comp_mx); end
683         return rrs;
684 end
685
686
687 function resolver:purge(soft)    -- - - - - - - - - - - - - - - - - - -  purge
688         if soft == 'soft' then
689                 self.time = socket.gettime();
690                 for class,types in pairs(self.cache or {}) do
691                         for type,names in pairs(types) do
692                                 for name,rrs in pairs(names) do
693                                         prune(rrs, self.time, 'soft')
694                                 end
695                         end
696                 end
697         else self.cache = {}; end
698 end
699
700
701 function resolver:query(qname, qtype, qclass)    -- - - - - - - - - - -- query
702         qname, qtype, qclass = standardize(qname, qtype, qclass)
703
704         if not self.server then self:adddefaultnameservers(); end
705
706         local question = encodeQuestion(qname, qtype, qclass);
707         local peek = self:peek (qname, qtype, qclass);
708         if peek then return peek; end
709
710         local header, id = encodeHeader();
711         --print ('query  id', id, qclass, qtype, qname)
712         local o = {
713                 packet = header..question,
714                 server = self.best_server,
715                 delay  = 1,
716                 retry  = socket.gettime() + self.delays[1]
717         };
718
719         -- remember the query
720         self.active[id] = self.active[id] or {};
721         self.active[id][question] = o;
722
723         -- remember which coroutine wants the answer
724         local co = coroutine.running();
725         if co then
726                 set(self.wanted, qclass, qtype, qname, co, true);
727                 --set(self.yielded, co, qclass, qtype, qname, true);
728         end
729
730         local conn, err = self:getsocket(o.server)
731         if not conn then
732                 return nil, err;
733         end
734         conn:send (o.packet)
735         
736         if timer and self.timeout then
737                 local num_servers = #self.server;
738                 local i = 1;
739                 timer.add_task(self.timeout, function ()
740                         if get(self.wanted, qclass, qtype, qname, co) then
741                                 if i < num_servers then
742                                         i = i + 1;
743                                         self:servfail(conn);
744                                         o.server = self.best_server;
745                                         conn, err = self:getsocket(o.server);
746                                         if conn then
747                                                 conn:send(o.packet);
748                                                 return self.timeout;
749                                         end
750                                 end
751                                 -- Tried everything, failed
752                                 self:cancel(qclass, qtype, qname, co, true);
753                         end
754                 end)
755         end
756         return true;
757 end
758
759 function resolver:servfail(sock)
760         -- Resend all queries for this server
761
762         local num = self.socketset[sock]
763
764         -- Socket is dead now
765         self:voidsocket(sock);
766
767         -- Find all requests to the down server, and retry on the next server
768         self.time = socket.gettime();
769         for id,queries in pairs(self.active) do
770                 for question,o in pairs(queries) do
771                         if o.server == num then -- This request was to the broken server
772                                 o.server = o.server + 1 -- Use next server
773                                 if o.server > #self.server then
774                                         o.server = 1;
775                                 end
776
777                                 o.retries = (o.retries or 0) + 1;
778                                 if o.retries >= #self.server then
779                                         --print('timeout');
780                                         queries[question] = nil;
781                                 else
782                                         local _a = self:getsocket(o.server);
783                                         if _a then _a:send(o.packet); end
784                                 end
785                         end
786                 end
787         end
788
789         if num == self.best_server then
790                 self.best_server = self.best_server + 1;
791                 if self.best_server > #self.server then
792                         -- Exhausted all servers, try first again
793                         self.best_server = 1;
794                 end
795         end
796 end
797
798 function resolver:settimeout(seconds)
799         self.timeout = seconds;
800 end
801
802 function resolver:receive(rset)    -- - - - - - - - - - - - - - - - -  receive
803         --print('receive');  print(self.socket);
804         self.time = socket.gettime();
805         rset = rset or self.socket;
806
807         local response;
808         for i,sock in pairs(rset) do
809
810                 if self.socketset[sock] then
811                         local packet = sock:receive();
812                         if packet then
813                                 response = self:decode(packet);
814                                 if response and self.active[response.header.id]
815                                         and self.active[response.header.id][response.question.raw] then
816                                         --print('received response');
817                                         --self.print(response);
818
819                                         for j,rr in pairs(response.answer) do
820                                                 if rr.name:sub(-#response.question[1].name, -1) == response.question[1].name then
821                                                         self:remember(rr, response.question[1].type)
822                                                 end
823                                         end
824
825                                         -- retire the query
826                                         local queries = self.active[response.header.id];
827                                         queries[response.question.raw] = nil;
828                                         
829                                         if not next(queries) then self.active[response.header.id] = nil; end
830                                         if not next(self.active) then self:closeall(); end
831
832                                         -- was the query on the wanted list?
833                                         local q = response.question[1];
834                                         local cos = get(self.wanted, q.class, q.type, q.name);
835                                         if cos then
836                                                 for co in pairs(cos) do
837                                                         set(self.yielded, co, q.class, q.type, q.name, nil);
838                                                         if coroutine.status(co) == "suspended" then coroutine.resume(co); end
839                                                 end
840                                                 set(self.wanted, q.class, q.type, q.name, nil);
841                                         end
842                                 end
843                         end
844                 end
845         end
846
847         return response;
848 end
849
850
851 function resolver:feed(sock, packet, force)
852         --print('receive'); print(self.socket);
853         self.time = socket.gettime();
854
855         local response = self:decode(packet, force);
856         if response and self.active[response.header.id]
857                 and self.active[response.header.id][response.question.raw] then
858                 --print('received response');
859                 --self.print(response);
860
861                 for j,rr in pairs(response.answer) do
862                         self:remember(rr, response.question[1].type);
863                 end
864
865                 -- retire the query
866                 local queries = self.active[response.header.id];
867                 queries[response.question.raw] = nil;
868                 if not next(queries) then self.active[response.header.id] = nil; end
869                 if not next(self.active) then self:closeall(); end
870
871                 -- was the query on the wanted list?
872                 local q = response.question[1];
873                 if q then
874                         local cos = get(self.wanted, q.class, q.type, q.name);
875                         if cos then
876                                 for co in pairs(cos) do
877                                         set(self.yielded, co, q.class, q.type, q.name, nil);
878                                         if coroutine.status(co) == "suspended" then coroutine.resume(co); end
879                                 end
880                                 set(self.wanted, q.class, q.type, q.name, nil);
881                         end
882                 end
883         end
884
885         return response;
886 end
887
888 function resolver:cancel(qclass, qtype, qname, co, call_handler)
889         local cos = get(self.wanted, qclass, qtype, qname);
890         if cos then
891                 if call_handler then
892                         coroutine.resume(co);
893                 end
894                 cos[co] = nil;
895         end
896 end
897
898 function resolver:pulse()    -- - - - - - - - - - - - - - - - - - - - -  pulse
899         --print(':pulse');
900         while self:receive() do end
901         if not next(self.active) then return nil; end
902
903         self.time = socket.gettime();
904         for id,queries in pairs(self.active) do
905                 for question,o in pairs(queries) do
906                         if self.time >= o.retry then
907
908                                 o.server = o.server + 1;
909                                 if o.server > #self.server then
910                                         o.server = 1;
911                                         o.delay = o.delay + 1;
912                                 end
913
914                                 if o.delay > #self.delays then
915                                         --print('timeout');
916                                         queries[question] = nil;
917                                         if not next(queries) then self.active[id] = nil; end
918                                         if not next(self.active) then return nil; end
919                                 else
920                                         --print('retry', o.server, o.delay);
921                                         local _a = self.socket[o.server];
922                                         if _a then _a:send(o.packet); end
923                                         o.retry = self.time + self.delays[o.delay];
924                                 end
925                         end
926                 end
927         end
928
929         if next(self.active) then return true; end
930         return nil;
931 end
932
933
934 function resolver:lookup(qname, qtype, qclass)    -- - - - - - - - - -  lookup
935         self:query (qname, qtype, qclass)
936         while self:pulse() do
937                 local recvt = {}
938                 for i, s in ipairs(self.socket) do
939                         recvt[i] = s
940                 end
941                 socket.select(recvt, nil, 4)
942         end
943         --print(self.cache);
944         return self:peek(qname, qtype, qclass);
945 end
946
947 function resolver:lookupex(handler, qname, qtype, qclass)    -- - - - - - - - - -  lookup
948         return self:peek(qname, qtype, qclass) or self:query(qname, qtype, qclass);
949 end
950
951 function resolver:tohostname(ip)
952         return dns.lookup(ip:gsub("(%d+)%.(%d+)%.(%d+)%.(%d+)", "%4.%3.%2.%1.in-addr.arpa."), "PTR");
953 end
954
955 --print ---------------------------------------------------------------- print
956
957
958 local hints = {    -- - - - - - - - - - - - - - - - - - - - - - - - - - - hints
959         qr = { [0]='query', 'response' },
960         opcode = { [0]='query', 'inverse query', 'server status request' },
961         aa = { [0]='non-authoritative', 'authoritative' },
962         tc = { [0]='complete', 'truncated' },
963         rd = { [0]='recursion not desired', 'recursion desired' },
964         ra = { [0]='recursion not available', 'recursion available' },
965         z  = { [0]='(reserved)' },
966         rcode = { [0]='no error', 'format error', 'server failure', 'name error', 'not implemented' },
967
968         type = dns.type,
969         class = dns.class
970 };
971
972
973 local function hint(p, s)    -- - - - - - - - - - - - - - - - - - - - - - hint
974         return (hints[s] and hints[s][p[s]]) or '';
975 end
976
977
978 function resolver.print(response)    -- - - - - - - - - - - - - resolver.print
979         for s,s in pairs { 'id', 'qr', 'opcode', 'aa', 'tc', 'rd', 'ra', 'z',
980                                                 'rcode', 'qdcount', 'ancount', 'nscount', 'arcount' } do
981                 print( string.format('%-30s', 'header.'..s), response.header[s], hint(response.header, s) );
982         end
983
984         for i,question in ipairs(response.question) do
985                 print(string.format ('question[%i].name         ', i), question.name);
986                 print(string.format ('question[%i].type         ', i), question.type);
987                 print(string.format ('question[%i].class        ', i), question.class);
988         end
989
990         local common = { name=1, type=1, class=1, ttl=1, rdlength=1, rdata=1 };
991         local tmp;
992         for s,s in pairs({'answer', 'authority', 'additional'}) do
993                 for i,rr in pairs(response[s]) do
994                         for j,t in pairs({ 'name', 'type', 'class', 'ttl', 'rdlength' }) do
995                                 tmp = string.format('%s[%i].%s', s, i, t);
996                                 print(string.format('%-30s', tmp), rr[t], hint(rr, t));
997                         end
998                         for j,t in pairs(rr) do
999                                 if not common[j] then
1000                                         tmp = string.format('%s[%i].%s', s, i, j);
1001                                         print(string.format('%-30s  %s', tostring(tmp), tostring(t)));
1002                                 end
1003                         end
1004                 end
1005         end
1006 end
1007
1008
1009 -- module api ------------------------------------------------------ module api
1010
1011
1012 function dns.resolver ()    -- - - - - - - - - - - - - - - - - - - - - resolver
1013         -- this function seems to be redundant with resolver.new ()
1014
1015         local r = { active = {}, cache = {}, unsorted = {}, wanted = {}, yielded = {}, best_server = 1 };
1016         setmetatable (r, resolver);
1017         setmetatable (r.cache, cache_metatable);
1018         setmetatable (r.unsorted, { __mode = 'kv' });
1019         return r;
1020 end
1021
1022 local _resolver = dns.resolver();
1023 dns._resolver = _resolver;
1024
1025 function dns.lookup(...)    -- - - - - - - - - - - - - - - - - - - - -  lookup
1026         return _resolver:lookup(...);
1027 end
1028
1029 function dns.tohostname(...)
1030         return _resolver:tohostname(...);
1031 end
1032
1033 function dns.purge(...)    -- - - - - - - - - - - - - - - - - - - - - -  purge
1034         return _resolver:purge(...);
1035 end
1036
1037 function dns.peek(...)    -- - - - - - - - - - - - - - - - - - - - - - -  peek
1038         return _resolver:peek(...);
1039 end
1040
1041 function dns.query(...)    -- - - - - - - - - - - - - - - - - - - - - -  query
1042         return _resolver:query(...);
1043 end
1044
1045 function dns.feed(...)    -- - - - - - - - - - - - - - - - - - - - - - -  feed
1046         return _resolver:feed(...);
1047 end
1048
1049 function dns.cancel(...)  -- - - - - - - - - - - - - - - - - - - - - -  cancel
1050         return _resolver:cancel(...);
1051 end
1052
1053 function dns.settimeout(...)
1054         return _resolver:settimeout(...);
1055 end
1056
1057 function dns.socket_wrapper_set(...)    -- - - - - - - - -  socket_wrapper_set
1058         return _resolver:socket_wrapper_set(...);
1059 end
1060
1061 return dns;