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