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