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