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