1 /*
   2  * Copyright (c) 1999, 2014, 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                             waited = true;
 463                         } else {
 464                             // no timeout is set so we wait infinitely until
 465                             // a response is received
 466                             // http://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-ldap.html#PROP
 467                             ldr.wait();
 468                         }
 469                     } else {
 470                         break;
 471                     }
 472                 }
 473             } catch (InterruptedException ex) {
 474                 throw new InterruptedNamingException(
 475                     "Interrupted during LDAP operation");
 476             }
 477         }
 478 
 479         if ((rber == null) && waited) {
 480             abandonRequest(ldr, null);
 481             throw new NamingException("LDAP response read timed out, timeout used:"
 482                             + readTimeout + "ms." );
 483 
 484         }
 485         return rber;
 486     }
 487 
 488 
 489     ////////////////////////////////////////////////////////////////////////////
 490     //
 491     // Methods to add, find, delete, and abandon requests made to server
 492     //
 493     ////////////////////////////////////////////////////////////////////////////
 494 
 495     private synchronized void addRequest(LdapRequest ldapRequest) {
 496 
 497         LdapRequest ldr = pendingRequests;
 498         if (ldr == null) {
 499             pendingRequests = ldapRequest;
 500             ldapRequest.next = null;
 501         } else {
 502             ldapRequest.next = pendingRequests;
 503             pendingRequests = ldapRequest;
 504         }
 505     }
 506 
 507     synchronized LdapRequest findRequest(int msgId) {
 508 
 509         LdapRequest ldr = pendingRequests;
 510         while (ldr != null) {
 511             if (ldr.msgId == msgId) {
 512                 return ldr;
 513             }
 514             ldr = ldr.next;
 515         }
 516         return null;
 517 
 518     }
 519 
 520     synchronized void removeRequest(LdapRequest req) {
 521         LdapRequest ldr = pendingRequests;
 522         LdapRequest ldrprev = null;
 523 
 524         while (ldr != null) {
 525             if (ldr == req) {
 526                 ldr.cancel();
 527 
 528                 if (ldrprev != null) {
 529                     ldrprev.next = ldr.next;
 530                 } else {
 531                     pendingRequests = ldr.next;
 532                 }
 533                 ldr.next = null;
 534             }
 535             ldrprev = ldr;
 536             ldr = ldr.next;
 537         }
 538     }
 539 
 540     void abandonRequest(LdapRequest ldr, Control[] reqCtls) {
 541         // Remove from queue
 542         removeRequest(ldr);
 543 
 544         BerEncoder ber = new BerEncoder(256);
 545         int abandonMsgId = getMsgId();
 546 
 547         //
 548         // build the abandon request.
 549         //
 550         try {
 551             ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
 552                 ber.encodeInt(abandonMsgId);
 553                 ber.encodeInt(ldr.msgId, LdapClient.LDAP_REQ_ABANDON);
 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(), 0,
 562                     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.abandon: " + ex);
 572         }
 573 
 574         // Don't expect any response for the abandon request.
 575     }
 576 
 577     synchronized void abandonOutstandingReqs(Control[] reqCtls) {
 578         LdapRequest ldr = pendingRequests;
 579 
 580         while (ldr != null) {
 581             abandonRequest(ldr, reqCtls);
 582             pendingRequests = ldr = ldr.next;
 583         }
 584     }
 585 
 586     ////////////////////////////////////////////////////////////////////////////
 587     //
 588     // Methods to unbind from server and clear up resources when object is
 589     // destroyed.
 590     //
 591     ////////////////////////////////////////////////////////////////////////////
 592 
 593     private void ldapUnbind(Control[] reqCtls) {
 594 
 595         BerEncoder ber = new BerEncoder(256);
 596         int unbindMsgId = getMsgId();
 597 
 598         //
 599         // build the unbind request.
 600         //
 601 
 602         try {
 603 
 604             ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
 605                 ber.encodeInt(unbindMsgId);
 606                 // IMPLICIT TAGS
 607                 ber.encodeByte(LdapClient.LDAP_REQ_UNBIND);
 608                 ber.encodeByte(0);
 609 
 610                 if (v3) {
 611                     LdapClient.encodeControls(ber, reqCtls);
 612                 }
 613             ber.endSeq();
 614 
 615             if (traceFile != null) {
 616                 Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(),
 617                     0, ber.getDataLen());
 618             }
 619 
 620             synchronized (this) {
 621                 outStream.write(ber.getBuf(), 0, ber.getDataLen());
 622                 outStream.flush();
 623             }
 624 
 625         } catch (IOException ex) {
 626             //System.err.println("ldap.unbind: " + ex);
 627         }
 628 
 629         // Don't expect any response for the unbind request.
 630     }
 631 
 632     /**
 633      * @param reqCtls Possibly null request controls that accompanies the
 634      *    abandon and unbind LDAP request.
 635      * @param notifyParent true means to call parent LdapClient back, notifying
 636      *    it that the connection has been closed; false means not to notify
 637      *    parent. If LdapClient invokes cleanup(), notifyParent should be set to
 638      *    false because LdapClient already knows that it is closing
 639      *    the connection. If Connection invokes cleanup(), notifyParent should be
 640      *    set to true because LdapClient needs to know about the closure.
 641      */
 642     void cleanup(Control[] reqCtls, boolean notifyParent) {
 643         boolean nparent = false;
 644 
 645         synchronized (this) {
 646             useable = false;
 647 
 648             if (sock != null) {
 649                 if (debug) {
 650                     System.err.println("Connection: closing socket: " + host + "," + port);
 651                 }
 652                 try {
 653                     if (!notifyParent) {
 654                         abandonOutstandingReqs(reqCtls);
 655                     }
 656                     if (bound) {
 657                         ldapUnbind(reqCtls);
 658                     }
 659                 } finally {
 660                     try {
 661                         outStream.flush();
 662                         sock.close();
 663                         unpauseReader();
 664                     } catch (IOException ie) {
 665                         if (debug)
 666                             System.err.println("Connection: problem closing socket: " + ie);
 667                     }
 668                     if (!notifyParent) {
 669                         LdapRequest ldr = pendingRequests;
 670                         while (ldr != null) {
 671                             ldr.cancel();
 672                             ldr = ldr.next;
 673                         }
 674                     }
 675                     sock = null;
 676                 }
 677                 nparent = notifyParent;
 678             }
 679             if (nparent) {
 680                 LdapRequest ldr = pendingRequests;
 681                 while (ldr != null) {
 682 
 683                     synchronized (ldr) {
 684                         ldr.notify();
 685                         ldr = ldr.next;
 686                     }
 687                 }
 688             }
 689         }
 690         if (nparent) {
 691             parent.processConnectionClosure();
 692         }
 693     }
 694 
 695 
 696     // Assume everything is "quiet"
 697     // "synchronize" might lead to deadlock so don't synchronize method
 698     // Use streamLock instead for synchronizing update to stream
 699 
 700     synchronized public void replaceStreams(InputStream newIn, OutputStream newOut) {
 701         if (debug) {
 702             System.err.println("Replacing " + inStream + " with: " + newIn);
 703             System.err.println("Replacing " + outStream + " with: " + newOut);
 704         }
 705 
 706         inStream = newIn;
 707 
 708         // Cleanup old stream
 709         try {
 710             outStream.flush();
 711         } catch (IOException ie) {
 712             if (debug)
 713                 System.err.println("Connection: cannot flush outstream: " + ie);
 714         }
 715 
 716         // Replace stream
 717         outStream = newOut;
 718     }
 719 
 720     /**
 721      * Used by Connection thread to read inStream into a local variable.
 722      * This ensures that there is no contention between the main thread
 723      * and the Connection thread when the main thread updates inStream.
 724      */
 725     synchronized private InputStream getInputStream() {
 726         return inStream;
 727     }
 728 
 729 
 730     ////////////////////////////////////////////////////////////////////////////
 731     //
 732     // Code for pausing/unpausing the reader thread ('worker')
 733     //
 734     ////////////////////////////////////////////////////////////////////////////
 735 
 736     /*
 737      * The main idea is to mark requests that need the reader thread to
 738      * pause after getting the response. When the reader thread gets the response,
 739      * it waits on a lock instead of returning to the read(). The next time a
 740      * request is sent, the reader is automatically unblocked if necessary.
 741      * Note that the reader must be unblocked BEFORE the request is sent.
 742      * Otherwise, there is a race condition where the request is sent and
 743      * the reader thread might read the response and be unblocked
 744      * by writeRequest().
 745      *
 746      * This pause gives the main thread (StartTLS or SASL) an opportunity to
 747      * update the reader's state (e.g., its streams) if necessary.
 748      * The assumption is that the connection will remain quiet during this pause
 749      * (i.e., no intervening requests being sent).
 750      *<p>
 751      * For dealing with StartTLS close,
 752      * when the read() exits either due to EOF or an exception,
 753      * the reader thread checks whether there is a new stream to read from.
 754      * If so, then it reattempts the read. Otherwise, the EOF or exception
 755      * is processed and the reader thread terminates.
 756      * In a StartTLS close, the client first replaces the SSL IO streams with
 757      * plain ones and then closes the SSL socket.
 758      * If the reader thread attempts to read, or was reading, from
 759      * the SSL socket (that is, it got to the read BEFORE replaceStreams()),
 760      * the SSL socket close will cause the reader thread to
 761      * get an EOF/exception and reexamine the input stream.
 762      * If the reader thread sees a new stream, it reattempts the read.
 763      * If the underlying socket is still alive, then the new read will succeed.
 764      * If the underlying socket has been closed also, then the new read will
 765      * fail and the reader thread exits.
 766      * If the reader thread attempts to read, or was reading, from the plain
 767      * socket (that is, it got to the read AFTER replaceStreams()), the
 768      * SSL socket close will have no effect on the reader thread.
 769      *
 770      * The check for new stream is made only
 771      * in the first attempt at reading a BER buffer; the reader should
 772      * never be in midst of reading a buffer when a nonfatal close occurs.
 773      * If this occurs, then the connection is in an inconsistent state and
 774      * the safest thing to do is to shut it down.
 775      */
 776 
 777     private Object pauseLock = new Object();  // lock for reader to wait on while paused
 778     private boolean paused = false;           // paused state of reader
 779 
 780     /*
 781      * Unpauses reader thread if it was paused
 782      */
 783     private void unpauseReader() throws IOException {
 784         synchronized (pauseLock) {
 785             if (paused) {
 786                 if (debug) {
 787                     System.err.println("Unpausing reader; read from: " +
 788                                         inStream);
 789                 }
 790                 paused = false;
 791                 pauseLock.notify();
 792             }
 793         }
 794     }
 795 
 796      /*
 797      * Pauses reader so that it stops reading from the input stream.
 798      * Reader blocks on pauseLock instead of read().
 799      * MUST be called from within synchronized (pauseLock) clause.
 800      */
 801     private void pauseReader() throws IOException {
 802         if (debug) {
 803             System.err.println("Pausing reader;  was reading from: " +
 804                                 inStream);
 805         }
 806         paused = true;
 807         try {
 808             while (paused) {
 809                 pauseLock.wait(); // notified by unpauseReader
 810             }
 811         } catch (InterruptedException e) {
 812             throw new InterruptedIOException(
 813                     "Pause/unpause reader has problems.");
 814         }
 815     }
 816 
 817 
 818     ////////////////////////////////////////////////////////////////////////////
 819     //
 820     // The LDAP Binding thread. It does the mux/demux of multiple requests
 821     // on the same TCP connection.
 822     //
 823     ////////////////////////////////////////////////////////////////////////////
 824 
 825 
 826     public void run() {
 827         byte inbuf[];   // Buffer for reading incoming bytes
 828         int inMsgId;    // Message id of incoming response
 829         int bytesread;  // Number of bytes in inbuf
 830         int br;         // Temp; number of bytes read from stream
 831         int offset;     // Offset of where to store bytes in inbuf
 832         int seqlen;     // Length of ASN sequence
 833         int seqlenlen;  // Number of sequence length bytes
 834         boolean eos;    // End of stream
 835         BerDecoder retBer;    // Decoder for ASN.1 BER data from inbuf
 836         InputStream in = null;
 837 
 838         try {
 839             while (true) {
 840                 try {
 841                     // type and length (at most 128 octets for long form)
 842                     inbuf = new byte[129];
 843 
 844                     offset = 0;
 845                     seqlen = 0;
 846                     seqlenlen = 0;
 847 
 848                     in = getInputStream();
 849 
 850                     // check that it is the beginning of a sequence
 851                     bytesread = in.read(inbuf, offset, 1);
 852                     if (bytesread < 0) {
 853                         if (in != getInputStream()) {
 854                             continue;   // a new stream to try
 855                         } else {
 856                             break; // EOF
 857                         }
 858                     }
 859 
 860                     if (inbuf[offset++] != (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR))
 861                         continue;
 862 
 863                     // get length of sequence
 864                     bytesread = in.read(inbuf, offset, 1);
 865                     if (bytesread < 0)
 866                         break; // EOF
 867                     seqlen = inbuf[offset++];
 868 
 869                     // if high bit is on, length is encoded in the
 870                     // subsequent length bytes and the number of length bytes
 871                     // is equal to & 0x80 (i.e. length byte with high bit off).
 872                     if ((seqlen & 0x80) == 0x80) {
 873                         seqlenlen = seqlen & 0x7f;  // number of length bytes
 874 
 875                         bytesread = 0;
 876                         eos = false;
 877 
 878                         // Read all length bytes
 879                         while (bytesread < seqlenlen) {
 880                             br = in.read(inbuf, offset+bytesread,
 881                                 seqlenlen-bytesread);
 882                             if (br < 0) {
 883                                 eos = true;
 884                                 break; // EOF
 885                             }
 886                             bytesread += br;
 887                         }
 888 
 889                         // end-of-stream reached before length bytes are read
 890                         if (eos)
 891                             break;  // EOF
 892 
 893                         // Add contents of length bytes to determine length
 894                         seqlen = 0;
 895                         for( int i = 0; i < seqlenlen; i++) {
 896                             seqlen = (seqlen << 8) + (inbuf[offset+i] & 0xff);
 897                         }
 898                         offset += bytesread;
 899                     }
 900 
 901                     // read in seqlen bytes
 902                     byte[] left = IOUtils.readFully(in, seqlen, false);
 903                     inbuf = Arrays.copyOf(inbuf, offset + left.length);
 904                     System.arraycopy(left, 0, inbuf, offset, left.length);
 905                     offset += left.length;
 906 /*
 907 if (dump > 0) {
 908 System.err.println("seqlen: " + seqlen);
 909 System.err.println("bufsize: " + offset);
 910 System.err.println("bytesleft: " + bytesleft);
 911 System.err.println("bytesread: " + bytesread);
 912 }
 913 */
 914 
 915 
 916                     try {
 917                         retBer = new BerDecoder(inbuf, 0, offset);
 918 
 919                         if (traceFile != null) {
 920                             Ber.dumpBER(traceFile, traceTagIn, inbuf, 0, offset);
 921                         }
 922 
 923                         retBer.parseSeq(null);
 924                         inMsgId = retBer.parseInt();
 925                         retBer.reset(); // reset offset
 926 
 927                         boolean needPause = false;
 928 
 929                         if (inMsgId == 0) {
 930                             // Unsolicited Notification
 931                             parent.processUnsolicited(retBer);
 932                         } else {
 933                             LdapRequest ldr = findRequest(inMsgId);
 934 
 935                             if (ldr != null) {
 936 
 937                                 /**
 938                                  * Grab pauseLock before making reply available
 939                                  * to ensure that reader goes into paused state
 940                                  * before writer can attempt to unpause reader
 941                                  */
 942                                 synchronized (pauseLock) {
 943                                     needPause = ldr.addReplyBer(retBer);
 944                                     if (needPause) {
 945                                         /*
 946                                          * Go into paused state; release
 947                                          * pauseLock
 948                                          */
 949                                         pauseReader();
 950                                     }
 951 
 952                                     // else release pauseLock
 953                                 }
 954                             } else {
 955                                 // System.err.println("Cannot find" +
 956                                 //              "LdapRequest for " + inMsgId);
 957                             }
 958                         }
 959                     } catch (Ber.DecodeException e) {
 960                         //System.err.println("Cannot parse Ber");
 961                     }
 962                 } catch (IOException ie) {
 963                     if (debug) {
 964                         System.err.println("Connection: Inside Caught " + ie);
 965                         ie.printStackTrace();
 966                     }
 967 
 968                     if (in != getInputStream()) {
 969                         // A new stream to try
 970                         // Go to top of loop and continue
 971                     } else {
 972                         if (debug) {
 973                             System.err.println("Connection: rethrowing " + ie);
 974                         }
 975                         throw ie;  // rethrow exception
 976                     }
 977                 }
 978             }
 979 
 980             if (debug) {
 981                 System.err.println("Connection: end-of-stream detected: "
 982                     + in);
 983             }
 984         } catch (IOException ex) {
 985             if (debug) {
 986                 System.err.println("Connection: Caught " + ex);
 987             }
 988             closureReason = ex;
 989         } finally {
 990             cleanup(null, true); // cleanup
 991         }
 992         if (debug) {
 993             System.err.println("Connection: Thread Exiting");
 994         }
 995     }
 996 
 997 
 998     // This code must be uncommented to run the LdapAbandonTest.
 999     /*public void sendSearchReqs(String dn, int numReqs) {
1000         int i;
1001         String attrs[] = null;
1002         for(i = 1; i <= numReqs; i++) {
1003             BerEncoder ber = new BerEncoder(2048);
1004 
1005             try {
1006             ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
1007                 ber.encodeInt(i);
1008                 ber.beginSeq(LdapClient.LDAP_REQ_SEARCH);
1009                     ber.encodeString(dn == null ? "" : dn);
1010                     ber.encodeInt(0, LdapClient.LBER_ENUMERATED);
1011                     ber.encodeInt(3, LdapClient.LBER_ENUMERATED);
1012                     ber.encodeInt(0);
1013                     ber.encodeInt(0);
1014                     ber.encodeBoolean(true);
1015                     LdapClient.encodeFilter(ber, "");
1016                     ber.beginSeq(Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR);
1017                         ber.encodeStringArray(attrs);
1018                     ber.endSeq();
1019                 ber.endSeq();
1020             ber.endSeq();
1021             writeRequest(ber, i);
1022             //System.err.println("wrote request " + i);
1023             } catch (Exception ex) {
1024             //System.err.println("ldap.search: Caught " + ex + " building req");
1025             }
1026 
1027         }
1028     } */
1029 }