001: /*
002: * Copyright 2002-2005 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.io.PrintStream;
029: import java.io.OutputStream;
030: import java.util.Hashtable;
031: import java.util.StringTokenizer;
032:
033: import javax.naming.ldap.Control;
034: import javax.naming.NamingException;
035: import javax.naming.CommunicationException;
036: import java.security.AccessController;
037: import java.security.PrivilegedAction;
038:
039: import com.sun.jndi.ldap.pool.PoolCleaner;
040: import com.sun.jndi.ldap.pool.Pool;
041:
042: /**
043: * Contains utilities for managing connection pools of LdapClient.
044: * Contains method for
045: * - checking whether attempted connection creation may be pooled
046: * - creating a pooled connection
047: * - closing idle connections.
048: *
049: * If a timeout period has been configured, then it will automatically
050: * close and remove idle connections (those that have not been
051: * used for the duration of the timeout period).
052: *
053: * @author Rosanna Lee
054: */
055:
056: public final class LdapPoolManager {
057: private static final String DEBUG = "com.sun.jndi.ldap.connect.pool.debug";
058:
059: public static final boolean debug = "all"
060: .equalsIgnoreCase(getProperty(DEBUG, null));
061:
062: public static final boolean trace = debug
063: || "fine".equalsIgnoreCase(getProperty(DEBUG, null));
064:
065: // ---------- System properties for connection pooling
066:
067: // Authentication mechanisms of connections that may be pooled
068: private static final String POOL_AUTH = "com.sun.jndi.ldap.connect.pool.authentication";
069:
070: // Protocol types of connections that may be pooled
071: private static final String POOL_PROTOCOL = "com.sun.jndi.ldap.connect.pool.protocol";
072:
073: // Maximum number of identical connections per pool
074: private static final String MAX_POOL_SIZE = "com.sun.jndi.ldap.connect.pool.maxsize";
075:
076: // Preferred number of identical connections per pool
077: private static final String PREF_POOL_SIZE = "com.sun.jndi.ldap.connect.pool.prefsize";
078:
079: // Initial number of identical connections per pool
080: private static final String INIT_POOL_SIZE = "com.sun.jndi.ldap.connect.pool.initsize";
081:
082: // Milliseconds to wait before closing idle connections
083: private static final String POOL_TIMEOUT = "com.sun.jndi.ldap.connect.pool.timeout";
084:
085: // Properties for DIGEST
086: private static final String SASL_CALLBACK = "java.naming.security.sasl.callback";
087:
088: // --------- Constants
089: private static final int DEFAULT_MAX_POOL_SIZE = 0;
090: private static final int DEFAULT_PREF_POOL_SIZE = 0;
091: private static final int DEFAULT_INIT_POOL_SIZE = 1;
092: private static final int DEFAULT_TIMEOUT = 0; // no timeout
093: private static final String DEFAULT_AUTH_MECHS = "none simple";
094: private static final String DEFAULT_PROTOCOLS = "plain";
095:
096: private static final int NONE = 0; // indices into pools
097: private static final int SIMPLE = 1;
098: private static final int DIGEST = 2;
099:
100: // --------- static fields
101: private static final long idleTimeout;// ms to wait before closing idle conn
102: private static final int maxSize; // max num of identical conns/pool
103: private static final int prefSize; // preferred num of identical conns/pool
104: private static final int initSize; // initial num of identical conns/pool
105:
106: private static boolean supportPlainProtocol = false;
107: private static boolean supportSslProtocol = false;
108:
109: // List of pools used for different auth types
110: private static final Pool[] pools = new Pool[3];
111:
112: static {
113: maxSize = getInteger(MAX_POOL_SIZE, DEFAULT_MAX_POOL_SIZE);
114:
115: prefSize = getInteger(PREF_POOL_SIZE, DEFAULT_PREF_POOL_SIZE);
116:
117: initSize = getInteger(INIT_POOL_SIZE, DEFAULT_INIT_POOL_SIZE);
118:
119: idleTimeout = getLong(POOL_TIMEOUT, DEFAULT_TIMEOUT);
120:
121: // Determine supported authentication mechanisms
122: String str = getProperty(POOL_AUTH, DEFAULT_AUTH_MECHS);
123: StringTokenizer parser = new StringTokenizer(str);
124: int count = parser.countTokens();
125: String mech;
126: int p;
127: for (int i = 0; i < count; i++) {
128: mech = parser.nextToken().toLowerCase();
129: if (mech.equals("anonymous")) {
130: mech = "none";
131: }
132:
133: p = findPool(mech);
134: if (p >= 0 && pools[p] == null) {
135: pools[p] = new Pool(initSize, prefSize, maxSize);
136: }
137: }
138:
139: // Determine supported protocols
140: str = getProperty(POOL_PROTOCOL, DEFAULT_PROTOCOLS);
141: parser = new StringTokenizer(str);
142: count = parser.countTokens();
143: String proto;
144: for (int i = 0; i < count; i++) {
145: proto = parser.nextToken();
146: if ("plain".equalsIgnoreCase(proto)) {
147: supportPlainProtocol = true;
148: } else if ("ssl".equalsIgnoreCase(proto)) {
149: supportSslProtocol = true;
150: } else {
151: // ignore
152: }
153: }
154:
155: if (idleTimeout > 0) {
156: // Create cleaner to expire idle connections
157: new PoolCleaner(idleTimeout, pools).start();
158: }
159:
160: if (debug) {
161: showStats(System.err);
162: }
163: }
164:
165: // Cannot instantiate one of these
166: private LdapPoolManager() {
167: }
168:
169: /**
170: * Find the index of the pool for the specified mechanism. If not
171: * one of "none", "simple", "DIGEST-MD5", or "GSSAPI",
172: * return -1.
173: * @param mech mechanism type
174: */
175: private static int findPool(String mech) {
176: if ("none".equalsIgnoreCase(mech)) {
177: return NONE;
178: } else if ("simple".equalsIgnoreCase(mech)) {
179: return SIMPLE;
180: } else if ("digest-md5".equalsIgnoreCase(mech)) {
181: return DIGEST;
182: }
183: return -1;
184: }
185:
186: /**
187: * Determines whether pooling is allowed given information on how
188: * the connection will be used.
189: *
190: * Non-configurable rejections:
191: * - nonstandard socketFactory has been specified: the pool manager
192: * cannot track input or parameters used by the socket factory and
193: * thus has no way of determining whether two connection requests
194: * are equivalent. Maybe in the future it might add a list of allowed
195: * socket factories to be configured
196: * - trace enabled (except when debugging)
197: * - for Digest authentication, if a callback handler has been specified:
198: * the pool manager cannot track input collected by the handler
199: * and thus has no way of determining whether two connection requests are
200: * equivalent. Maybe in the future it might add a list of allowed
201: * callback handlers.
202: *
203: * Configurable tests:
204: * - Pooling for the requested protocol (plain or ssl) is supported
205: * - Pooling for the requested authentication mechanism is supported
206: *
207: */
208: static boolean isPoolingAllowed(String socketFactory,
209: OutputStream trace, String authMech, String protocol,
210: Hashtable env) throws NamingException {
211:
212: if (trace != null
213: && !debug
214:
215: // Requesting plain protocol but it is not supported
216: || (protocol == null && !supportPlainProtocol)
217:
218: // Requesting ssl protocol but it is not supported
219: || ("ssl".equalsIgnoreCase(protocol) && !supportSslProtocol)) {
220:
221: d("Pooling disallowed due to tracing or unsupported pooling of protocol");
222: return false;
223: }
224: // pooling of custom socket factory is possible only if the
225: // socket factory interface implements java.util.comparator
226: String COMPARATOR = "java.util.Comparator";
227: boolean foundSockCmp = false;
228: if ((socketFactory != null)
229: && !socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
230: try {
231: Class socketFactoryClass = Obj.helper
232: .loadClass(socketFactory);
233: Class[] interfaces = socketFactoryClass.getInterfaces();
234: for (int i = 0; i < interfaces.length; i++) {
235: if (interfaces[i].getCanonicalName().equals(
236: COMPARATOR)) {
237: foundSockCmp = true;
238: }
239: }
240: } catch (Exception e) {
241: CommunicationException ce = new CommunicationException(
242: "Loading the socket factory");
243: ce.setRootCause(e);
244: throw ce;
245: }
246: if (!foundSockCmp) {
247: return false;
248: }
249: }
250: // Cannot use pooling if authMech is not a supported mechs
251: // Cannot use pooling if authMech contains multiple mechs
252: int p = findPool(authMech);
253: if (p < 0 || pools[p] == null) {
254: d("authmech not found: ", authMech);
255:
256: return false;
257: }
258:
259: d("using authmech: ", authMech);
260:
261: switch (p) {
262: case NONE:
263: case SIMPLE:
264: return true;
265:
266: case DIGEST:
267: // Provider won't be able to determine connection identity
268: // if an alternate callback handler is used
269: return (env == null || env.get(SASL_CALLBACK) == null);
270: }
271: return false;
272: }
273:
274: /**
275: * Obtains a pooled connection that either already exists or is
276: * newly created using the parameters supplied. If it is newly
277: * created, it needs to go through the authentication checks to
278: * determine whether an LDAP bind is necessary.
279: *
280: * Caller needs to invoke ldapClient.authenticateCalled() to
281: * determine whether ldapClient.authenticate() needs to be invoked.
282: * Caller has that responsibility because caller needs to deal
283: * with the LDAP bind response, which might involve referrals,
284: * response controls, errors, etc. This method is responsible only
285: * for establishing the connection.
286: *
287: * @return an LdapClient that is pooled.
288: */
289: static LdapClient getLdapClient(String host, int port,
290: String socketFactory, int connTimeout, int readTimeout,
291: OutputStream trace, int version, String authMech,
292: Control[] ctls, String protocol, String user,
293: Object passwd, Hashtable env) throws NamingException {
294:
295: // Create base identity for LdapClient
296: ClientId id = null;
297: Pool pool;
298:
299: int p = findPool(authMech);
300: if (p < 0 || (pool = pools[p]) == null) {
301: throw new IllegalArgumentException(
302: "Attempting to use pooling for an unsupported mechanism: "
303: + authMech);
304: }
305: switch (p) {
306: case NONE:
307: id = new ClientId(version, host, port, protocol, ctls,
308: trace, socketFactory);
309: break;
310:
311: case SIMPLE:
312: // Add identity information used in simple authentication
313: id = new SimpleClientId(version, host, port, protocol,
314: ctls, trace, socketFactory, user, passwd);
315: break;
316:
317: case DIGEST:
318: // Add user/passwd/realm/authzid/qop/strength/maxbuf/mutual/policy*
319: id = new DigestClientId(version, host, port, protocol,
320: ctls, trace, socketFactory, user, passwd, env);
321: break;
322: }
323:
324: return (LdapClient) pool.getPooledConnection(id, connTimeout,
325: new LdapClientFactory(host, port, socketFactory,
326: connTimeout, readTimeout, trace));
327: }
328:
329: public static void showStats(PrintStream out) {
330: out.println("***** start *****");
331: out.println("idle timeout: " + idleTimeout);
332: out.println("maximum pool size: " + maxSize);
333: out.println("preferred pool size: " + prefSize);
334: out.println("initial pool size: " + initSize);
335: out.println("protocol types: "
336: + (supportPlainProtocol ? "plain " : "")
337: + (supportSslProtocol ? "ssl" : ""));
338: out.println("authentication types: "
339: + (pools[NONE] != null ? "none " : "")
340: + (pools[SIMPLE] != null ? "simple " : "")
341: + (pools[DIGEST] != null ? "DIGEST-MD5 " : ""));
342:
343: for (int i = 0; i < pools.length; i++) {
344: if (pools[i] != null) {
345: out.println((i == NONE ? "anonymous pools"
346: : i == SIMPLE ? "simple auth pools"
347: : i == DIGEST ? "digest pools" : "")
348: + ":");
349: pools[i].showStats(out);
350: }
351: }
352: out.println("***** end *****");
353: }
354:
355: /**
356: * Closes idle connections idle since specified time.
357: *
358: * @param threshold Close connections idle since this time, as
359: * specified in milliseconds since "the epoch".
360: * @see java.util.Date
361: */
362: public static void expire(long threshold) {
363: for (int i = 0; i < pools.length; i++) {
364: if (pools[i] != null) {
365: pools[i].expire(threshold);
366: }
367: }
368: }
369:
370: private static void d(String msg) {
371: if (debug) {
372: System.err.println("LdapPoolManager: " + msg);
373: }
374: }
375:
376: private static void d(String msg, String o) {
377: if (debug) {
378: System.err.println("LdapPoolManager: " + msg + o);
379: }
380: }
381:
382: private static final String getProperty(final String propName,
383: final String defVal) {
384: return (String) AccessController
385: .doPrivileged(new PrivilegedAction() {
386: public Object run() {
387: try {
388: return System.getProperty(propName, defVal);
389: } catch (SecurityException e) {
390: return defVal;
391: }
392: }
393: });
394: }
395:
396: private static final int getInteger(final String propName,
397: final int defVal) {
398: Integer val = (Integer) AccessController
399: .doPrivileged(new PrivilegedAction() {
400: public Object run() {
401: try {
402: return Integer.getInteger(propName, defVal);
403: } catch (SecurityException e) {
404: return new Integer(defVal);
405: }
406: }
407: });
408: return val.intValue();
409: }
410:
411: private static final long getLong(final String propName,
412: final long defVal) {
413: Long val = (Long) AccessController
414: .doPrivileged(new PrivilegedAction() {
415: public Object run() {
416: try {
417: return Long.getLong(propName, defVal);
418: } catch (SecurityException e) {
419: return new Long(defVal);
420: }
421: }
422: });
423: return val.longValue();
424: }
425: }
|