001: /*
002: * Copyright 2002-2003 Sun Microsystems, Inc. All Rights Reserved.
003: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
004: *
005: * This code is free software; you can redistribute it and/or modify it
006: * under the terms of the GNU General Public License version 2 only, as
007: * published by the Free Software Foundation. Sun designates this
008: * particular file as subject to the "Classpath" exception as provided
009: * by Sun in the LICENSE file that accompanied this code.
010: *
011: * This code is distributed in the hope that it will be useful, but WITHOUT
012: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
013: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
014: * version 2 for more details (a copy is included in the LICENSE file that
015: * accompanied this code).
016: *
017: * You should have received a copy of the GNU General Public License version
018: * 2 along with this work; if not, write to the Free Software Foundation,
019: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
020: *
021: * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
022: * CA 95054 USA or visit www.sun.com if you need additional information or
023: * have any questions.
024: */
025:
026: package com.sun.jndi.ldap;
027:
028: import java.util.Arrays;
029: import java.util.Enumeration;
030: import java.util.Hashtable;
031: import java.util.NoSuchElementException;
032: import java.util.Random;
033: import java.util.StringTokenizer;
034: import java.util.List;
035:
036: import javax.naming.*;
037: import javax.naming.directory.*;
038: import javax.naming.spi.NamingManager;
039: import javax.naming.ldap.LdapName;
040: import javax.naming.ldap.Rdn;
041:
042: import com.sun.jndi.ldap.LdapURL;
043:
044: /**
045: * This class discovers the location of LDAP services by querying DNS.
046: * See http://www.ietf.org/internet-drafts/draft-ietf-ldapext-locate-07.txt
047: */
048:
049: class ServiceLocator {
050:
051: private static final String SRV_RR = "SRV";
052:
053: private static final String[] SRV_RR_ATTR = new String[] { SRV_RR };
054:
055: private static final Random random = new Random();
056:
057: private ServiceLocator() {
058: }
059:
060: /**
061: * Maps a distinguished name (RFC 2253) to a fully qualified domain name.
062: * Processes a sequence of RDNs having a DC attribute.
063: * The special RDN "DC=." denotes the root of the domain tree.
064: * Multi-valued RDNs, non-DC attributes, binary-valued attributes and the
065: * RDN "DC=." all reset the domain name and processing continues.
066: *
067: * @param dn A string distinguished name (RFC 2253).
068: * @return A domain name or null if none can be derived.
069: * @throw InvalidNameException If the distinugished name is invalid.
070: */
071: static String mapDnToDomainName(String dn)
072: throws InvalidNameException {
073: if (dn == null) {
074: return null;
075: }
076: StringBuffer domain = new StringBuffer();
077: LdapName ldapName = new LdapName(dn);
078:
079: // process RDNs left-to-right
080: //List<Rdn> rdnList = ldapName.getRdns();
081:
082: List rdnList = ldapName.getRdns();
083: for (int i = rdnList.size() - 1; i >= 0; i--) {
084: //Rdn rdn = rdnList.get(i);
085: Rdn rdn = (Rdn) rdnList.get(i);
086:
087: // single-valued RDN with a DC attribute
088: if ((rdn.size() == 1)
089: && ("dc".equalsIgnoreCase(rdn.getType()))) {
090: Object attrval = rdn.getValue();
091: if (attrval instanceof String) {
092: if (attrval.equals(".")
093: || (domain.length() == 1 && domain
094: .charAt(0) == '.')) {
095: domain.setLength(0); // reset (when current or previous
096: // RDN value is "DC=.")
097: }
098: if (domain.length() > 0) {
099: domain.append('.');
100: }
101: domain.append(attrval);
102: } else {
103: domain.setLength(0); // reset (when binary-valued attribute)
104: }
105: } else {
106: domain.setLength(0); // reset (when multi-valued RDN or non-DC)
107: }
108: }
109: return (domain.length() != 0) ? domain.toString() : null;
110: }
111:
112: /**
113: * Locates the LDAP service for a given domain.
114: * Queries DNS for a list of LDAP Service Location Records (SRV) for a
115: * given domain name.
116: *
117: * @param domainName A string domain name.
118: * @param environment The possibly null environment of the context.
119: * @return An ordered list of hostports for the LDAP service or null if
120: * the service has not been located.
121: */
122: static String[] getLdapService(String domainName,
123: Hashtable environment) {
124:
125: if (domainName == null || domainName.length() == 0) {
126: return null;
127: }
128:
129: String dnsUrl = "dns:///_ldap._tcp." + domainName;
130: String[] hostports = null;
131:
132: try {
133: // Create the DNS context using NamingManager rather than using
134: // the initial context constructor. This avoids having the initial
135: // context constructor call itself (when processing the URL
136: // argument in the getAttributes call).
137: Context ctx = NamingManager.getURLContext("dns",
138: environment);
139: if (!(ctx instanceof DirContext)) {
140: return null; // cannot create a DNS context
141: }
142: Attributes attrs = ((DirContext) ctx).getAttributes(dnsUrl,
143: SRV_RR_ATTR);
144: Attribute attr;
145:
146: if (attrs != null && ((attr = attrs.get(SRV_RR)) != null)) {
147: int numValues = attr.size();
148: int numRecords = 0;
149: SrvRecord[] srvRecords = new SrvRecord[numValues];
150:
151: // create the service records
152: int i = 0;
153: int j = 0;
154: while (i < numValues) {
155: try {
156: srvRecords[j] = new SrvRecord((String) attr
157: .get(i));
158: j++;
159: } catch (Exception e) {
160: // ignore bad value
161: }
162: i++;
163: }
164: numRecords = j;
165:
166: // trim
167: if (numRecords < numValues) {
168: SrvRecord[] trimmed = new SrvRecord[numRecords];
169: System.arraycopy(srvRecords, 0, trimmed, 0,
170: numRecords);
171: srvRecords = trimmed;
172: }
173:
174: // Sort the service records in ascending order of their
175: // priority value. For records with equal priority, move
176: // those with weight 0 to the top of the list.
177: if (numRecords > 1) {
178: Arrays.sort(srvRecords);
179: }
180:
181: // extract the host and port number from each service record
182: hostports = extractHostports(srvRecords);
183: }
184: } catch (NamingException e) {
185: // ignore
186: }
187: return hostports;
188: }
189:
190: /**
191: * Extract hosts and port numbers from a list of SRV records.
192: * An array of hostports is returned or null if none were found.
193: */
194: private static String[] extractHostports(SrvRecord[] srvRecords) {
195: String[] hostports = null;
196:
197: int head = 0;
198: int tail = 0;
199: int sublistLength = 0;
200: int k = 0;
201: for (int i = 0; i < srvRecords.length; i++) {
202: if (hostports == null) {
203: hostports = new String[srvRecords.length];
204: }
205: // find the head and tail of the list of records having the same
206: // priority value.
207: head = i;
208: while (i < srvRecords.length - 1
209: && srvRecords[i].priority == srvRecords[i + 1].priority) {
210: i++;
211: }
212: tail = i;
213:
214: // select hostports from the sublist
215: sublistLength = (tail - head) + 1;
216: for (int j = 0; j < sublistLength; j++) {
217: hostports[k++] = selectHostport(srvRecords, head, tail);
218: }
219: }
220: return hostports;
221: }
222:
223: /*
224: * Randomly select a service record in the range [head, tail] and return
225: * its hostport value. Follows the algorithm in RFC 2782.
226: */
227: private static String selectHostport(SrvRecord[] srvRecords,
228: int head, int tail) {
229: if (head == tail) {
230: return srvRecords[head].hostport;
231: }
232:
233: // compute the running sum for records between head and tail
234: int sum = 0;
235: for (int i = head; i <= tail; i++) {
236: if (srvRecords[i] != null) {
237: sum += srvRecords[i].weight;
238: srvRecords[i].sum = sum;
239: }
240: }
241: String hostport = null;
242:
243: // If all records have zero weight, select first available one;
244: // otherwise, randomly select a record according to its weight
245: int target = (sum == 0 ? 0 : random.nextInt(sum + 1));
246: for (int i = head; i <= tail; i++) {
247: if (srvRecords[i] != null && srvRecords[i].sum >= target) {
248: hostport = srvRecords[i].hostport;
249: srvRecords[i] = null; // make this record unavailable
250: break;
251: }
252: }
253: return hostport;
254: }
255:
256: /**
257: * This class holds a DNS service (SRV) record.
258: * See http://www.ietf.org/rfc/rfc2782.txt
259: */
260:
261: static class SrvRecord implements Comparable {
262:
263: int priority;
264: int weight;
265: int sum;
266: String hostport;
267:
268: /**
269: * Creates a service record object from a string record.
270: * DNS supplies the string record in the following format:
271: * <pre>
272: * <Priority> " " <Weight> " " <Port> " " <Host>
273: * </pre>
274: */
275: SrvRecord(String srvRecord) throws Exception {
276: StringTokenizer tokenizer = new StringTokenizer(srvRecord,
277: " ");
278: String port;
279:
280: if (tokenizer.countTokens() == 4) {
281: priority = Integer.parseInt(tokenizer.nextToken());
282: weight = Integer.parseInt(tokenizer.nextToken());
283: port = tokenizer.nextToken();
284: hostport = tokenizer.nextToken() + ":" + port;
285: } else {
286: throw new IllegalArgumentException();
287: }
288: }
289:
290: /*
291: * Sort records in ascending order of priority value. For records with
292: * equal priority move those with weight 0 to the top of the list.
293: */
294: public int compareTo(Object o) {
295: SrvRecord that = (SrvRecord) o;
296: if (priority > that.priority) {
297: return 1; // this > that
298: } else if (priority < that.priority) {
299: return -1; // this < that
300: } else if (weight == 0 && that.weight != 0) {
301: return -1; // this < that
302: } else if (weight != 0 && that.weight == 0) {
303: return 1; // this > that
304: } else {
305: return 0; // this == that
306: }
307: }
308: }
309: }
|