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