Prepare required data folder for integration tests
[prosody.git] / net / resolvers / basic.lua
blob56f9c77d2438af50424d04636603b10a966c1256
1 local adns = require "net.adns";
2 local inet_pton = require "util.net".pton;
3 local unpack = table.unpack or unpack; -- luacheck: ignore 113
5 local methods = {};
6 local resolver_mt = { __index = methods };
8 -- Find the next target to connect to, and
9 -- pass it to cb()
10 function methods:next(cb)
11 if self.targets then
12 if #self.targets == 0 then
13 cb(nil);
14 return;
15 end
16 local next_target = table.remove(self.targets, 1);
17 cb(unpack(next_target, 1, 4));
18 return;
19 end
21 local targets = {};
22 local n = 2;
23 local function ready()
24 n = n - 1;
25 if n > 0 then return; end
26 self.targets = targets;
27 self:next(cb);
28 end
30 local is_ip = inet_pton(self.hostname);
31 if is_ip then
32 if #is_ip == 16 then
33 cb(self.conn_type.."6", self.hostname, self.port, self.extra);
34 elseif #is_ip == 4 then
35 cb(self.conn_type.."4", self.hostname, self.port, self.extra);
36 end
37 return;
38 end
40 -- Resolve DNS to target list
41 local dns_resolver = adns.resolver();
42 dns_resolver:lookup(function (answer)
43 if answer then
44 for _, record in ipairs(answer) do
45 table.insert(targets, { self.conn_type.."4", record.a, self.port, self.extra });
46 end
47 end
48 ready();
49 end, self.hostname, "A", "IN");
51 dns_resolver:lookup(function (answer)
52 if answer then
53 for _, record in ipairs(answer) do
54 table.insert(targets, { self.conn_type.."6", record.aaaa, self.port, self.extra });
55 end
56 end
57 ready();
58 end, self.hostname, "AAAA", "IN");
59 end
61 local function new(hostname, port, conn_type, extra)
62 return setmetatable({
63 hostname = hostname;
64 port = port;
65 conn_type = conn_type or "tcp";
66 extra = extra;
67 }, resolver_mt);
68 end
70 return {
71 new = new;