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