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         local co = coroutine.running();
726         local q = get(self.wanted, qclass, qtype, qname);
727         if co and q then
728                 -- We are already waiting for a reply to an identical query.
729                 set(self.wanted, qclass, qtype, qname, co, true);
730                 return true;
731         end
732
733         if not self.server then self:adddefaultnameservers(); end
734
735         local question = encodeQuestion(qname, qtype, qclass);
736         local peek = self:peek (qname, qtype, qclass);
737         if peek then return peek; end
738
739         local header, id = encodeHeader();
740         --print ('query  id', id, qclass, qtype, qname)
741         local o = {
742                 packet = header..question,
743                 server = self.best_server,
744                 delay  = 1,
745                 retry  = socket.gettime() + self.delays[1]
746         };
747
748         -- remember the query
749         self.active[id] = self.active[id] or {};
750         self.active[id][question] = o;
751
752         -- remember which coroutine wants the answer
753         if co then
754                 set(self.wanted, qclass, qtype, qname, co, true);
755                 --set(self.yielded, co, qclass, qtype, qname, true);
756         end
757
758         local conn, err = self:getsocket(o.server)
759         if not conn then
760                 return nil, err;
761         end
762         conn:send (o.packet)
763
764         if timer and self.timeout then
765                 local num_servers = #self.server;
766                 local i = 1;
767                 timer.add_task(self.timeout, function ()
768                         if get(self.wanted, qclass, qtype, qname, co) then
769                                 if i < num_servers then
770                                         i = i + 1;
771                                         self:servfail(conn);
772                                         o.server = self.best_server;
773                                         conn, err = self:getsocket(o.server);
774                                         if conn then
775                                                 conn:send(o.packet);
776                                                 return self.timeout;
777                                         end
778                                 end
779                                 -- Tried everything, failed
780                                 self:cancel(qclass, qtype, qname, co, true);
781                         end
782                 end)
783         end
784         return true;
785 end
786
787 function resolver:servfail(sock)
788         -- Resend all queries for this server
789
790         local num = self.socketset[sock]
791
792         -- Socket is dead now
793         self:voidsocket(sock);
794
795         -- Find all requests to the down server, and retry on the next server
796         self.time = socket.gettime();
797         for id,queries in pairs(self.active) do
798                 for question,o in pairs(queries) do
799                         if o.server == num then -- This request was to the broken server
800                                 o.server = o.server + 1 -- Use next server
801                                 if o.server > #self.server then
802                                         o.server = 1;
803                                 end
804
805                                 o.retries = (o.retries or 0) + 1;
806                                 if o.retries >= #self.server then
807                                         --print('timeout');
808                                         queries[question] = nil;
809                                 else
810                                         local _a = self:getsocket(o.server);
811                                         if _a then _a:send(o.packet); end
812                                 end
813                         end
814                 end
815                 if next(queries) == nil then
816                         self.active[id] = nil;
817                 end
818         end
819
820         if num == self.best_server then
821                 self.best_server = self.best_server + 1;
822                 if self.best_server > #self.server then
823                         -- Exhausted all servers, try first again
824                         self.best_server = 1;
825                 end
826         end
827 end
828
829 function resolver:settimeout(seconds)
830         self.timeout = seconds;
831 end
832
833 function resolver:receive(rset)    -- - - - - - - - - - - - - - - - -  receive
834         --print('receive');  print(self.socket);
835         self.time = socket.gettime();
836         rset = rset or self.socket;
837
838         local response;
839         for i,sock in pairs(rset) do
840
841                 if self.socketset[sock] then
842                         local packet = sock:receive();
843                         if packet then
844                                 response = self:decode(packet);
845                                 if response and self.active[response.header.id]
846                                         and self.active[response.header.id][response.question.raw] then
847                                         --print('received response');
848                                         --self.print(response);
849
850                                         for j,rr in pairs(response.answer) do
851                                                 if rr.name:sub(-#response.question[1].name, -1) == response.question[1].name then
852                                                         self:remember(rr, response.question[1].type)
853                                                 end
854                                         end
855
856                                         -- retire the query
857                                         local queries = self.active[response.header.id];
858                                         queries[response.question.raw] = nil;
859
860                                         if not next(queries) then self.active[response.header.id] = nil; end
861                                         if not next(self.active) then self:closeall(); end
862
863                                         -- was the query on the wanted list?
864                                         local q = response.question[1];
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
875                         end
876                 end
877         end
878
879         return response;
880 end
881
882
883 function resolver:feed(sock, packet, force)
884         --print('receive'); print(self.socket);
885         self.time = socket.gettime();
886
887         local response = self:decode(packet, force);
888         if response and self.active[response.header.id]
889                 and self.active[response.header.id][response.question.raw] then
890                 --print('received response');
891                 --self.print(response);
892
893                 for j,rr in pairs(response.answer) do
894                         self:remember(rr, response.question[1].type);
895                 end
896
897                 -- retire the query
898                 local queries = self.active[response.header.id];
899                 queries[response.question.raw] = nil;
900                 if not next(queries) then self.active[response.header.id] = nil; end
901                 if not next(self.active) then self:closeall(); end
902
903                 -- was the query on the wanted list?
904                 local q = response.question[1];
905                 if q then
906                         local cos = get(self.wanted, q.class, q.type, q.name);
907                         if cos then
908                                 for co in pairs(cos) do
909                                         set(self.yielded, co, q.class, q.type, q.name, nil);
910                                         if coroutine.status(co) == "suspended" then coroutine.resume(co); end
911                                 end
912                                 set(self.wanted, q.class, q.type, q.name, nil);
913                         end
914                 end
915         end
916
917         return response;
918 end
919
920 function resolver:cancel(qclass, qtype, qname, co, call_handler)
921         local cos = get(self.wanted, qclass, qtype, qname);
922         if cos then
923                 if call_handler then
924                         coroutine.resume(co);
925                 end
926                 cos[co] = nil;
927         end
928 end
929
930 function resolver:pulse()    -- - - - - - - - - - - - - - - - - - - - -  pulse
931         --print(':pulse');
932         while self:receive() do end
933         if not next(self.active) then return nil; end
934
935         self.time = socket.gettime();
936         for id,queries in pairs(self.active) do
937                 for question,o in pairs(queries) do
938                         if self.time >= o.retry then
939
940                                 o.server = o.server + 1;
941                                 if o.server > #self.server then
942                                         o.server = 1;
943                                         o.delay = o.delay + 1;
944                                 end
945
946                                 if o.delay > #self.delays then
947                                         --print('timeout');
948                                         queries[question] = nil;
949                                         if not next(queries) then self.active[id] = nil; end
950                                         if not next(self.active) then return nil; end
951                                 else
952                                         --print('retry', o.server, o.delay);
953                                         local _a = self.socket[o.server];
954                                         if _a then _a:send(o.packet); end
955                                         o.retry = self.time + self.delays[o.delay];
956                                 end
957                         end
958                 end
959         end
960
961         if next(self.active) then return true; end
962         return nil;
963 end
964
965
966 function resolver:lookup(qname, qtype, qclass)    -- - - - - - - - - -  lookup
967         self:query (qname, qtype, qclass)
968         while self:pulse() do
969                 local recvt = {}
970                 for i, s in ipairs(self.socket) do
971                         recvt[i] = s
972                 end
973                 socket.select(recvt, nil, 4)
974         end
975         --print(self.cache);
976         return self:peek(qname, qtype, qclass);
977 end
978
979 function resolver:lookupex(handler, qname, qtype, qclass)    -- - - - - - - - - -  lookup
980         return self:peek(qname, qtype, qclass) or self:query(qname, qtype, qclass);
981 end
982
983 function resolver:tohostname(ip)
984         return dns.lookup(ip:gsub("(%d+)%.(%d+)%.(%d+)%.(%d+)", "%4.%3.%2.%1.in-addr.arpa."), "PTR");
985 end
986
987 --print ---------------------------------------------------------------- print
988
989
990 local hints = {    -- - - - - - - - - - - - - - - - - - - - - - - - - - - hints
991         qr = { [0]='query', 'response' },
992         opcode = { [0]='query', 'inverse query', 'server status request' },
993         aa = { [0]='non-authoritative', 'authoritative' },
994         tc = { [0]='complete', 'truncated' },
995         rd = { [0]='recursion not desired', 'recursion desired' },
996         ra = { [0]='recursion not available', 'recursion available' },
997         z  = { [0]='(reserved)' },
998         rcode = { [0]='no error', 'format error', 'server failure', 'name error', 'not implemented' },
999
1000         type = dns.type,
1001         class = dns.class
1002 };
1003
1004
1005 local function hint(p, s)    -- - - - - - - - - - - - - - - - - - - - - - hint
1006         return (hints[s] and hints[s][p[s]]) or '';
1007 end
1008
1009
1010 function resolver.print(response)    -- - - - - - - - - - - - - resolver.print
1011         for s,s in pairs { 'id', 'qr', 'opcode', 'aa', 'tc', 'rd', 'ra', 'z',
1012                                                 'rcode', 'qdcount', 'ancount', 'nscount', 'arcount' } do
1013                 print( string.format('%-30s', 'header.'..s), response.header[s], hint(response.header, s) );
1014         end
1015
1016         for i,question in ipairs(response.question) do
1017                 print(string.format ('question[%i].name         ', i), question.name);
1018                 print(string.format ('question[%i].type         ', i), question.type);
1019                 print(string.format ('question[%i].class        ', i), question.class);
1020         end
1021
1022         local common = { name=1, type=1, class=1, ttl=1, rdlength=1, rdata=1 };
1023         local tmp;
1024         for s,s in pairs({'answer', 'authority', 'additional'}) do
1025                 for i,rr in pairs(response[s]) do
1026                         for j,t in pairs({ 'name', 'type', 'class', 'ttl', 'rdlength' }) do
1027                                 tmp = string.format('%s[%i].%s', s, i, t);
1028                                 print(string.format('%-30s', tmp), rr[t], hint(rr, t));
1029                         end
1030                         for j,t in pairs(rr) do
1031                                 if not common[j] then
1032                                         tmp = string.format('%s[%i].%s', s, i, j);
1033                                         print(string.format('%-30s  %s', tostring(tmp), tostring(t)));
1034                                 end
1035                         end
1036                 end
1037         end
1038 end
1039
1040
1041 -- module api ------------------------------------------------------ module api
1042
1043
1044 function dns.resolver ()    -- - - - - - - - - - - - - - - - - - - - - resolver
1045         -- this function seems to be redundant with resolver.new ()
1046
1047         local r = { active = {}, cache = {}, unsorted = {}, wanted = {}, yielded = {}, best_server = 1 };
1048         setmetatable (r, resolver);
1049         setmetatable (r.cache, cache_metatable);
1050         setmetatable (r.unsorted, { __mode = 'kv' });
1051         return r;
1052 end
1053
1054 local _resolver = dns.resolver();
1055 dns._resolver = _resolver;
1056
1057 function dns.lookup(...)    -- - - - - - - - - - - - - - - - - - - - -  lookup
1058         return _resolver:lookup(...);
1059 end
1060
1061 function dns.tohostname(...)
1062         return _resolver:tohostname(...);
1063 end
1064
1065 function dns.purge(...)    -- - - - - - - - - - - - - - - - - - - - - -  purge
1066         return _resolver:purge(...);
1067 end
1068
1069 function dns.peek(...)    -- - - - - - - - - - - - - - - - - - - - - - -  peek
1070         return _resolver:peek(...);
1071 end
1072
1073 function dns.query(...)    -- - - - - - - - - - - - - - - - - - - - - -  query
1074         return _resolver:query(...);
1075 end
1076
1077 function dns.feed(...)    -- - - - - - - - - - - - - - - - - - - - - - -  feed
1078         return _resolver:feed(...);
1079 end
1080
1081 function dns.cancel(...)  -- - - - - - - - - - - - - - - - - - - - - -  cancel
1082         return _resolver:cancel(...);
1083 end
1084
1085 function dns.settimeout(...)
1086         return _resolver:settimeout(...);
1087 end
1088
1089 function dns.cache()
1090         return _resolver.cache;
1091 end
1092
1093 function dns.socket_wrapper_set(...)    -- - - - - - - - -  socket_wrapper_set
1094         return _resolver:socket_wrapper_set(...);
1095 end
1096
1097 return dns;