util.encodings: Spell out all IDNA 2008 options ICU has
[prosody.git] / net / resolvers / service.lua
blob62d269e5a71e47b53e75592d55116ad3f0ca6ce8
1 local adns = require "net.adns";
2 local basic = require "net.resolvers.basic";
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 self.resolver = basic.new(unpack(next_target, 1, 4));
18 self.resolver:next(function (...)
19 if ... == nil then
20 self:next(cb);
21 else
22 cb(...);
23 end
24 end);
25 return;
26 end
28 local targets = {};
29 local function ready()
30 self.targets = targets;
31 self:next(cb);
32 end
34 -- Resolve DNS to target list
35 local dns_resolver = adns.resolver();
36 dns_resolver:lookup(function (answer, err)
37 if not answer and not err then
38 -- net.adns returns nil if there are zero records or nxdomain
39 answer = {};
40 end
41 if answer then
42 if #answer == 0 then
43 if self.extra and self.extra.default_port then
44 table.insert(targets, { self.hostname, self.extra.default_port, self.conn_type, self.extra });
45 end
46 ready();
47 return;
48 end
50 if #answer == 1 and answer[1].srv.target == "." then -- No service here
51 ready();
52 return;
53 end
55 table.sort(answer, function (a, b) return a.srv.priority < b.srv.priority end);
56 for _, record in ipairs(answer) do
57 table.insert(targets, { record.srv.target, record.srv.port, self.conn_type, self.extra });
58 end
59 end
60 ready();
61 end, "_" .. self.service .. "._" .. self.conn_type .. "." .. self.hostname, "SRV", "IN");
62 end
64 local function new(hostname, service, conn_type, extra)
65 return setmetatable({
66 hostname = hostname;
67 service = service;
68 conn_type = conn_type or "tcp";
69 extra = extra;
70 }, resolver_mt);
71 end
73 return {
74 new = new;