src/jdk.dns.client/unix/classes/jdk/dns/conf/DnsResolverConfiguration.java
branchaefimov-dns-client-branch
changeset 58870 35c438a6d45c
child 59101 258033faefc9
equal deleted inserted replaced
58869:cc66ac8c7646 58870:35c438a6d45c
       
     1 /*
       
     2  * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package jdk.dns.conf;
       
    27 
       
    28 import jdk.dns.client.internal.util.ReloadTracker;
       
    29 
       
    30 import java.io.BufferedReader;
       
    31 import java.io.FileReader;
       
    32 import java.io.IOException;
       
    33 import java.nio.file.Paths;
       
    34 import java.security.AccessController;
       
    35 import java.security.PrivilegedAction;
       
    36 import java.security.PrivilegedExceptionAction;
       
    37 import java.util.Collections;
       
    38 import java.util.LinkedList;
       
    39 import java.util.List;
       
    40 import java.util.StringTokenizer;
       
    41 import java.util.concurrent.locks.ReadWriteLock;
       
    42 import java.util.concurrent.locks.ReentrantReadWriteLock;
       
    43 
       
    44 /*
       
    45  * An implementation of DnsResolverConfiguration for Solaris
       
    46  * and Linux.
       
    47  */
       
    48 
       
    49 public class DnsResolverConfiguration {
       
    50     // Lock held whilst loading configuration or checking
       
    51     private static final ReadWriteLock LOCK = new ReentrantReadWriteLock();
       
    52 
       
    53     //
       
    54     private static String RESOLV_CONF_LOCATION = java.security.AccessController.doPrivileged(
       
    55             (PrivilegedAction<String>) () -> System.getProperty("jdk.dns.client.resolv.conf", "/etc/resolv.conf"));
       
    56     private static final ReloadTracker RESOLVE_CONF_TRACKER;
       
    57 
       
    58 
       
    59     // Cache timeout (300 seconds) - should be converted into property
       
    60     // or configured as preference in the future.
       
    61     private static final int TIMEOUT = 300_000;
       
    62 
       
    63     // Parse /etc/resolv.conf to get the values for a particular
       
    64     // keyword.
       
    65     //
       
    66     private List<String> resolvconf(String keyword,
       
    67                                           int maxperkeyword,
       
    68                                           int maxkeywords) {
       
    69         LinkedList<String> ll = new LinkedList<>();
       
    70 
       
    71         try {
       
    72             BufferedReader in =
       
    73                     new BufferedReader(new FileReader(RESOLV_CONF_LOCATION));
       
    74             String line;
       
    75             while ((line = in.readLine()) != null) {
       
    76                 int maxvalues = maxperkeyword;
       
    77                 if (line.isEmpty())
       
    78                     continue;
       
    79                 if (line.charAt(0) == '#' || line.charAt(0) == ';')
       
    80                     continue;
       
    81                 if (!line.startsWith(keyword))
       
    82                     continue;
       
    83                 String value = line.substring(keyword.length());
       
    84                 if (value.isEmpty())
       
    85                     continue;
       
    86                 if (value.charAt(0) != ' ' && value.charAt(0) != '\t')
       
    87                     continue;
       
    88                 StringTokenizer st = new StringTokenizer(value, " \t");
       
    89                 while (st.hasMoreTokens()) {
       
    90                     String val = st.nextToken();
       
    91                     if (val.charAt(0) == '#' || val.charAt(0) == ';') {
       
    92                         break;
       
    93                     }
       
    94                     if ("nameserver".equals(keyword)) {
       
    95                         if (val.indexOf(':') >= 0 &&
       
    96                                 val.indexOf('.') < 0 && // skip for IPv4 literals with port
       
    97                                 val.indexOf('[') < 0 &&
       
    98                                 val.indexOf(']') < 0) {
       
    99                             // IPv6 literal, in non-BSD-style.
       
   100                             val = "[" + val + "]";
       
   101                         }
       
   102                     }
       
   103                     ll.add(val);
       
   104                     if (--maxvalues == 0) {
       
   105                         break;
       
   106                     }
       
   107                 }
       
   108                 if (--maxkeywords == 0) {
       
   109                     break;
       
   110                 }
       
   111             }
       
   112             in.close();
       
   113         } catch (IOException ioe) {
       
   114             // problem reading value
       
   115         }
       
   116 
       
   117         return Collections.unmodifiableList(ll);
       
   118     }
       
   119 
       
   120     private volatile List<String> searchlist = Collections.emptyList();
       
   121     private volatile List<String> nameservers = Collections.emptyList();
       
   122     private volatile String domain = "";
       
   123 
       
   124 
       
   125     // Load DNS configuration from OS
       
   126     private void loadConfig() {
       
   127         LOCK.readLock().lock();
       
   128         try {
       
   129             var rs = RESOLVE_CONF_TRACKER.getReloadStatus();
       
   130             if (!rs.isReloadNeeded() || !rs.isFileExists()) {
       
   131                 return;
       
   132             }
       
   133         } finally {
       
   134             LOCK.readLock().unlock();
       
   135         }
       
   136 
       
   137         LOCK.writeLock().lock();
       
   138         try {
       
   139             var rs = RESOLVE_CONF_TRACKER.getReloadStatus();
       
   140             // Check if reload is needed again
       
   141             if (rs.isReloadNeeded()) {
       
   142                 if (rs.isFileExists()) {
       
   143                     // get the name servers from /etc/resolv.conf
       
   144                     nameservers =
       
   145                             java.security.AccessController.doPrivileged(
       
   146                                     (PrivilegedAction<List<String>>) () -> {
       
   147                                         // typically MAXNS is 3 but we've picked 5 here
       
   148                                         // to allow for additional servers if required.
       
   149                                         return resolvconf("nameserver", 1, 5);
       
   150                                     });
       
   151 
       
   152                     // get the search list (or domain)
       
   153                     searchlist = getSearchList();
       
   154 
       
   155                     // update the timestamp on the configuration
       
   156                     RESOLVE_CONF_TRACKER.updateTimestamps(rs);
       
   157                 } else {
       
   158                     nameservers = Collections.emptyList();
       
   159                     searchlist = Collections.emptyList();
       
   160                 }
       
   161             }
       
   162         } finally {
       
   163             LOCK.writeLock().unlock();
       
   164         }
       
   165     }
       
   166 
       
   167     // obtain search list or local domain
       
   168     private List<String> getSearchList() {
       
   169 
       
   170         List<String> sl;
       
   171 
       
   172         // first try the search keyword in /etc/resolv.conf
       
   173 
       
   174         /* run */
       
   175         sl = java.security.AccessController.doPrivileged(
       
   176                 (PrivilegedAction<List<String>>) () -> {
       
   177                     List<String> ll;
       
   178 
       
   179                     // first try search keyword (max 6 domains)
       
   180                     ll = resolvconf("search", 6, 1);
       
   181                     if (ll.size() > 0) {
       
   182                         domain = ll.get(0);
       
   183                         return ll;
       
   184                     }
       
   185 
       
   186                     return null;
       
   187 
       
   188                 });
       
   189         if (sl != null) {
       
   190             return sl;
       
   191         }
       
   192 
       
   193         // No search keyword so use local domain
       
   194 
       
   195 
       
   196         // LOCALDOMAIN has absolute priority on Solaris
       
   197 
       
   198         String localDomain = localDomain0();
       
   199         if (localDomain != null && !localDomain.isEmpty()) {
       
   200             sl = new LinkedList<>();
       
   201             sl.add(localDomain);
       
   202             return Collections.unmodifiableList(sl);
       
   203         }
       
   204 
       
   205         // try domain keyword in /etc/resolv.conf
       
   206 
       
   207         /* run */
       
   208         sl = java.security.AccessController.doPrivileged(
       
   209                 (PrivilegedAction<List<String>>) () -> {
       
   210                     List<String> ll;
       
   211 
       
   212                     ll = resolvconf("domain", 1, 1);
       
   213                     if (ll.size() > 0) {
       
   214                         domain = ll.get(0);
       
   215                         return ll;
       
   216                     }
       
   217                     return null;
       
   218 
       
   219                 });
       
   220         if (sl != null) {
       
   221             // sl is already UnmodifiableList
       
   222             return sl;
       
   223         }
       
   224 
       
   225         // no local domain so try fallback (RPC) domain or
       
   226         // hostName
       
   227 
       
   228         sl = new LinkedList<>();
       
   229         String domain = fallbackDomain0();
       
   230         if (domain != null && !domain.isEmpty()) {
       
   231             sl.add(domain);
       
   232         }
       
   233 
       
   234         return Collections.unmodifiableList(sl);
       
   235     }
       
   236 
       
   237 
       
   238     // ----
       
   239 
       
   240     public DnsResolverConfiguration() {
       
   241     }
       
   242 
       
   243     @SuppressWarnings("unchecked")
       
   244     public List<String> searchlist() {
       
   245         loadConfig();
       
   246         // List is unmodifiable
       
   247         return searchlist;
       
   248     }
       
   249 
       
   250     @SuppressWarnings("unchecked")
       
   251     public List<String> nameservers() {
       
   252         loadConfig();
       
   253         // List is unmodifiable
       
   254         return nameservers;
       
   255     }
       
   256 
       
   257     public String domain() {
       
   258         loadConfig();
       
   259         return domain;
       
   260     }
       
   261 
       
   262     // --- Native methods --
       
   263 
       
   264     static native String localDomain0();
       
   265 
       
   266     static native String fallbackDomain0();
       
   267 
       
   268     static {
       
   269         var pa = (PrivilegedAction<Void>) () -> {System.loadLibrary("resolver"); return null;};
       
   270         if (System.getSecurityManager() == null) {
       
   271             pa.run();
       
   272         } else {
       
   273             AccessController.doPrivileged(pa);
       
   274         }
       
   275         var pea = (PrivilegedExceptionAction<ReloadTracker>) () ->
       
   276                 ReloadTracker.newInstance(Paths.get(RESOLV_CONF_LOCATION), TIMEOUT);
       
   277         // TODO: Revisit
       
   278         try {
       
   279             RESOLVE_CONF_TRACKER = System.getSecurityManager() == null ? pea.run()
       
   280                     : AccessController.doPrivileged(pea);
       
   281         } catch (Exception e) {
       
   282             throw new RuntimeException("Can't instantiate resolver configuration file tracker", e);
       
   283         }
       
   284     }
       
   285 
       
   286 }