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