/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
//import javax.net.SocketFactory;
/**
* A thread that creates a connection to an LDAP server.
* After the connection, the thread reads from the connection.
* A caller can invoke methods on the instance to read LDAP responses
* and to send LDAP requests.
* <p>
* There is a one-to-one correspondence between an LdapClient and
* a Connection. Access to Connection and its methods is only via
* LdapClient with two exceptions: SASL authentication and StartTLS.
* SASL needs to access Connection's socket IO streams (in order to do encryption
* of the security layer). StartTLS needs to do replace IO streams
* and close the IO streams on nonfatal close. The code for SASL
* authentication can be treated as being the same as from LdapClient
* because the SASL code is only ever called from LdapClient, from
* inside LdapClient's synchronized authenticate() method. StartTLS is called
* directly by the application but should only occur when the underlying
* connection is quiet.
* <p>
* In terms of synchronization, worry about data structures
* used by the Connection thread because that usage might contend
* with calls by the main threads (i.e., those that call LdapClient).
* Main threads need to worry about contention with each other.
* Fields that Connection thread uses:
* inStream - synced access and update; initialized in constructor;
* referenced outside class unsync'ed (by LdapSasl) only
* when connection is quiet
* traceFile, traceTagIn, traceTagOut - no sync; debugging only
* parent - no sync; initialized in constructor; no updates
* pendingRequests - sync
* pauseLock - per-instance lock;
* paused - sync via pauseLock (pauseReader())
* Members used by main threads (LdapClient):
* host, port - unsync; read-only access for StartTLS and debug messages
* setBound(), setV3() - no sync; called only by LdapClient.authenticate(),
* which is a sync method called only when connection is "quiet"
* getMsgId() - sync
* writeRequest(), removeRequest(),findRequest(), abandonOutstandingReqs() -
* access to shared pendingRequests is sync
* writeRequest(), abandonRequest(), ldapUnbind() - access to outStream sync
* cleanup() - sync
* readReply() - access to sock sync
* unpauseReader() - (indirectly via writeRequest) sync on pauseLock
* Members used by SASL auth (main thread):
* inStream, outStream - no sync; used to construct new stream; accessed
* only when conn is "quiet" and not shared
* replaceStreams() - sync method
* Members used by StartTLS:
* inStream, outStream - no sync; used to record the existing streams;
* accessed only when conn is "quiet" and not shared
* replaceStreams() - sync method
* <p>
* Handles anonymous, simple, and SASL bind for v3; anonymous and simple
* for v2.
* %%% made public for access by LdapSasl %%%
*
* @author Vincent Ryan
* @author Rosanna Lee
* @author Jagane Sundar
*/
private static final boolean debug = false;
// used by StartTlsResponse when creating an SSL socket
// used by StartTlsResponse when creating an SSL socket
// All three are initialized in constructor and read-only afterwards
// Initialized in constructor; read and used externally (LdapSasl);
// Updated in replaceStreams() during "quiet", unshared, period
// Initialized in constructor; read and used externally (LdapSasl);
// Updated in replaceOutputStream() during "quiet", unshared, period
// Initialized in constructor; read and used externally (TLS) to
// get new IO streams; closed during cleanup
// For processing "disconnect" unsolicited notification
// Initialized in constructor
// Incremented and returned in sync getMsgId()
//
// The list of ldapRequests pending on this binding
//
// Accessed only within sync methods
int readTimeout;
int connectTimeout;
// true means v3; false means v2
// Called in LdapClient.authenticate() (which is synchronized)
// when connection is "quiet" and not shared; no need to synchronize
void setV3(boolean v) {
v3 = v;
}
// A BIND request has been successfully made on this connection
// When cleaning up, remember to do an UNBIND
// Called in LdapClient.authenticate() (which is synchronized)
// when connection is "quiet" and not shared; no need to synchronize
void setBound() {
bound = true;
}
////////////////////////////////////////////////////////////////////////////
//
// Create an LDAP Binding object and bind to a particular server
//
////////////////////////////////////////////////////////////////////////////
this.readTimeout = readTimeout;
this.connectTimeout = connectTimeout;
}
//
// Connect to server
//
try {
if (debug) {
}
} catch (InvocationTargetException e) {
// realException.printStackTrace();
throw ce;
} catch (Exception e) {
// Class.forName() seems to do more error checking
// and will throw IllegalArgumentException and such.
// That's why we need to have a catch all here and
// ignore generic exceptions.
// Also catches all IO errors generated by socket creation.
ce.setRootCause(e);
throw ce;
}
}
/*
* Create an InetSocketAddress using the specified hostname and port number.
*/
throws NoSuchMethodException {
try {
String.class, int.class});
} catch (ClassNotFoundException e) {
throw new NoSuchMethodException();
} catch (InstantiationException e) {
throw new NoSuchMethodException();
} catch (InvocationTargetException e) {
throw new NoSuchMethodException();
} catch (IllegalAccessException e) {
throw new NoSuchMethodException();
}
}
/*
* Create a Socket object using the specified socket factory and time limit.
*
* If a timeout is supplied and unconnected sockets are supported then
* an unconnected socket is created and the timeout is applied when
* connecting the socket. If a timeout is supplied but unconnected sockets
* are not supported then the timeout is ignored and a connected socket
* is created.
*/
int connectTimeout) throws Exception {
if (socketFactory != null) {
// create the factory
// create the socket
if (connectTimeout > 0) {
try {
new Class[]{});
int.class});
// unconnected socket
socket =
if (debug) {
"a timeout using supplied socket factory");
}
// connected socket
} catch (NoSuchMethodException e) {
// continue (but ignore connectTimeout)
}
}
if (debug) {
"supplied socket factory");
}
// connected socket
}
} else {
if (connectTimeout > 0) {
try {
int.class});
if (debug) {
"a timeout");
}
} catch (NoSuchMethodException e) {
// continue (but ignore connectTimeout)
}
}
if (debug) {
}
// connected socket
}
}
// For LDAP connect timeouts on LDAP over SSL connections must treat
// the SSL handshake following socket connection as part of the timeout.
// So explicitly set a socket read timeout, trigger the SSL handshake,
// then reset the timeout.
}
return socket;
}
////////////////////////////////////////////////////////////////////////////
//
// Methods to IO to the LDAP server
//
////////////////////////////////////////////////////////////////////////////
synchronized int getMsgId() {
return ++outMsgId;
}
}
boolean pauseAfterReceipt) throws IOException {
}
}
// unpause reader so that it can get response
// NOTE: Must do this before writing request, otherwise might
// create a race condition where the writer unblocks its own response
if (debug) {
}
try {
synchronized (this) {
}
} catch (IOException e) {
throw (closureReason = e); // rethrow
}
return req;
}
/**
* Reads a reply; waits until one is ready.
*/
throws IOException, NamingException {
boolean waited = false;
try {
// If socket closed, don't even try
synchronized (this) {
"; socket closed");
}
}
synchronized (ldr) {
// check if condition has changed since our last check
// will be woken up before readTimeout only if reply is
// available
waited = true;
} else {
}
} else {
break;
}
}
} catch (InterruptedException ex) {
throw new InterruptedNamingException(
"Interrupted during LDAP operation");
}
}
throw new NamingException("LDAP response read timed out, timeout used:"
+ readTimeout + "ms." );
}
return rber;
}
////////////////////////////////////////////////////////////////////////////
//
// Methods to add, find, delete, and abandon requests made to server
//
////////////////////////////////////////////////////////////////////////////
} else {
}
}
return ldr;
}
}
return null;
}
} else {
}
}
}
}
// Remove from queue
int abandonMsgId = getMsgId();
//
// build the abandon request.
//
try {
if (v3) {
}
ber.getDataLen());
}
synchronized (this) {
}
} catch (IOException ex) {
//System.err.println("ldap.abandon: " + ex);
}
// Dont expect any response for the abandon request.
}
}
}
////////////////////////////////////////////////////////////////////////////
//
// Methods to unbind from server and clear up resources when object is
// destroyed.
//
////////////////////////////////////////////////////////////////////////////
int unbindMsgId = getMsgId();
//
// build the unbind request.
//
try {
// IMPLICIT TAGS
if (v3) {
}
}
synchronized (this) {
}
} catch (IOException ex) {
//System.err.println("ldap.unbind: " + ex);
}
// Dont expect any response for the unbind request.
}
/**
* @param reqCtls Possibly null request controls that accompanies the
* abandon and unbind LDAP request.
* @param notifyParent true means to call parent LdapClient back, notifying
* it that the connection has been closed; false means not to notify
* parent. If LdapClient invokes cleanup(), notifyParent should be set to
* false because LdapClient already knows that it is closing
* the connection. If Connection invokes cleanup(), notifyParent should be
* set to true because LdapClient needs to know about the closure.
*/
boolean nparent = false;
synchronized (this) {
useable = false;
if (debug) {
}
try {
if (!notifyParent) {
}
if (bound) {
}
} finally {
try {
} catch (IOException ie) {
if (debug)
}
if (!notifyParent) {
}
}
}
}
if (nparent) {
synchronized (ldr) {
}
}
}
}
if (nparent) {
}
}
// Assume everything is "quiet"
// "synchronize" might lead to deadlock so don't synchronize method
// Use streamLock instead for synchronizing update to stream
if (debug) {
}
// Cleanup old stream
try {
} catch (IOException ie) {
if (debug)
}
// Replace stream
}
/**
* Used by Connection thread to read inStream into a local variable.
* This ensures that there is no contention between the main thread
* and the Connection thread when the main thread updates inStream.
*/
return inStream;
}
////////////////////////////////////////////////////////////////////////////
//
//
////////////////////////////////////////////////////////////////////////////
/*
* The main idea is to mark requests that need the reader thread to
* pause after getting the response. When the reader thread gets the response,
* it waits on a lock instead of returning to the read(). The next time a
* request is sent, the reader is automatically unblocked if necessary.
* Note that the reader must be unblocked BEFORE the request is sent.
* Otherwise, there is a race condition where the request is sent and
* the reader thread might read the response and be unblocked
* by writeRequest().
*
* This pause gives the main thread (StartTLS or SASL) an opportunity to
* update the reader's state (e.g., its streams) if necessary.
* The assumption is that the connection will remain quiet during this pause
* (i.e., no intervening requests being sent).
*<p>
* For dealing with StartTLS close,
* when the read() exits either due to EOF or an exception,
* the reader thread checks whether there is a new stream to read from.
* If so, then it reattempts the read. Otherwise, the EOF or exception
* is processed and the reader thread terminates.
* In a StartTLS close, the client first replaces the SSL IO streams with
* plain ones and then closes the SSL socket.
* If the reader thread attempts to read, or was reading, from
* the SSL socket (that is, it got to the read BEFORE replaceStreams()),
* the SSL socket close will cause the reader thread to
* If the reader thread sees a new stream, it reattempts the read.
* If the underlying socket is still alive, then the new read will succeed.
* If the underlying socket has been closed also, then the new read will
* fail and the reader thread exits.
* If the reader thread attempts to read, or was reading, from the plain
* socket (that is, it got to the read AFTER replaceStreams()), the
* SSL socket close will have no effect on the reader thread.
*
* The check for new stream is made only
* in the first attempt at reading a BER buffer; the reader should
* never be in midst of reading a buffer when a nonfatal close occurs.
* If this occurs, then the connection is in an inconsistent state and
* the safest thing to do is to shut it down.
*/
/*
* Unpauses reader thread if it was paused
*/
synchronized (pauseLock) {
if (paused) {
if (debug) {
inStream);
}
paused = false;
}
}
}
/*
* Pauses reader so that it stops reading from the input stream.
* Reader blocks on pauseLock instead of read().
* MUST be called from within synchronized (pauseLock) clause.
*/
if (debug) {
inStream);
}
paused = true;
try {
while (paused) {
}
} catch (InterruptedException e) {
throw new InterruptedIOException(
}
}
////////////////////////////////////////////////////////////////////////////
//
// on the same TCP connection.
//
////////////////////////////////////////////////////////////////////////////
public void run() {
byte inbuf[]; // Buffer for reading incoming bytes
int inMsgId; // Message id of incoming response
int bytesread; // Number of bytes in inbuf
int br; // Temp; number of bytes read from stream
int offset; // Offset of where to store bytes in inbuf
int seqlen; // Length of ASN sequence
int seqlenlen; // Number of sequence length bytes
boolean eos; // End of stream
try {
while (true) {
try {
// type and length (at most 128 octets for long form)
inbuf = new byte[129];
offset = 0;
seqlen = 0;
seqlenlen = 0;
in = getInputStream();
// check that it is the beginning of a sequence
if (bytesread < 0) {
if (in != getInputStream()) {
continue; // a new stream to try
} else {
break; // EOF
}
}
continue;
// get length of sequence
if (bytesread < 0)
break; // EOF
// if high bit is on, length is encoded in the
// subsequent length bytes and the number of length bytes
// is equal to & 0x80 (i.e. length byte with high bit off).
bytesread = 0;
eos = false;
// Read all length bytes
if (br < 0) {
eos = true;
break; // EOF
}
}
// end-of-stream reached before length bytes are read
if (eos)
break; // EOF
// Add contents of length bytes to determine length
seqlen = 0;
for( int i = 0; i < seqlenlen; i++) {
}
}
// read in seqlen bytes
/*
if (dump > 0) {
System.err.println("seqlen: " + seqlen);
System.err.println("bufsize: " + offset);
System.err.println("bytesleft: " + bytesleft);
System.err.println("bytesread: " + bytesread);
}
*/
try {
}
boolean needPause = false;
if (inMsgId == 0) {
// Unsolicited Notification
} else {
/**
* Grab pauseLock before making reply available
* to ensure that reader goes into paused state
* before writer can attempt to unpause reader
*/
synchronized (pauseLock) {
if (needPause) {
/*
* Go into paused state; release
* pauseLock
*/
pauseReader();
}
// else release pauseLock
}
} else {
// System.err.println("Cannot find" +
// "LdapRequest for " + inMsgId);
}
}
} catch (Ber.DecodeException e) {
//System.err.println("Cannot parse Ber");
}
} catch (IOException ie) {
if (debug) {
}
if (in != getInputStream()) {
// A new stream to try
// Go to top of loop and continue
} else {
if (debug) {
}
throw ie; // rethrow exception
}
}
}
if (debug) {
+ in);
}
} catch (IOException ex) {
if (debug) {
}
closureReason = ex;
} finally {
}
if (debug) {
}
}
// This code must be uncommented to run the LdapAbandonTest.
/*public void sendSearchReqs(String dn, int numReqs) {
int i;
String attrs[] = null;
for(i = 1; i <= numReqs; i++) {
BerEncoder ber = new BerEncoder(2048);
try {
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeInt(i);
ber.beginSeq(LdapClient.LDAP_REQ_SEARCH);
ber.encodeString(dn == null ? "" : dn);
ber.encodeInt(0, LdapClient.LBER_ENUMERATED);
ber.encodeInt(3, LdapClient.LBER_ENUMERATED);
ber.encodeInt(0);
ber.encodeInt(0);
ber.encodeBoolean(true);
LdapClient.encodeFilter(ber, "");
ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
ber.encodeStringArray(attrs);
ber.endSeq();
ber.endSeq();
ber.endSeq();
writeRequest(ber, i);
//System.err.println("wrote request " + i);
} catch (Exception ex) {
//System.err.println("ldap.search: Caught " + ex + " building req");
}
}
} */
}