Path: blob/master/src/java.naming/share/classes/com/sun/jndi/ldap/Connection.java
41161 views
/*1* Copyright (c) 1999, 2021, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package com.sun.jndi.ldap;2627import java.io.BufferedInputStream;28import java.io.BufferedOutputStream;29import java.io.InterruptedIOException;30import java.io.IOException;31import java.io.OutputStream;32import java.io.InputStream;33import java.net.InetSocketAddress;34import java.net.Socket;35import javax.net.ssl.SSLSocket;3637import javax.naming.CommunicationException;38import javax.naming.ServiceUnavailableException;39import javax.naming.NamingException;40import javax.naming.InterruptedNamingException;4142import javax.naming.ldap.Control;4344import java.lang.reflect.Method;45import java.lang.reflect.InvocationTargetException;46import java.security.AccessController;47import java.security.PrivilegedAction;48import java.security.cert.Certificate;49import java.security.cert.X509Certificate;50import java.util.Arrays;51import java.util.concurrent.CompletableFuture;52import java.util.concurrent.ExecutionException;53import javax.net.SocketFactory;54import javax.net.ssl.SSLParameters;55import javax.net.ssl.HandshakeCompletedEvent;56import javax.net.ssl.HandshakeCompletedListener;57import javax.net.ssl.SSLPeerUnverifiedException;58import javax.security.sasl.SaslException;5960/**61* A thread that creates a connection to an LDAP server.62* After the connection, the thread reads from the connection.63* A caller can invoke methods on the instance to read LDAP responses64* and to send LDAP requests.65* <p>66* There is a one-to-one correspondence between an LdapClient and67* a Connection. Access to Connection and its methods is only via68* LdapClient with two exceptions: SASL authentication and StartTLS.69* SASL needs to access Connection's socket IO streams (in order to do encryption70* of the security layer). StartTLS needs to do replace IO streams71* and close the IO streams on nonfatal close. The code for SASL72* authentication can be treated as being the same as from LdapClient73* because the SASL code is only ever called from LdapClient, from74* inside LdapClient's synchronized authenticate() method. StartTLS is called75* directly by the application but should only occur when the underlying76* connection is quiet.77* <p>78* In terms of synchronization, worry about data structures79* used by the Connection thread because that usage might contend80* with calls by the main threads (i.e., those that call LdapClient).81* Main threads need to worry about contention with each other.82* Fields that Connection thread uses:83* inStream - synced access and update; initialized in constructor;84* referenced outside class unsync'ed (by LdapSasl) only85* when connection is quiet86* traceFile, traceTagIn, traceTagOut - no sync; debugging only87* parent - no sync; initialized in constructor; no updates88* pendingRequests - sync89* pauseLock - per-instance lock;90* paused - sync via pauseLock (pauseReader())91* Members used by main threads (LdapClient):92* host, port - unsync; read-only access for StartTLS and debug messages93* setBound(), setV3() - no sync; called only by LdapClient.authenticate(),94* which is a sync method called only when connection is "quiet"95* getMsgId() - sync96* writeRequest(), removeRequest(),findRequest(), abandonOutstandingReqs() -97* access to shared pendingRequests is sync98* writeRequest(), abandonRequest(), ldapUnbind() - access to outStream sync99* cleanup() - sync100* readReply() - access to sock sync101* unpauseReader() - (indirectly via writeRequest) sync on pauseLock102* Members used by SASL auth (main thread):103* inStream, outStream - no sync; used to construct new stream; accessed104* only when conn is "quiet" and not shared105* replaceStreams() - sync method106* Members used by StartTLS:107* inStream, outStream - no sync; used to record the existing streams;108* accessed only when conn is "quiet" and not shared109* replaceStreams() - sync method110* <p>111* Handles anonymous, simple, and SASL bind for v3; anonymous and simple112* for v2.113* %%% made public for access by LdapSasl %%%114*115* @author Vincent Ryan116* @author Rosanna Lee117* @author Jagane Sundar118*/119public final class Connection implements Runnable {120121private static final boolean debug = false;122private static final int dump = 0; // > 0 r, > 1 rw123124125private final Thread worker; // Initialized in constructor126127private boolean v3 = true; // Set in setV3()128129public final String host; // used by LdapClient for generating exception messages130// used by StartTlsResponse when creating an SSL socket131public final int port; // used by LdapClient for generating exception messages132// used by StartTlsResponse when creating an SSL socket133134private boolean bound = false; // Set in setBound()135136// All three are initialized in constructor and read-only afterwards137private OutputStream traceFile = null;138private String traceTagIn = null;139private String traceTagOut = null;140141// Initialized in constructor; read and used externally (LdapSasl);142// Updated in replaceStreams() during "quiet", unshared, period143public InputStream inStream; // must be public; used by LdapSasl144145// Initialized in constructor; read and used externally (LdapSasl);146// Updated in replaceOutputStream() during "quiet", unshared, period147public OutputStream outStream; // must be public; used by LdapSasl148149// Initialized in constructor; read and used externally (TLS) to150// get new IO streams; closed during cleanup151public Socket sock; // for TLS152153// For processing "disconnect" unsolicited notification154// Initialized in constructor155private final LdapClient parent;156157// Incremented and returned in sync getMsgId()158private int outMsgId = 0;159160//161// The list of ldapRequests pending on this binding162//163// Accessed only within sync methods164private LdapRequest pendingRequests = null;165166volatile IOException closureReason = null;167volatile boolean useable = true; // is Connection still useable168169int readTimeout;170int connectTimeout;171172// Is connection upgraded to SSL via STARTTLS extended operation173private volatile boolean isUpgradedToStartTls;174175// Lock to maintain isUpgradedToStartTls state176final Object startTlsLock = new Object();177178private static final boolean IS_HOSTNAME_VERIFICATION_DISABLED179= hostnameVerificationDisabledValue();180181private static boolean hostnameVerificationDisabledValue() {182PrivilegedAction<String> act = () -> System.getProperty(183"com.sun.jndi.ldap.object.disableEndpointIdentification");184@SuppressWarnings("removal")185String prop = AccessController.doPrivileged(act);186if (prop == null) {187return false;188}189return prop.isEmpty() ? true : Boolean.parseBoolean(prop);190}191// true means v3; false means v2192// Called in LdapClient.authenticate() (which is synchronized)193// when connection is "quiet" and not shared; no need to synchronize194void setV3(boolean v) {195v3 = v;196}197198// A BIND request has been successfully made on this connection199// When cleaning up, remember to do an UNBIND200// Called in LdapClient.authenticate() (which is synchronized)201// when connection is "quiet" and not shared; no need to synchronize202void setBound() {203bound = true;204}205206////////////////////////////////////////////////////////////////////////////207//208// Create an LDAP Binding object and bind to a particular server209//210////////////////////////////////////////////////////////////////////////////211212Connection(LdapClient parent, String host, int port, String socketFactory,213int connectTimeout, int readTimeout, OutputStream trace) throws NamingException {214215this.host = host;216this.port = port;217this.parent = parent;218this.readTimeout = readTimeout;219this.connectTimeout = connectTimeout;220221if (trace != null) {222traceFile = trace;223traceTagIn = "<- " + host + ":" + port + "\n\n";224traceTagOut = "-> " + host + ":" + port + "\n\n";225}226227//228// Connect to server229//230try {231sock = createSocket(host, port, socketFactory, connectTimeout);232233if (debug) {234System.err.println("Connection: opening socket: " + host + "," + port);235}236237inStream = new BufferedInputStream(sock.getInputStream());238outStream = new BufferedOutputStream(sock.getOutputStream());239240} catch (InvocationTargetException e) {241Throwable realException = e.getCause();242// realException.printStackTrace();243244CommunicationException ce =245new CommunicationException(host + ":" + port);246ce.setRootCause(realException);247throw ce;248} catch (Exception e) {249// We need to have a catch all here and250// ignore generic exceptions.251// Also catches all IO errors generated by socket creation.252CommunicationException ce =253new CommunicationException(host + ":" + port);254ce.setRootCause(e);255throw ce;256}257258worker = Obj.helper.createThread(this);259worker.setDaemon(true);260worker.start();261}262263/*264* Create an InetSocketAddress using the specified hostname and port number.265*/266private InetSocketAddress createInetSocketAddress(String host, int port) {267return new InetSocketAddress(host, port);268}269270/*271* Create a Socket object using the specified socket factory and time limit.272*273* If a timeout is supplied and unconnected sockets are supported then274* an unconnected socket is created and the timeout is applied when275* connecting the socket. If a timeout is supplied but unconnected sockets276* are not supported then the timeout is ignored and a connected socket277* is created.278*/279private Socket createSocket(String host, int port, String socketFactory,280int connectTimeout) throws Exception {281282Socket socket = null;283284if (socketFactory != null) {285286// create the factory287288@SuppressWarnings("unchecked")289Class<? extends SocketFactory> socketFactoryClass =290(Class<? extends SocketFactory>)Obj.helper.loadClass(socketFactory);291Method getDefault =292socketFactoryClass.getMethod("getDefault", new Class<?>[]{});293SocketFactory factory = (SocketFactory) getDefault.invoke(null, new Object[]{});294295// create the socket296297if (connectTimeout > 0) {298299InetSocketAddress endpoint =300createInetSocketAddress(host, port);301302// unconnected socket303socket = factory.createSocket();304305if (debug) {306System.err.println("Connection: creating socket with " +307"a timeout using supplied socket factory");308}309310// connected socket311socket.connect(endpoint, connectTimeout);312}313314// continue (but ignore connectTimeout)315if (socket == null) {316if (debug) {317System.err.println("Connection: creating socket using " +318"supplied socket factory");319}320// connected socket321socket = factory.createSocket(host, port);322}323} else {324325if (connectTimeout > 0) {326327InetSocketAddress endpoint = createInetSocketAddress(host, port);328329socket = new Socket();330331if (debug) {332System.err.println("Connection: creating socket with " +333"a timeout");334}335socket.connect(endpoint, connectTimeout);336}337338// continue (but ignore connectTimeout)339340if (socket == null) {341if (debug) {342System.err.println("Connection: creating socket");343}344// connected socket345socket = new Socket(host, port);346}347}348349// For LDAP connect timeouts on LDAP over SSL connections must treat350// the SSL handshake following socket connection as part of the timeout.351// So explicitly set a socket read timeout, trigger the SSL handshake,352// then reset the timeout.353if (socket instanceof SSLSocket) {354SSLSocket sslSocket = (SSLSocket) socket;355if (!IS_HOSTNAME_VERIFICATION_DISABLED) {356SSLParameters param = sslSocket.getSSLParameters();357param.setEndpointIdentificationAlgorithm("LDAPS");358sslSocket.setSSLParameters(param);359}360setHandshakeCompletedListener(sslSocket);361if (connectTimeout > 0) {362int socketTimeout = sslSocket.getSoTimeout();363sslSocket.setSoTimeout(connectTimeout); // reuse full timeout value364sslSocket.startHandshake();365sslSocket.setSoTimeout(socketTimeout);366}367}368return socket;369}370371////////////////////////////////////////////////////////////////////////////372//373// Methods to IO to the LDAP server374//375////////////////////////////////////////////////////////////////////////////376377synchronized int getMsgId() {378return ++outMsgId;379}380381LdapRequest writeRequest(BerEncoder ber, int msgId) throws IOException {382return writeRequest(ber, msgId, false /* pauseAfterReceipt */, -1);383}384385LdapRequest writeRequest(BerEncoder ber, int msgId,386boolean pauseAfterReceipt) throws IOException {387return writeRequest(ber, msgId, pauseAfterReceipt, -1);388}389390LdapRequest writeRequest(BerEncoder ber, int msgId,391boolean pauseAfterReceipt, int replyQueueCapacity) throws IOException {392393LdapRequest req =394new LdapRequest(msgId, pauseAfterReceipt, replyQueueCapacity);395addRequest(req);396397if (traceFile != null) {398Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0, ber.getDataLen());399}400401402// unpause reader so that it can get response403// NOTE: Must do this before writing request, otherwise might404// create a race condition where the writer unblocks its own response405unpauseReader();406407if (debug) {408System.err.println("Writing request to: " + outStream);409}410411try {412synchronized (this) {413outStream.write(ber.getBuf(), 0, ber.getDataLen());414outStream.flush();415}416} catch (IOException e) {417cleanup(null, true);418throw (closureReason = e); // rethrow419}420421return req;422}423424/**425* Reads a reply; waits until one is ready.426*/427BerDecoder readReply(LdapRequest ldr) throws IOException, NamingException {428BerDecoder rber;429430// If socket closed, don't even try431synchronized (this) {432if (sock == null) {433throw new ServiceUnavailableException(host + ":" + port +434"; socket closed");435}436}437438NamingException namingException = null;439try {440// if no timeout is set so we wait infinitely until441// a response is received OR until the connection is closed or cancelled442// http://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-ldap.html#PROP443rber = ldr.getReplyBer(readTimeout);444} catch (InterruptedException ex) {445throw new InterruptedNamingException(446"Interrupted during LDAP operation");447} catch (CommunicationException ce) {448// Re-throw449throw ce;450} catch (NamingException ne) {451// Connection is timed out OR closed/cancelled452namingException = ne;453rber = null;454}455456if (rber == null) {457abandonRequest(ldr, null);458}459// namingException can be not null in the following cases:460// a) The response is timed-out461// b) LDAP request connection has been closed or cancelled462// The exception message is initialized in LdapRequest::getReplyBer463if (namingException != null) {464// Re-throw NamingException after all cleanups are done465throw namingException;466}467return rber;468}469470////////////////////////////////////////////////////////////////////////////471//472// Methods to add, find, delete, and abandon requests made to server473//474////////////////////////////////////////////////////////////////////////////475476private synchronized void addRequest(LdapRequest ldapRequest) {477478LdapRequest ldr = pendingRequests;479if (ldr == null) {480pendingRequests = ldapRequest;481ldapRequest.next = null;482} else {483ldapRequest.next = pendingRequests;484pendingRequests = ldapRequest;485}486}487488synchronized LdapRequest findRequest(int msgId) {489490LdapRequest ldr = pendingRequests;491while (ldr != null) {492if (ldr.msgId == msgId) {493return ldr;494}495ldr = ldr.next;496}497return null;498499}500501synchronized void removeRequest(LdapRequest req) {502LdapRequest ldr = pendingRequests;503LdapRequest ldrprev = null;504505while (ldr != null) {506if (ldr == req) {507ldr.cancel();508509if (ldrprev != null) {510ldrprev.next = ldr.next;511} else {512pendingRequests = ldr.next;513}514ldr.next = null;515}516ldrprev = ldr;517ldr = ldr.next;518}519}520521void abandonRequest(LdapRequest ldr, Control[] reqCtls) {522// Remove from queue523removeRequest(ldr);524525BerEncoder ber = new BerEncoder(256);526int abandonMsgId = getMsgId();527528//529// build the abandon request.530//531try {532ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);533ber.encodeInt(abandonMsgId);534ber.encodeInt(ldr.msgId, LdapClient.LDAP_REQ_ABANDON);535536if (v3) {537LdapClient.encodeControls(ber, reqCtls);538}539ber.endSeq();540541if (traceFile != null) {542Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0,543ber.getDataLen());544}545546synchronized (this) {547outStream.write(ber.getBuf(), 0, ber.getDataLen());548outStream.flush();549}550551} catch (IOException ex) {552//System.err.println("ldap.abandon: " + ex);553}554555// Don't expect any response for the abandon request.556}557558synchronized void abandonOutstandingReqs(Control[] reqCtls) {559LdapRequest ldr = pendingRequests;560561while (ldr != null) {562abandonRequest(ldr, reqCtls);563pendingRequests = ldr = ldr.next;564}565}566567////////////////////////////////////////////////////////////////////////////568//569// Methods to unbind from server and clear up resources when object is570// destroyed.571//572////////////////////////////////////////////////////////////////////////////573574private void ldapUnbind(Control[] reqCtls) {575576BerEncoder ber = new BerEncoder(256);577int unbindMsgId = getMsgId();578579//580// build the unbind request.581//582583try {584585ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);586ber.encodeInt(unbindMsgId);587// IMPLICIT TAGS588ber.encodeByte(LdapClient.LDAP_REQ_UNBIND);589ber.encodeByte(0);590591if (v3) {592LdapClient.encodeControls(ber, reqCtls);593}594ber.endSeq();595596if (traceFile != null) {597Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(),5980, ber.getDataLen());599}600601synchronized (this) {602outStream.write(ber.getBuf(), 0, ber.getDataLen());603outStream.flush();604}605606} catch (IOException ex) {607//System.err.println("ldap.unbind: " + ex);608}609610// Don't expect any response for the unbind request.611}612613/**614* @param reqCtls Possibly null request controls that accompanies the615* abandon and unbind LDAP request.616* @param notifyParent true means to call parent LdapClient back, notifying617* it that the connection has been closed; false means not to notify618* parent. If LdapClient invokes cleanup(), notifyParent should be set to619* false because LdapClient already knows that it is closing620* the connection. If Connection invokes cleanup(), notifyParent should be621* set to true because LdapClient needs to know about the closure.622*/623void cleanup(Control[] reqCtls, boolean notifyParent) {624boolean nparent = false;625626synchronized (this) {627useable = false;628629if (sock != null) {630if (debug) {631System.err.println("Connection: closing socket: " + host + "," + port);632}633try {634if (!notifyParent) {635abandonOutstandingReqs(reqCtls);636}637if (bound) {638ldapUnbind(reqCtls);639}640} finally {641try {642outStream.flush();643sock.close();644unpauseReader();645} catch (IOException ie) {646if (debug)647System.err.println("Connection: problem closing socket: " + ie);648}649if (!notifyParent) {650LdapRequest ldr = pendingRequests;651while (ldr != null) {652ldr.cancel();653ldr = ldr.next;654}655}656if (isTlsConnection() && tlsHandshakeListener != null) {657if (closureReason != null) {658CommunicationException ce = new CommunicationException();659ce.setRootCause(closureReason);660tlsHandshakeListener.tlsHandshakeCompleted.completeExceptionally(ce);661} else {662tlsHandshakeListener.tlsHandshakeCompleted.cancel(false);663}664}665sock = null;666}667nparent = notifyParent;668}669if (nparent) {670LdapRequest ldr = pendingRequests;671while (ldr != null) {672ldr.close();673ldr = ldr.next;674}675}676}677if (nparent) {678parent.processConnectionClosure();679}680}681682683// Assume everything is "quiet"684// "synchronize" might lead to deadlock so don't synchronize method685// Use streamLock instead for synchronizing update to stream686687synchronized public void replaceStreams(InputStream newIn, OutputStream newOut) {688if (debug) {689System.err.println("Replacing " + inStream + " with: " + newIn);690System.err.println("Replacing " + outStream + " with: " + newOut);691}692693inStream = newIn;694695// Cleanup old stream696try {697outStream.flush();698} catch (IOException ie) {699if (debug)700System.err.println("Connection: cannot flush outstream: " + ie);701}702703// Replace stream704outStream = newOut;705}706707/*708* Replace streams and set isUpdradedToStartTls flag to the provided value709*/710synchronized public void replaceStreams(InputStream newIn, OutputStream newOut, boolean isStartTls) {711synchronized (startTlsLock) {712replaceStreams(newIn, newOut);713isUpgradedToStartTls = isStartTls;714}715}716717/*718* Returns true if connection was upgraded to SSL with STARTTLS extended operation719*/720public boolean isUpgradedToStartTls() {721return isUpgradedToStartTls;722}723724/**725* Used by Connection thread to read inStream into a local variable.726* This ensures that there is no contention between the main thread727* and the Connection thread when the main thread updates inStream.728*/729synchronized private InputStream getInputStream() {730return inStream;731}732733734////////////////////////////////////////////////////////////////////////////735//736// Code for pausing/unpausing the reader thread ('worker')737//738////////////////////////////////////////////////////////////////////////////739740/*741* The main idea is to mark requests that need the reader thread to742* pause after getting the response. When the reader thread gets the response,743* it waits on a lock instead of returning to the read(). The next time a744* request is sent, the reader is automatically unblocked if necessary.745* Note that the reader must be unblocked BEFORE the request is sent.746* Otherwise, there is a race condition where the request is sent and747* the reader thread might read the response and be unblocked748* by writeRequest().749*750* This pause gives the main thread (StartTLS or SASL) an opportunity to751* update the reader's state (e.g., its streams) if necessary.752* The assumption is that the connection will remain quiet during this pause753* (i.e., no intervening requests being sent).754*<p>755* For dealing with StartTLS close,756* when the read() exits either due to EOF or an exception,757* the reader thread checks whether there is a new stream to read from.758* If so, then it reattempts the read. Otherwise, the EOF or exception759* is processed and the reader thread terminates.760* In a StartTLS close, the client first replaces the SSL IO streams with761* plain ones and then closes the SSL socket.762* If the reader thread attempts to read, or was reading, from763* the SSL socket (that is, it got to the read BEFORE replaceStreams()),764* the SSL socket close will cause the reader thread to765* get an EOF/exception and reexamine the input stream.766* If the reader thread sees a new stream, it reattempts the read.767* If the underlying socket is still alive, then the new read will succeed.768* If the underlying socket has been closed also, then the new read will769* fail and the reader thread exits.770* If the reader thread attempts to read, or was reading, from the plain771* socket (that is, it got to the read AFTER replaceStreams()), the772* SSL socket close will have no effect on the reader thread.773*774* The check for new stream is made only775* in the first attempt at reading a BER buffer; the reader should776* never be in midst of reading a buffer when a nonfatal close occurs.777* If this occurs, then the connection is in an inconsistent state and778* the safest thing to do is to shut it down.779*/780781private final Object pauseLock = new Object(); // lock for reader to wait on while paused782private boolean paused = false; // paused state of reader783784/*785* Unpauses reader thread if it was paused786*/787private void unpauseReader() throws IOException {788synchronized (pauseLock) {789if (paused) {790if (debug) {791System.err.println("Unpausing reader; read from: " +792inStream);793}794paused = false;795pauseLock.notify();796}797}798}799800/*801* Pauses reader so that it stops reading from the input stream.802* Reader blocks on pauseLock instead of read().803* MUST be called from within synchronized (pauseLock) clause.804*/805private void pauseReader() throws IOException {806if (debug) {807System.err.println("Pausing reader; was reading from: " +808inStream);809}810paused = true;811try {812while (paused) {813pauseLock.wait(); // notified by unpauseReader814}815} catch (InterruptedException e) {816throw new InterruptedIOException(817"Pause/unpause reader has problems.");818}819}820821822////////////////////////////////////////////////////////////////////////////823//824// The LDAP Binding thread. It does the mux/demux of multiple requests825// on the same TCP connection.826//827////////////////////////////////////////////////////////////////////////////828829830public void run() {831byte inbuf[]; // Buffer for reading incoming bytes832int inMsgId; // Message id of incoming response833int bytesread; // Number of bytes in inbuf834int br; // Temp; number of bytes read from stream835int offset; // Offset of where to store bytes in inbuf836int seqlen; // Length of ASN sequence837int seqlenlen; // Number of sequence length bytes838boolean eos; // End of stream839BerDecoder retBer; // Decoder for ASN.1 BER data from inbuf840InputStream in = null;841842try {843while (true) {844try {845// type and length (at most 128 octets for long form)846inbuf = new byte[129];847848offset = 0;849seqlen = 0;850seqlenlen = 0;851852in = getInputStream();853854// check that it is the beginning of a sequence855bytesread = in.read(inbuf, offset, 1);856if (bytesread < 0) {857if (in != getInputStream()) {858continue; // a new stream to try859} else {860break; // EOF861}862}863864if (inbuf[offset++] != (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR))865continue;866867// get length of sequence868bytesread = in.read(inbuf, offset, 1);869if (bytesread < 0)870break; // EOF871seqlen = inbuf[offset++];872873// if high bit is on, length is encoded in the874// subsequent length bytes and the number of length bytes875// is equal to & 0x80 (i.e. length byte with high bit off).876if ((seqlen & 0x80) == 0x80) {877seqlenlen = seqlen & 0x7f; // number of length bytes878// Check the length of length field, since seqlen is int879// the number of bytes can't be greater than 4880if (seqlenlen > 4) {881throw new IOException("Length coded with too many bytes: " + seqlenlen);882}883884bytesread = 0;885eos = false;886887// Read all length bytes888while (bytesread < seqlenlen) {889br = in.read(inbuf, offset+bytesread,890seqlenlen-bytesread);891if (br < 0) {892eos = true;893break; // EOF894}895bytesread += br;896}897898// end-of-stream reached before length bytes are read899if (eos)900break; // EOF901902// Add contents of length bytes to determine length903seqlen = 0;904for( int i = 0; i < seqlenlen; i++) {905seqlen = (seqlen << 8) + (inbuf[offset+i] & 0xff);906}907offset += bytesread;908}909910if (seqlenlen > bytesread) {911throw new IOException("Unexpected EOF while reading length");912}913914if (seqlen < 0) {915throw new IOException("Length too big: " + (((long) seqlen) & 0xFFFFFFFFL));916}917// read in seqlen bytes918byte[] left = readFully(in, seqlen);919inbuf = Arrays.copyOf(inbuf, offset + left.length);920System.arraycopy(left, 0, inbuf, offset, left.length);921offset += left.length;922923try {924retBer = new BerDecoder(inbuf, 0, offset);925926if (traceFile != null) {927Ber.dumpBER(traceFile, traceTagIn, inbuf, 0, offset);928}929930retBer.parseSeq(null);931inMsgId = retBer.parseInt();932retBer.reset(); // reset offset933934boolean needPause = false;935936if (inMsgId == 0) {937// Unsolicited Notification938parent.processUnsolicited(retBer);939} else {940LdapRequest ldr = findRequest(inMsgId);941942if (ldr != null) {943944/**945* Grab pauseLock before making reply available946* to ensure that reader goes into paused state947* before writer can attempt to unpause reader948*/949synchronized (pauseLock) {950needPause = ldr.addReplyBer(retBer);951if (needPause) {952/*953* Go into paused state; release954* pauseLock955*/956pauseReader();957}958959// else release pauseLock960}961} else {962// System.err.println("Cannot find" +963// "LdapRequest for " + inMsgId);964}965}966} catch (Ber.DecodeException e) {967//System.err.println("Cannot parse Ber");968}969} catch (IOException ie) {970if (debug) {971System.err.println("Connection: Inside Caught " + ie);972ie.printStackTrace();973}974975if (in != getInputStream()) {976// A new stream to try977// Go to top of loop and continue978} else {979if (debug) {980System.err.println("Connection: rethrowing " + ie);981}982throw ie; // rethrow exception983}984}985}986987if (debug) {988System.err.println("Connection: end-of-stream detected: "989+ in);990}991} catch (IOException ex) {992if (debug) {993System.err.println("Connection: Caught " + ex);994}995closureReason = ex;996} finally {997cleanup(null, true); // cleanup998}999if (debug) {1000System.err.println("Connection: Thread Exiting");1001}1002}10031004private static byte[] readFully(InputStream is, int length)1005throws IOException1006{1007byte[] buf = new byte[Math.min(length, 8192)];1008int nread = 0;1009while (nread < length) {1010int bytesToRead;1011if (nread >= buf.length) { // need to allocate a larger buffer1012bytesToRead = Math.min(length - nread, buf.length + 8192);1013if (buf.length < nread + bytesToRead) {1014buf = Arrays.copyOf(buf, nread + bytesToRead);1015}1016} else {1017bytesToRead = buf.length - nread;1018}1019int count = is.read(buf, nread, bytesToRead);1020if (count < 0) {1021if (buf.length != nread)1022buf = Arrays.copyOf(buf, nread);1023break;1024}1025nread += count;1026}1027return buf;1028}10291030public boolean isTlsConnection() {1031return (sock instanceof SSLSocket) || isUpgradedToStartTls;1032}10331034/*1035* tlsHandshakeListener can be created for initial secure connection1036* and updated by StartTLS extended operation. It is used later by LdapClient1037* to create TLS Channel Binding data on the base of TLS server certificate1038*/1039private volatile HandshakeListener tlsHandshakeListener;10401041synchronized public void setHandshakeCompletedListener(SSLSocket sslSocket) {1042if (tlsHandshakeListener != null)1043tlsHandshakeListener.tlsHandshakeCompleted.cancel(false);10441045tlsHandshakeListener = new HandshakeListener();1046sslSocket.addHandshakeCompletedListener(tlsHandshakeListener);1047}10481049public X509Certificate getTlsServerCertificate()1050throws SaslException {1051try {1052if (isTlsConnection() && tlsHandshakeListener != null)1053return tlsHandshakeListener.tlsHandshakeCompleted.get();1054} catch (InterruptedException iex) {1055throw new SaslException("TLS Handshake Exception ", iex);1056} catch (ExecutionException eex) {1057throw new SaslException("TLS Handshake Exception ", eex.getCause());1058}1059return null;1060}10611062private class HandshakeListener implements HandshakeCompletedListener {10631064private final CompletableFuture<X509Certificate> tlsHandshakeCompleted =1065new CompletableFuture<>();1066@Override1067public void handshakeCompleted(HandshakeCompletedEvent event) {1068try {1069X509Certificate tlsServerCert = null;1070Certificate[] certs;1071if (event.getSocket().getUseClientMode()) {1072certs = event.getPeerCertificates();1073} else {1074certs = event.getLocalCertificates();1075}1076if (certs != null && certs.length > 0 &&1077certs[0] instanceof X509Certificate) {1078tlsServerCert = (X509Certificate) certs[0];1079}1080tlsHandshakeCompleted.complete(tlsServerCert);1081} catch (SSLPeerUnverifiedException ex) {1082CommunicationException ce = new CommunicationException();1083ce.setRootCause(closureReason);1084tlsHandshakeCompleted.completeExceptionally(ex);1085}1086}1087}1088}108910901091