Wed, 09 Sep 2020 14:19:14 -0400
8062947: Fix exception message to correctly represent LDAP connection failure
Reviewed-by: dfuchs, xyin, vtewari
1 /*
2 * Copyright (c) 1999, 2020, 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 */
26 package com.sun.jndi.ldap;
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;
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;
50 /**
51 * A thread that creates a connection to an LDAP server.
52 * After the connection, the thread reads from the connection.
53 * A caller can invoke methods on the instance to read LDAP responses
54 * and to send LDAP requests.
55 * <p>
56 * There is a one-to-one correspondence between an LdapClient and
57 * a Connection. Access to Connection and its methods is only via
58 * LdapClient with two exceptions: SASL authentication and StartTLS.
59 * SASL needs to access Connection's socket IO streams (in order to do encryption
60 * of the security layer). StartTLS needs to do replace IO streams
61 * and close the IO streams on nonfatal close. The code for SASL
62 * authentication can be treated as being the same as from LdapClient
63 * because the SASL code is only ever called from LdapClient, from
64 * inside LdapClient's synchronized authenticate() method. StartTLS is called
65 * directly by the application but should only occur when the underlying
66 * connection is quiet.
67 * <p>
68 * In terms of synchronization, worry about data structures
69 * used by the Connection thread because that usage might contend
70 * with calls by the main threads (i.e., those that call LdapClient).
71 * Main threads need to worry about contention with each other.
72 * Fields that Connection thread uses:
73 * inStream - synced access and update; initialized in constructor;
74 * referenced outside class unsync'ed (by LdapSasl) only
75 * when connection is quiet
76 * traceFile, traceTagIn, traceTagOut - no sync; debugging only
77 * parent - no sync; initialized in constructor; no updates
78 * pendingRequests - sync
79 * pauseLock - per-instance lock;
80 * paused - sync via pauseLock (pauseReader())
81 * Members used by main threads (LdapClient):
82 * host, port - unsync; read-only access for StartTLS and debug messages
83 * setBound(), setV3() - no sync; called only by LdapClient.authenticate(),
84 * which is a sync method called only when connection is "quiet"
85 * getMsgId() - sync
86 * writeRequest(), removeRequest(),findRequest(), abandonOutstandingReqs() -
87 * access to shared pendingRequests is sync
88 * writeRequest(), abandonRequest(), ldapUnbind() - access to outStream sync
89 * cleanup() - sync
90 * readReply() - access to sock sync
91 * unpauseReader() - (indirectly via writeRequest) sync on pauseLock
92 * Members used by SASL auth (main thread):
93 * inStream, outStream - no sync; used to construct new stream; accessed
94 * only when conn is "quiet" and not shared
95 * replaceStreams() - sync method
96 * Members used by StartTLS:
97 * inStream, outStream - no sync; used to record the existing streams;
98 * accessed only when conn is "quiet" and not shared
99 * replaceStreams() - sync method
100 * <p>
101 * Handles anonymous, simple, and SASL bind for v3; anonymous and simple
102 * for v2.
103 * %%% made public for access by LdapSasl %%%
104 *
105 * @author Vincent Ryan
106 * @author Rosanna Lee
107 * @author Jagane Sundar
108 */
109 public final class Connection implements Runnable {
111 private static final boolean debug = false;
112 private static final int dump = 0; // > 0 r, > 1 rw
115 final private Thread worker; // Initialized in constructor
117 private boolean v3 = true; // Set in setV3()
119 final public String host; // used by LdapClient for generating exception messages
120 // used by StartTlsResponse when creating an SSL socket
121 final public int port; // used by LdapClient for generating exception messages
122 // used by StartTlsResponse when creating an SSL socket
124 private boolean bound = false; // Set in setBound()
126 // All three are initialized in constructor and read-only afterwards
127 private OutputStream traceFile = null;
128 private String traceTagIn = null;
129 private String traceTagOut = null;
131 // Initialized in constructor; read and used externally (LdapSasl);
132 // Updated in replaceStreams() during "quiet", unshared, period
133 public InputStream inStream; // must be public; used by LdapSasl
135 // Initialized in constructor; read and used externally (LdapSasl);
136 // Updated in replaceOutputStream() during "quiet", unshared, period
137 public OutputStream outStream; // must be public; used by LdapSasl
139 // Initialized in constructor; read and used externally (TLS) to
140 // get new IO streams; closed during cleanup
141 public Socket sock; // for TLS
143 // For processing "disconnect" unsolicited notification
144 // Initialized in constructor
145 final private LdapClient parent;
147 // Incremented and returned in sync getMsgId()
148 private int outMsgId = 0;
150 //
151 // The list of ldapRequests pending on this binding
152 //
153 // Accessed only within sync methods
154 private LdapRequest pendingRequests = null;
156 volatile IOException closureReason = null;
157 volatile boolean useable = true; // is Connection still useable
159 int readTimeout;
160 int connectTimeout;
161 private static final boolean IS_HOSTNAME_VERIFICATION_DISABLED
162 = hostnameVerificationDisabledValue();
164 private static boolean hostnameVerificationDisabledValue() {
165 PrivilegedAction<String> act = () -> System.getProperty(
166 "com.sun.jndi.ldap.object.disableEndpointIdentification");
167 String prop = AccessController.doPrivileged(act);
168 if (prop == null) {
169 return false;
170 }
171 return prop.isEmpty() ? true : Boolean.parseBoolean(prop);
172 }
173 // true means v3; false means v2
174 // Called in LdapClient.authenticate() (which is synchronized)
175 // when connection is "quiet" and not shared; no need to synchronize
176 void setV3(boolean v) {
177 v3 = v;
178 }
180 // A BIND request has been successfully made on this connection
181 // When cleaning up, remember to do an UNBIND
182 // Called in LdapClient.authenticate() (which is synchronized)
183 // when connection is "quiet" and not shared; no need to synchronize
184 void setBound() {
185 bound = true;
186 }
188 ////////////////////////////////////////////////////////////////////////////
189 //
190 // Create an LDAP Binding object and bind to a particular server
191 //
192 ////////////////////////////////////////////////////////////////////////////
194 Connection(LdapClient parent, String host, int port, String socketFactory,
195 int connectTimeout, int readTimeout, OutputStream trace) throws NamingException {
197 this.host = host;
198 this.port = port;
199 this.parent = parent;
200 this.readTimeout = readTimeout;
201 this.connectTimeout = connectTimeout;
203 if (trace != null) {
204 traceFile = trace;
205 traceTagIn = "<- " + host + ":" + port + "\n\n";
206 traceTagOut = "-> " + host + ":" + port + "\n\n";
207 }
209 //
210 // Connect to server
211 //
212 try {
213 sock = createSocket(host, port, socketFactory, connectTimeout);
215 if (debug) {
216 System.err.println("Connection: opening socket: " + host + "," + port);
217 }
219 inStream = new BufferedInputStream(sock.getInputStream());
220 outStream = new BufferedOutputStream(sock.getOutputStream());
222 } catch (InvocationTargetException e) {
223 Throwable realException = e.getTargetException();
224 // realException.printStackTrace();
226 CommunicationException ce =
227 new CommunicationException(host + ":" + port);
228 ce.setRootCause(realException);
229 throw ce;
230 } catch (Exception e) {
231 // Class.forName() seems to do more error checking
232 // and will throw IllegalArgumentException and such.
233 // That's why we need to have a catch all here and
234 // ignore generic exceptions.
235 // Also catches all IO errors generated by socket creation.
236 CommunicationException ce =
237 new CommunicationException(host + ":" + port);
238 ce.setRootCause(e);
239 throw ce;
240 }
242 worker = Obj.helper.createThread(this);
243 worker.setDaemon(true);
244 worker.start();
245 }
247 /*
248 * Create an InetSocketAddress using the specified hostname and port number.
249 */
250 private Object createInetSocketAddress(String host, int port)
251 throws NoSuchMethodException {
253 try {
254 Class<?> inetSocketAddressClass =
255 Class.forName("java.net.InetSocketAddress");
257 Constructor<?> inetSocketAddressCons =
258 inetSocketAddressClass.getConstructor(new Class<?>[]{
259 String.class, int.class});
261 return inetSocketAddressCons.newInstance(new Object[]{
262 host, new Integer(port)});
264 } catch (ClassNotFoundException |
265 InstantiationException |
266 InvocationTargetException |
267 IllegalAccessException e) {
268 throw new NoSuchMethodException();
270 }
271 }
273 /*
274 * Create a Socket object using the specified socket factory and time limit.
275 *
276 * If a timeout is supplied and unconnected sockets are supported then
277 * an unconnected socket is created and the timeout is applied when
278 * connecting the socket. If a timeout is supplied but unconnected sockets
279 * are not supported then the timeout is ignored and a connected socket
280 * is created.
281 */
282 private Socket createSocket(String host, int port, String socketFactory,
283 int connectTimeout) throws Exception {
285 Socket socket = null;
287 if (socketFactory != null) {
289 // create the factory
291 Class<?> socketFactoryClass = Obj.helper.loadClass(socketFactory);
292 Method getDefault =
293 socketFactoryClass.getMethod("getDefault", new Class<?>[]{});
294 Object factory = getDefault.invoke(null, new Object[]{});
296 // create the socket
298 Method createSocket = null;
300 if (connectTimeout > 0) {
302 try {
303 createSocket = socketFactoryClass.getMethod("createSocket",
304 new Class<?>[]{});
306 Method connect = Socket.class.getMethod("connect",
307 new Class<?>[]{Class.forName("java.net.SocketAddress"),
308 int.class});
309 Object endpoint = createInetSocketAddress(host, port);
311 // unconnected socket
312 socket =
313 (Socket)createSocket.invoke(factory, new Object[]{});
315 if (debug) {
316 System.err.println("Connection: creating socket with " +
317 "a timeout using supplied socket factory");
318 }
320 // connected socket
321 connect.invoke(socket, new Object[]{
322 endpoint, new Integer(connectTimeout)});
324 } catch (NoSuchMethodException e) {
325 // continue (but ignore connectTimeout)
326 }
327 }
329 if (socket == null) {
330 createSocket = socketFactoryClass.getMethod("createSocket",
331 new Class<?>[]{String.class, int.class});
333 if (debug) {
334 System.err.println("Connection: creating socket using " +
335 "supplied socket factory");
336 }
337 // connected socket
338 socket = (Socket) createSocket.invoke(factory,
339 new Object[]{host, new Integer(port)});
340 }
341 } else {
343 if (connectTimeout > 0) {
345 try {
346 Constructor<Socket> socketCons =
347 Socket.class.getConstructor(new Class<?>[]{});
349 Method connect = Socket.class.getMethod("connect",
350 new Class<?>[]{Class.forName("java.net.SocketAddress"),
351 int.class});
352 Object endpoint = createInetSocketAddress(host, port);
354 socket = socketCons.newInstance(new Object[]{});
356 if (debug) {
357 System.err.println("Connection: creating socket with " +
358 "a timeout");
359 }
360 connect.invoke(socket, new Object[]{
361 endpoint, new Integer(connectTimeout)});
363 } catch (NoSuchMethodException e) {
364 // continue (but ignore connectTimeout)
365 }
366 }
368 if (socket == null) {
369 if (debug) {
370 System.err.println("Connection: creating socket");
371 }
372 // connected socket
373 socket = new Socket(host, port);
374 }
375 }
377 // For LDAP connect timeouts on LDAP over SSL connections must treat
378 // the SSL handshake following socket connection as part of the timeout.
379 // So explicitly set a socket read timeout, trigger the SSL handshake,
380 // then reset the timeout.
381 if (socket instanceof SSLSocket) {
382 SSLSocket sslSocket = (SSLSocket) socket;
383 if (!IS_HOSTNAME_VERIFICATION_DISABLED) {
384 SSLParameters param = sslSocket.getSSLParameters();
385 param.setEndpointIdentificationAlgorithm("LDAPS");
386 sslSocket.setSSLParameters(param);
387 }
388 if (connectTimeout > 0) {
389 int socketTimeout = sslSocket.getSoTimeout();
390 sslSocket.setSoTimeout(connectTimeout); // reuse full timeout value
391 sslSocket.startHandshake();
392 sslSocket.setSoTimeout(socketTimeout);
393 }
394 }
395 return socket;
396 }
398 ////////////////////////////////////////////////////////////////////////////
399 //
400 // Methods to IO to the LDAP server
401 //
402 ////////////////////////////////////////////////////////////////////////////
404 synchronized int getMsgId() {
405 return ++outMsgId;
406 }
408 LdapRequest writeRequest(BerEncoder ber, int msgId) throws IOException {
409 return writeRequest(ber, msgId, false /* pauseAfterReceipt */, -1);
410 }
412 LdapRequest writeRequest(BerEncoder ber, int msgId,
413 boolean pauseAfterReceipt) throws IOException {
414 return writeRequest(ber, msgId, pauseAfterReceipt, -1);
415 }
417 LdapRequest writeRequest(BerEncoder ber, int msgId,
418 boolean pauseAfterReceipt, int replyQueueCapacity) throws IOException {
420 LdapRequest req =
421 new LdapRequest(msgId, pauseAfterReceipt, replyQueueCapacity);
422 addRequest(req);
424 if (traceFile != null) {
425 Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0, ber.getDataLen());
426 }
429 // unpause reader so that it can get response
430 // NOTE: Must do this before writing request, otherwise might
431 // create a race condition where the writer unblocks its own response
432 unpauseReader();
434 if (debug) {
435 System.err.println("Writing request to: " + outStream);
436 }
438 try {
439 synchronized (this) {
440 outStream.write(ber.getBuf(), 0, ber.getDataLen());
441 outStream.flush();
442 }
443 } catch (IOException e) {
444 cleanup(null, true);
445 throw (closureReason = e); // rethrow
446 }
448 return req;
449 }
451 /**
452 * Reads a reply; waits until one is ready.
453 */
454 BerDecoder readReply(LdapRequest ldr) throws IOException, NamingException {
455 BerDecoder rber;
457 NamingException namingException = null;
458 try {
459 // if no timeout is set so we wait infinitely until
460 // a response is received OR until the connection is closed or cancelled
461 // http://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-ldap.html#PROP
462 rber = ldr.getReplyBer(readTimeout);
463 } catch (InterruptedException ex) {
464 throw new InterruptedNamingException(
465 "Interrupted during LDAP operation");
466 } catch (CommunicationException ce) {
467 // Re-throw
468 throw ce;
469 } catch (NamingException ne) {
470 // Connection is timed out OR closed/cancelled
471 namingException = ne;
472 rber = null;
473 }
475 if (rber == null) {
476 abandonRequest(ldr, null);
477 }
478 // namingException can be not null in the following cases:
479 // a) The response is timed-out
480 // b) LDAP request connection has been closed or cancelled
481 // The exception message is initialized in LdapRequest::getReplyBer
482 if (namingException != null) {
483 // Re-throw NamingException after all cleanups are done
484 throw namingException;
485 }
486 return rber;
487 }
489 ////////////////////////////////////////////////////////////////////////////
490 //
491 // Methods to add, find, delete, and abandon requests made to server
492 //
493 ////////////////////////////////////////////////////////////////////////////
495 private synchronized void addRequest(LdapRequest ldapRequest) {
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 }
507 synchronized LdapRequest findRequest(int msgId) {
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;
518 }
520 synchronized void removeRequest(LdapRequest req) {
521 LdapRequest ldr = pendingRequests;
522 LdapRequest ldrprev = null;
524 while (ldr != null) {
525 if (ldr == req) {
526 ldr.cancel();
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 }
540 void abandonRequest(LdapRequest ldr, Control[] reqCtls) {
541 // Remove from queue
542 removeRequest(ldr);
544 BerEncoder ber = new BerEncoder(256);
545 int abandonMsgId = getMsgId();
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);
555 if (v3) {
556 LdapClient.encodeControls(ber, reqCtls);
557 }
558 ber.endSeq();
560 if (traceFile != null) {
561 Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(), 0,
562 ber.getDataLen());
563 }
565 synchronized (this) {
566 outStream.write(ber.getBuf(), 0, ber.getDataLen());
567 outStream.flush();
568 }
570 } catch (IOException ex) {
571 //System.err.println("ldap.abandon: " + ex);
572 }
574 // Don't expect any response for the abandon request.
575 }
577 synchronized void abandonOutstandingReqs(Control[] reqCtls) {
578 LdapRequest ldr = pendingRequests;
580 while (ldr != null) {
581 abandonRequest(ldr, reqCtls);
582 pendingRequests = ldr = ldr.next;
583 }
584 }
586 ////////////////////////////////////////////////////////////////////////////
587 //
588 // Methods to unbind from server and clear up resources when object is
589 // destroyed.
590 //
591 ////////////////////////////////////////////////////////////////////////////
593 private void ldapUnbind(Control[] reqCtls) {
595 BerEncoder ber = new BerEncoder(256);
596 int unbindMsgId = getMsgId();
598 //
599 // build the unbind request.
600 //
602 try {
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);
610 if (v3) {
611 LdapClient.encodeControls(ber, reqCtls);
612 }
613 ber.endSeq();
615 if (traceFile != null) {
616 Ber.dumpBER(traceFile, traceTagOut, ber.getBuf(),
617 0, ber.getDataLen());
618 }
620 synchronized (this) {
621 outStream.write(ber.getBuf(), 0, ber.getDataLen());
622 outStream.flush();
623 }
625 } catch (IOException ex) {
626 //System.err.println("ldap.unbind: " + ex);
627 }
629 // Don't expect any response for the unbind request.
630 }
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;
645 synchronized (this) {
646 useable = false;
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 ldr.close();
683 ldr = ldr.next;
684 }
685 }
686 }
687 if (nparent) {
688 parent.processConnectionClosure();
689 }
690 }
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
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 }
703 inStream = newIn;
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 }
713 // Replace stream
714 outStream = newOut;
715 }
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 }
727 ////////////////////////////////////////////////////////////////////////////
728 //
729 // Code for pausing/unpausing the reader thread ('worker')
730 //
731 ////////////////////////////////////////////////////////////////////////////
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 */
774 private final Object pauseLock = new Object(); // lock for reader to wait on while paused
775 private boolean paused = false; // paused state of reader
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 }
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 }
815 ////////////////////////////////////////////////////////////////////////////
816 //
817 // The LDAP Binding thread. It does the mux/demux of multiple requests
818 // on the same TCP connection.
819 //
820 ////////////////////////////////////////////////////////////////////////////
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;
835 try {
836 while (true) {
837 try {
838 // type and length (at most 128 octets for long form)
839 inbuf = new byte[129];
841 offset = 0;
842 seqlen = 0;
843 seqlenlen = 0;
845 in = getInputStream();
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 }
857 if (inbuf[offset++] != (Ber.ASN_SEQUENCE | Ber.ASN_CONSTRUCTOR))
858 continue;
860 // get length of sequence
861 bytesread = in.read(inbuf, offset, 1);
862 if (bytesread < 0)
863 break; // EOF
864 seqlen = inbuf[offset++];
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
872 bytesread = 0;
873 eos = false;
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 }
886 // end-of-stream reached before length bytes are read
887 if (eos)
888 break; // EOF
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 }
898 // read in seqlen bytes
899 byte[] left = readFully(in, seqlen);
900 inbuf = Arrays.copyOf(inbuf, offset + left.length);
901 System.arraycopy(left, 0, inbuf, offset, left.length);
902 offset += left.length;
904 try {
905 retBer = new BerDecoder(inbuf, 0, offset);
907 if (traceFile != null) {
908 Ber.dumpBER(traceFile, traceTagIn, inbuf, 0, offset);
909 }
911 retBer.parseSeq(null);
912 inMsgId = retBer.parseInt();
913 retBer.reset(); // reset offset
915 boolean needPause = false;
917 if (inMsgId == 0) {
918 // Unsolicited Notification
919 parent.processUnsolicited(retBer);
920 } else {
921 LdapRequest ldr = findRequest(inMsgId);
923 if (ldr != null) {
925 /**
926 * Grab pauseLock before making reply available
927 * to ensure that reader goes into paused state
928 * before writer can attempt to unpause reader
929 */
930 synchronized (pauseLock) {
931 needPause = ldr.addReplyBer(retBer);
932 if (needPause) {
933 /*
934 * Go into paused state; release
935 * pauseLock
936 */
937 pauseReader();
938 }
940 // else release pauseLock
941 }
942 } else {
943 // System.err.println("Cannot find" +
944 // "LdapRequest for " + inMsgId);
945 }
946 }
947 } catch (Ber.DecodeException e) {
948 //System.err.println("Cannot parse Ber");
949 }
950 } catch (IOException ie) {
951 if (debug) {
952 System.err.println("Connection: Inside Caught " + ie);
953 ie.printStackTrace();
954 }
956 if (in != getInputStream()) {
957 // A new stream to try
958 // Go to top of loop and continue
959 } else {
960 if (debug) {
961 System.err.println("Connection: rethrowing " + ie);
962 }
963 throw ie; // rethrow exception
964 }
965 }
966 }
968 if (debug) {
969 System.err.println("Connection: end-of-stream detected: "
970 + in);
971 }
972 } catch (IOException ex) {
973 if (debug) {
974 System.err.println("Connection: Caught " + ex);
975 }
976 closureReason = ex;
977 } finally {
978 cleanup(null, true); // cleanup
979 }
980 if (debug) {
981 System.err.println("Connection: Thread Exiting");
982 }
983 }
985 private static byte[] readFully(InputStream is, int length)
986 throws IOException
987 {
988 byte[] buf = new byte[Math.min(length, 8192)];
989 int nread = 0;
990 while (nread < length) {
991 int bytesToRead;
992 if (nread >= buf.length) { // need to allocate a larger buffer
993 bytesToRead = Math.min(length - nread, buf.length + 8192);
994 if (buf.length < nread + bytesToRead) {
995 buf = Arrays.copyOf(buf, nread + bytesToRead);
996 }
997 } else {
998 bytesToRead = buf.length - nread;
999 }
1000 int count = is.read(buf, nread, bytesToRead);
1001 if (count < 0) {
1002 if (buf.length != nread)
1003 buf = Arrays.copyOf(buf, nread);
1004 break;
1005 }
1006 nread += count;
1007 }
1008 return buf;
1009 }
1010 }