1 /*
   2  * Copyright (c) 1999, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package com.sun.jndi.ldap;
  27 
  28 import java.io.BufferedInputStream;
  29 import java.io.BufferedOutputStream;
  30 import java.io.InterruptedIOException;
  31 import java.io.IOException;
  32 import java.io.OutputStream;
  33 import java.io.InputStream;
  34 import java.net.InetSocketAddress;
  35 import java.net.Socket;
  36 import javax.net.ssl.SSLSocket;
  37 
  38 import javax.naming.CommunicationException;
  39 import javax.naming.ServiceUnavailableException;
  40 import javax.naming.NamingException;
  41 import javax.naming.InterruptedNamingException;
  42 
  43 import javax.naming.ldap.Control;
  44 
  45 import java.lang.reflect.Method;
  46 import java.lang.reflect.InvocationTargetException;
  47 import java.security.AccessController;
  48 import java.security.PrivilegedAction;
  49 import java.util.Arrays;
  50 import javax.net.SocketFactory;
  51 import javax.net.ssl.SSLParameters;
  52 
  53 /**
  54   * A thread that creates a connection to an LDAP server.
  55   * After the connection, the thread reads from the connection.
  56   * A caller can invoke methods on the instance to read LDAP responses
  57   * and to send LDAP requests.
  58   * <p>
  59   * There is a one-to-one correspondence between an LdapClient and
  60   * a Connection. Access to Connection and its methods is only via
  61   * LdapClient with two exceptions: SASL authentication and StartTLS.
  62   * SASL needs to access Connection's socket IO streams (in order to do encryption
  63   * of the security layer). StartTLS needs to do replace IO streams
  64   * and close the IO  streams on nonfatal close. The code for SASL
  65   * authentication can be treated as being the same as from LdapClient
  66   * because the SASL code is only ever called from LdapClient, from
  67   * inside LdapClient's synchronized authenticate() method. StartTLS is called
  68   * directly by the application but should only occur when the underlying
  69   * connection is quiet.
  70   * <p>
  71   * In terms of synchronization, worry about data structures
  72   * used by the Connection thread because that usage might contend
  73   * with calls by the main threads (i.e., those that call LdapClient).
  74   * Main threads need to worry about contention with each other.
  75   * Fields that Connection thread uses:
  76   *     inStream - synced access and update; initialized in constructor;
  77   *           referenced outside class unsync'ed (by LdapSasl) only
  78   *           when connection is quiet
  79   *     traceFile, traceTagIn, traceTagOut - no sync; debugging only
  80   *     parent - no sync; initialized in constructor; no updates
  81   *     pendingRequests - sync
  82   *     pauseLock - per-instance lock;
  83   *     paused - sync via pauseLock (pauseReader())
  84   * Members used by main threads (LdapClient):
  85   *     host, port - unsync; read-only access for StartTLS and debug messages
  86   *     setBound(), setV3() - no sync; called only by LdapClient.authenticate(),
  87   *             which is a sync method called only when connection is "quiet"
  88   *     getMsgId() - sync
  89   *     writeRequest(), removeRequest(),findRequest(), abandonOutstandingReqs() -
  90   *             access to shared pendingRequests is sync
  91   *     writeRequest(),  abandonRequest(), ldapUnbind() - access to outStream sync
  92   *     cleanup() - sync
  93   *     readReply() - access to sock sync
  94   *     unpauseReader() - (indirectly via writeRequest) sync on pauseLock
  95   * Members used by SASL auth (main thread):
  96   *     inStream, outStream - no sync; used to construct new stream; accessed
  97   *             only when conn is "quiet" and not shared
  98   *     replaceStreams() - sync method
  99   * Members used by StartTLS:
 100   *     inStream, outStream - no sync; used to record the existing streams;
 101   *             accessed only when conn is "quiet" and not shared
 102   *     replaceStreams() - sync method
 103   * <p>
 104   * Handles anonymous, simple, and SASL bind for v3; anonymous and simple
 105   * for v2.
 106   * %%% made public for access by LdapSasl %%%
 107   *
 108   * @author Vincent Ryan
 109   * @author Rosanna Lee
 110   * @author Jagane Sundar
 111   */
 112 public final class Connection implements Runnable {
 113 
 114     private static final boolean debug = false;
 115     private static final int dump = 0; // > 0 r, > 1 rw
 116 
 117 
 118     final private Thread worker;    // Initialized in constructor
 119 
 120     private boolean v3 = true;       // Set in setV3()
 121 
 122     final public String host;  // used by LdapClient for generating exception messages
 123                          // used by StartTlsResponse when creating an SSL socket
 124     final public int port;     // used by LdapClient for generating exception messages
 125                          // used by StartTlsResponse when creating an SSL socket
 126 
 127     private boolean bound = false;   // Set in setBound()
 128 
 129     // All three are initialized in constructor and read-only afterwards
 130     private OutputStream traceFile = null;
 131     private String traceTagIn = null;
 132     private String traceTagOut = null;
 133 
 134     // Initialized in constructor; read and used externally (LdapSasl);
 135     // Updated in replaceStreams() during "quiet", unshared, period
 136     public InputStream inStream;   // must be public; used by LdapSasl
 137 
 138     // Initialized in constructor; read and used externally (LdapSasl);
 139     // Updated in replaceOutputStream() during "quiet", unshared, period
 140     public OutputStream outStream; // must be public; used by LdapSasl
 141 
 142     // Initialized in constructor; read and used externally (TLS) to
 143     // get new IO streams; closed during cleanup
 144     public Socket sock;            // for TLS
 145 
 146     // For processing "disconnect" unsolicited notification
 147     // Initialized in constructor
 148     final private LdapClient parent;
 149 
 150     // Incremented and returned in sync getMsgId()
 151     private int outMsgId = 0;
 152 
 153     //
 154     // The list of ldapRequests pending on this binding
 155     //
 156     // Accessed only within sync methods
 157     private LdapRequest pendingRequests = null;
 158 
 159     volatile IOException closureReason = null;
 160     volatile boolean useable = true;  // is Connection still useable
 161 
 162     int readTimeout;
 163     int connectTimeout;
 164     private static final boolean IS_HOSTNAME_VERIFICATION_DISABLED
 165             = hostnameVerificationDisabledValue();
 166 
 167     private static boolean hostnameVerificationDisabledValue() {
 168         PrivilegedAction<String> act = () -> System.getProperty(
 169                 "com.sun.jndi.ldap.object.disableEndpointIdentification");
 170         String prop = AccessController.doPrivileged(act);
 171         if (prop == null) {
 172             return false;
 173         }
 174         return prop.isEmpty() ? true : Boolean.parseBoolean(prop);
 175     }
 176     // true means v3; false means v2
 177     // Called in LdapClient.authenticate() (which is synchronized)
 178     // when connection is "quiet" and not shared; no need to synchronize
 179     void setV3(boolean v) {
 180         v3 = v;
 181     }
 182 
 183     // A BIND request has been successfully made on this connection
 184     // When cleaning up, remember to do an UNBIND
 185     // Called in LdapClient.authenticate() (which is synchronized)
 186     // when connection is "quiet" and not shared; no need to synchronize
 187     void setBound() {
 188         bound = true;
 189     }
 190 
 191     ////////////////////////////////////////////////////////////////////////////
 192     //
 193     // Create an LDAP Binding object and bind to a particular server
 194     //
 195     ////////////////////////////////////////////////////////////////////////////
 196 
 197     Connection(LdapClient parent, String host, int port, String socketFactory,
 198         int connectTimeout, int readTimeout, OutputStream trace) throws NamingException {
 199 
 200         this.host = host;
 201         this.port = port;
 202         this.parent = parent;
 203         this.readTimeout = readTimeout;
 204         this.connectTimeout = connectTimeout;
 205 
 206         if (trace != null) {
 207             traceFile = trace;
 208             traceTagIn = "<- " + host + ":" + port + "\n\n";
 209             traceTagOut = "-> " + host + ":" + port + "\n\n";
 210         }
 211 
 212         //
 213         // Connect to server
 214         //
 215         try {
 216             sock = createSocket(host, port, socketFactory, connectTimeout);
 217 
 218             if (debug) {
 219                 System.err.println("Connection: opening socket: " + host + "," + port);
 220             }
 221 
 222             inStream = new BufferedInputStream(sock.getInputStream());
 223             outStream = new BufferedOutputStream(sock.getOutputStream());
 224 
 225         } catch (InvocationTargetException e) {
 226             Throwable realException = e.getTargetException();
 227             // realException.printStackTrace();
 228 
 229             CommunicationException ce =
 230                 new CommunicationException(host + ":" + port);
 231             ce.setRootCause(realException);
 232             throw ce;
 233         } catch (Exception e) {
 234             // We need to have a catch all here and
 235             // ignore generic exceptions.
 236             // Also catches all IO errors generated by socket creation.
 237             CommunicationException ce =
 238                 new CommunicationException(host + ":" + port);
 239             ce.setRootCause(e);
 240             throw ce;
 241         }
 242 
 243         worker = Obj.helper.createThread(this);
 244         worker.setDaemon(true);
 245         worker.start();
 246     }
 247 
 248     /*
 249      * Create an InetSocketAddress using the specified hostname and port number.
 250      */
 251     private InetSocketAddress createInetSocketAddress(String host, int port) {
 252             return new InetSocketAddress(host, port);
 253     }
 254 
 255     /*
 256      * Create a Socket object using the specified socket factory and time limit.
 257      *
 258      * If a timeout is supplied and unconnected sockets are supported then
 259      * an unconnected socket is created and the timeout is applied when
 260      * connecting the socket. If a timeout is supplied but unconnected sockets
 261      * are not supported then the timeout is ignored and a connected socket
 262      * is created.
 263      */
 264     private Socket createSocket(String host, int port, String socketFactory,
 265             int connectTimeout) throws Exception {
 266 
 267         Socket socket = null;
 268 
 269         if (socketFactory != null) {
 270 
 271             // create the factory
 272 
 273             @SuppressWarnings("unchecked")
 274             Class<? extends SocketFactory> socketFactoryClass =
 275                 (Class<? extends SocketFactory>)Obj.helper.loadClass(socketFactory);
 276             Method getDefault =
 277                 socketFactoryClass.getMethod("getDefault", new Class<?>[]{});
 278             SocketFactory factory = (SocketFactory) getDefault.invoke(null, new Object[]{});
 279 
 280             // create the socket
 281 
 282             if (connectTimeout > 0) {
 283 
 284                 InetSocketAddress endpoint =
 285                         createInetSocketAddress(host, port);
 286 
 287                 // unconnected socket
 288                 socket = factory.createSocket();
 289 
 290                 if (debug) {
 291                     System.err.println("Connection: creating socket with " +
 292                             "a timeout using supplied socket factory");
 293                 }
 294 
 295                 // connected socket
 296                 socket.connect(endpoint, connectTimeout);
 297             }
 298 
 299             // continue (but ignore connectTimeout)
 300             if (socket == null) {
 301                 if (debug) {
 302                     System.err.println("Connection: creating socket using " +
 303                         "supplied socket factory");
 304                 }
 305                 // connected socket
 306                 socket = factory.createSocket(host, port);
 307             }
 308         } else {
 309 
 310             if (connectTimeout > 0) {
 311 
 312                     InetSocketAddress endpoint = createInetSocketAddress(host, port);
 313 
 314                     socket = new Socket();
 315 
 316                     if (debug) {
 317                         System.err.println("Connection: creating socket with " +
 318                             "a timeout");
 319                     }
 320                     socket.connect(endpoint, connectTimeout);
 321             }
 322 
 323             // continue (but ignore connectTimeout)
 324 
 325             if (socket == null) {
 326                 if (debug) {
 327                     System.err.println("Connection: creating socket");
 328                 }
 329                 // connected socket
 330                 socket = new Socket(host, port);
 331             }
 332         }
 333 
 334         // For LDAP connect timeouts on LDAP over SSL connections must treat
 335         // the SSL handshake following socket connection as part of the timeout.
 336         // So explicitly set a socket read timeout, trigger the SSL handshake,
 337         // then reset the timeout.
 338         if (socket instanceof SSLSocket) {
 339             SSLSocket sslSocket = (SSLSocket) socket;
 340             int socketTimeout = sslSocket.getSoTimeout();
 341             if (!IS_HOSTNAME_VERIFICATION_DISABLED) {
 342                 SSLParameters param = sslSocket.getSSLParameters();
 343                 param.setEndpointIdentificationAlgorithm("LDAPS");
 344                 sslSocket.setSSLParameters(param);
 345             }
 346             if (connectTimeout > 0) {
 347                 sslSocket.setSoTimeout(connectTimeout); // reuse full timeout value
 348             }
 349             sslSocket.startHandshake();
 350             sslSocket.setSoTimeout(socketTimeout);
 351         }
 352         return socket;
 353     }
 354 
 355     ////////////////////////////////////////////////////////////////////////////
 356     //
 357     // Methods to IO to the LDAP server
 358     //
 359     ////////////////////////////////////////////////////////////////////////////
 360 
 361     synchronized int getMsgId() {
 362         return ++outMsgId;
 363     }
 364 
 365     LdapRequest writeRequest(BerEncoder ber, int msgId) throws IOException {
 366         return writeRequest(ber, msgId, false /* pauseAfterReceipt */, -1);
 367     }
 368 
 369     LdapRequest writeRequest(BerEncoder ber, int msgId,
 370         boolean pauseAfterReceipt) throws IOException {
 371         return writeRequest(ber, msgId, pauseAfterReceipt, -1);
 372     }
 373 
 374     LdapRequest writeRequest(BerEncoder ber, int msgId,
 375         boolean pauseAfterReceipt, int replyQueueCapacity) throws IOException {
 376 
 377         LdapRequest req =
 378             new LdapRequest(msgId, pauseAfterReceipt, replyQueueCapacity);
 379         addRequest(req);
 380 
 381         if (traceFile != null) {
 382             Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0, ber.getDataLen());
 383         }
 384 
 385 
 386         // unpause reader so that it can get response
 387         // NOTE: Must do this before writing request, otherwise might
 388         // create a race condition where the writer unblocks its own response
 389         unpauseReader();
 390 
 391         if (debug) {
 392             System.err.println("Writing request to: " + outStream);
 393         }
 394 
 395         try {
 396             synchronized (this) {
 397                 outStream.write(ber.getBuf(), 0, ber.getDataLen());
 398                 outStream.flush();
 399             }
 400         } catch (IOException e) {
 401             cleanup(null, true);
 402             throw (closureReason = e); // rethrow
 403         }
 404 
 405         return req;
 406     }
 407 
 408     /**
 409      * Reads a reply; waits until one is ready.
 410      */
 411     BerDecoder readReply(LdapRequest ldr) throws IOException, NamingException {
 412         BerDecoder rber;
 413 
 414             try {
 415                 // if no timeout is set so we wait infinitely until
 416                 // a response is received
 417                 // http://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-ldap.html#PROP
 418                 rber = ldr.getReplyBer(readTimeout);
 419             } catch (InterruptedException ex) {
 420                 throw new InterruptedNamingException(
 421                     "Interrupted during LDAP operation");
 422             }
 423 
 424         if (rber == null) {
 425             abandonRequest(ldr, null);
 426             throw new NamingException(
 427                     "LDAP response read timed out, timeout used:"
 428                             + readTimeout + "ms." );
 429 
 430         }
 431         return rber;
 432     }
 433 
 434     ////////////////////////////////////////////////////////////////////////////
 435     //
 436     // Methods to add, find, delete, and abandon requests made to server
 437     //
 438     ////////////////////////////////////////////////////////////////////////////
 439 
 440     private synchronized void addRequest(LdapRequest ldapRequest) {
 441 
 442         LdapRequest ldr = pendingRequests;
 443         if (ldr == null) {
 444             pendingRequests = ldapRequest;
 445             ldapRequest.next = null;
 446         } else {
 447             ldapRequest.next = pendingRequests;
 448             pendingRequests = ldapRequest;
 449         }
 450     }
 451 
 452     synchronized LdapRequest findRequest(int msgId) {
 453 
 454         LdapRequest ldr = pendingRequests;
 455         while (ldr != null) {
 456             if (ldr.msgId == msgId) {
 457                 return ldr;
 458             }
 459             ldr = ldr.next;
 460         }
 461         return null;
 462 
 463     }
 464 
 465     synchronized void removeRequest(LdapRequest req) {
 466         LdapRequest ldr = pendingRequests;
 467         LdapRequest ldrprev = null;
 468 
 469         while (ldr != null) {
 470             if (ldr == req) {
 471                 ldr.cancel();
 472 
 473                 if (ldrprev != null) {
 474                     ldrprev.next = ldr.next;
 475                 } else {
 476                     pendingRequests = ldr.next;
 477                 }
 478                 ldr.next = null;
 479             }
 480             ldrprev = ldr;
 481             ldr = ldr.next;
 482         }
 483     }
 484 
 485     void abandonRequest(LdapRequest ldr, Control[] reqCtls) {
 486         // Remove from queue
 487         removeRequest(ldr);
 488 
 489         BerEncoder ber = new BerEncoder(256);
 490         int abandonMsgId = getMsgId();
 491 
 492         //
 493         // build the abandon request.
 494         //
 495         try {
 496             ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
 497                 ber.encodeInt(abandonMsgId);
 498                 ber.encodeInt(ldr.msgId, LdapClient.LDAP_REQ_ABANDON);
 499 
 500                 if (v3) {
 501                     LdapClient.encodeControls(ber, reqCtls);
 502                 }
 503             ber.endSeq();
 504 
 505             if (traceFile != null) {
 506                 Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0,
 507                     ber.getDataLen());
 508             }
 509 
 510             synchronized (this) {
 511                 outStream.write(ber.getBuf(), 0, ber.getDataLen());
 512                 outStream.flush();
 513             }
 514 
 515         } catch (IOException ex) {
 516             //System.err.println("ldap.abandon: " + ex);
 517         }
 518 
 519         // Don't expect any response for the abandon request.
 520     }
 521 
 522     synchronized void abandonOutstandingReqs(Control[] reqCtls) {
 523         LdapRequest ldr = pendingRequests;
 524 
 525         while (ldr != null) {
 526             abandonRequest(ldr, reqCtls);
 527             pendingRequests = ldr = ldr.next;
 528         }
 529     }
 530 
 531     ////////////////////////////////////////////////////////////////////////////
 532     //
 533     // Methods to unbind from server and clear up resources when object is
 534     // destroyed.
 535     //
 536     ////////////////////////////////////////////////////////////////////////////
 537 
 538     private void ldapUnbind(Control[] reqCtls) {
 539 
 540         BerEncoder ber = new BerEncoder(256);
 541         int unbindMsgId = getMsgId();
 542 
 543         //
 544         // build the unbind request.
 545         //
 546 
 547         try {
 548 
 549             ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
 550                 ber.encodeInt(unbindMsgId);
 551                 // IMPLICIT TAGS
 552                 ber.encodeByte(LdapClient.LDAP_REQ_UNBIND);
 553                 ber.encodeByte(0);
 554 
 555                 if (v3) {
 556                     LdapClient.encodeControls(ber, reqCtls);
 557                 }
 558             ber.endSeq();
 559 
 560             if (traceFile != null) {
 561                 Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(),
 562                     0, ber.getDataLen());
 563             }
 564 
 565             synchronized (this) {
 566                 outStream.write(ber.getBuf(), 0, ber.getDataLen());
 567                 outStream.flush();
 568             }
 569 
 570         } catch (IOException ex) {
 571             //System.err.println("ldap.unbind: " + ex);
 572         }
 573 
 574         // Don't expect any response for the unbind request.
 575     }
 576 
 577     /**
 578      * @param reqCtls Possibly null request controls that accompanies the
 579      *    abandon and unbind LDAP request.
 580      * @param notifyParent true means to call parent LdapClient back, notifying
 581      *    it that the connection has been closed; false means not to notify
 582      *    parent. If LdapClient invokes cleanup(), notifyParent should be set to
 583      *    false because LdapClient already knows that it is closing
 584      *    the connection. If Connection invokes cleanup(), notifyParent should be
 585      *    set to true because LdapClient needs to know about the closure.
 586      */
 587     void cleanup(Control[] reqCtls, boolean notifyParent) {
 588         boolean nparent = false;
 589 
 590         synchronized (this) {
 591             useable = false;
 592 
 593             if (sock != null) {
 594                 if (debug) {
 595                     System.err.println("Connection: closing socket: " + host + "," + port);
 596                 }
 597                 try {
 598                     if (!notifyParent) {
 599                         abandonOutstandingReqs(reqCtls);
 600                     }
 601                     if (bound) {
 602                         ldapUnbind(reqCtls);
 603                     }
 604                 } finally {
 605                     try {
 606                         outStream.flush();
 607                         sock.close();
 608                         unpauseReader();
 609                     } catch (IOException ie) {
 610                         if (debug)
 611                             System.err.println("Connection: problem closing socket: " + ie);
 612                     }
 613                     if (!notifyParent) {
 614                         LdapRequest ldr = pendingRequests;
 615                         while (ldr != null) {
 616                             ldr.cancel();
 617                             ldr = ldr.next;
 618                         }
 619                     }
 620                     sock = null;
 621                 }
 622                 nparent = notifyParent;
 623             }
 624             if (nparent) {
 625                 LdapRequest ldr = pendingRequests;
 626                 while (ldr != null) {
 627                     ldr.close();
 628                         ldr = ldr.next;
 629                     }
 630                 }
 631             }
 632         if (nparent) {
 633             parent.processConnectionClosure();
 634         }
 635     }
 636 
 637 
 638     // Assume everything is "quiet"
 639     // "synchronize" might lead to deadlock so don't synchronize method
 640     // Use streamLock instead for synchronizing update to stream
 641 
 642     synchronized public void replaceStreams(InputStream newIn, OutputStream newOut) {
 643         if (debug) {
 644             System.err.println("Replacing " + inStream + " with: " + newIn);
 645             System.err.println("Replacing " + outStream + " with: " + newOut);
 646         }
 647 
 648         inStream = newIn;
 649 
 650         // Cleanup old stream
 651         try {
 652             outStream.flush();
 653         } catch (IOException ie) {
 654             if (debug)
 655                 System.err.println("Connection: cannot flush outstream: " + ie);
 656         }
 657 
 658         // Replace stream
 659         outStream = newOut;
 660     }
 661 
 662     /**
 663      * Used by Connection thread to read inStream into a local variable.
 664      * This ensures that there is no contention between the main thread
 665      * and the Connection thread when the main thread updates inStream.
 666      */
 667     synchronized private InputStream getInputStream() {
 668         return inStream;
 669     }
 670 
 671 
 672     ////////////////////////////////////////////////////////////////////////////
 673     //
 674     // Code for pausing/unpausing the reader thread ('worker')
 675     //
 676     ////////////////////////////////////////////////////////////////////////////
 677 
 678     /*
 679      * The main idea is to mark requests that need the reader thread to
 680      * pause after getting the response. When the reader thread gets the response,
 681      * it waits on a lock instead of returning to the read(). The next time a
 682      * request is sent, the reader is automatically unblocked if necessary.
 683      * Note that the reader must be unblocked BEFORE the request is sent.
 684      * Otherwise, there is a race condition where the request is sent and
 685      * the reader thread might read the response and be unblocked
 686      * by writeRequest().
 687      *
 688      * This pause gives the main thread (StartTLS or SASL) an opportunity to
 689      * update the reader's state (e.g., its streams) if necessary.
 690      * The assumption is that the connection will remain quiet during this pause
 691      * (i.e., no intervening requests being sent).
 692      *<p>
 693      * For dealing with StartTLS close,
 694      * when the read() exits either due to EOF or an exception,
 695      * the reader thread checks whether there is a new stream to read from.
 696      * If so, then it reattempts the read. Otherwise, the EOF or exception
 697      * is processed and the reader thread terminates.
 698      * In a StartTLS close, the client first replaces the SSL IO streams with
 699      * plain ones and then closes the SSL socket.
 700      * If the reader thread attempts to read, or was reading, from
 701      * the SSL socket (that is, it got to the read BEFORE replaceStreams()),
 702      * the SSL socket close will cause the reader thread to
 703      * get an EOF/exception and reexamine the input stream.
 704      * If the reader thread sees a new stream, it reattempts the read.
 705      * If the underlying socket is still alive, then the new read will succeed.
 706      * If the underlying socket has been closed also, then the new read will
 707      * fail and the reader thread exits.
 708      * If the reader thread attempts to read, or was reading, from the plain
 709      * socket (that is, it got to the read AFTER replaceStreams()), the
 710      * SSL socket close will have no effect on the reader thread.
 711      *
 712      * The check for new stream is made only
 713      * in the first attempt at reading a BER buffer; the reader should
 714      * never be in midst of reading a buffer when a nonfatal close occurs.
 715      * If this occurs, then the connection is in an inconsistent state and
 716      * the safest thing to do is to shut it down.
 717      */
 718 
 719     private final Object pauseLock = new Object();  // lock for reader to wait on while paused
 720     private boolean paused = false;           // paused state of reader
 721 
 722     /*
 723      * Unpauses reader thread if it was paused
 724      */
 725     private void unpauseReader() throws IOException {
 726         synchronized (pauseLock) {
 727             if (paused) {
 728                 if (debug) {
 729                     System.err.println("Unpausing reader; read from: " +
 730                                         inStream);
 731                 }
 732                 paused = false;
 733                 pauseLock.notify();
 734             }
 735         }
 736     }
 737 
 738      /*
 739      * Pauses reader so that it stops reading from the input stream.
 740      * Reader blocks on pauseLock instead of read().
 741      * MUST be called from within synchronized (pauseLock) clause.
 742      */
 743     private void pauseReader() throws IOException {
 744         if (debug) {
 745             System.err.println("Pausing reader;  was reading from: " +
 746                                 inStream);
 747         }
 748         paused = true;
 749         try {
 750             while (paused) {
 751                 pauseLock.wait(); // notified by unpauseReader
 752             }
 753         } catch (InterruptedException e) {
 754             throw new InterruptedIOException(
 755                     "Pause/unpause reader has problems.");
 756         }
 757     }
 758 
 759 
 760     ////////////////////////////////////////////////////////////////////////////
 761     //
 762     // The LDAP Binding thread. It does the mux/demux of multiple requests
 763     // on the same TCP connection.
 764     //
 765     ////////////////////////////////////////////////////////////////////////////
 766 
 767 
 768     public void run() {
 769         byte inbuf[];   // Buffer for reading incoming bytes
 770         int inMsgId;    // Message id of incoming response
 771         int bytesread;  // Number of bytes in inbuf
 772         int br;         // Temp; number of bytes read from stream
 773         int offset;     // Offset of where to store bytes in inbuf
 774         int seqlen;     // Length of ASN sequence
 775         int seqlenlen;  // Number of sequence length bytes
 776         boolean eos;    // End of stream
 777         BerDecoder retBer;    // Decoder for ASN.1 BER data from inbuf
 778         InputStream in = null;
 779 
 780         try {
 781             while (true) {
 782                 try {
 783                     // type and length (at most 128 octets for long form)
 784                     inbuf = new byte[129];
 785 
 786                     offset = 0;
 787                     seqlen = 0;
 788                     seqlenlen = 0;
 789 
 790                     in = getInputStream();
 791 
 792                     // check that it is the beginning of a sequence
 793                     bytesread = in.read(inbuf, offset, 1);
 794                     if (bytesread < 0) {
 795                         if (in != getInputStream()) {
 796                             continue;   // a new stream to try
 797                         } else {
 798                             break; // EOF
 799                         }
 800                     }
 801 
 802                     if (inbuf[offset++] != (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR))
 803                         continue;
 804 
 805                     // get length of sequence
 806                     bytesread = in.read(inbuf, offset, 1);
 807                     if (bytesread < 0)
 808                         break; // EOF
 809                     seqlen = inbuf[offset++];
 810 
 811                     // if high bit is on, length is encoded in the
 812                     // subsequent length bytes and the number of length bytes
 813                     // is equal to & 0x80 (i.e. length byte with high bit off).
 814                     if ((seqlen & 0x80) == 0x80) {
 815                         seqlenlen = seqlen & 0x7f;  // number of length bytes
 816 
 817                         bytesread = 0;
 818                         eos = false;
 819 
 820                         // Read all length bytes
 821                         while (bytesread < seqlenlen) {
 822                             br = in.read(inbuf, offset+bytesread,
 823                                 seqlenlen-bytesread);
 824                             if (br < 0) {
 825                                 eos = true;
 826                                 break; // EOF
 827                             }
 828                             bytesread += br;
 829                         }
 830 
 831                         // end-of-stream reached before length bytes are read
 832                         if (eos)
 833                             break;  // EOF
 834 
 835                         // Add contents of length bytes to determine length
 836                         seqlen = 0;
 837                         for( int i = 0; i < seqlenlen; i++) {
 838                             seqlen = (seqlen << 8) + (inbuf[offset+i] & 0xff);
 839                         }
 840                         offset += bytesread;
 841                     }
 842 
 843                     // read in seqlen bytes
 844                     byte[] left = readFully(in, seqlen);
 845                     inbuf = Arrays.copyOf(inbuf, offset + left.length);
 846                     System.arraycopy(left, 0, inbuf, offset, left.length);
 847                     offset += left.length;
 848 /*
 849 if (dump > 0) {
 850 System.err.println("seqlen: " + seqlen);
 851 System.err.println("bufsize: " + offset);
 852 System.err.println("bytesleft: " + bytesleft);
 853 System.err.println("bytesread: " + bytesread);
 854 }
 855 */
 856 
 857 
 858                     try {
 859                         retBer = new BerDecoder(inbuf, 0, offset);
 860 
 861                         if (traceFile != null) {
 862                             Ber.dumpBER(traceFile, traceTagIn, inbuf, 0, offset);
 863                         }
 864 
 865                         retBer.parseSeq(null);
 866                         inMsgId = retBer.parseInt();
 867                         retBer.reset(); // reset offset
 868 
 869                         boolean needPause = false;
 870 
 871                         if (inMsgId == 0) {
 872                             // Unsolicited Notification
 873                             parent.processUnsolicited(retBer);
 874                         } else {
 875                             LdapRequest ldr = findRequest(inMsgId);
 876 
 877                             if (ldr != null) {
 878 
 879                                 /**
 880                                  * Grab pauseLock before making reply available
 881                                  * to ensure that reader goes into paused state
 882                                  * before writer can attempt to unpause reader
 883                                  */
 884                                 synchronized (pauseLock) {
 885                                     needPause = ldr.addReplyBer(retBer);
 886                                     if (needPause) {
 887                                         /*
 888                                          * Go into paused state; release
 889                                          * pauseLock
 890                                          */
 891                                         pauseReader();
 892                                     }
 893 
 894                                     // else release pauseLock
 895                                 }
 896                             } else {
 897                                 // System.err.println("Cannot find" +
 898                                 //              "LdapRequest for " + inMsgId);
 899                             }
 900                         }
 901                     } catch (Ber.DecodeException e) {
 902                         //System.err.println("Cannot parse Ber");
 903                     }
 904                 } catch (IOException ie) {
 905                     if (debug) {
 906                         System.err.println("Connection: Inside Caught " + ie);
 907                         ie.printStackTrace();
 908                     }
 909 
 910                     if (in != getInputStream()) {
 911                         // A new stream to try
 912                         // Go to top of loop and continue
 913                     } else {
 914                         if (debug) {
 915                             System.err.println("Connection: rethrowing " + ie);
 916                         }
 917                         throw ie;  // rethrow exception
 918                     }
 919                 }
 920             }
 921 
 922             if (debug) {
 923                 System.err.println("Connection: end-of-stream detected: "
 924                     + in);
 925             }
 926         } catch (IOException ex) {
 927             if (debug) {
 928                 System.err.println("Connection: Caught " + ex);
 929             }
 930             closureReason = ex;
 931         } finally {
 932             cleanup(null, true); // cleanup
 933         }
 934         if (debug) {
 935             System.err.println("Connection: Thread Exiting");
 936         }
 937     }
 938 
 939     private static byte[] readFully(InputStream is, int length)
 940         throws IOException
 941     {
 942         byte[] buf = new byte[Math.min(length, 8192)];
 943         int nread = 0;
 944         while (nread < length) {
 945             int bytesToRead;
 946             if (nread >= buf.length) {  // need to allocate a larger buffer
 947                 bytesToRead = Math.min(length - nread, buf.length + 8192);
 948                 if (buf.length < nread + bytesToRead) {
 949                     buf = Arrays.copyOf(buf, nread + bytesToRead);
 950                 }
 951             } else {
 952                 bytesToRead = buf.length - nread;
 953             }
 954             int count = is.read(buf, nread, bytesToRead);
 955             if (count < 0) {
 956                 if (buf.length != nread)
 957                     buf = Arrays.copyOf(buf, nread);
 958                 break;
 959             }
 960             nread += count;
 961         }
 962         return buf;
 963     }
 964 
 965     // This code must be uncommented to run the LdapAbandonTest.
 966     /*public void sendSearchReqs(String dn, int numReqs) {
 967         int i;
 968         String attrs[] = null;
 969         for(i = 1; i <= numReqs; i++) {
 970             BerEncoder ber = new BerEncoder(2048);
 971 
 972             try {
 973             ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
 974                 ber.encodeInt(i);
 975                 ber.beginSeq(LdapClient.LDAP_REQ_SEARCH);
 976                     ber.encodeString(dn == null ? "" : dn);
 977                     ber.encodeInt(0, LdapClient.LBER_ENUMERATED);
 978                     ber.encodeInt(3, LdapClient.LBER_ENUMERATED);
 979                     ber.encodeInt(0);
 980                     ber.encodeInt(0);
 981                     ber.encodeBoolean(true);
 982                     LdapClient.encodeFilter(ber, "");
 983                     ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
 984                         ber.encodeStringArray(attrs);
 985                     ber.endSeq();
 986                 ber.endSeq();
 987             ber.endSeq();
 988             writeRequest(ber, i);
 989             //System.err.println("wrote request " + i);
 990             } catch (Exception ex) {
 991             //System.err.println("ldap.search: Caught " + ex + " building req");
 992             }
 993 
 994         }
 995     } */
 996 }