Debian Codegraph @

java-sdk/ietfldap/org/ietf/ldap/LDAPConnThread.java

raw symbols SCIP
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * ***** BEGIN LICENSE BLOCK *****
4 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
5 *
6 * The contents of this file are subject to the Mozilla Public License Version
7 * 1.1 (the "License"); you may not use this file except in compliance with
8 * the License. You may obtain a copy of the License at
9 * http://www.mozilla.org/MPL/
10 *
11 * Software distributed under the License is distributed on an "AS IS" basis,
12 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
13 * for the specific language governing rights and limitations under the
14 * License.
15 *
16 * The Original Code is mozilla.org code.
17 *
18 * The Initial Developer of the Original Code is
19 * Netscape Communications Corporation.
20 * Portions created by the Initial Developer are Copyright (C) 2001
21 * the Initial Developer. All Rights Reserved.
22 *
23 * Contributor(s):
24 *
25 * Alternatively, the contents of this file may be used under the terms of
26 * either the GNU General Public License Version 2 or later (the "GPL"), or
27 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
28 * in which case the provisions of the GPL or the LGPL are applicable instead
29 * of those above. If you wish to allow use of your version of this file only
30 * under the terms of either the GPL or the LGPL, and not to allow others to
31 * use your version of this file under the terms of the MPL, indicate your
32 * decision by deleting the provisions above and replace them with the notice
33 * and other provisions required by the GPL or the LGPL. If you do not delete
34 * the provisions above, a recipient may use your version of this file under
35 * the terms of any one of the MPL, the GPL or the LGPL.
36 *
37 * ***** END LICENSE BLOCK ***** */
38 package org.ietf.ldap;
39
40 import java.io.BufferedInputStream;
41 import java.io.BufferedOutputStream;
42 import java.io.IOException;
43 import java.io.InputStream;
44 import java.io.OutputStream;
45 import java.io.PrintWriter;
46 import java.net.Socket;
47 import java.text.SimpleDateFormat;
48 import java.util.Date;
49 import java.util.Enumeration;
50 import java.util.Hashtable;
51 import java.util.Vector;
52
53 import org.ietf.ldap.ber.stream.BERElement;
54 import org.ietf.ldap.client.JDAPBERTagDecoder;
55 import org.ietf.ldap.client.opers.JDAPAbandonRequest;
56 import org.ietf.ldap.client.opers.JDAPProtocolOp;
57 import org.ietf.ldap.client.opers.JDAPUnbindRequest;
58
59 /**
60 * Multiple LDAPConnection clones can share a single physical connection,
61 * which is maintained by a thread.
62 *
63 * +----------------+
64 * | LDAPConnection | --------+
65 * +----------------+ |
66 * |
67 * +----------------+ | +----------------+
68 * | LDAPConnection | --------+------- | LDAPConnThread |
69 * +----------------+ | +----------------+
70 * |
71 * +----------------+ |
72 * | LDAPConnection | --------+
73 * +----------------+
74 *
75 * All LDAPConnections send requests and get responses from
76 * LDAPConnThread (a thread).
77 */
78 class LDAPConnThread extends Thread {
79
80 /**
81 * Constants
82 */
83 private final static int MAXMSGID = Integer.MAX_VALUE;
84 private final static int BACKLOG_CHKCNT = 50;
85
86 /**
87 * Internal variables
88 */
89 transient private static int _highMsgId;
90 transient private InputStream _serverInput;
91 transient private OutputStream _serverOutput;
92 transient private Hashtable<Integer, LDAPMessageQueue> _requests;
93 transient private Hashtable<Integer, Vector<Object>> _messages = null;
94 transient private Vector<LDAPConnection> _registered;
95 transient private boolean _disconnected = false;
96 transient private LDAPCache _cache = null;
97 transient private boolean _doRun = true;
98 private Socket _socket = null;
99 transient private Thread _thread = null;
100 transient Object _sendRequestLock = new Object();
101 transient LDAPConnSetupMgr _connMgr = null;
102 transient Object _traceOutput = null;
103 transient private int _backlogCheckCounter = BACKLOG_CHKCNT;
104
105
106 // Time Stamp format Hour(0-23):Minute:Second.Milliseconds used for
107 // trace msgs
108 static SimpleDateFormat _timeFormat =
109 new SimpleDateFormat( "HH:mm:ss.SSS" );
110
111 /**
112 * Constructs a connection thread that maintains connection to the
113 * LDAP server
114 *
115 * @param connMgr
116 * @param cache
117 * @param traceOutput
118 */
119 public LDAPConnThread( LDAPConnSetupMgr connMgr,
120 LDAPCache cache,
121 Object traceOutput )
122 throws LDAPException {
123 super( "LDAPConnThread " + connMgr.getHost() +
124 ":" + connMgr.getPort() );
125 _requests = new Hashtable<>();
126 _registered = new Vector<>();
127 _connMgr = connMgr;
128 _socket = connMgr.getSocket();
129 setCache( cache );
130 setTraceOutput( traceOutput );
131
132 // Allow the application to exit if only LDAPConnThread threads are
133 // running
134 setDaemon( true );
135
136 try {
137 _serverInput =
138 new BufferedInputStream( _socket.getInputStream() );
139 _serverOutput =
140 new BufferedOutputStream( _socket.getOutputStream() );
141 } catch ( IOException e ) {
142 // a kludge to make the thread go away. Since the thread has already
143 // been created, the only way to clean up the thread is to call the
144 // start() method. Otherwise, the exit method will be never called
145 // because the start() was never called. In the run method, stop
146 // is called right away if _doRun is false.
147 _doRun = false;
148 start();
149 throw new LDAPException ( "failed to connect to server " +
150 _connMgr.getHost(),
151 LDAPException.CONNECT_ERROR );
152 }
153
154 if ( traceOutput != null ) {
155 StringBuffer sb = new StringBuffer( " connected to " );
156 sb.append( _connMgr.getLDAPUrl() );
157 logTraceMessage( sb );
158 }
159
160 start(); /* start the thread */
161 }
162
163 InputStream getInputStream() {
164 return _serverInput;
165 }
166
167 void setInputStream( InputStream is ) {
168 _serverInput = is;
169 }
170
171 OutputStream getOutputStream() {
172 return _serverOutput;
173 }
174
175 void setOutputStream( OutputStream os ) {
176 _serverOutput = os;
177 }
178
179 void setTraceOutput( Object traceOutput ) {
180 synchronized ( _sendRequestLock ) {
181 if ( traceOutput == null ) {
182 _traceOutput = null;
183 } else if ( traceOutput instanceof OutputStream ) {
184 _traceOutput = new PrintWriter( (OutputStream)traceOutput );
185 } else if ( traceOutput instanceof LDAPTraceWriter ) {
186 _traceOutput = traceOutput;
187 }
188 }
189 }
190
191 void logTraceMessage( StringBuffer msg ) {
192 if ( _traceOutput == null ) {
193 return;
194 }
195 String timeStamp = _timeFormat.format( new Date() );
196 StringBuffer sb = new StringBuffer( timeStamp );
197 sb.append( " ldc=" );
198 sb.append( _connMgr.getID() );
199
200 synchronized( _sendRequestLock ) {
201 if ( _traceOutput instanceof PrintWriter ) {
202 PrintWriter traceOutput = (PrintWriter)_traceOutput;
203 traceOutput.print( sb ); // header
204 traceOutput.println( msg );
205 traceOutput.flush();
206 } else if ( _traceOutput instanceof LDAPTraceWriter ) {
207 sb.append( msg );
208 ((LDAPTraceWriter)_traceOutput).write( sb.toString() );
209 }
210 }
211 }
212
213 /**
214 * Set the cache to use for searches.
215 * @param cache The cache to use for searches; <CODE>null</CODE> for no
216 * cache
217 */
218 synchronized void setCache( LDAPCache cache ) {
219 _cache = cache;
220 _messages = (_cache != null) ? new Hashtable<>() : null;
221 }
222
223 /**
224 * Allocates a new LDAP message ID. These are arbitrary numbers used to
225 * correlate client requests with server responses.
226 *
227 * @return new unique msgId
228 */
229 private int allocateId() {
230 synchronized( _sendRequestLock ) {
231 _highMsgId = (_highMsgId + 1) % MAXMSGID;
232 return _highMsgId;
233 }
234 }
235
236 /**
237 * Sends an LDAP request via this connection thread
238 *
239 * @param request request to send
240 * @param toNotify response queue to receive the response
241 * when ready
242 */
243 void sendRequest( LDAPConnection conn, JDAPProtocolOp request,
244 LDAPMessageQueue toNotify, LDAPConstraints cons )
245 throws LDAPException {
246 if ( !_doRun ) {
247 throw new LDAPException ( "not connected to a server",
248 LDAPException.SERVER_DOWN );
249 }
250 LDAPMessage msg =
251 new LDAPMessage( allocateId(), request, cons.getControls() );
252
253 LDAPMessageQueueImpl queue = (LDAPMessageQueueImpl)toNotify;
254 if ( queue != null ) {
255 if ( !(request instanceof JDAPAbandonRequest ||
256 request instanceof JDAPUnbindRequest) ) {
257 /* Only worry about toNotify if we expect a response... */
258 this._requests.put( msg.getMessageID(), queue );
259 /* Notify the backlog checker that there may be another
260 outstanding request */
261 resultRetrieved();
262 }
263 queue.addRequest( msg.getMessageID(), conn, this,
264 cons.getTimeLimit() );
265 }
266
267 synchronized( _sendRequestLock ) {
268 try {
269 if ( _traceOutput != null ) {
270 logTraceMessage( msg.toTraceString() );
271 }
272 msg.write( _serverOutput );
273 _serverOutput.flush();
274 } catch ( IOException e ) {
275 networkError( e );
276 }
277 }
278 }
279
280 /**
281 * Registers with this connection thread
282 *
283 * @param conn LDAP connection
284 */
285 public synchronized void register( LDAPConnection conn ) {
286 if ( !_registered.contains( conn ) )
287 _registered.addElement( conn );
288 }
289
290 int getClientCount() {
291 return _registered.size();
292 }
293
294 boolean isRunning() {
295 return _doRun;
296 }
297
298 /**
299 * Deregisters with this connection thread. If all connections
300 * are deregistered, this thread is to be killed.
301 *
302 * @param conn LDAP connection
303 */
304 public synchronized void deregister(LDAPConnection conn) {
305 _registered.removeElement( conn );
306 if ( _registered.size() == 0 ) {
307 try {
308 if ( !_disconnected ) {
309 LDAPSearchConstraints cons = conn.getSearchConstraints();
310 sendRequest( null, new JDAPUnbindRequest(), null, cons );
311 }
312
313 // must be set after the call to sendRequest
314 _doRun =false;
315
316 if ( (_thread != null) &&
317 (_thread != Thread.currentThread()) ) {
318
319 _thread.interrupt();
320
321 // Wait up to 1 sec for thread to accept disconnect
322 // notification. When the interrupt is accepted,
323 // _thread is set to null. See run() method.
324 try {
325 wait( 1000 );
326 }
327 catch ( InterruptedException e ) {
328 }
329 }
330
331 } catch( Exception e ) {
332 LDAPConnection.printDebug( e.toString() );
333 }
334 finally {
335 cleanUp();
336 }
337 }
338 }
339
340 /**
341 * Cleans up before shutting down the thread
342 */
343 private void cleanUp() {
344 if ( !_disconnected ) {
345 try {
346 _serverOutput.close();
347 } catch ( Exception e ) {
348 } finally {
349 _serverOutput = null;
350 }
351
352 try {
353 _serverInput.close ();
354 } catch ( Exception e ) {
355 } finally {
356 _serverInput = null;
357 }
358
359 try {
360 _socket.close ();
361 } catch ( Exception e ) {
362 } finally {
363 _socket = null;
364 }
365
366 _disconnected = true;
367
368 /**
369 * Notify the Connection Setup Manager that the connection was
370 * terminated by the user
371 */
372 _connMgr.disconnect();
373
374 /**
375 * Cancel all outstanding requests
376 */
377 if ( _requests != null ) {
378 Enumeration<LDAPMessageQueue> requests = _requests.elements();
379 while ( requests.hasMoreElements() ) {
380 LDAPMessageQueueImpl queue =
381 (LDAPMessageQueueImpl)requests.nextElement();
382 queue.removeAllRequests( this );
383 }
384 }
385
386 /**
387 * Notify all the registered queues of this mishap.
388 * IMPORTANT: This needs to be done last. Otherwise, the socket
389 * input stream and output stream might never get closed and the
390 * whole task will get stuck when trying to stop the
391 * LDAPConnThread.
392 */
393
394 if ( _registered != null ) {
395 Vector<LDAPConnection> registerCopy = (Vector<LDAPConnection>)_registered.clone();
396
397 Enumeration<LDAPConnection> cancelled = registerCopy.elements();
398
399 while ( cancelled.hasMoreElements() ) {
400 LDAPConnection c = cancelled.nextElement();
401 c.deregisterConnection();
402 }
403 }
404 _registered.clear();
405 _registered = null;
406 _messages = null;
407 _requests.clear();
408 _cache = null;
409 }
410 }
411
412 /**
413 * Sleep if there is a backlog of search results
414 */
415 private void checkBacklog() throws InterruptedException{
416
417 while ( true ) {
418
419 if ( _requests.size() == 0 ) {
420 return;
421 }
422
423 Enumeration<LDAPMessageQueue> queues = _requests.elements();
424 while( queues.hasMoreElements() ) {
425 LDAPMessageQueue l = queues.nextElement();
426
427 // If there are any threads waiting for a regular response
428 // message, we have to go read the next incoming message
429 if ( !(l instanceof LDAPSearchQueue ) ) {
430 return;
431 }
432
433 LDAPSearchQueue sl = (LDAPSearchQueue)l;
434
435 // should never happen, but just in case
436 if ( sl.getSearchConstraints() == null ) {
437 return;
438 }
439
440 int slMaxBacklog = sl.getSearchConstraints().getMaxBacklog();
441 int slBatchSize = sl.getSearchConstraints().getBatchSize();
442
443 // Disabled backlog check ?
444 if ( slMaxBacklog == 0 ) {
445 return;
446 }
447
448 // Synch op with zero batch size ?
449 if ( !sl.isAsynchOp() && slBatchSize == 0 ) {
450 return;
451 }
452
453 // Max backlog not reached for at least one queue ?
454 // (if multiple requests are in progress)
455 if ( sl.getMessageCount() < slMaxBacklog ) {
456 return;
457 }
458 }
459
460 synchronized( this ) {
461 wait( 3000 );
462 }
463 }
464 }
465
466
467
468 /**
469 * This is called when a search result has been retrieved from the incoming
470 * queue. We use the notification to unblock the queue thread, if it
471 * is waiting for the backlog to lighten.
472 */
473 synchronized void resultRetrieved() {
474 notifyAll();
475 }
476
477 /**
478 * Reads from the LDAP server input stream for incoming LDAP messages.
479 */
480 public void run() {
481
482 // if there is a problem establishing a connection to the server,
483 // stop the thread right away...
484 if ( !_doRun ) {
485 return;
486 }
487
488 _thread = Thread.currentThread();
489 LDAPMessage msg = null;
490 JDAPBERTagDecoder decoder = new JDAPBERTagDecoder();
491
492 while ( _doRun ) {
493 Thread.yield();
494 int[] nread = new int[1];
495 nread[0] = 0;
496 try {
497
498 // Check after every BACKLOG_CHKCNT number of messages if the
499 // backlog is too high
500 if ( --_backlogCheckCounter <= 0 ) {
501 _backlogCheckCounter = BACKLOG_CHKCNT;
502 checkBacklog();
503 }
504
505 BERElement element = BERElement.getElement( decoder,
506 _serverInput,
507 nread );
508 msg = LDAPMessage.parseMessage( element );
509
510 if ( _traceOutput != null ) {
511 logTraceMessage( msg.toTraceString() );
512 }
513
514 // pass in the ber element size to approximate the size of the
515 // cache entry, thereby avoiding serialization of the entry
516 // stored in the cache
517 processResponse( msg, nread[0] );
518
519 } catch ( Exception e ) {
520 if (_doRun) {
521 networkError( e );
522 } else {
523 // interrupted from deregister()
524 synchronized( this ) {
525 _thread = null;
526 notifyAll();
527 }
528 }
529 }
530 }
531 }
532
533 /**
534 * When a response arrives from the LDAP server, it is processed by
535 * this routine. It will pass the message on to the listening object
536 * associated with the LDAP msgId.
537 * @param msg New message from LDAP server
538 */
539 private void processResponse( LDAPMessage msg, int size ) {
540 Integer messageID = msg.getMessageID();
541 LDAPMessageQueueImpl l =
542 (LDAPMessageQueueImpl)_requests.get( messageID );
543 if ( l == null ) {
544 return; /* nobody is waiting for this response (!) */
545 }
546
547 // For asynch operations controls are to be read from the LDAPMessage
548 // For synch operations controls are copied into the LDAPConnection
549 // For synch search operations, controls are also copied into
550 // LDAPSearchResults (see LDAPConnection.checkSearchMsg())
551 if ( ! l.isAsynchOp() ) {
552
553 /* Were there any controls for this client? */
554 LDAPControl[] con = msg.getControls();
555 if ( con != null ) {
556 int msgid = msg.getMessageID();
557 LDAPConnection ldc = l.getConnection( msgid );
558 if ( ldc != null ) {
559 ldc.setResponseControls(
560 this, new LDAPResponseControl(ldc, msgid, con) );
561 }
562 }
563 }
564
565 if ( (_cache != null) && (l instanceof LDAPSearchQueue) ) {
566 cacheSearchResult( (LDAPSearchQueue)l, msg, size );
567 }
568
569 l.addMessage( msg );
570
571 if ( msg instanceof LDAPResponse ) {
572 _requests.remove( messageID );
573 if ( _requests.size() == 0 ) {
574 _backlogCheckCounter = BACKLOG_CHKCNT;
575 }
576 }
577 }
578
579 /**
580 * Collects search results to be added to the LDAPCache. Search results are
581 * packaged in a vector and temporary stored into a hashtable _messages
582 * using the message id as the key. The vector first element (at index 0)
583 * is a Long integer representing the total size of all LDAPEntries entries.
584 * It is followed by the actual LDAPEntries.
585 * If the total size of entries exceeds the LDAPCache max size, or a
586 * referral has been received, caching of search results is disabled and
587 * the entry is not added to the LDAPCache. A disabled search request is
588 * denoted by setting the entry size to -1.
589 */
590 private synchronized void cacheSearchResult( LDAPSearchQueue l,
591 LDAPMessage msg, int size ) {
592 Integer messageID = msg.getMessageID();
593 Long key = l.getKey();
594 Vector<Object> v = null;
595
596 if ( (_cache == null) || (key == null) ) {
597 return;
598 }
599
600 if ( msg instanceof LDAPSearchResult ) {
601
602 // Get the vector containing the LDAPMessages for the specified
603 // messageID
604 v = _messages.get( messageID );
605 if ( v == null ) {
606 _messages.put( messageID, v = new Vector<>() );
607 v.addElement( 0L );
608 }
609
610 // Return if the entry size is -1, i.e. caching is disabled
611 if ( ((Long)v.firstElement()).longValue() == -1L ) {
612 return;
613 }
614
615 // add the size of the current LDAPMessage to the lump sum
616 // assume the size of LDAPMessage is more or less the same as
617 // the size of LDAPEntry. Eventually an LDAPEntry object gets
618 // stored in the cache instead of the LDAPMessage object.
619 long entrySize = ((Long)v.firstElement()).longValue() + size;
620
621 // If the entrySize exceeds the cache size, discard the collected
622 // entries and disble collecting of entries for this search request
623 // by setting the entry size to -1.
624 if ( entrySize > _cache.getSize() ) {
625 v.removeAllElements();
626 v.addElement( -1L );
627 return;
628 }
629
630 // update the lump sum located in the first element of the vector
631 v.setElementAt( entrySize, 0 );
632
633 // convert LDAPMessage object into LDAPEntry which is stored to the
634 // end of the Vector
635 v.addElement( ((LDAPSearchResult)msg).getEntry() );
636
637 } else if ( msg instanceof LDAPSearchResultReference ) {
638
639 // If a search reference is received disable caching of
640 // this search request
641 v = _messages.get(messageID);
642 if ( v == null ) {
643 _messages.put( messageID, v = new Vector<>() );
644 }
645 else {
646 v.removeAllElements();
647 }
648 v.addElement( -1L );
649
650 } else if ( msg instanceof LDAPResponse ) {
651
652 // The search request has completed. Store the cache entry
653 // in the LDAPCache if the operation has succeded and caching
654 // is not disabled due to the entry size or referrals
655
656 boolean fail = ((LDAPResponse)msg).getResultCode() > 0;
657 v = _messages.remove( messageID );
658
659 if ( !fail ) {
660 // If v is null, meaning there are no search results from the
661 // server
662 if ( v == null ) {
663 v = new Vector<>();
664 v.addElement( 0L );
665 }
666
667 // add the new entry if the entry size is not -1 (caching
668 // disabled)
669 if ( ((Long)v.firstElement()).longValue() != -1L ) {
670 _cache.addEntry( key, v );
671 }
672 }
673 }
674 }
675
676 /**
677 * Stop dispatching responses for a particular message ID
678 *
679 * @param id Message ID for which to discard responses
680 */
681 void abandon( int id ) {
682 if ( !_doRun ) {
683 return;
684 }
685
686 LDAPMessageQueueImpl l =
687 (LDAPMessageQueueImpl)_requests.remove( id );
688 // Clean up cache if enabled
689 if ( _messages != null ) {
690 _messages.remove( id );
691 }
692 if ( l != null ) {
693 l.removeRequest( id );
694 }
695 resultRetrieved(); // If LDAPConnThread is blocked in checkBacklog()
696 }
697
698 /**
699 * Changes the queue for a message ID. Required when
700 * LDAPMessageQueue.merge() is invoked.
701 *
702 * @param id Message ID for which to change the queue
703 * @return Previous queue
704 */
705 LDAPMessageQueue changeQueue( int id, LDAPMessageQueue toNotify ) {
706 if ( !_doRun ) {
707 LDAPMessageQueueImpl queue = (LDAPMessageQueueImpl)toNotify;
708 queue.setException( this,
709 new LDAPException( "Server down",
710 LDAPException.OTHER ) );
711 return null;
712 }
713 return _requests.put( id, toNotify );
714 }
715
716 /**
717 * Handles network errors. Basically shuts down the whole connection.
718 *
719 * @param e The exception which was caught while trying to read from
720 * input stream.
721 */
722 private synchronized void networkError( Exception e ) {
723 _doRun = false;
724
725 // notify the Connection Setup Manager that the connection is lost
726 _connMgr.invalidateConnection();
727
728 try {
729
730 // notify each queue that the server is down.
731 Enumeration<LDAPMessageQueue> requests = _requests.elements();
732 while ( requests.hasMoreElements() ) {
733 LDAPMessageQueueImpl queue =
734 (LDAPMessageQueueImpl)requests.nextElement();
735 queue.setException( this,
736 new LDAPException( "Server down",
737 LDAPException.OTHER) );
738 }
739
740 } catch( NullPointerException ee ) {
741 System.err.println( "Exception: " + ee.toString() );
742 }
743
744 cleanUp();
745 }
746 }