1 /*
   2  * Copyright (c) 2002, 2011, 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 com.sun.jndi.ldap;
  27 
  28 import java.util.Arrays;
  29 import java.util.Hashtable;
  30 import java.util.Random;
  31 import java.util.StringTokenizer;
  32 import java.util.List;
  33 
  34 import javax.naming.*;
  35 import javax.naming.directory.*;
  36 import javax.naming.spi.NamingManager;
  37 import javax.naming.ldap.LdapName;
  38 import javax.naming.ldap.Rdn;
  39 
  40 /**
  41  * This class discovers the location of LDAP services by querying DNS.
  42  * See http://www.ietf.org/internet-drafts/draft-ietf-ldapext-locate-07.txt
  43  */
  44 
  45 class ServiceLocator {
  46 
  47     private static final String SRV_RR = "SRV";
  48 
  49     private static final String[] SRV_RR_ATTR = new String[]{SRV_RR};
  50 
  51     private static final Random random = new Random();
  52 
  53     private ServiceLocator() {
  54     }
  55 
  56     /**
  57      * Maps a distinguished name (RFC 2253) to a fully qualified domain name.
  58      * Processes a sequence of RDNs having a DC attribute.
  59      * The special RDN "DC=." denotes the root of the domain tree.
  60      * Multi-valued RDNs, non-DC attributes, binary-valued attributes and the
  61      * RDN "DC=." all reset the domain name and processing continues.
  62      *
  63      * @param dn A string distinguished name (RFC 2253).
  64      * @return A domain name or null if none can be derived.
  65      * @throws InvalidNameException If the distinguished name is invalid.
  66      */
  67     static String mapDnToDomainName(String dn) throws InvalidNameException {
  68         if (dn == null) {
  69             return null;
  70         }
  71         StringBuilder domain = new StringBuilder();
  72         LdapName ldapName = new LdapName(dn);
  73 
  74         // process RDNs left-to-right
  75         //List<Rdn> rdnList = ldapName.getRdns();
  76 
  77         List<Rdn> rdnList = ldapName.getRdns();
  78         for (int i = rdnList.size() - 1; i >= 0; i--) {
  79             //Rdn rdn = rdnList.get(i);
  80             Rdn rdn = rdnList.get(i);
  81 
  82             // single-valued RDN with a DC attribute
  83             if ((rdn.size() == 1) &&
  84                 ("dc".equalsIgnoreCase(rdn.getType()) )) {
  85                 Object attrval = rdn.getValue();
  86                 if (attrval instanceof String) {
  87                     if (attrval.equals(".") ||
  88                         (domain.length() == 1 && domain.charAt(0) == '.')) {
  89                         domain.setLength(0); // reset (when current or previous
  90                                              //        RDN value is "DC=.")
  91                     }
  92                     if (domain.length() > 0) {
  93                         domain.append('.');
  94                     }
  95                     domain.append(attrval);
  96                 } else {
  97                     domain.setLength(0); // reset (when binary-valued attribute)
  98                 }
  99             } else {
 100                 domain.setLength(0); // reset (when multi-valued RDN or non-DC)
 101             }
 102         }
 103         return (domain.length() != 0) ? domain.toString() : null;
 104     }
 105 
 106     /**
 107      * Locates the LDAP service for a given domain.
 108      * Queries DNS for a list of LDAP Service Location Records (SRV) for a
 109      * given domain name.
 110      *
 111      * @param domainName A string domain name.
 112      * @param environment The possibly null environment of the context.
 113      * @return An ordered list of hostports for the LDAP service or null if
 114      *         the service has not been located.
 115      */
 116     static String[] getLdapService(String domainName, Hashtable<?,?> environment) {
 117 
 118         if (domainName == null || domainName.length() == 0) {
 119             return null;
 120         }
 121 
 122         String dnsUrl = "dns:///_ldap._tcp." + domainName;
 123         String[] hostports = null;
 124 
 125         try {
 126             // Create the DNS context using NamingManager rather than using
 127             // the initial context constructor. This avoids having the initial
 128             // context constructor call itself (when processing the URL
 129             // argument in the getAttributes call).
 130             Context ctx = NamingManager.getURLContext("dns", environment);
 131             if (!(ctx instanceof DirContext)) {
 132                 return null; // cannot create a DNS context
 133             }
 134             Attributes attrs =
 135                 ((DirContext)ctx).getAttributes(dnsUrl, SRV_RR_ATTR);
 136             Attribute attr;
 137 
 138             if (attrs != null && ((attr = attrs.get(SRV_RR)) != null)) {
 139                 int numValues = attr.size();
 140                 int numRecords = 0;
 141                 SrvRecord[] srvRecords = new SrvRecord[numValues];
 142 
 143                 // create the service records
 144                 int i = 0;
 145                 int j = 0;
 146                 while (i < numValues) {
 147                     try {
 148                         srvRecords[j] = new SrvRecord((String) attr.get(i));
 149                         j++;
 150                     } catch (Exception e) {
 151                         // ignore bad value
 152                     }
 153                     i++;
 154                 }
 155                 numRecords = j;
 156 
 157                 // trim
 158                 if (numRecords < numValues) {
 159                     SrvRecord[] trimmed = new SrvRecord[numRecords];
 160                     System.arraycopy(srvRecords, 0, trimmed, 0, numRecords);
 161                     srvRecords = trimmed;
 162                 }
 163 
 164                 // Sort the service records in ascending order of their
 165                 // priority value. For records with equal priority, move
 166                 // those with weight 0 to the top of the list.
 167                 if (numRecords > 1) {
 168                     Arrays.sort(srvRecords);
 169                 }
 170 
 171                 // extract the host and port number from each service record
 172                 hostports = extractHostports(srvRecords);
 173             }
 174         } catch (NamingException e) {
 175             // ignore
 176         }
 177         return hostports;
 178     }
 179 
 180     /**
 181      * Extract hosts and port numbers from a list of SRV records.
 182      * An array of hostports is returned or null if none were found.
 183      */
 184     private static String[] extractHostports(SrvRecord[] srvRecords) {
 185         String[] hostports = null;
 186 
 187         int head = 0;
 188         int tail = 0;
 189         int sublistLength = 0;
 190         int k = 0;
 191         for (int i = 0; i < srvRecords.length; i++) {
 192             if (hostports == null) {
 193                 hostports = new String[srvRecords.length];
 194             }
 195             // find the head and tail of the list of records having the same
 196             // priority value.
 197             head = i;
 198             while (i < srvRecords.length - 1 &&
 199                 srvRecords[i].priority == srvRecords[i + 1].priority) {
 200                 i++;
 201             }
 202             tail = i;
 203 
 204             // select hostports from the sublist
 205             sublistLength = (tail - head) + 1;
 206             for (int j = 0; j < sublistLength; j++) {
 207                 hostports[k++] = selectHostport(srvRecords, head, tail);
 208             }
 209         }
 210         return hostports;
 211     }
 212 
 213     /*
 214      * Randomly select a service record in the range [head, tail] and return
 215      * its hostport value. Follows the algorithm in RFC 2782.
 216      */
 217     private static String selectHostport(SrvRecord[] srvRecords, int head,
 218             int tail) {
 219         if (head == tail) {
 220             return srvRecords[head].hostport;
 221         }
 222 
 223         // compute the running sum for records between head and tail
 224         int sum = 0;
 225         for (int i = head; i <= tail; i++) {
 226             if (srvRecords[i] != null) {
 227                 sum += srvRecords[i].weight;
 228                 srvRecords[i].sum = sum;
 229             }
 230         }
 231         String hostport = null;
 232 
 233         // If all records have zero weight, select first available one;
 234         // otherwise, randomly select a record according to its weight
 235         int target = (sum == 0 ? 0 : random.nextInt(sum + 1));
 236         for (int i = head; i <= tail; i++) {
 237             if (srvRecords[i] != null && srvRecords[i].sum >= target) {
 238                 hostport = srvRecords[i].hostport;
 239                 srvRecords[i] = null; // make this record unavailable
 240                 break;
 241             }
 242         }
 243         return hostport;
 244     }
 245 
 246 /**
 247  * This class holds a DNS service (SRV) record.
 248  * See http://www.ietf.org/rfc/rfc2782.txt
 249  */
 250 
 251 static class SrvRecord implements Comparable<SrvRecord> {
 252 
 253     int priority;
 254     int weight;
 255     int sum;
 256     String hostport;
 257 
 258     /**
 259      * Creates a service record object from a string record.
 260      * DNS supplies the string record in the following format:
 261      * <pre>
 262      *     <Priority> " " <Weight> " " <Port> " " <Host>
 263      * </pre>
 264      */
 265     SrvRecord(String srvRecord) throws Exception {
 266         StringTokenizer tokenizer = new StringTokenizer(srvRecord, " ");
 267         String port;
 268 
 269         if (tokenizer.countTokens() == 4) {
 270             priority = Integer.parseInt(tokenizer.nextToken());
 271             weight = Integer.parseInt(tokenizer.nextToken());
 272             port = tokenizer.nextToken();
 273             hostport = tokenizer.nextToken() + ":" + port;
 274         } else {
 275             throw new IllegalArgumentException();
 276         }
 277     }
 278 
 279     /*
 280      * Sort records in ascending order of priority value. For records with
 281      * equal priority move those with weight 0 to the top of the list.
 282      */
 283     public int compareTo(SrvRecord that) {
 284         if (priority > that.priority) {
 285             return 1; // this > that
 286         } else if (priority < that.priority) {
 287             return -1; // this < that
 288         } else if (weight == 0 && that.weight != 0) {
 289             return -1; // this < that
 290         } else if (weight != 0 && that.weight == 0) {
 291             return 1; // this > that
 292         } else {
 293             return 0; // this == that
 294         }
 295     }
 296 }
 297 }