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