Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/com/sun/jndi/ldap/Connection.java
38924 views
/*1* Copyright (c) 1999, 2020, 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.IOException;30import java.io.InputStream;31import java.io.InterruptedIOException;32import java.io.OutputStream;33import java.lang.reflect.Constructor;34import java.lang.reflect.InvocationTargetException;35import java.lang.reflect.Method;36import java.net.Socket;37import java.security.AccessController;38import java.security.PrivilegedAction;39import java.util.Arrays;4041import javax.naming.CommunicationException;42import javax.naming.InterruptedNamingException;43import javax.naming.NamingException;44import javax.naming.ServiceUnavailableException;45import javax.naming.ldap.Control;46import javax.net.ssl.SSLParameters;47import javax.net.ssl.SSLSocket;4849/**50* A thread that creates a connection to an LDAP server.51* After the connection, the thread reads from the connection.52* A caller can invoke methods on the instance to read LDAP responses53* and to send LDAP requests.54* <p>55* There is a one-to-one correspondence between an LdapClient and56* a Connection. Access to Connection and its methods is only via57* LdapClient with two exceptions: SASL authentication and StartTLS.58* SASL needs to access Connection's socket IO streams (in order to do encryption59* of the security layer). StartTLS needs to do replace IO streams60* and close the IO streams on nonfatal close. The code for SASL61* authentication can be treated as being the same as from LdapClient62* because the SASL code is only ever called from LdapClient, from63* inside LdapClient's synchronized authenticate() method. StartTLS is called64* directly by the application but should only occur when the underlying65* connection is quiet.66* <p>67* In terms of synchronization, worry about data structures68* used by the Connection thread because that usage might contend69* with calls by the main threads (i.e., those that call LdapClient).70* Main threads need to worry about contention with each other.71* Fields that Connection thread uses:72* inStream - synced access and update; initialized in constructor;73* referenced outside class unsync'ed (by LdapSasl) only74* when connection is quiet75* traceFile, traceTagIn, traceTagOut - no sync; debugging only76* parent - no sync; initialized in constructor; no updates77* pendingRequests - sync78* pauseLock - per-instance lock;79* paused - sync via pauseLock (pauseReader())80* Members used by main threads (LdapClient):81* host, port - unsync; read-only access for StartTLS and debug messages82* setBound(), setV3() - no sync; called only by LdapClient.authenticate(),83* which is a sync method called only when connection is "quiet"84* getMsgId() - sync85* writeRequest(), removeRequest(),findRequest(), abandonOutstandingReqs() -86* access to shared pendingRequests is sync87* writeRequest(), abandonRequest(), ldapUnbind() - access to outStream sync88* cleanup() - sync89* readReply() - access to sock sync90* unpauseReader() - (indirectly via writeRequest) sync on pauseLock91* Members used by SASL auth (main thread):92* inStream, outStream - no sync; used to construct new stream; accessed93* only when conn is "quiet" and not shared94* replaceStreams() - sync method95* Members used by StartTLS:96* inStream, outStream - no sync; used to record the existing streams;97* accessed only when conn is "quiet" and not shared98* replaceStreams() - sync method99* <p>100* Handles anonymous, simple, and SASL bind for v3; anonymous and simple101* for v2.102* %%% made public for access by LdapSasl %%%103*104* @author Vincent Ryan105* @author Rosanna Lee106* @author Jagane Sundar107*/108public final class Connection implements Runnable {109110private static final boolean debug = false;111private static final int dump = 0; // > 0 r, > 1 rw112113114final private Thread worker; // Initialized in constructor115116private boolean v3 = true; // Set in setV3()117118final public String host; // used by LdapClient for generating exception messages119// used by StartTlsResponse when creating an SSL socket120final public int port; // used by LdapClient for generating exception messages121// used by StartTlsResponse when creating an SSL socket122123private boolean bound = false; // Set in setBound()124125// All three are initialized in constructor and read-only afterwards126private OutputStream traceFile = null;127private String traceTagIn = null;128private String traceTagOut = null;129130// Initialized in constructor; read and used externally (LdapSasl);131// Updated in replaceStreams() during "quiet", unshared, period132public InputStream inStream; // must be public; used by LdapSasl133134// Initialized in constructor; read and used externally (LdapSasl);135// Updated in replaceOutputStream() during "quiet", unshared, period136public OutputStream outStream; // must be public; used by LdapSasl137138// Initialized in constructor; read and used externally (TLS) to139// get new IO streams; closed during cleanup140public Socket sock; // for TLS141142// For processing "disconnect" unsolicited notification143// Initialized in constructor144final private LdapClient parent;145146// Incremented and returned in sync getMsgId()147private int outMsgId = 0;148149//150// The list of ldapRequests pending on this binding151//152// Accessed only within sync methods153private LdapRequest pendingRequests = null;154155volatile IOException closureReason = null;156volatile boolean useable = true; // is Connection still useable157158int readTimeout;159int connectTimeout;160161// Is connection upgraded to SSL via STARTTLS extended operation162private volatile boolean isUpgradedToStartTls;163164// Lock to maintain isUpgradedToStartTls state165final Object startTlsLock = new Object();166167private static final boolean IS_HOSTNAME_VERIFICATION_DISABLED168= hostnameVerificationDisabledValue();169170private static boolean hostnameVerificationDisabledValue() {171PrivilegedAction<String> act = () -> System.getProperty(172"com.sun.jndi.ldap.object.disableEndpointIdentification");173String prop = AccessController.doPrivileged(act);174if (prop == null) {175return false;176}177return prop.isEmpty() ? true : Boolean.parseBoolean(prop);178}179// true means v3; false means v2180// Called in LdapClient.authenticate() (which is synchronized)181// when connection is "quiet" and not shared; no need to synchronize182void setV3(boolean v) {183v3 = v;184}185186// A BIND request has been successfully made on this connection187// When cleaning up, remember to do an UNBIND188// Called in LdapClient.authenticate() (which is synchronized)189// when connection is "quiet" and not shared; no need to synchronize190void setBound() {191bound = true;192}193194////////////////////////////////////////////////////////////////////////////195//196// Create an LDAP Binding object and bind to a particular server197//198////////////////////////////////////////////////////////////////////////////199200Connection(LdapClient parent, String host, int port, String socketFactory,201int connectTimeout, int readTimeout, OutputStream trace) throws NamingException {202203this.host = host;204this.port = port;205this.parent = parent;206this.readTimeout = readTimeout;207this.connectTimeout = connectTimeout;208209if (trace != null) {210traceFile = trace;211traceTagIn = "<- " + host + ":" + port + "\n\n";212traceTagOut = "-> " + host + ":" + port + "\n\n";213}214215//216// Connect to server217//218try {219sock = createSocket(host, port, socketFactory, connectTimeout);220221if (debug) {222System.err.println("Connection: opening socket: " + host + "," + port);223}224225inStream = new BufferedInputStream(sock.getInputStream());226outStream = new BufferedOutputStream(sock.getOutputStream());227228} catch (InvocationTargetException e) {229Throwable realException = e.getTargetException();230// realException.printStackTrace();231232CommunicationException ce =233new CommunicationException(host + ":" + port);234ce.setRootCause(realException);235throw ce;236} catch (Exception e) {237// Class.forName() seems to do more error checking238// and will throw IllegalArgumentException and such.239// That's why we need to have a catch all here and240// ignore generic exceptions.241// Also catches all IO errors generated by socket creation.242CommunicationException ce =243new CommunicationException(host + ":" + port);244ce.setRootCause(e);245throw ce;246}247248worker = Obj.helper.createThread(this);249worker.setDaemon(true);250worker.start();251}252253/*254* Create an InetSocketAddress using the specified hostname and port number.255*/256private Object createInetSocketAddress(String host, int port)257throws NoSuchMethodException {258259try {260Class<?> inetSocketAddressClass =261Class.forName("java.net.InetSocketAddress");262263Constructor<?> inetSocketAddressCons =264inetSocketAddressClass.getConstructor(new Class<?>[]{265String.class, int.class});266267return inetSocketAddressCons.newInstance(new Object[]{268host, new Integer(port)});269270} catch (ClassNotFoundException |271InstantiationException |272InvocationTargetException |273IllegalAccessException e) {274throw new NoSuchMethodException();275276}277}278279/*280* Create a Socket object using the specified socket factory and time limit.281*282* If a timeout is supplied and unconnected sockets are supported then283* an unconnected socket is created and the timeout is applied when284* connecting the socket. If a timeout is supplied but unconnected sockets285* are not supported then the timeout is ignored and a connected socket286* is created.287*/288private Socket createSocket(String host, int port, String socketFactory,289int connectTimeout) throws Exception {290291Socket socket = null;292293if (socketFactory != null) {294295// create the factory296297Class<?> socketFactoryClass = Obj.helper.loadClass(socketFactory);298Method getDefault =299socketFactoryClass.getMethod("getDefault", new Class<?>[]{});300Object factory = getDefault.invoke(null, new Object[]{});301302// create the socket303304Method createSocket = null;305306if (connectTimeout > 0) {307308try {309createSocket = socketFactoryClass.getMethod("createSocket",310new Class<?>[]{});311312Method connect = Socket.class.getMethod("connect",313new Class<?>[]{Class.forName("java.net.SocketAddress"),314int.class});315Object endpoint = createInetSocketAddress(host, port);316317// unconnected socket318socket =319(Socket)createSocket.invoke(factory, new Object[]{});320321if (debug) {322System.err.println("Connection: creating socket with " +323"a timeout using supplied socket factory");324}325326// connected socket327connect.invoke(socket, new Object[]{328endpoint, new Integer(connectTimeout)});329330} catch (NoSuchMethodException e) {331// continue (but ignore connectTimeout)332}333}334335if (socket == null) {336createSocket = socketFactoryClass.getMethod("createSocket",337new Class<?>[]{String.class, int.class});338339if (debug) {340System.err.println("Connection: creating socket using " +341"supplied socket factory");342}343// connected socket344socket = (Socket) createSocket.invoke(factory,345new Object[]{host, new Integer(port)});346}347} else {348349if (connectTimeout > 0) {350351try {352Constructor<Socket> socketCons =353Socket.class.getConstructor(new Class<?>[]{});354355Method connect = Socket.class.getMethod("connect",356new Class<?>[]{Class.forName("java.net.SocketAddress"),357int.class});358Object endpoint = createInetSocketAddress(host, port);359360socket = socketCons.newInstance(new Object[]{});361362if (debug) {363System.err.println("Connection: creating socket with " +364"a timeout");365}366connect.invoke(socket, new Object[]{367endpoint, new Integer(connectTimeout)});368369} catch (NoSuchMethodException e) {370// continue (but ignore connectTimeout)371}372}373374if (socket == null) {375if (debug) {376System.err.println("Connection: creating socket");377}378// connected socket379socket = new Socket(host, port);380}381}382383// For LDAP connect timeouts on LDAP over SSL connections must treat384// the SSL handshake following socket connection as part of the timeout.385// So explicitly set a socket read timeout, trigger the SSL handshake,386// then reset the timeout.387if (socket instanceof SSLSocket) {388SSLSocket sslSocket = (SSLSocket) socket;389if (!IS_HOSTNAME_VERIFICATION_DISABLED) {390SSLParameters param = sslSocket.getSSLParameters();391param.setEndpointIdentificationAlgorithm("LDAPS");392sslSocket.setSSLParameters(param);393}394if (connectTimeout > 0) {395int socketTimeout = sslSocket.getSoTimeout();396sslSocket.setSoTimeout(connectTimeout); // reuse full timeout value397sslSocket.startHandshake();398sslSocket.setSoTimeout(socketTimeout);399}400}401return socket;402}403404////////////////////////////////////////////////////////////////////////////405//406// Methods to IO to the LDAP server407//408////////////////////////////////////////////////////////////////////////////409410synchronized int getMsgId() {411return ++outMsgId;412}413414LdapRequest writeRequest(BerEncoder ber, int msgId) throws IOException {415return writeRequest(ber, msgId, false /* pauseAfterReceipt */, -1);416}417418LdapRequest writeRequest(BerEncoder ber, int msgId,419boolean pauseAfterReceipt) throws IOException {420return writeRequest(ber, msgId, pauseAfterReceipt, -1);421}422423LdapRequest writeRequest(BerEncoder ber, int msgId,424boolean pauseAfterReceipt, int replyQueueCapacity) throws IOException {425426LdapRequest req =427new LdapRequest(msgId, pauseAfterReceipt, replyQueueCapacity);428addRequest(req);429430if (traceFile != null) {431Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0, ber.getDataLen());432}433434435// unpause reader so that it can get response436// NOTE: Must do this before writing request, otherwise might437// create a race condition where the writer unblocks its own response438unpauseReader();439440if (debug) {441System.err.println("Writing request to: " + outStream);442}443444try {445synchronized (this) {446outStream.write(ber.getBuf(), 0, ber.getDataLen());447outStream.flush();448}449} catch (IOException e) {450cleanup(null, true);451throw (closureReason = e); // rethrow452}453454return req;455}456457/**458* Reads a reply; waits until one is ready.459*/460BerDecoder readReply(LdapRequest ldr) throws IOException, NamingException {461BerDecoder rber;462463NamingException namingException = null;464try {465// if no timeout is set so we wait infinitely until466// a response is received OR until the connection is closed or cancelled467// http://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-ldap.html#PROP468rber = ldr.getReplyBer(readTimeout);469} catch (InterruptedException ex) {470throw new InterruptedNamingException(471"Interrupted during LDAP operation");472} catch (CommunicationException ce) {473// Re-throw474throw ce;475} catch (NamingException ne) {476// Connection is timed out OR closed/cancelled477namingException = ne;478rber = null;479}480481if (rber == null) {482abandonRequest(ldr, null);483}484// namingException can be not null in the following cases:485// a) The response is timed-out486// b) LDAP request connection has been closed or cancelled487// The exception message is initialized in LdapRequest::getReplyBer488if (namingException != null) {489// Re-throw NamingException after all cleanups are done490throw namingException;491}492return rber;493}494495////////////////////////////////////////////////////////////////////////////496//497// Methods to add, find, delete, and abandon requests made to server498//499////////////////////////////////////////////////////////////////////////////500501private synchronized void addRequest(LdapRequest ldapRequest) {502503LdapRequest ldr = pendingRequests;504if (ldr == null) {505pendingRequests = ldapRequest;506ldapRequest.next = null;507} else {508ldapRequest.next = pendingRequests;509pendingRequests = ldapRequest;510}511}512513synchronized LdapRequest findRequest(int msgId) {514515LdapRequest ldr = pendingRequests;516while (ldr != null) {517if (ldr.msgId == msgId) {518return ldr;519}520ldr = ldr.next;521}522return null;523524}525526synchronized void removeRequest(LdapRequest req) {527LdapRequest ldr = pendingRequests;528LdapRequest ldrprev = null;529530while (ldr != null) {531if (ldr == req) {532ldr.cancel();533534if (ldrprev != null) {535ldrprev.next = ldr.next;536} else {537pendingRequests = ldr.next;538}539ldr.next = null;540}541ldrprev = ldr;542ldr = ldr.next;543}544}545546void abandonRequest(LdapRequest ldr, Control[] reqCtls) {547// Remove from queue548removeRequest(ldr);549550BerEncoder ber = new BerEncoder(256);551int abandonMsgId = getMsgId();552553//554// build the abandon request.555//556try {557ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);558ber.encodeInt(abandonMsgId);559ber.encodeInt(ldr.msgId, LdapClient.LDAP_REQ_ABANDON);560561if (v3) {562LdapClient.encodeControls(ber, reqCtls);563}564ber.endSeq();565566if (traceFile != null) {567Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0,568ber.getDataLen());569}570571synchronized (this) {572outStream.write(ber.getBuf(), 0, ber.getDataLen());573outStream.flush();574}575576} catch (IOException ex) {577//System.err.println("ldap.abandon: " + ex);578}579580// Don't expect any response for the abandon request.581}582583synchronized void abandonOutstandingReqs(Control[] reqCtls) {584LdapRequest ldr = pendingRequests;585586while (ldr != null) {587abandonRequest(ldr, reqCtls);588pendingRequests = ldr = ldr.next;589}590}591592////////////////////////////////////////////////////////////////////////////593//594// Methods to unbind from server and clear up resources when object is595// destroyed.596//597////////////////////////////////////////////////////////////////////////////598599private void ldapUnbind(Control[] reqCtls) {600601BerEncoder ber = new BerEncoder(256);602int unbindMsgId = getMsgId();603604//605// build the unbind request.606//607608try {609610ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);611ber.encodeInt(unbindMsgId);612// IMPLICIT TAGS613ber.encodeByte(LdapClient.LDAP_REQ_UNBIND);614ber.encodeByte(0);615616if (v3) {617LdapClient.encodeControls(ber, reqCtls);618}619ber.endSeq();620621if (traceFile != null) {622Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(),6230, ber.getDataLen());624}625626synchronized (this) {627outStream.write(ber.getBuf(), 0, ber.getDataLen());628outStream.flush();629}630631} catch (IOException ex) {632//System.err.println("ldap.unbind: " + ex);633}634635// Don't expect any response for the unbind request.636}637638/**639* @param reqCtls Possibly null request controls that accompanies the640* abandon and unbind LDAP request.641* @param notifyParent true means to call parent LdapClient back, notifying642* it that the connection has been closed; false means not to notify643* parent. If LdapClient invokes cleanup(), notifyParent should be set to644* false because LdapClient already knows that it is closing645* the connection. If Connection invokes cleanup(), notifyParent should be646* set to true because LdapClient needs to know about the closure.647*/648void cleanup(Control[] reqCtls, boolean notifyParent) {649boolean nparent = false;650651synchronized (this) {652useable = false;653654if (sock != null) {655if (debug) {656System.err.println("Connection: closing socket: " + host + "," + port);657}658try {659if (!notifyParent) {660abandonOutstandingReqs(reqCtls);661}662if (bound) {663ldapUnbind(reqCtls);664}665} finally {666try {667outStream.flush();668sock.close();669unpauseReader();670} catch (IOException ie) {671if (debug)672System.err.println("Connection: problem closing socket: " + ie);673}674if (!notifyParent) {675LdapRequest ldr = pendingRequests;676while (ldr != null) {677ldr.cancel();678ldr = ldr.next;679}680}681sock = null;682}683nparent = notifyParent;684}685if (nparent) {686LdapRequest ldr = pendingRequests;687while (ldr != null) {688ldr.close();689ldr = ldr.next;690}691}692}693if (nparent) {694parent.processConnectionClosure();695}696}697698699// Assume everything is "quiet"700// "synchronize" might lead to deadlock so don't synchronize method701// Use streamLock instead for synchronizing update to stream702703synchronized public void replaceStreams(InputStream newIn, OutputStream newOut) {704if (debug) {705System.err.println("Replacing " + inStream + " with: " + newIn);706System.err.println("Replacing " + outStream + " with: " + newOut);707}708709inStream = newIn;710711// Cleanup old stream712try {713outStream.flush();714} catch (IOException ie) {715if (debug)716System.err.println("Connection: cannot flush outstream: " + ie);717}718719// Replace stream720outStream = newOut;721}722723/*724* Replace streams and set isUpdradedToStartTls flag to the provided value725*/726synchronized public void replaceStreams(InputStream newIn, OutputStream newOut, boolean isStartTls) {727synchronized (startTlsLock) {728replaceStreams(newIn, newOut);729isUpgradedToStartTls = isStartTls;730}731}732733/*734* Returns true if connection was upgraded to SSL with STARTTLS extended operation735*/736public boolean isUpgradedToStartTls() {737return isUpgradedToStartTls;738}739740/**741* Used by Connection thread to read inStream into a local variable.742* This ensures that there is no contention between the main thread743* and the Connection thread when the main thread updates inStream.744*/745synchronized private InputStream getInputStream() {746return inStream;747}748749750////////////////////////////////////////////////////////////////////////////751//752// Code for pausing/unpausing the reader thread ('worker')753//754////////////////////////////////////////////////////////////////////////////755756/*757* The main idea is to mark requests that need the reader thread to758* pause after getting the response. When the reader thread gets the response,759* it waits on a lock instead of returning to the read(). The next time a760* request is sent, the reader is automatically unblocked if necessary.761* Note that the reader must be unblocked BEFORE the request is sent.762* Otherwise, there is a race condition where the request is sent and763* the reader thread might read the response and be unblocked764* by writeRequest().765*766* This pause gives the main thread (StartTLS or SASL) an opportunity to767* update the reader's state (e.g., its streams) if necessary.768* The assumption is that the connection will remain quiet during this pause769* (i.e., no intervening requests being sent).770*<p>771* For dealing with StartTLS close,772* when the read() exits either due to EOF or an exception,773* the reader thread checks whether there is a new stream to read from.774* If so, then it reattempts the read. Otherwise, the EOF or exception775* is processed and the reader thread terminates.776* In a StartTLS close, the client first replaces the SSL IO streams with777* plain ones and then closes the SSL socket.778* If the reader thread attempts to read, or was reading, from779* the SSL socket (that is, it got to the read BEFORE replaceStreams()),780* the SSL socket close will cause the reader thread to781* get an EOF/exception and reexamine the input stream.782* If the reader thread sees a new stream, it reattempts the read.783* If the underlying socket is still alive, then the new read will succeed.784* If the underlying socket has been closed also, then the new read will785* fail and the reader thread exits.786* If the reader thread attempts to read, or was reading, from the plain787* socket (that is, it got to the read AFTER replaceStreams()), the788* SSL socket close will have no effect on the reader thread.789*790* The check for new stream is made only791* in the first attempt at reading a BER buffer; the reader should792* never be in midst of reading a buffer when a nonfatal close occurs.793* If this occurs, then the connection is in an inconsistent state and794* the safest thing to do is to shut it down.795*/796797private final Object pauseLock = new Object(); // lock for reader to wait on while paused798private boolean paused = false; // paused state of reader799800/*801* Unpauses reader thread if it was paused802*/803private void unpauseReader() throws IOException {804synchronized (pauseLock) {805if (paused) {806if (debug) {807System.err.println("Unpausing reader; read from: " +808inStream);809}810paused = false;811pauseLock.notify();812}813}814}815816/*817* Pauses reader so that it stops reading from the input stream.818* Reader blocks on pauseLock instead of read().819* MUST be called from within synchronized (pauseLock) clause.820*/821private void pauseReader() throws IOException {822if (debug) {823System.err.println("Pausing reader; was reading from: " +824inStream);825}826paused = true;827try {828while (paused) {829pauseLock.wait(); // notified by unpauseReader830}831} catch (InterruptedException e) {832throw new InterruptedIOException(833"Pause/unpause reader has problems.");834}835}836837838////////////////////////////////////////////////////////////////////////////839//840// The LDAP Binding thread. It does the mux/demux of multiple requests841// on the same TCP connection.842//843////////////////////////////////////////////////////////////////////////////844845846public void run() {847byte inbuf[]; // Buffer for reading incoming bytes848int inMsgId; // Message id of incoming response849int bytesread; // Number of bytes in inbuf850int br; // Temp; number of bytes read from stream851int offset; // Offset of where to store bytes in inbuf852int seqlen; // Length of ASN sequence853int seqlenlen; // Number of sequence length bytes854boolean eos; // End of stream855BerDecoder retBer; // Decoder for ASN.1 BER data from inbuf856InputStream in = null;857858try {859while (true) {860try {861// type and length (at most 128 octets for long form)862inbuf = new byte[129];863864offset = 0;865seqlen = 0;866seqlenlen = 0;867868in = getInputStream();869870// check that it is the beginning of a sequence871bytesread = in.read(inbuf, offset, 1);872if (bytesread < 0) {873if (in != getInputStream()) {874continue; // a new stream to try875} else {876break; // EOF877}878}879880if (inbuf[offset++] != (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR))881continue;882883// get length of sequence884bytesread = in.read(inbuf, offset, 1);885if (bytesread < 0)886break; // EOF887seqlen = inbuf[offset++];888889// if high bit is on, length is encoded in the890// subsequent length bytes and the number of length bytes891// is equal to & 0x80 (i.e. length byte with high bit off).892if ((seqlen & 0x80) == 0x80) {893seqlenlen = seqlen & 0x7f; // number of length bytes894// Check the length of length field, since seqlen is int895// the number of bytes can't be greater than 4896if (seqlenlen > 4) {897throw new IOException("Length coded with too many bytes: " + seqlenlen);898}899900bytesread = 0;901eos = false;902903// Read all length bytes904while (bytesread < seqlenlen) {905br = in.read(inbuf, offset+bytesread,906seqlenlen-bytesread);907if (br < 0) {908eos = true;909break; // EOF910}911bytesread += br;912}913914// end-of-stream reached before length bytes are read915if (eos)916break; // EOF917918// Add contents of length bytes to determine length919seqlen = 0;920for( int i = 0; i < seqlenlen; i++) {921seqlen = (seqlen << 8) + (inbuf[offset+i] & 0xff);922}923offset += bytesread;924}925926if (seqlenlen > bytesread) {927throw new IOException("Unexpected EOF while reading length");928}929930if (seqlen < 0) {931throw new IOException("Length too big: " + (((long) seqlen) & 0xFFFFFFFFL));932}933// read in seqlen bytes934byte[] left = readFully(in, seqlen);935inbuf = Arrays.copyOf(inbuf, offset + left.length);936System.arraycopy(left, 0, inbuf, offset, left.length);937offset += left.length;938939try {940retBer = new BerDecoder(inbuf, 0, offset);941942if (traceFile != null) {943Ber.dumpBER(traceFile, traceTagIn, inbuf, 0, offset);944}945946retBer.parseSeq(null);947inMsgId = retBer.parseInt();948retBer.reset(); // reset offset949950boolean needPause = false;951952if (inMsgId == 0) {953// Unsolicited Notification954parent.processUnsolicited(retBer);955} else {956LdapRequest ldr = findRequest(inMsgId);957958if (ldr != null) {959960/**961* Grab pauseLock before making reply available962* to ensure that reader goes into paused state963* before writer can attempt to unpause reader964*/965synchronized (pauseLock) {966needPause = ldr.addReplyBer(retBer);967if (needPause) {968/*969* Go into paused state; release970* pauseLock971*/972pauseReader();973}974975// else release pauseLock976}977} else {978// System.err.println("Cannot find" +979// "LdapRequest for " + inMsgId);980}981}982} catch (Ber.DecodeException e) {983//System.err.println("Cannot parse Ber");984}985} catch (IOException ie) {986if (debug) {987System.err.println("Connection: Inside Caught " + ie);988ie.printStackTrace();989}990991if (in != getInputStream()) {992// A new stream to try993// Go to top of loop and continue994} else {995if (debug) {996System.err.println("Connection: rethrowing " + ie);997}998throw ie; // rethrow exception999}1000}1001}10021003if (debug) {1004System.err.println("Connection: end-of-stream detected: "1005+ in);1006}1007} catch (IOException ex) {1008if (debug) {1009System.err.println("Connection: Caught " + ex);1010}1011closureReason = ex;1012} finally {1013cleanup(null, true); // cleanup1014}1015if (debug) {1016System.err.println("Connection: Thread Exiting");1017}1018}10191020private static byte[] readFully(InputStream is, int length)1021throws IOException1022{1023byte[] buf = new byte[Math.min(length, 8192)];1024int nread = 0;1025while (nread < length) {1026int bytesToRead;1027if (nread >= buf.length) { // need to allocate a larger buffer1028bytesToRead = Math.min(length - nread, buf.length + 8192);1029if (buf.length < nread + bytesToRead) {1030buf = Arrays.copyOf(buf, nread + bytesToRead);1031}1032} else {1033bytesToRead = buf.length - nread;1034}1035int count = is.read(buf, nread, bytesToRead);1036if (count < 0) {1037if (buf.length != nread)1038buf = Arrays.copyOf(buf, nread);1039break;1040}1041nread += count;1042}1043return buf;1044}1045}104610471048