/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 2001
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
package org.ietf.ldap;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.security.auth.callback.CallbackHandler;
import org.ietf.ldap.client.JDAPAVA;
import org.ietf.ldap.client.opers.JDAPAbandonRequest;
import org.ietf.ldap.client.opers.JDAPAddRequest;
import org.ietf.ldap.client.opers.JDAPBindRequest;
import org.ietf.ldap.client.opers.JDAPCompareRequest;
import org.ietf.ldap.client.opers.JDAPDeleteRequest;
import org.ietf.ldap.client.opers.JDAPExtendedRequest;
import org.ietf.ldap.client.opers.JDAPExtendedResponse;
import org.ietf.ldap.client.opers.JDAPModifyRDNRequest;
import org.ietf.ldap.client.opers.JDAPModifyRequest;
import org.ietf.ldap.client.opers.JDAPProtocolOp;
import org.ietf.ldap.client.opers.JDAPResult;
import org.ietf.ldap.client.opers.JDAPSearchRequest;
import org.ietf.ldap.client.opers.JDAPSearchResultReference;
/**
* Represents a connection to an LDAP server.
*
* Use objects of this class to perform LDAP operations (such as
* search, modify, and add) on an LDAP server.
*
* To perform an LDAP operation on a server, you need to follow
* these steps:
*
*
*
Create a new LDAPConnection object.
*
Use the connect method to connect to the
* LDAP server.
*
Use the authenticate method to authenticate
* to server.
*
Perform the LDAP operation.
*
Use the disconnect method to disconnect from
* the server when done.
*
*
*
* All operations block until completion (with the exception of
* the search method in which the results may not all return at
* the same time).
*
*
* This class also specifies a default set of constraints
* (such as the maximum length of time to allow for an operation before timing out)
* which apply to all operations. To get and set these constraints,
* use the getOption and setOption methods.
* To override these constraints for an individual operation,
* define a new set of constraints by creating a LDAPConstraints
* object and pass the object to the method for the operation. For search
* operations, additional constraints are defined in LDAPSearchConstraints
* (a subclass of LDAPConstraints). To override the default search
* constraints, create an LDAPSearchConstraints object and pass it
* to the search method.
*
*
* If you set up your client to follow referrals automatically,
* an operation that results in a referral will create a new connection
* to the LDAP server identified in the referral. In order to have
* your client authenticate to that LDAP server automatically, you need
* to define a class that implements the LDAPAuthHandler interface.
* In your definition of the class, you need to define a
* getAuthProvider method that creates an LDAPAuthProvider
* object containing the distinguished name and password to use for reauthentication.
*
*
* Most errors that occur raise the same exception (LDAPException).
* In order to determine the exact problem that occurred, you can retrieve the
* result code from this exception and compare its value against a set of defined
* result codes.
*
*
* @version 1.0
* @see org.ietf.ldap.LDAPConstraints
* @see org.ietf.ldap.LDAPSearchConstraints
* @see org.ietf.ldap.LDAPAuthHandler
* @see org.ietf.ldap.LDAPAuthProvider
* @see org.ietf.ldap.LDAPException
*/
public class LDAPConnection implements Cloneable, Serializable {
static final long serialVersionUID = -8698420087475771144L;
/**
* Version of the LDAP protocol used by default.
* LDAP_VERSION is 2, so your client will
* attempt to authenticate to LDAP servers as an LDAP v2 client.
* The following is an example of some code that prints the
* value of this variable:
*
*
*
* LDAPConnection ld = new LDAPConnection();
* System.out.println( "The default LDAP protocol version used is "
* ld.LDAP_VERSION );
*
*
* @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
*/
public final static int LDAP_VERSION = 2;
/**
* Name of the property specifying the version of the SDK.
*
* To get the version number, pass this name to the
* getProperty method. The SDK version number
* is of the type Float. For example:
* @see org.ietf.ldap.LDAPConnection#getProperty(java.lang.String)
*/
public final static String LDAP_PROPERTY_SDK = "version.sdk";
/**
* Name of the property specifying the highest supported version of
* the LDAP protocol.
*
* To get the version number, pass this name to the
* getProperty method. The LDAP protocol version number
* is of the type Float. For example:
* @see org.ietf.ldap.LDAPConnection#getProperty(java.lang.String)
*/
public final static String LDAP_PROPERTY_PROTOCOL = "version.protocol";
/**
* Name of the property specifying the types of authentication allowed by this
* API (for example, anonymous authentication and simple authentication).
*
* To get the supported types, pass this name to the
* getProperty method. The value of this property is
* of the type String. For example:
* @see org.ietf.ldap.LDAPConnection#getProperty(java.lang.String)
*/
public final static String LDAP_PROPERTY_SECURITY = "version.security";
/**
* Name of the property to enable/disable LDAP message trace.
*
* The property can be specified either as a system property
* (java -D command line option), or programmatically with the
* setProperty method.
*
* When -D command line option is used, defining the property with
* no value will send the trace output to the standard error. If the
* value is defined, it is assumed to be the name of an output file.
* If the file name is prefixed with a '+' character, the file is
* opened in append mode.
*
* When the property is set with the setProperty method,
* the property value must be either a String (represents a file name)
* an OutputStream or an instance of LDAPTraceWriter. To stop tracing,
* null should be passed as the property value.
*
* @see org.ietf.ldap.LDAPConnection#setProperty(java.lang.String, java.lang.Object)
*/
public final static String TRACE_PROPERTY = "com.org.ietf.ldap.trace";
/**
* Specifies the serial connection setup policy when a list of hosts is
* passed to the connect method.
* @see org.ietf.ldap.LDAPConnection#setConnSetupDelay(int)
*/
public final static int NODELAY_SERIAL = -1;
/**
* Specifies the parallel connection setup policy with no delay when a
* list of hosts is passed to the connect method.
* For each host in the list, a separate thread is created to attempt
* to connect to the host. All threads are started simultaneously.
* @see org.ietf.ldap.LDAPConnection#setConnSetupDelay(int)
*/
public final static int NODELAY_PARALLEL = 0;
/**
* Constants
*/
private final static String defaultFilter = "(objectClass=*)";
private final static LDAPConstraints readConstraints = new
LDAPSearchConstraints();
/**
* The default port number for LDAP servers. You can specify
* this identifier when calling the LDAPConnection.connect
* method to connect to an LDAP server.
* @see org.ietf.ldap.LDAPConnection#connect
*/
public final static int DEFAULT_PORT = 389;
/**
* Option specifying how aliases are dereferenced.
*
*
* This option can have one of the following values:
*
*
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int DEREF = 2;
/**
* Option specifying the maximum number of search results to
* return.
*
*
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int SIZELIMIT = 3;
/**
* Option specifying the maximum number of milliseconds to
* wait for an operation to complete.
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int TIMELIMIT = 4;
/**
* Option specifying the maximum number of milliseconds the
* server should spend returning search results before aborting
* the search.
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int SERVER_TIMELIMIT = 5;
/**
* Option specifying whether or not referrals to other LDAP
* servers are followed automatically.
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
* @see org.ietf.ldap.LDAPAuthHandler
* @see org.ietf.ldap.LDAPAuthProvider
*/
public static final int REFERRALS = 8;
/**
* Option specifying the object containing the method for
* getting authentication information (the distinguished name
* and password) used during a referral. For example, when
* referred to another LDAP server, your client uses this object
* to obtain the DN and password. Your client authenticates to
* the LDAP server using this DN and password.
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
* @see org.ietf.ldap.LDAPAuthHandler
* @see org.ietf.ldap.LDAPAuthProvider
*/
public static final int REFERRALS_REBIND_PROC = 9;
/**
* Option specifying the maximum number of referrals to follow
* in a sequence when requesting an LDAP operation.
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int REFERRALS_HOP_LIMIT = 10;
/**
* Option specifying the object containing the method for
* authenticating to the server.
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
* @see org.ietf.ldap.LDAPBindHandler
*/
public static final int BIND = 13;
/**
* Option specifying the version of the LDAP protocol
* used by your client when interacting with the LDAP server.
* If no version is set, the default version is 2. If you
* are planning to use LDAP v3 features (such as controls
* or extended operations), you should set this version to 3
* or specify version 3 as an argument to the authenticate
* method of the LDAPConnection object.
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
* @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
*/
public static final int PROTOCOL_VERSION = 17;
/**
* Option specifying the number of results to return at a time.
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int BATCHSIZE = 20;
/*
* Valid options for Scope
*/
/**
* Specifies that the scope of a search includes
* only the base DN (distinguished name).
* @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
*/
public static final int SCOPE_BASE = 0;
/**
* Specifies that the scope of a search includes
* only the entries one level below the base DN (distinguished name).
* @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints) */
public static final int SCOPE_ONE = 1;
/**
* Specifies that the scope of a search includes
* the base DN (distinguished name) and all entries at all levels
* beneath that base.
* @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints) */
public static final int SCOPE_SUB = 2;
/*
* Valid options for Dereference
*/
/**
* Specifies that aliases are never dereferenced.
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int DEREF_NEVER = 0;
/**
* Specifies that aliases are dereferenced when searching the
* entries beneath the starting point of the search (but
* not when finding the starting entry).
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int DEREF_SEARCHING = 1;
/**
* Specifies that aliases are dereferenced when finding the
* starting point for the search (but not when searching
* under that starting entry).
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int DEREF_FINDING = 2;
/**
* Specifies that aliases are always dereferenced.
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int DEREF_ALWAYS = 3;
/**
* Option specifying server controls for LDAP operations. These
* controls are passed to the LDAP server. They may also be returned by
* the server.
* @see org.ietf.ldap.LDAPControl
* @see org.ietf.ldap.LDAPConnection#getOption
* @see org.ietf.ldap.LDAPConnection#setOption
*/
public static final int SERVERCONTROLS = 12;
/**
* Attribute type that you can specify in the LDAPConnection
* search method if you don't want to retrieve any of the
* attribute types for entries found by the search.
* @see org.ietf.ldap.LDAPConnection#search
*/
public static final String NO_ATTRS = "1.1";
/**
* Attribute type that you can specify in the LDAPConnection
* search method if you want to retrieve all attribute types.
* You can use this if you want to retrieve all attributes in
* addition to an operational attribute. For example:
*
* @see org.ietf.ldap.LDAPConnection#search
*/
public static final String ALL_USER_ATTRS = "*";
/**
* Internal variables
*/
private LDAPSearchConstraints _defaultConstraints =
new LDAPSearchConstraints();
// A clone of constraints for the successful bind. Used by
// "smart failover" for the automatic rebind
private LDAPConstraints _rebindConstraints;
private Vector _responseListeners;
private Vector _searchListeners;
private boolean _bound;
private String _prevBoundDN;
private byte[] _prevBoundPasswd;
private String _boundDN;
private byte[] _boundPasswd;
private int _protocolVersion = LDAP_VERSION;
private LDAPConnSetupMgr _connMgr;
private int _connSetupDelay = -1;
private int _connectTimeout = 0;
private LDAPSocketFactory _factory;
/* _thread does all socket i/o for the object and any clones */
private transient LDAPConnThread _thread = null;
/* To manage received server controls on a per-thread basis,
we keep a table of active threads and a table of controls,
indexed by thread */
private Vector _attachedList = new Vector<>();
private Hashtable> _responseControlTable = new Hashtable<>();
private LDAPCache _cache = null;
static Hashtable> _threadConnTable = new Hashtable<>();
// This handles the case when the client lost the connection to the
// server. After the client reconnects with the server, the bound resets
// to false. If the client used to have anonymous bind, then this boolean
// will take care of the case whether the client should send anonymous bind
// request to the server.
private boolean _anonymousBound = false;
private LDAPSaslBind _saslBinder = null;
private CallbackHandler _saslCallbackHandler = null;
private Properties _securityProperties;
private Hashtable _properties = new Hashtable<>();
private LDAPConnection _referralConnection;
private String _authMethod = "none";
/**
* Properties
*/
private final static Float SdkVersion = 4.14f;
private final static Float ProtocolVersion = 3.0f;
private final static String SecurityVersion = new String("none,simple,sasl");
private final static Float MajorVersion = 4.0f;
private final static Float MinorVersion = 0.14f;
private final static String DELIM = "#";
private final static String PersistSearchPackageName =
"org.ietf.ldap.controls.LDAPPersistSearchControl";
final static String EXTERNAL_MECHANISM = "external";
private final static String EXTERNAL_MECHANISM_PACKAGE =
"com.netscape.sasl";
final static String DEFAULT_SASL_PACKAGE =
"com.netscape.sasl";
final static String SCHEMA_BUG_PROPERTY =
"com.org.ietf.ldap.schema.quoting";
final static String SASL_PACKAGE_PROPERTY =
"com.org.ietf.ldap.saslpackage";
/**
* Constructs a new LDAPConnection object,
* which represents a connection to an LDAP server.
*
* Calling the constructor does not actually establish
* the connection. To connect to the LDAP server, use the
* connect method.
*
* @see org.ietf.ldap.LDAPConnection#connect(java.lang.String, int)
* @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
*/
public LDAPConnection() {
super();
_factory = null;
_properties.put(LDAP_PROPERTY_SDK, SdkVersion);
_properties.put(LDAP_PROPERTY_PROTOCOL, ProtocolVersion);
_properties.put(LDAP_PROPERTY_SECURITY, SecurityVersion);
_properties.put("version.major", MajorVersion);
_properties.put("version.minor", MinorVersion);
}
/**
* Constructs a new LDAPConnection object that
* will use the specified socket factory class to create
* socket connections. The socket factory class must implement
* the LDAPSocketFactory interface.
* (For example, the LDAPSSLSocketFactory
* class implements this interface.)
*
*
* Note that calling the LDAPConnection constructor
* does not actually establish a connection to an LDAP server.
* To connect to an LDAP server, use the
* connect method. The socket connection will be
* constructed when this method is called.
*
*
* @see org.ietf.ldap.LDAPSocketFactory
* @see org.ietf.ldap.LDAPSSLSocketFactory
* @see org.ietf.ldap.LDAPConnection#connect(java.lang.String, int)
* @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
* @see org.ietf.ldap.LDAPConnection#getSocketFactory
* @see org.ietf.ldap.LDAPConnection#setSocketFactory(org.ietf.ldap.LDAPSocketFactory)
*/
public LDAPConnection( LDAPSocketFactory factory ) {
this();
_factory = factory;
}
/**
* Abandons a current search operation, notifying the server not
* to send additional search results.
*
* @param searchResults the search results returned when the search
* was started
* @exception LDAPException Failed to notify the LDAP server.
* @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
* @see org.ietf.ldap.LDAPSearchResults
*/
public void abandon( LDAPSearchResults searchResults )
throws LDAPException {
abandon( searchResults, _defaultConstraints );
}
/**
* Abandons a current search operation, notifying the server not
* to send additional search results.
*
* @param searchResults the search results returned when the search
* was started
* @param cons preferences for the operation
* @exception LDAPException Failed to notify the LDAP server.
* @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
* @see org.ietf.ldap.LDAPSearchResults
*/
public void abandon( LDAPSearchResults searchResults,
LDAPConstraints cons )
throws LDAPException {
if ( (!isConnected()) || (searchResults == null) ) {
return;
}
int id = searchResults.getMessageID();
if ( id != -1 ) {
abandon( id );
}
}
/**
* Cancels the ldap request with the specified id and discards
* any results already received.
*
* @param id an LDAP request id
* @exception LDAPException Failed to send request.
*/
public void abandon( int id ) throws LDAPException {
abandon( id, _defaultConstraints );
}
/**
* Cancels the ldap request with the specified id and discards
* any results already received.
*
* @param id an LDAP request id
* @param cons preferences for the operation
* @exception LDAPException Failed to send request.
*/
public void abandon( int id,
LDAPConstraints cons ) throws LDAPException {
if (!isConnected()) {
return;
}
for (int i=0; i<3; i++) {
try {
/* Tell listener thread to discard results */
_thread.abandon( id );
/* Tell server to stop sending results */
_thread.sendRequest(null, new JDAPAbandonRequest(id), null, _defaultConstraints);
/* No response is forthcoming */
break;
} catch (NullPointerException ne) {
// do nothing
}
}
if (_thread == null) {
throw new LDAPException("Failed to send abandon request to the server.",
LDAPException.OTHER);
}
}
/**
* Cancels all outstanding search requests associated with this
* LDAPSearchQueue object and discards any results already received.
*
* @param searchlistener a search listener returned from a search
* @exception LDAPException Failed to send request.
*/
public void abandon( LDAPSearchQueue searchlistener )
throws LDAPException {
abandon( searchlistener, _defaultConstraints );
}
/**
* Cancels all outstanding search requests associated with this
* LDAPSearchQueue object and discards any results already received.
*
* @param searchlistener a search listener returned from a search
* @param cons preferences for the operation
* @exception LDAPException Failed to send request.
*/
public void abandon( LDAPSearchQueue searchlistener,
LDAPConstraints cons )
throws LDAPException {
int[] ids = searchlistener.getMessageIDs();
for (int i=0; i < ids.length; i++) {
searchlistener.removeRequest(ids[i]);
abandon(ids[i]);
}
}
/**
* Adds an entry to the directory.
*
* Before using this method, you need to create an
* LDAPEntry object and use it to specify the
* distinguished name and attributes of the new entry. Make sure
* to specify values for all required attributes in the
* entry. If all required attributes are not specified and the LDAP server
* checks the entry against the schema, an LDAPException
* may be thrown (where the LDAP result code is
* OBJECT_CLASS_VIOLATION).
*
* For example, the following section of code creates an
* LDAPEntry object for a new entry and uses the object
* to add the new entry to the directory. Because the definition of
* the LDAP inetOrgPerson class specifies that the
* cn, sn, and objectclass
* attributes are required, these attributes are specified as part
* of the new entry. (mail is not required but is shown
* here as an example of specifying additional attributes.)
*
*
* @param entry LDAPEntry object specifying the distinguished name and
* attributes of the new entry
* @exception LDAPException Failed to add the specified entry to the
* directory.
* @see org.ietf.ldap.LDAPEntry
*/
public void add( LDAPEntry entry ) throws LDAPException {
add(entry, _defaultConstraints);
}
/**
* Adds an entry to the directory and allows you to specify preferences
* for this LDAP add operation by using an
* LDAPConstraints object. For
* example, you can specify whether or not to follow referrals.
* You can also apply LDAP v3 controls to the operation.
*
*
* @param entry LDAPEntry object specifying the distinguished name and
* attributes of the new entry
* @param cons the set of preferences to apply to this operation
* @exception LDAPException Failed to add the specified entry to the
* directory.
* @see org.ietf.ldap.LDAPEntry
* @see org.ietf.ldap.LDAPConstraints
*/
public void add( LDAPEntry entry, LDAPConstraints cons )
throws LDAPException {
internalBind (cons);
LDAPResponseQueue myListener = getResponseListener ();
LDAPAttributeSet attrs = entry.getAttributeSet ();
LDAPAttribute[] attrList = new LDAPAttribute[attrs.size()];
Iterator it = attrs.iterator();
for( int i = 0; i < attrs.size(); i++ ) {
attrList[i] = it.next();
}
int attrPosition = 0;
LDAPMessage response;
try {
sendRequest (new JDAPAddRequest (entry.getDN(), attrList),
myListener, cons);
response = myListener.getResponse();
checkMsg (response);
} catch (LDAPReferralException e) {
performReferrals(e, cons, JDAPProtocolOp.ADD_REQUEST,
null, 0, null, null, false, null, entry, null, null);
} finally {
releaseResponseListener (myListener);
}
}
/**
* Adds an entry to the directory.
*
* @param entry LDAPEntry object specifying the distinguished name and
* attributes of the new entry
* @param listener handler for messages returned from a server in response
* to this request. If it is null, a listener object is created internally.
* @param cons constraints specific to the operation
* @return LDAPResponseQueue handler for messages returned from a server
* in response to this request.
* @exception LDAPException Failed to send request.
* @see org.ietf.ldap.LDAPEntry
* @see org.ietf.ldap.LDAPResponseQueue
*/
public LDAPResponseQueue add( LDAPEntry entry,
LDAPResponseQueue listener )
throws LDAPException{
return add( entry, listener, _defaultConstraints );
}
/**
* Adds an entry to the directory and allows you to specify constraints
* for this LDAP add operation by using an LDAPConstraints
* object. For example, you can specify whether or not to follow referrals.
* You can also apply LDAP v3 controls to the operation.
*
*
* @param entry LDAPEntry object specifying the distinguished name and
* attributes of the new entry
* @param listener handler for messages returned from a server in response
* to this request. If it is null, a listener object is created internally.
* @param cons constraints specific to the operation
* @return LDAPResponseQueue handler for messages returned from a server
* in response to this request
* @exception LDAPException Failed to send request.
* @see org.ietf.ldap.LDAPEntry
* @see org.ietf.ldap.LDAPResponseQueue
* @see org.ietf.ldap.LDAPConstraints
*/
public LDAPResponseQueue add( LDAPEntry entry,
LDAPResponseQueue listener,
LDAPConstraints cons )
throws LDAPException{
if (cons == null) {
cons = _defaultConstraints;
}
internalBind (cons);
if (listener == null) {
listener = new LDAPResponseQueue(/*asynchOp=*/true);
}
LDAPAttributeSet attrs = entry.getAttributeSet ();
LDAPAttribute[] attrList = new LDAPAttribute[attrs.size()];
Iterator it = attrs.iterator();
for( int i = 0; i < attrs.size(); i++ ) {
attrList[i] = it.next();
}
int attrPosition = 0;
sendRequest (new JDAPAddRequest (entry.getDN(), attrList),
listener, cons);
return listener;
}
/**
* Registers an object to be notified on arrival of an unsolicited
* message from a server
*
* @param listener An object to be notified on arrival of an
* unsolicited message from a server
*/
public void addUnsolicitedNotificationListener(
LDAPUnsolicitedNotificationListener listener ) {
}
/**
* Authenticates to the LDAP server (to which you are currently
* connected) using the specified name and password.
* If you are not already connected to the LDAP server, this
* method attempts to reconnect to the server.
*
*
* For example, the following section of code authenticates the
* client as Barbara Jensen. The code assumes that the client
* has already established a connection with an LDAP server.
*
*
*
* String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
* String myPW = "hifalutin";
* try {
* myConn.bind( myDN, myPW.getBytes() );
* } catch ( LDAPException e ) {
* switch( e.getResultCode() ) {
* case e.NO_SUCH_OBJECT:
* System.out.println( "The specified user does not exist." );
* break;
* case e.INVALID_CREDENTIALS:
* System.out.println( "Invalid password." );
* break;
* default:
* System.out.println( "Error number: " + e.getResultCode() );
* System.out.println( "Failed to authentice as " + myDN );
* break;
* }
* return;
* }
* System.out.println( "Authenticated as " + myDN );
*
*
* @param dn distinguished name used for authentication
* @param passwd password used for authentication
* @exception LDAPException Failed to authenticate to the LDAP server.
*/
private void bind( String dn, byte[] passwd) throws LDAPException {
bind( _protocolVersion, dn, passwd, _defaultConstraints );
}
/**
* Authenticates to the LDAP server (to which you are currently
* connected) using the specified name and password. The
* default protocol version (version 2) is used. If the server
* doesn't support the default version, an LDAPException is thrown
* with the error code PROTOCOL_ERROR. This method allows the
* user to specify the preferences for the bind operation.
*
* @param dn distinguished name used for authentication
* @param passwd password used for authentication
* @param cons preferences for the bind operation
* @exception LDAPException Failed to authenticate to the LDAP server.
*/
private void bind( String dn, byte[] passwd,
LDAPConstraints cons ) throws LDAPException {
bind( _protocolVersion, dn, passwd, cons );
}
/**
* Authenticates to the LDAP server (to which you are currently
* connected) using the specified name and password, and
* requests that the server use at least the specified
* protocol version. If the server doesn't support that
* level, an LDAPException is thrown with the error code
* PROTOCOL_ERROR.
*
* @param version required LDAP protocol version
* @param dn distinguished name used for authentication
* @param passwd password used for authentication
* @exception LDAPException Failed to authenticate to the LDAP server.
*/
public void bind( int version, String dn, byte[] passwd )
throws LDAPException {
bind( version, dn, passwd, _defaultConstraints );
}
/**
* Authenticates to the LDAP server (to which you are currently
* connected) using the specified name and password, and
* requesting that the server use at least the specified
* protocol version. If the server doesn't support that
* level, an LDAPException is thrown with the error code
* PROTOCOL_ERROR. This method allows the user to specify the
* preferences for the bind operation.
*
* @param version required LDAP protocol version
* @param dn distinguished name used for authentication
* @param passwd password used for authentication
* @param cons preferences for the bind operation
* @exception LDAPException Failed to authenticate to the LDAP server.
*/
public void bind( int version, String dn, byte[] passwd,
LDAPConstraints cons ) throws LDAPException {
_prevBoundDN = _boundDN;
_prevBoundPasswd = _boundPasswd;
_boundDN = dn;
_boundPasswd = passwd;
_anonymousBound =
((_prevBoundDN == null) || (_prevBoundPasswd == null));
internalBind (version, true, cons);
}
/**
* Authenticates to the LDAP server (to which the object is currently
* connected) using the specified name and whatever SASL mechanisms
* are supported by the server. Each supported mechanism in turn
* is tried until authentication succeeds or an exception is thrown.
* If the object has been disconnected from an LDAP server, this
* method attempts to reconnect to the server. If the object had
* already authenticated, the old authentication is discarded.
*
* @param dn if non-null and non-empty, specifies that the connection and
* all operations through it should authenticate with dn as the
* distinguished name
* @param authzid If not null and not empty, an LDAP authzID [AUTH]
* to be passed to the SASL layer. If null or empty,
* the authzId will be treated as an empty string
* and processed as per RFC 2222 [SASL].
* @param props Optional qualifiers for the authentication session
* @param cbh a class which the SASL framework can call to
* obtain additional required information
* @exception LDAPException Failed to authenticate to the LDAP server.
*/
public void bind( String dn,
String authzid,
Map props,
CallbackHandler cbh )
throws LDAPException {
bind( dn, authzid, props, cbh, _defaultConstraints );
}
/**
* Authenticates to the LDAP server (to which the object is currently
* connected) using the specified name and whatever SASL mechanisms
* are supported by the server. Each supported mechanism in turn
* is tried until authentication succeeds or an exception is thrown.
* If the object has been disconnected from an LDAP server, this
* method attempts to reconnect to the server. If the object had
* already authenticated, the old authentication is discarded.
*
* @param dn if non-null and non-empty, specifies that the connection and
* all operations through it should authenticate with dn as the
* distinguished name
* @param authzid If not null and not empty, an LDAP authzID [AUTH]
* to be passed to the SASL layer. If null or empty,
* the authzId will be treated as an empty string
* and processed as per RFC 2222 [SASL].
* @param props Optional qualifiers for the authentication session
* @param cbh a class which the SASL framework can call to
* obtain additional required information
* @param cons preferences for the bind operation
* @exception LDAPException Failed to authenticate to the LDAP server.
*/
public void bind( String dn,
String authzid,
Map props,
CallbackHandler cbh,
LDAPConstraints cons )
throws LDAPException {
if ( !isConnected() ) {
connect();
}
// Get the list of mechanisms from the server
String[] attrs = { "supportedSaslMechanisms" };
LDAPEntry entry = read( "", attrs );
LDAPAttribute attr = entry.getAttribute( attrs[0] );
if ( attr == null ) {
throw new LDAPException( "Not found in root DSE: " +
attrs[0],
LDAPException.NO_SUCH_ATTRIBUTE );
}
bind( dn, authzid, attr.getStringValueArray(), props, cbh, cons );
}
/**
* Authenticates to the LDAP server (to which the object is currently
* connected) using the specified name and a specified SASL mechanism
* or set of mechanisms. If the requested SASL mechanism is not
* available, an exception is thrown. If the object has been
* disconnected from an LDAP server, this method attempts to reconnect
* to the server. If the object had already authenticated, the old
* authentication is discarded.
*
* @param dn if non-null and non-empty, specifies that the connection and
* all operations through it should authenticate with dn as the
* distinguished name
* @param authzid If not null and not empty, an LDAP authzID [AUTH]
* to be passed to the SASL layer. If null or empty,
* the authzId will be treated as an empty string
* and processed as per RFC 2222 [SASL].
* @param props Optional qualifiers for the authentication session
* @param mechanisms a list of acceptable mechanisms. The first one
* for which a Mechanism Driver can be instantiated is returned.
* @param cbh a class which the SASL framework can call to
* obtain additional required information
* @exception LDAPException Failed to authenticate to the LDAP server.
* @see org.ietf.ldap.LDAPConnection#bind(String, String, Map,
* CallbackHandler)
*/
public void bind( String dn,
String authzid,
String[] mechanisms,
Map props,
CallbackHandler cbh )
throws LDAPException {
bind( dn, authzid, mechanisms, props, cbh, _defaultConstraints );
}
/**
* Authenticates to the LDAP server (to which the object is currently
* connected) using the specified name and a specified SASL mechanism
* or set of mechanisms. If the requested SASL mechanism is not
* available, an exception is thrown. If the object has been
* disconnected from an LDAP server, this method attempts to reconnect
* to the server. If the object had already authenticated, the old
* authentication is discarded.
*
* @param dn if non-null and non-empty, specifies that the connection and
* all operations through it should authenticate with dn as the
* distinguished name
* @param authzid If not null and not empty, an LDAP authzID [AUTH]
* to be passed to the SASL layer. If null or empty,
* the authzId will be treated as an empty string
* and processed as per RFC 2222 [SASL].
* @param props Optional qualifiers for the authentication session
* @param mechanisms a list of acceptable mechanisms. The first one
* for which a Mechanism Driver can be instantiated is returned.
* @param cbh a class which the SASL framework can call to
* obtain additional required information
* @param cons preferences for the bind operation
* @exception LDAPException Failed to authenticate to the LDAP server.
* @see org.ietf.ldap.LDAPConnection#bind(String, String, Map,
* CallbackHandler, LDAPConstraints)
*/
public void bind( String dn,
String authzid,
String[] mechanisms,
Map props,
CallbackHandler cbh,
LDAPConstraints cons )
throws LDAPException {
if ( !isConnected() ) {
connect();
} else {
// If the thread has more than one LDAPConnection, then
// we should disconnect first. Otherwise,
// we can reuse the same thread for the rebind.
if (_thread.getClientCount() > 1) {
disconnect();
connect();
}
}
_boundDN = null;
_protocolVersion = 3; // Must be 3 for SASL
if ( props == null ) {
props = new Hashtable<>();
}
_saslBinder = new LDAPSaslBind( dn, mechanisms,
props, cbh );
_saslCallbackHandler = cbh;
_saslBinder.bind( this );
_authMethod = "sasl";
_boundDN = dn;
}
/**
* Authenticates to the LDAP server (to which the object is currently
* connected) using the specified name and password. If the object
* has been disconnected from an LDAP server, this method attempts to
* reconnect to the server. If the object had already authenticated, the
* old authentication is discarded.
*
* @param version required LDAP protocol version
* @param dn if non-null and non-empty, specifies that the connection
* and all operations through it should authenticate with dn as the
* distinguished name
* @param passwd if non-null and non-empty, specifies that the connection
* and all operations through it should authenticate with dn as the
* distinguished name and passwd as password
* @param listener handler for messages returned from a server in response
* to this request. If it is null, a listener object is created internally.
* @return LDAPResponseQueue handler for messages returned from a server
* in response to this request.
* @exception LDAPException Failed to send request.
* @see org.ietf.ldap.LDAPResponseQueue
*/
public LDAPResponseQueue bind( int version,
String dn,
byte[] passwd,
LDAPResponseQueue listener )
throws LDAPException{
return bind( version, dn, passwd, listener, _defaultConstraints );
}
/**
* Authenticates to the LDAP server (to which the object is currently
* connected) using the specified name and password. If the object
* has been disconnected from an LDAP server, this method attempts to
* reconnect to the server. If the object had already authenticated, the
* old authentication is discarded.
*
* @param dn if non-null and non-empty, specifies that the connection
* and all operations through it should authenticate with dn as the
* distinguished name
* @param passwd if non-null and non-empty, specifies that the connection
* and all operations through it should authenticate with dn as the
* distinguished name and passwd as password
* @param listener handler for messages returned from a server in response
* to this request. If it is null, a listener object is created internally.
* @return LDAPResponseQueue handler for messages returned from a server
* in response to this request.
* @exception LDAPException Failed to send request.
* @see org.ietf.ldap.LDAPResponseQueue
*/
private LDAPResponseQueue bind( String dn,
byte[] passwd,
LDAPResponseQueue listener)
throws LDAPException{
return bind( _protocolVersion, dn, passwd, listener,
_defaultConstraints );
}
/**
* Authenticates to the LDAP server (to which the object is currently
* connected) using the specified name and password and allows you
* to specify constraints for this LDAP add operation by using an
* LDAPConstraints object. If the object
* has been disconnected from an LDAP server, this method attempts to
* reconnect to the server. If the object had already authenticated, the
* old authentication is discarded.
*
* @param dn if non-null and non-empty, specifies that the connection
* and all operations through it should authenticate with dn as the
* distinguished name
* @param passwd if non-null and non-empty, specifies that the connection
* and all operations through it should authenticate with dn as the
* distinguished name and passwd as password
* @param listener handler for messages returned from a server in response
* to this request. If it is null, a listener object is created internally.
* @param cons constraints specific to the operation
* @return LDAPResponseQueue handler for messages returned from a server
* in response to this request.
* @exception LDAPException Failed to send request.
* @see org.ietf.ldap.LDAPResponseQueue
* @see org.ietf.ldap.LDAPConstraints
*/
private LDAPResponseQueue bind( String dn,
byte[] passwd,
LDAPResponseQueue listener,
LDAPConstraints cons )
throws LDAPException{
return bind( _protocolVersion, dn, passwd, listener, cons );
}
/**
* Authenticates to the LDAP server (to which the object is currently
* connected) using the specified name and password and allows you
* to specify constraints for this LDAP add operation by using an
* LDAPConstraints object. If the object
* has been disconnected from an LDAP server, this method attempts to
* reconnect to the server. If the object had already authenticated, the
* old authentication is discarded.
*
* @param version required LDAP protocol version
* @param dn if non-null and non-empty, specifies that the connection
* and all operations through it should authenticate with dn as the
* distinguished name
* @param passwd if non-null and non-empty, specifies that the connection
* and all operations through it should authenticate with dn as the
* distinguished name and passwd as password
* @param listener handler for messages returned from a server in response
* to this request. If it is null, a listener object is created internally.
* @param cons constraints specific to the operation
* @return LDAPResponseQueue handler for messages returned from a server
* in response to this request.
* @exception LDAPException Failed to send request.
* @see org.ietf.ldap.LDAPResponseQueue
* @see org.ietf.ldap.LDAPConstraints
*/
public LDAPResponseQueue bind( int version,
String dn,
byte[] passwd,
LDAPResponseQueue listener,
LDAPConstraints cons )
throws LDAPException{
if (cons == null) {
cons = _defaultConstraints;
}
_prevBoundDN = _boundDN;
_prevBoundPasswd = _boundPasswd;
_boundDN = dn;
_boundPasswd = passwd;
_protocolVersion = version;
if (_thread == null) {
connect();
}
else if (_thread.getClientCount() > 1) {
disconnect();
connect();
}
if (listener == null) {
listener = new LDAPResponseQueue(/*asynchOp=*/true);
}
sendRequest(new JDAPBindRequest(version, _boundDN, _boundPasswd),
listener, cons);
return listener;
}
/**
* Authenticates to the LDAP server (to which the object is currently
* connected) using the specified name and a specified SASL mechanism
* or set of mechanisms. If the requested SASL mechanism is not
* available, an exception is thrown. If the object has been
* disconnected from an LDAP server, this method attempts to reconnect
* to the server. If the object had already authenticated, the old
* authentication is discarded.
*
* @param dn if non-null and non-empty, specifies that the connection and
* all operations through it should authenticate with dn as the
* distinguished name
* @param authzid If not null and not empty, an LDAP authzID [AUTH]
* to be passed to the SASL layer. If null or empty,
* the authzId will be treated as an empty string
* and processed as per RFC 2222 [SASL].
* @param mechanisms a list of acceptable mechanisms. The first one
* for which a Mechanism Driver can be instantiated is returned.
* @param packageName a package containing a SASL ClientFactory,
* e.g. "myclasses.SASL". If null, a system default is used.
* @param cbh a class which the SASL framework can call to
* obtain additional required information
* @exception LDAPException Failed to authenticate to the LDAP server.
* @deprecated Please use authenticate without packageName
* instead.
*/
public void bind( String dn,
String authzid,
String[] mechanisms,
String packageName,
Map props,
CallbackHandler cbh,
LDAPConstraints cons )
throws LDAPException {
if ( props == null ) {
props = new Hashtable<>();
}
props.put( LDAPSaslBind.CLIENTPKGS, packageName );
bind( dn, authzid, mechanisms, props, cbh, cons );
}
/**
* Creates and returns a copy of the object. The new
* LDAPConnection object contains the same information as
* the original connection, including:
*
*
the default search constraints
*
host name and port number of the LDAP server
*
the DN and password used to authenticate to the LDAP server
*
*
* @return the LDAPconnection object representing the
* new object.
*/
public synchronized Object clone() {
try {
LDAPConnection c = (LDAPConnection)super.clone();
if (!isConnected()) {
this.internalBind(_defaultConstraints);
}
c._defaultConstraints =
(LDAPSearchConstraints)_defaultConstraints.clone();
c._responseListeners = null;
c._searchListeners = null;
c._bound = this._bound;
c._connMgr = _connMgr;
c._connSetupDelay = _connSetupDelay;
c._boundDN = this._boundDN;
c._boundPasswd = this._boundPasswd;
c._prevBoundDN = this._prevBoundDN;
c._prevBoundPasswd = this._prevBoundPasswd;
c._anonymousBound = this._anonymousBound;
c.setCache(this._cache); // increments cache reference cnt
c._factory = this._factory;
c._thread = this._thread; /* share current connection thread */
synchronized (_threadConnTable) {
Vector v = _threadConnTable.get(this._thread);
if (v != null) {
v.addElement(c);
} else {
printDebug("Failed to clone");
return null;
}
}
c._thread.register(c);
return c;
} catch (Exception e) {
}
return null;
}
/**
* Checks to see if an entry contains an attribute with a specified value.
* Returns true if the entry has the value. Returns
* false if the entry does not have the value or the
* attribute. To represent the value that you want compared, you need
* to create an LDAPAttribute object.
*
* Note that only string values can be compared.
*
* For example, the following section of code checks to see if the entry
* "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US" contains
* the attribute "mail" with the value "bjensen@aceindustry.com".
*
*
* ...
* LDAPConnection myConn = new LDAPConnection();
* ...
* String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
* String nameOfAttr = "mail";
* String valOfAttr = "bjensen@aceindustry.com";
* LDAPAttribute cmpThisAttr = new LDAPAttribute( nameOfAttr, valOfAttr );
* boolean hasValue = myConn.compare( myDN, cmpThisAttr );
* if ( hasValue ) {
* System.out.println( "Attribute and value found in entry." );
* } else {
* System.out.println( "Attribute and value not found in entry." );
* }
* ...
*
* @param DN the distinguished name of the entry to use in
* the comparison
* @param attr the attribute to compare against the entry.
* (The method checks to see if the entry has an attribute with the same name
* and value as this attribute.)
* @return true if the entry contains the specified attribute and value.
* @exception LDAPException Failed to perform the comparison.
* @see org.ietf.ldap.LDAPAttribute
*/
public boolean compare( String DN, LDAPAttribute attr )
throws LDAPException {
return compare( DN, attr, _defaultConstraints );
}
public boolean compare( String DN, LDAPAttribute attr,
LDAPConstraints cons ) throws LDAPException {
internalBind(cons);
LDAPResponseQueue myListener = getResponseListener ();
Enumeration en = attr.getStringValues();
String val = en.nextElement();
JDAPAVA ass = new JDAPAVA(attr.getName(), val);
LDAPMessage response;
try {
sendRequest (new JDAPCompareRequest (DN, ass), myListener, cons);
response = myListener.getResponse ();
int resultCode = ((JDAPResult)response.getProtocolOp()).getResultCode();
if (resultCode == JDAPResult.COMPARE_FALSE) {
return false;
}
if (resultCode == JDAPResult.COMPARE_TRUE) {
return true;
}
checkMsg (response);
} catch (LDAPReferralException e) {
Vector