0N/A/*
2120N/A * Copyright (c) 2002, 2005, 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
0N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
0N/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,
1472N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1472N/A *
1472N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
0N/A * or visit www.oracle.com if you need additional information or have any
0N/A * questions.
0N/A */
1879N/A
1879N/Apackage com.sun.jndi.ldap;
1879N/A
1879N/Aimport java.io.PrintStream;
1879N/Aimport java.io.OutputStream;
1879N/Aimport java.util.Hashtable;
1879N/Aimport java.util.StringTokenizer;
1879N/A
1879N/Aimport javax.naming.ldap.Control;
0N/Aimport javax.naming.NamingException;
0N/Aimport javax.naming.CommunicationException;
0N/Aimport java.security.AccessController;
0N/Aimport java.security.PrivilegedAction;
0N/A
0N/Aimport com.sun.jndi.ldap.pool.PoolCleaner;
0N/Aimport com.sun.jndi.ldap.pool.Pool;
0N/A
1172N/A/**
0N/A * Contains utilities for managing connection pools of LdapClient.
0N/A * Contains method for
0N/A * - checking whether attempted connection creation may be pooled
0N/A * - creating a pooled connection
0N/A * - closing idle connections.
0N/A *
0N/A * If a timeout period has been configured, then it will automatically
0N/A * close and remove idle connections (those that have not been
0N/A * used for the duration of the timeout period).
0N/A *
0N/A * @author Rosanna Lee
0N/A */
0N/A
0N/Apublic final class LdapPoolManager {
0N/A private static final String DEBUG =
0N/A "com.sun.jndi.ldap.connect.pool.debug";
0N/A
2312N/A public static final boolean debug =
2312N/A "all".equalsIgnoreCase(getProperty(DEBUG, null));
2312N/A
2312N/A public static final boolean trace = debug ||
2312N/A "fine".equalsIgnoreCase(getProperty(DEBUG, null));
2312N/A
0N/A // ---------- System properties for connection pooling
0N/A
0N/A // Authentication mechanisms of connections that may be pooled
0N/A private static final String POOL_AUTH =
0N/A "com.sun.jndi.ldap.connect.pool.authentication";
0N/A
0N/A // Protocol types of connections that may be pooled
2312N/A private static final String POOL_PROTOCOL =
2312N/A "com.sun.jndi.ldap.connect.pool.protocol";
0N/A
2312N/A // Maximum number of identical connections per pool
2312N/A private static final String MAX_POOL_SIZE =
2312N/A "com.sun.jndi.ldap.connect.pool.maxsize";
2312N/A
0N/A // Preferred number of identical connections per pool
0N/A private static final String PREF_POOL_SIZE =
0N/A "com.sun.jndi.ldap.connect.pool.prefsize";
0N/A
0N/A // Initial number of identical connections per pool
0N/A private static final String INIT_POOL_SIZE =
0N/A "com.sun.jndi.ldap.connect.pool.initsize";
0N/A
0N/A // Milliseconds to wait before closing idle connections
0N/A private static final String POOL_TIMEOUT =
0N/A "com.sun.jndi.ldap.connect.pool.timeout";
0N/A
0N/A // Properties for DIGEST
0N/A private static final String SASL_CALLBACK =
0N/A "java.naming.security.sasl.callback";
0N/A
0N/A // --------- Constants
0N/A private static final int DEFAULT_MAX_POOL_SIZE = 0;
0N/A private static final int DEFAULT_PREF_POOL_SIZE = 0;
0N/A private static final int DEFAULT_INIT_POOL_SIZE = 1;
0N/A private static final int DEFAULT_TIMEOUT = 0; // no timeout
2230N/A private static final String DEFAULT_AUTH_MECHS = "none simple";
0N/A private static final String DEFAULT_PROTOCOLS = "plain";
0N/A
0N/A private static final int NONE = 0; // indices into pools
0N/A private static final int SIMPLE = 1;
0N/A private static final int DIGEST = 2;
0N/A
0N/A // --------- static fields
0N/A private static final long idleTimeout;// ms to wait before closing idle conn
2230N/A private static final int maxSize; // max num of identical conns/pool
2230N/A private static final int prefSize; // preferred num of identical conns/pool
0N/A private static final int initSize; // initial num of identical conns/pool
0N/A
0N/A private static boolean supportPlainProtocol = false;
0N/A private static boolean supportSslProtocol = false;
0N/A
0N/A // List of pools used for different auth types
0N/A private static final Pool[] pools = new Pool[3];
0N/A
2230N/A static {
0N/A maxSize = getInteger(MAX_POOL_SIZE, DEFAULT_MAX_POOL_SIZE);
0N/A
0N/A prefSize = getInteger(PREF_POOL_SIZE, DEFAULT_PREF_POOL_SIZE);
0N/A
0N/A initSize = getInteger(INIT_POOL_SIZE, DEFAULT_INIT_POOL_SIZE);
0N/A
0N/A idleTimeout = getLong(POOL_TIMEOUT, DEFAULT_TIMEOUT);
0N/A
0N/A // Determine supported authentication mechanisms
0N/A String str = getProperty(POOL_AUTH, DEFAULT_AUTH_MECHS);
0N/A StringTokenizer parser = new StringTokenizer(str);
0N/A int count = parser.countTokens();
0N/A String mech;
0N/A int p;
0N/A for (int i = 0; i < count; i++) {
0N/A mech = parser.nextToken().toLowerCase();
0N/A if (mech.equals("anonymous")) {
0N/A mech = "none";
0N/A }
0N/A
0N/A p = findPool(mech);
0N/A if (p >= 0 && pools[p] == null) {
0N/A pools[p] = new Pool(initSize, prefSize, maxSize);
0N/A }
2312N/A }
2312N/A
0N/A // Determine supported protocols
0N/A str= getProperty(POOL_PROTOCOL, DEFAULT_PROTOCOLS);
0N/A parser = new StringTokenizer(str);
0N/A count = parser.countTokens();
0N/A String proto;
0N/A for (int i = 0; i < count; i++) {
0N/A proto = parser.nextToken();
0N/A if ("plain".equalsIgnoreCase(proto)) {
0N/A supportPlainProtocol = true;
0N/A } else if ("ssl".equalsIgnoreCase(proto)) {
0N/A supportSslProtocol = true;
0N/A } else {
0N/A // ignore
2312N/A }
0N/A }
0N/A
0N/A if (idleTimeout > 0) {
0N/A // Create cleaner to expire idle connections
0N/A new PoolCleaner(idleTimeout, pools).start();
0N/A }
0N/A
0N/A if (debug) {
0N/A showStats(System.err);
0N/A }
0N/A }
0N/A
0N/A // Cannot instantiate one of these
0N/A private LdapPoolManager() {
0N/A }
0N/A
0N/A /**
0N/A * Find the index of the pool for the specified mechanism. If not
0N/A * one of "none", "simple", "DIGEST-MD5", or "GSSAPI",
0N/A * return -1.
0N/A * @param mech mechanism type
0N/A */
0N/A private static int findPool(String mech) {
0N/A if ("none".equalsIgnoreCase(mech)) {
0N/A return NONE;
0N/A } else if ("simple".equalsIgnoreCase(mech)) {
0N/A return SIMPLE;
0N/A } else if ("digest-md5".equalsIgnoreCase(mech)) {
0N/A return DIGEST;
0N/A }
0N/A return -1;
0N/A }
0N/A
0N/A /**
0N/A * Determines whether pooling is allowed given information on how
0N/A * the connection will be used.
0N/A *
0N/A * Non-configurable rejections:
0N/A * - nonstandard socketFactory has been specified: the pool manager
0N/A * cannot track input or parameters used by the socket factory and
0N/A * thus has no way of determining whether two connection requests
2312N/A * are equivalent. Maybe in the future it might add a list of allowed
2312N/A * socket factories to be configured
2312N/A * - trace enabled (except when debugging)
2312N/A * - for Digest authentication, if a callback handler has been specified:
2312N/A * the pool manager cannot track input collected by the handler
2312N/A * and thus has no way of determining whether two connection requests are
0N/A * equivalent. Maybe in the future it might add a list of allowed
367N/A * callback handlers.
367N/A *
0N/A * Configurable tests:
0N/A * - Pooling for the requested protocol (plain or ssl) is supported
0N/A * - Pooling for the requested authentication mechanism is supported
0N/A *
2312N/A */
2312N/A static boolean isPoolingAllowed(String socketFactory, OutputStream trace,
2312N/A String authMech, String protocol, Hashtable env)
2312N/A throws NamingException {
0N/A
2312N/A if (trace != null && !debug
2312N/A
2312N/A // Requesting plain protocol but it is not supported
2312N/A || (protocol == null && !supportPlainProtocol)
2312N/A
2312N/A // Requesting ssl protocol but it is not supported
2312N/A || ("ssl".equalsIgnoreCase(protocol) && !supportSslProtocol)) {
2312N/A
0N/A d("Pooling disallowed due to tracing or unsupported pooling of protocol");
0N/A return false;
0N/A }
0N/A // pooling of custom socket factory is possible only if the
0N/A // socket factory interface implements java.util.comparator
0N/A String COMPARATOR = "java.util.Comparator";
0N/A boolean foundSockCmp = false;
0N/A if ((socketFactory != null) &&
0N/A !socketFactory.equals(LdapCtx.DEFAULT_SSL_FACTORY)) {
0N/A try {
0N/A Class socketFactoryClass = Obj.helper.loadClass(socketFactory);
0N/A Class[] interfaces = socketFactoryClass.getInterfaces();
0N/A for (int i = 0; i < interfaces.length; i++) {
0N/A if (interfaces[i].getCanonicalName().equals(COMPARATOR)) {
0N/A foundSockCmp = true;
0N/A }
0N/A }
0N/A } catch (Exception e) {
0N/A CommunicationException ce =
0N/A new CommunicationException("Loading the socket factory");
0N/A ce.setRootCause(e);
0N/A throw ce;
0N/A }
0N/A if (!foundSockCmp) {
0N/A return false;
0N/A }
0N/A }
0N/A // Cannot use pooling if authMech is not a supported mechs
0N/A // Cannot use pooling if authMech contains multiple mechs
0N/A int p = findPool(authMech);
0N/A if (p < 0 || pools[p] == null) {
0N/A d("authmech not found: ", authMech);
0N/A
0N/A return false;
0N/A }
0N/A
0N/A d("using authmech: ", authMech);
0N/A
0N/A switch (p) {
0N/A case NONE:
0N/A case SIMPLE:
0N/A return true;
0N/A
0N/A case DIGEST:
0N/A // Provider won't be able to determine connection identity
0N/A // if an alternate callback handler is used
0N/A return (env == null || env.get(SASL_CALLBACK) == null);
0N/A }
0N/A return false;
0N/A }
0N/A
0N/A /**
0N/A * Obtains a pooled connection that either already exists or is
0N/A * newly created using the parameters supplied. If it is newly
0N/A * created, it needs to go through the authentication checks to
0N/A * determine whether an LDAP bind is necessary.
0N/A *
0N/A * Caller needs to invoke ldapClient.authenticateCalled() to
0N/A * determine whether ldapClient.authenticate() needs to be invoked.
0N/A * Caller has that responsibility because caller needs to deal
0N/A * with the LDAP bind response, which might involve referrals,
0N/A * response controls, errors, etc. This method is responsible only
0N/A * for establishing the connection.
0N/A *
0N/A * @return an LdapClient that is pooled.
0N/A */
0N/A static LdapClient getLdapClient(String host, int port, String socketFactory,
0N/A int connTimeout, int readTimeout, OutputStream trace, int version,
0N/A String authMech, Control[] ctls, String protocol, String user,
0N/A Object passwd, Hashtable env) throws NamingException {
0N/A
0N/A // Create base identity for LdapClient
0N/A ClientId id = null;
0N/A Pool pool;
0N/A
0N/A int p = findPool(authMech);
0N/A if (p < 0 || (pool=pools[p]) == null) {
0N/A throw new IllegalArgumentException(
0N/A "Attempting to use pooling for an unsupported mechanism: " +
0N/A authMech);
0N/A }
0N/A switch (p) {
0N/A case NONE:
0N/A id = new ClientId(version, host, port, protocol,
0N/A ctls, trace, socketFactory);
0N/A break;
0N/A
0N/A case SIMPLE:
0N/A // Add identity information used in simple authentication
39N/A id = new SimpleClientId(version, host, port, protocol,
39N/A ctls, trace, socketFactory, user, passwd);
0N/A break;
0N/A
0N/A case DIGEST:
0N/A // Add user/passwd/realm/authzid/qop/strength/maxbuf/mutual/policy*
0N/A id = new DigestClientId(version, host, port, protocol,
0N/A ctls, trace, socketFactory, user, passwd, env);
39N/A break;
0N/A }
0N/A
0N/A return (LdapClient) pool.getPooledConnection(id, connTimeout,
0N/A new LdapClientFactory(host, port, socketFactory, connTimeout,
0N/A readTimeout, trace));
0N/A }
0N/A
0N/A public static void showStats(PrintStream out) {
0N/A out.println("***** start *****");
0N/A out.println("idle timeout: " + idleTimeout);
0N/A out.println("maximum pool size: " + maxSize);
0N/A out.println("preferred pool size: " + prefSize);
0N/A out.println("initial pool size: " + initSize);
0N/A out.println("protocol types: " + (supportPlainProtocol ? "plain " : "") +
0N/A (supportSslProtocol ? "ssl" : ""));
0N/A out.println("authentication types: " +
0N/A (pools[NONE] != null ? "none " : "") +
0N/A (pools[SIMPLE] != null ? "simple " : "") +
0N/A (pools[DIGEST] != null ? "DIGEST-MD5 " : ""));
0N/A
0N/A for (int i = 0; i < pools.length; i++) {
0N/A if (pools[i] != null) {
0N/A out.println(
0N/A (i == NONE ? "anonymous pools" :
0N/A i == SIMPLE ? "simple auth pools" :
1172N/A i == DIGEST ? "digest pools" : "")
1172N/A + ":");
1172N/A pools[i].showStats(out);
1172N/A }
401N/A }
401N/A out.println("***** end *****");
401N/A }
401N/A
0N/A /**
401N/A * Closes idle connections idle since specified time.
401N/A *
401N/A * @param threshold Close connections idle since this time, as
0N/A * specified in milliseconds since "the epoch".
0N/A * @see java.util.Date
0N/A */
0N/A public static void expire(long threshold) {
0N/A for (int i = 0; i < pools.length; i++) {
0N/A if (pools[i] != null) {
0N/A pools[i].expire(threshold);
0N/A }
0N/A }
0N/A }
0N/A
0N/A private static void d(String msg) {
0N/A if (debug) {
0N/A System.err.println("LdapPoolManager: " + msg);
0N/A }
0N/A }
0N/A
0N/A private static void d(String msg, String o) {
0N/A if (debug) {
0N/A System.err.println("LdapPoolManager: " + msg + o);
0N/A }
0N/A }
0N/A
0N/A private static final String getProperty(final String propName,
0N/A final String defVal) {
0N/A return (String) AccessController.doPrivileged(
0N/A new PrivilegedAction() {
0N/A public Object run() {
0N/A try {
0N/A return System.getProperty(propName, defVal);
0N/A } catch (SecurityException e) {
0N/A return defVal;
0N/A }
0N/A }
0N/A });
0N/A }
0N/A
2312N/A private static final int getInteger(final String propName,
2312N/A final int defVal) {
2312N/A Integer val = (Integer) AccessController.doPrivileged(
0N/A new PrivilegedAction() {
0N/A public Object run() {
0N/A try {
0N/A return Integer.getInteger(propName, defVal);
0N/A } catch (SecurityException e) {
0N/A return new Integer(defVal);
0N/A }
0N/A }
0N/A });
0N/A return val.intValue();
0N/A }
0N/A
0N/A private static final long getLong(final String propName,
0N/A final long defVal) {
0N/A Long val = (Long) AccessController.doPrivileged(
0N/A new PrivilegedAction() {
0N/A public Object run() {
0N/A try {
0N/A return Long.getLong(propName, defVal);
0N/A } catch (SecurityException e) {
605N/A return new Long(defVal);
0N/A }
0N/A }
0N/A });
0N/A return val.longValue();
1172N/A }
1172N/A}
1172N/A