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