<div dir="ltr">Hello,<div><br></div><div>While investigating DNS resolution failure using Netty (<a href="https://github.com/netty/netty/issues/9796">https://github.com/netty/netty/issues/9796</a>), I came across an old JDK bug where on Windows, the list of OS name servers includes those for disabled interfaces (<a href="https://bugs.openjdk.java.net/browse/JDK-7006496">https://bugs.openjdk.java.net/browse/JDK-7006496</a>). This is problematic since it will often include values from a previously registered network that is not available anymore, hence resolution requests would be guaranteed to fail.</div><div><br></div><div>The current approach reads DNS name servers from the registry, where it isn't possible to read whether an adapter is actually enabled or not. However, Windows Vista+ (minimum JDK8+ supported Windows) include an API that can be used to examine whether an adapter is currently enabled, and also return its DNS servers. So I've created this patch to update the name server lookup to use this technique. I can confirm that now only name servers from enabled adapters are loaded. A side effect is the previous approach could only read IPv4 - now IPv6 DNS servers are also loaded. The unix implementation seems to do this too, so I don't think this should cause issues but I can filter to only IPv4 to be more conservative if desired.</div><div><br></div><div>I have also cleaned some low hanging fruit in what seems to be very old code</div><div><br></div><div>- Use ArrayList instead of LinkedList since it can be accurately preallocated and is not mutated</div><div>- Use nanoTime instead of currentTimeMillis for refresh timer to not cause problems during OS time changes.</div><div>- Simplify tokenizer to only tokenize on space, there is never a comma separated list passed to it as we create the list in our JNI code</div><div><br></div><div>This is my first patch for OpenJDK - happy to accept any feedback.</div><div><br></div><div>Thanks for the consideration.</div><div><br></div><div>Inlined patch follows (also attached but I've had attached patch scrubbed when submitting to jmh-dev before...)</div><div><br></div><div>diff --git a/src/java.base/windows/classes/sun/net/dns/ResolverConfigurationImpl.java b/src/java.base/windows/classes/sun/net/dns/ResolverConfigurationImpl.java<br>index 2250b3158e..dde871cf19 100644<br>--- a/src/java.base/windows/classes/sun/net/dns/ResolverConfigurationImpl.java<br>+++ b/src/java.base/windows/classes/sun/net/dns/ResolverConfigurationImpl.java<br>@@ -25,9 +25,10 @@<br> <br> package sun.net.dns;<br> <br>+import java.util.ArrayList;<br> import java.util.List;<br>-import java.util.LinkedList;<br> import java.util.StringTokenizer;<br>+import java.util.concurrent.TimeUnit;<br> <br> /*<br>  * An implementation of sun.net.ResolverConfiguration for Windows.<br>@@ -50,30 +51,65 @@ public class ResolverConfigurationImpl<br> <br>     // Cache timeout (120 seconds) - should be converted into property<br>     // or configured as preference in the future.<br>-    private static final int TIMEOUT = 120000;<br>+    private static final long TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(120);<br> <br>     // DNS suffix list and name servers populated by native method<br>     private static String os_searchlist;<br>     private static String os_nameservers;<br> <br>     // Cached lists<br>-    private static LinkedList<String> searchlist;<br>-    private static LinkedList<String> nameservers;<br>+    private static ArrayList<String> searchlist;<br>+    private static ArrayList<String> nameservers;<br> <br>-    // Parse string that consists of token delimited by space or commas<br>-    // and return LinkedHashMap<br>-    private LinkedList<String> stringToList(String str) {<br>-        LinkedList<String> ll = new LinkedList<>();<br>+    // Parse string that consists of token delimited by space <br>+    // and return ArrayList<br>+    private ArrayList<String> stringToList(String str) {<br>+        ArrayList<String> l = allocateListForDelimitedString(str);<br> <br>         // comma and space are valid delimiters<br>-        StringTokenizer st = new StringTokenizer(str, ", ");<br>+        StringTokenizer st = new StringTokenizer(str, " ");<br>         while (st.hasMoreTokens()) {<br>             String s = st.nextToken();<br>-            if (!ll.contains(s)) {<br>-                ll.add(s);<br>+            if (!l.contains(s)) {<br>+                l.add(s);<br>             }<br>         }<br>-        return ll;<br>+        return l;<br>+    }<br>+<br>+    // Parse string that consists of token delimited by space<br>+    // and return ArrayList. Converts IPv6 addresses to BSD-style.<br>+    private ArrayList<String> addressesToList(String str) {<br>+        ArrayList<String> l = allocateListForDelimitedString(str);<br>+<br>+        // comma and space are valid delimiters<br>+        StringTokenizer st = new StringTokenizer(str, " ");<br>+        while (st.hasMoreTokens()) {<br>+            String s = st.nextToken();<br>+            if (!s.isEmpty()) {<br>+                if (s.indexOf(':') >= 0 && s.charAt(0) != '[') {<br>+                    // Not BSD style<br>+                    s = '[' + s + ']';<br>+                }<br>+                if (!l.contains(s)) {<br>+                    l.add(s);<br>+                }<br>+            }<br>+        }<br>+        return l;<br>+    }<br>+<br>+    private ArrayList<String> allocateListForDelimitedString(String str) {<br>+        int num = 0;<br>+        for (int i = 0; i < str.length(); i++) {<br>+            char c = str.charAt(i);<br>+            // String is space separated list of items<br>+            if (c == ' ') {<br>+                num++;<br>+            }<br>+        }<br>+        // Actual num is number of delimiters + 1<br>+        return new ArrayList<String>(num + 1);<br>     }<br> <br>     // Load DNS configuration from OS<br>@@ -88,8 +124,8 @@ public class ResolverConfigurationImpl<br>             changed = false;<br>         } else {<br>             if (lastRefresh >= 0) {<br>-                long currTime = System.currentTimeMillis();<br>-                if ((currTime - lastRefresh) < TIMEOUT) {<br>+                long currTime = System.nanoTime();<br>+                if ((currTime - lastRefresh) < TIMEOUT_NANOS) {<br>                     return;<br>                 }<br>             }<br>@@ -100,9 +136,9 @@ public class ResolverConfigurationImpl<br>         //<br>         loadDNSconfig0();<br> <br>-        lastRefresh = System.currentTimeMillis();<br>+        lastRefresh = System.nanoTime();<br>         searchlist = stringToList(os_searchlist);<br>-        nameservers = stringToList(os_nameservers);<br>+        nameservers = addressesToList(os_nameservers);<br>         os_searchlist = null;                       // can be GC'ed<br>         os_nameservers = null;<br>     }<br>diff --git a/src/java.base/windows/native/libnet/NetworkInterface_winXP.c b/src/java.base/windows/native/libnet/NetworkInterface_winXP.c<br>index f2368bafcb..297a1561ef 100644<br>--- a/src/java.base/windows/native/libnet/NetworkInterface_winXP.c<br>+++ b/src/java.base/windows/native/libnet/NetworkInterface_winXP.c<br>@@ -73,8 +73,8 @@ const int MAX_TRIES = 3;<br>  * for each adapter on the system. Returned in *adapters.<br>  * Buffer is malloc'd and must be freed (unless error returned)<br>  */<br>-static int getAdapters (JNIEnv *env, IP_ADAPTER_ADDRESSES **adapters) {<br>-    DWORD ret, flags;<br>+int getAdapters (JNIEnv *env, int flags, IP_ADAPTER_ADDRESSES **adapters) {<br>+    DWORD ret;<br>     IP_ADAPTER_ADDRESSES *adapterInfo;<br>     ULONG len;<br>     int try;<br>@@ -87,9 +87,6 @@ static int getAdapters (JNIEnv *env, IP_ADAPTER_ADDRESSES **adapters) {<br>     }<br> <br>     len = BUFF_SIZE;<br>-    flags = GAA_FLAG_SKIP_DNS_SERVER;<br>-    flags |= GAA_FLAG_SKIP_MULTICAST;<br>-    flags |= GAA_FLAG_INCLUDE_PREFIX;<br>     ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterInfo, &len);<br> <br>     for (try = 0; ret == ERROR_BUFFER_OVERFLOW && try < MAX_TRIES; ++try) {<br>@@ -240,7 +237,7 @@ static int ipinflen = 2048;<br>  */<br> int getAllInterfacesAndAddresses (JNIEnv *env, netif **netifPP)<br> {<br>-    DWORD ret;<br>+    DWORD ret, flags;<br>     MIB_IPADDRTABLE *tableP;<br>     IP_ADAPTER_ADDRESSES *ptr, *adapters=NULL;<br>     ULONG len=ipinflen, count=0;<br>@@ -296,7 +293,11 @@ int getAllInterfacesAndAddresses (JNIEnv *env, netif **netifPP)<br>         }<br>     }<br>     free(tableP);<br>-    ret = getAdapters (env, &adapters);<br>+<br>+    flags = GAA_FLAG_SKIP_DNS_SERVER;<br>+    flags |= GAA_FLAG_SKIP_MULTICAST;<br>+    flags |= GAA_FLAG_INCLUDE_PREFIX;<br>+    ret = getAdapters (env, flags, &adapters);<br>     if (ret != ERROR_SUCCESS) {<br>         goto err;<br>     }<br>diff --git a/src/java.base/windows/native/libnet/ResolverConfigurationImpl.c b/src/java.base/windows/native/libnet/ResolverConfigurationImpl.c<br>index 13b28044a5..83100aa9ad 100644<br>--- a/src/java.base/windows/native/libnet/ResolverConfigurationImpl.c<br>+++ b/src/java.base/windows/native/libnet/ResolverConfigurationImpl.c<br>@@ -30,6 +30,7 @@<br> #include <iprtrmib.h><br> #include <time.h><br> #include <assert.h><br>+#include <winsock2.h><br> #include <iphlpapi.h><br> <br> #include "jni_util.h"<br>@@ -48,6 +49,8 @@<br> static jfieldID searchlistID;<br> static jfieldID nameserversID;<br> <br>+extern int getAdapters(JNIEnv *env, int flags, IP_ADAPTER_ADDRESSES **adapters);<br>+<br> /*<br>  * Utility routine to append s2 to s1 with a space delimiter.<br>  *  strappend(s1="abc", "def")  => "abc def"<br>@@ -72,29 +75,19 @@ void strappend(char *s1, char *s2) {<br> }<br> <br> /*<br>- * Windows 2000/XP<br>- *<br>- * Use registry approach based on settings described in Appendix C<br>- * of "Microsoft Windows 2000 TCP/IP Implementation Details".<br>- *<br>- * DNS suffix list is obtained from SearchList registry setting. If<br>- * this is not specified we compile suffix list based on the<br>- * per-connection domain suffix.<br>- *<br>- * DNS name servers and domain settings are on a per-connection<br>- * basic. We therefore enumerate the network adapters to get the<br>- * names of each adapter and then query the corresponding registry<br>- * settings to obtain NameServer/DhcpNameServer and Domain/DhcpDomain.<br>+ * Use DNS server addresses returned by GetAdaptersAddresses for currently <br>+ * active interfaces.<br>  */<br>-static int loadConfig(char *sl, char *ns) {<br>-    IP_ADAPTER_INFO *adapterP;<br>-    ULONG size;<br>-    DWORD ret;<br>+static int loadConfig(JNIEnv *env, char *sl, char *ns) {<br>+    IP_ADAPTER_ADDRESSES *adapters, *adapter;<br>+    IP_ADAPTER_DNS_SERVER_ADDRESS *dnsServer;<br>+    SOCKADDR *address;<br>+    IP_ADAPTER_DNS_SUFFIX *suffix;<br>+    DWORD ret, flags;<br>     DWORD dwLen;<br>     ULONG ulType;<br>     char result[MAX_STR_LEN];<br>     HANDLE hKey;<br>-    int gotSearchList = 0;<br> <br>     /*<br>      * First see if there is a global suffix list specified.<br>@@ -112,122 +105,58 @@ static int loadConfig(char *sl, char *ns) {<br>             assert(ulType == REG_SZ);<br>             if (strlen(result) > 0) {<br>                 strappend(sl, result);<br>-                gotSearchList = 1;<br>             }<br>         }<br>         RegCloseKey(hKey);<br>     }<br> <br>-    /*<br>-     * Ask the IP Helper library to enumerate the adapters<br>-     */<br>-    size = sizeof(IP_ADAPTER_INFO);<br>-    adapterP = (IP_ADAPTER_INFO *)malloc(size);<br>-    if (adapterP == NULL) {<br>-        return STS_ERROR;<br>-    }<br>-    ret = GetAdaptersInfo(adapterP, &size);<br>-    if (ret == ERROR_BUFFER_OVERFLOW) {<br>-        IP_ADAPTER_INFO *newAdapterP = (IP_ADAPTER_INFO *)realloc(adapterP, size);<br>-        if (newAdapterP == NULL) {<br>-            free(adapterP);<br>-            return STS_ERROR;<br>-        }<br>-        adapterP = newAdapterP;<br> <br>-        ret = GetAdaptersInfo(adapterP, &size);<br>+    // We only need DNS server addresses so skip everything else.<br>+    flags = GAA_FLAG_SKIP_UNICAST;<br>+    flags |= GAA_FLAG_SKIP_ANYCAST;<br>+    flags |= GAA_FLAG_SKIP_MULTICAST;<br>+    flags |= GAA_FLAG_SKIP_FRIENDLY_NAME;<br>+    ret = getAdapters(env, flags, &adapters);<br>+    if (ret != ERROR_SUCCESS) {<br>+        return STS_ERROR;<br>     }<br> <br>-    /*<br>-     * Iterate through the list of adapters as registry settings are<br>-     * keyed on the adapter name (GUID).<br>-     */<br>-    if (ret == ERROR_SUCCESS) {<br>-        IP_ADAPTER_INFO *curr = adapterP;<br>-        while (curr != NULL) {<br>-            char key[MAX_STR_LEN];<br>-<br>-            sprintf(key,<br>-                "SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters\\Interfaces\\%s",<br>-                curr->AdapterName);<br>-<br>-            ret = RegOpenKeyEx(HKEY_LOCAL_MACHINE,<br>-                               key,<br>-                               0,<br>-                               KEY_READ,<br>-                               (PHKEY)&hKey);<br>-            if (ret == ERROR_SUCCESS) {<br>-                DWORD enableDhcp = 0;<br>-<br>-                /*<br>-                 * Is DHCP enabled on this interface<br>-                 */<br>-                dwLen = sizeof(enableDhcp);<br>-                ret = RegQueryValueEx(hKey, "EnableDhcp", NULL, &ulType,<br>-                                     (LPBYTE)&enableDhcp, &dwLen);<br>-<br>-                /*<br>-                 * If we don't have the suffix list when get the Domain<br>-                 * or DhcpDomain. If DHCP is enabled then Domain overides<br>-                 * DhcpDomain<br>-                 */<br>-                if (!gotSearchList) {<br>-                    result[0] = '\0';<br>-                    dwLen = sizeof(result);<br>-                    ret = RegQueryValueEx(hKey, "Domain", NULL, &ulType,<br>-                                         (LPBYTE)&result, &dwLen);<br>-                    if (((ret != ERROR_SUCCESS) || (strlen(result) == 0)) &&<br>-                        enableDhcp) {<br>-                        dwLen = sizeof(result);<br>-                        ret = RegQueryValueEx(hKey, "DhcpDomain", NULL, &ulType,<br>-                                              (LPBYTE)&result, &dwLen);<br>-                    }<br>-                    if (ret == ERROR_SUCCESS) {<br>-                        assert(ulType == REG_SZ);<br>-                        strappend(sl, result);<br>-                    }<br>-                }<br>-<br>-                /*<br>-                 * Get DNS servers based on NameServer or DhcpNameServer<br>-                 * registry setting. If NameServer is set then it overrides<br>-                 * DhcpNameServer (even if DHCP is enabled).<br>-                 */<br>-                result[0] = '\0';<br>+    adapter = adapters;<br>+    while (adapter != NULL) {<br>+        // Only load config from enabled adapters.<br>+        if (adapter->OperStatus == IfOperStatusUp) {<br>+            dnsServer = adapter->FirstDnsServerAddress;<br>+            while (dnsServer != NULL) {<br>+                address = dnsServer->Address.lpSockaddr;<br>                 dwLen = sizeof(result);<br>-                ret = RegQueryValueEx(hKey, "NameServer", NULL, &ulType,<br>-                                     (LPBYTE)&result, &dwLen);<br>-                if (((ret != ERROR_SUCCESS) || (strlen(result) == 0)) &&<br>-                    enableDhcp) {<br>-                    dwLen = sizeof(result);<br>-                    ret = RegQueryValueEx(hKey, "DhcpNameServer", NULL, &ulType,<br>-                                          (LPBYTE)&result, &dwLen);<br>-                }<br>-                if (ret == ERROR_SUCCESS) {<br>-                    assert(ulType == REG_SZ);<br>+                ret = WSAAddressToStringA(dnsServer->Address.lpSockaddr, <br>+                          dnsServer->Address.iSockaddrLength, NULL,<br>+                          result, &dwLen);<br>+                if (ret == 0) {<br>                     strappend(ns, result);<br>                 }<br> <br>-                /*<br>-                 * Finished with this registry key<br>-                 */<br>-                RegCloseKey(hKey);<br>+                dnsServer = dnsServer->Next;<br>             }<br> <br>-            /*<br>-             * Onto the next adapeter<br>-             */<br>-            curr = curr->Next;<br>+            // Add connection-specific search domains in addition to global one.<br>+            suffix = adapter->FirstDnsSuffix;<br>+            while (suffix != NULL) {<br>+                ret = WideCharToMultiByte(CP_UTF8, 0, suffix->String, -1, <br>+                    result, sizeof(result), NULL, NULL);<br>+                if (ret != 0) {<br>+                    strappend(sl, result);<br>+                }<br>+<br>+                suffix = suffix->Next;<br>+            }<br>         }<br>-    }<br> <br>-    /*<br>-     * Free the adpater structure<br>-     */<br>-    if (adapterP) {<br>-        free(adapterP);<br>+        adapter = adapter->Next;<br>     }<br> <br>+    free(adapters);<br>+<br>     return STS_SL_FOUND & STS_NS_FOUND;<br> }<br> <br>@@ -260,7 +189,7 @@ Java_sun_net_dns_ResolverConfigurationImpl_loadDNSconfig0(JNIEnv *env, jclass cl<br>     searchlist[0] = '\0';<br>     nameservers[0] = '\0';<br> <br>-    if (loadConfig(searchlist, nameservers) != STS_ERROR) {<br>+    if (loadConfig(env, searchlist, nameservers) != STS_ERROR) {<br> <br>         /*<br>          * Populate static fields in sun.net.DefaultResolverConfiguration<br></div></div>