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