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