0N/A/*
2362N/A * Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage com.sun.jndi.ldap;
0N/A
0N/Aimport java.util.Arrays;
0N/Aimport java.util.Enumeration;
0N/Aimport java.util.Hashtable;
0N/Aimport java.util.NoSuchElementException;
0N/Aimport java.util.Random;
0N/Aimport java.util.StringTokenizer;
0N/Aimport java.util.List;
0N/A
0N/Aimport javax.naming.*;
0N/Aimport javax.naming.directory.*;
0N/Aimport javax.naming.spi.NamingManager;
0N/Aimport javax.naming.ldap.LdapName;
0N/Aimport javax.naming.ldap.Rdn;
0N/A
0N/Aimport com.sun.jndi.ldap.LdapURL;
0N/A
0N/A/**
0N/A * This class discovers the location of LDAP services by querying DNS.
0N/A * See http://www.ietf.org/internet-drafts/draft-ietf-ldapext-locate-07.txt
0N/A */
0N/A
0N/Aclass ServiceLocator {
0N/A
0N/A private static final String SRV_RR = "SRV";
0N/A
0N/A private static final String[] SRV_RR_ATTR = new String[]{SRV_RR};
0N/A
0N/A private static final Random random = new Random();
0N/A
0N/A private ServiceLocator() {
0N/A }
0N/A
0N/A /**
0N/A * Maps a distinguished name (RFC 2253) to a fully qualified domain name.
0N/A * Processes a sequence of RDNs having a DC attribute.
0N/A * The special RDN "DC=." denotes the root of the domain tree.
0N/A * Multi-valued RDNs, non-DC attributes, binary-valued attributes and the
0N/A * RDN "DC=." all reset the domain name and processing continues.
0N/A *
0N/A * @param dn A string distinguished name (RFC 2253).
0N/A * @return A domain name or null if none can be derived.
0N/A * @throw InvalidNameException If the distinugished name is invalid.
0N/A */
0N/A static String mapDnToDomainName(String dn) throws InvalidNameException {
0N/A if (dn == null) {
0N/A return null;
0N/A }
0N/A StringBuffer domain = new StringBuffer();
0N/A LdapName ldapName = new LdapName(dn);
0N/A
0N/A // process RDNs left-to-right
0N/A //List<Rdn> rdnList = ldapName.getRdns();
0N/A
0N/A List rdnList = ldapName.getRdns();
0N/A for (int i = rdnList.size() - 1; i >= 0; i--) {
0N/A //Rdn rdn = rdnList.get(i);
0N/A Rdn rdn = (Rdn) rdnList.get(i);
0N/A
0N/A // single-valued RDN with a DC attribute
0N/A if ((rdn.size() == 1) &&
0N/A ("dc".equalsIgnoreCase(rdn.getType()) )) {
0N/A Object attrval = rdn.getValue();
0N/A if (attrval instanceof String) {
0N/A if (attrval.equals(".") ||
0N/A (domain.length() == 1 && domain.charAt(0) == '.')) {
0N/A domain.setLength(0); // reset (when current or previous
0N/A // RDN value is "DC=.")
0N/A }
0N/A if (domain.length() > 0) {
0N/A domain.append('.');
0N/A }
0N/A domain.append(attrval);
0N/A } else {
0N/A domain.setLength(0); // reset (when binary-valued attribute)
0N/A }
0N/A } else {
0N/A domain.setLength(0); // reset (when multi-valued RDN or non-DC)
0N/A }
0N/A }
0N/A return (domain.length() != 0) ? domain.toString() : null;
0N/A }
0N/A
0N/A /**
0N/A * Locates the LDAP service for a given domain.
0N/A * Queries DNS for a list of LDAP Service Location Records (SRV) for a
0N/A * given domain name.
0N/A *
0N/A * @param domainName A string domain name.
0N/A * @param environment The possibly null environment of the context.
0N/A * @return An ordered list of hostports for the LDAP service or null if
0N/A * the service has not been located.
0N/A */
0N/A static String[] getLdapService(String domainName, Hashtable environment) {
0N/A
0N/A if (domainName == null || domainName.length() == 0) {
0N/A return null;
0N/A }
0N/A
0N/A String dnsUrl = "dns:///_ldap._tcp." + domainName;
0N/A String[] hostports = null;
0N/A
0N/A try {
0N/A // Create the DNS context using NamingManager rather than using
0N/A // the initial context constructor. This avoids having the initial
0N/A // context constructor call itself (when processing the URL
0N/A // argument in the getAttributes call).
0N/A Context ctx = NamingManager.getURLContext("dns", environment);
0N/A if (!(ctx instanceof DirContext)) {
0N/A return null; // cannot create a DNS context
0N/A }
0N/A Attributes attrs =
0N/A ((DirContext)ctx).getAttributes(dnsUrl, SRV_RR_ATTR);
0N/A Attribute attr;
0N/A
0N/A if (attrs != null && ((attr = attrs.get(SRV_RR)) != null)) {
0N/A int numValues = attr.size();
0N/A int numRecords = 0;
0N/A SrvRecord[] srvRecords = new SrvRecord[numValues];
0N/A
0N/A // create the service records
0N/A int i = 0;
0N/A int j = 0;
0N/A while (i < numValues) {
0N/A try {
0N/A srvRecords[j] = new SrvRecord((String) attr.get(i));
0N/A j++;
0N/A } catch (Exception e) {
0N/A // ignore bad value
0N/A }
0N/A i++;
0N/A }
0N/A numRecords = j;
0N/A
0N/A // trim
0N/A if (numRecords < numValues) {
0N/A SrvRecord[] trimmed = new SrvRecord[numRecords];
0N/A System.arraycopy(srvRecords, 0, trimmed, 0, numRecords);
0N/A srvRecords = trimmed;
0N/A }
0N/A
0N/A // Sort the service records in ascending order of their
0N/A // priority value. For records with equal priority, move
0N/A // those with weight 0 to the top of the list.
0N/A if (numRecords > 1) {
0N/A Arrays.sort(srvRecords);
0N/A }
0N/A
0N/A // extract the host and port number from each service record
0N/A hostports = extractHostports(srvRecords);
0N/A }
0N/A } catch (NamingException e) {
0N/A // ignore
0N/A }
0N/A return hostports;
0N/A }
0N/A
0N/A /**
0N/A * Extract hosts and port numbers from a list of SRV records.
0N/A * An array of hostports is returned or null if none were found.
0N/A */
0N/A private static String[] extractHostports(SrvRecord[] srvRecords) {
0N/A String[] hostports = null;
0N/A
0N/A int head = 0;
0N/A int tail = 0;
0N/A int sublistLength = 0;
0N/A int k = 0;
0N/A for (int i = 0; i < srvRecords.length; i++) {
0N/A if (hostports == null) {
0N/A hostports = new String[srvRecords.length];
0N/A }
0N/A // find the head and tail of the list of records having the same
0N/A // priority value.
0N/A head = i;
0N/A while (i < srvRecords.length - 1 &&
0N/A srvRecords[i].priority == srvRecords[i + 1].priority) {
0N/A i++;
0N/A }
0N/A tail = i;
0N/A
0N/A // select hostports from the sublist
0N/A sublistLength = (tail - head) + 1;
0N/A for (int j = 0; j < sublistLength; j++) {
0N/A hostports[k++] = selectHostport(srvRecords, head, tail);
0N/A }
0N/A }
0N/A return hostports;
0N/A }
0N/A
0N/A /*
0N/A * Randomly select a service record in the range [head, tail] and return
0N/A * its hostport value. Follows the algorithm in RFC 2782.
0N/A */
0N/A private static String selectHostport(SrvRecord[] srvRecords, int head,
0N/A int tail) {
0N/A if (head == tail) {
0N/A return srvRecords[head].hostport;
0N/A }
0N/A
0N/A // compute the running sum for records between head and tail
0N/A int sum = 0;
0N/A for (int i = head; i <= tail; i++) {
0N/A if (srvRecords[i] != null) {
0N/A sum += srvRecords[i].weight;
0N/A srvRecords[i].sum = sum;
0N/A }
0N/A }
0N/A String hostport = null;
0N/A
0N/A // If all records have zero weight, select first available one;
0N/A // otherwise, randomly select a record according to its weight
0N/A int target = (sum == 0 ? 0 : random.nextInt(sum + 1));
0N/A for (int i = head; i <= tail; i++) {
0N/A if (srvRecords[i] != null && srvRecords[i].sum >= target) {
0N/A hostport = srvRecords[i].hostport;
0N/A srvRecords[i] = null; // make this record unavailable
0N/A break;
0N/A }
0N/A }
0N/A return hostport;
0N/A }
0N/A
0N/A/**
0N/A * This class holds a DNS service (SRV) record.
0N/A * See http://www.ietf.org/rfc/rfc2782.txt
0N/A */
0N/A
0N/Astatic class SrvRecord implements Comparable {
0N/A
0N/A int priority;
0N/A int weight;
0N/A int sum;
0N/A String hostport;
0N/A
0N/A /**
0N/A * Creates a service record object from a string record.
0N/A * DNS supplies the string record in the following format:
0N/A * <pre>
0N/A * <Priority> " " <Weight> " " <Port> " " <Host>
0N/A * </pre>
0N/A */
0N/A SrvRecord(String srvRecord) throws Exception {
0N/A StringTokenizer tokenizer = new StringTokenizer(srvRecord, " ");
0N/A String port;
0N/A
0N/A if (tokenizer.countTokens() == 4) {
0N/A priority = Integer.parseInt(tokenizer.nextToken());
0N/A weight = Integer.parseInt(tokenizer.nextToken());
0N/A port = tokenizer.nextToken();
0N/A hostport = tokenizer.nextToken() + ":" + port;
0N/A } else {
0N/A throw new IllegalArgumentException();
0N/A }
0N/A }
0N/A
0N/A /*
0N/A * Sort records in ascending order of priority value. For records with
0N/A * equal priority move those with weight 0 to the top of the list.
0N/A */
0N/A public int compareTo(Object o) {
0N/A SrvRecord that = (SrvRecord) o;
0N/A if (priority > that.priority) {
0N/A return 1; // this > that
0N/A } else if (priority < that.priority) {
0N/A return -1; // this < that
0N/A } else if (weight == 0 && that.weight != 0) {
0N/A return -1; // this < that
0N/A } else if (weight != 0 && that.weight == 0) {
0N/A return 1; // this > that
0N/A } else {
0N/A return 0; // this == that
0N/A }
0N/A }
0N/A}
0N/A}