1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty5.resolver.dns;
17
18 import io.netty5.util.internal.SocketUtils;
19 import io.netty5.util.internal.logging.InternalLogger;
20 import io.netty5.util.internal.logging.InternalLoggerFactory;
21
22 import javax.naming.Context;
23 import javax.naming.NamingException;
24 import javax.naming.directory.DirContext;
25 import javax.naming.directory.InitialDirContext;
26 import java.net.InetSocketAddress;
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.util.Hashtable;
30 import java.util.List;
31
32 final class DirContextUtils {
33 private static final InternalLogger logger =
34 InternalLoggerFactory.getInstance(DirContextUtils.class);
35
36 private DirContextUtils() { }
37
38 static void addNameServers(List<InetSocketAddress> defaultNameServers, int defaultPort) {
39
40
41
42
43
44 Hashtable<String, String> env = new Hashtable<>();
45 env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
46 env.put("java.naming.provider.url", "dns://");
47
48 try {
49 DirContext ctx = new InitialDirContext(env);
50 String dnsUrls = (String) ctx.getEnvironment().get("java.naming.provider.url");
51
52 if (dnsUrls != null && !dnsUrls.isEmpty()) {
53 String[] servers = dnsUrls.split(" ");
54 for (String server : servers) {
55 try {
56 URI uri = new URI(server);
57 String host = new URI(server).getHost();
58
59 if (host == null || host.isEmpty()) {
60 logger.debug(
61 "Skipping a nameserver URI as host portion could not be extracted: {}", server);
62
63 continue;
64 }
65 int port = uri.getPort();
66 defaultNameServers.add(SocketUtils.socketAddress(uri.getHost(), port == -1 ?
67 defaultPort : port));
68 } catch (URISyntaxException e) {
69 logger.debug("Skipping a malformed nameserver URI: {}", server, e);
70 }
71 }
72 }
73 } catch (NamingException ignore) {
74
75 }
76 }
77 }