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