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