Debian Codegraph @

java-sdk/ietfldap/org/ietf/ldap/LDAPControl.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.ByteArrayInputStream;
41 import java.io.ByteArrayOutputStream;
42 import java.io.IOException;
43 import java.io.Serializable;
44 import java.lang.reflect.Constructor;
45 import java.lang.reflect.InvocationTargetException;
46 import java.util.Hashtable;
47
48 import org.ietf.ldap.ber.stream.BERBoolean;
49 import org.ietf.ldap.ber.stream.BERElement;
50 import org.ietf.ldap.ber.stream.BEROctetString;
51 import org.ietf.ldap.ber.stream.BERSequence;
52 import org.ietf.ldap.ber.stream.BERTag;
53 import org.ietf.ldap.client.JDAPBERTagDecoder;
54 import org.ietf.ldap.controls.LDAPEntryChangeControl;
55 import org.ietf.ldap.controls.LDAPPasswordExpiredControl;
56 import org.ietf.ldap.controls.LDAPPasswordExpiringControl;
57 import org.ietf.ldap.controls.LDAPSortControl;
58 import org.ietf.ldap.controls.LDAPVirtualListResponse;
59 import org.ietf.ldap.util.LDIF;
60
61 /**
62 * Represents arbitrary control data that can be used with a
63 * a particular LDAP operation. LDAP controls are part of version 3
64 * of the LDAP protocol.
65 * <P>
66 *
67 * LDAP controls allow you to extend the functionality of
68 * an LDAP operation. For example, you can use an LDAP control
69 * for the search operation to sort search results on an LDAP server.
70 * <P>
71 *
72 * An LDAP control can be either a <B>server control</B> or
73 * a <B>client control</B>:
74 * <P>
75 * <UL>
76 * <LI><B>Server controls</B> can be sent to the LDAP server or returned
77 * by the server on any operation.
78 * <LI><B>Client controls</B> are intended to affect only the client side
79 * of the operation.
80 * </UL>
81 * <P>
82 *
83 * An LDAP control consists of the following information:
84 * <P>
85 * <UL>
86 * <LI>A unique object ID (OID) that identifies the control.<P>
87 * <LI>A &quot;criticality&quot; field, which indicates whether or
88 * not the control is critical to the operation. (If the control is
89 * critical to the operation and the server does not support the control,
90 * the server should not execute the operation.)<P>
91 * <LI>Data pertaining to the control.<P>
92 * </UL>
93 * <P>
94 *
95 * To determine which server controls are supported by a particular server,
96 * you need to search for the root DSE (DSA-specific entry, where DSA is
97 * another term for &quot;LDAP server&quot;) and find the values of the
98 * <CODE>supportedControl</CODE> attribute. This attribute contains the
99 * object IDs (OIDs) of the controls supported by this server.
100 * <P>
101 *
102 * The following section of code demonstrates how to get the list
103 * of the server controls supported by an LDAP server.
104 * <P>
105 *
106 * <PRE>
107 * public static void main( String[] args )
108 * {
109 * LDAPConnection ld = new LDAPConnection();
110 * try {
111 * String MY_HOST = "localhost";
112 * int MY_PORT = 389;
113 * ld.connect( MY_HOST, MY_PORT );
114 * try {
115 * ld.authenticate( 3, "cn=Directory Manager", "23skidoo" );
116 * } catch( LDAPException e ) {
117 * System.out.println( "LDAP server does not support v3." );
118 * ld.disconnect();
119 * System.exit(1);
120 * }
121 *
122 * String MY_FILT = "(objectclass=*)";
123 * String MY_BASE = "";
124 * String getAttrs[] = { "supportedControl" };
125 * LDAPSearchResults res = ld.search( MY_BASE,
126 * LDAPConnection.SCOPE_BASE, MY_FILT, getAttrs, false );
127 *
128 * while ( res.hasMoreElements() ) {
129 * LDAPEntry findEntry = (LDAPEntry)res.nextElement();
130 * LDAPAttributeSet findAttrs = findEntry.getAttributeSet();
131 * Enumeration enumAttrs = findAttrs.getAttributes();
132 *
133 * while ( enumAttrs.hasMoreElements() ) {
134 * LDAPAttribute anAttr = (LDAPAttribute)enumAttrs.nextElement();
135 * String attrName = anAttr.getName();
136 * System.out.println( attrName );
137 * Enumeration enumVals = anAttr.getStringValues();
138 *
139 * while ( enumVals.hasMoreElements() ) {
140 * String aVal = ( String )enumVals.nextElement();
141 * System.out.println( "\t" + aVal );
142 * }
143 * }
144 * }
145 * }
146 * catch( LDAPException e ) {
147 * System.out.println( "Error: " + e.toString() );
148 * }
149 * try {
150 * ld.disconnect();
151 * }
152 * catch( LDAPException e ) {
153 * System.exit(1);
154 * }
155 * System.exit(0);
156 * }
157 * </PRE>
158 * <P>
159 *
160 * If you compile and run this example against an LDAP server that
161 * supports v3 of the protocol, you might receive the following results:
162 * <P>
163 *
164 * <PRE>
165 * supportedcontrol
166 * 2.16.840.1.113730.3.4.2
167 * 2.16.840.1.113730.3.4.3
168 * 2.16.840.1.113730.3.4.4
169 * 2.16.840.1.113730.3.4.5
170 * 1.2.840.113556.1.4.473
171 * </PRE>
172 * <P>
173 *
174 * For more information on LDAP controls, see the Internet-Draft on
175 * the LDAP v3 protocol. (Note that this internet draft is still a
176 * work in progress. You can find the latest draft at the <A
177 * HREF="http://www.ietf.cnri.reston.va.us/html.charters/asid-charter.html"
178 * TARGET="_blank">ASID home page</A>.
179 * <P>
180 *
181 * @version 1.0
182 * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean)
183 * @see org.ietf.ldap.LDAPConnection#getOption
184 * @see org.ietf.ldap.LDAPConnection#setOption
185 * @see org.ietf.ldap.LDAPConnection#getResponseControls
186 * @see org.ietf.ldap.LDAPConstraints#getControls
187 * @see org.ietf.ldap.LDAPConstraints#setControls
188 */
189 public class LDAPControl implements Cloneable, Serializable {
190 static final long serialVersionUID = 5149887553272603753L;
191 public final static String MANAGEDSAIT = "2.16.840.1.113730.3.4.2";
192 /* Password information sent back to client */
193 public final static String PWEXPIRED = "2.16.840.1.113730.3.4.4";
194 public final static String PWEXPIRING = "2.16.840.1.113730.3.4.5";
195
196 /**
197 * Default constructor for the <CODE>LDAPControl</CODE> class.
198 */
199 public LDAPControl()
200 {
201 }
202
203 /**
204 * Constructs a new <CODE>LDAPControl</CODE> object using the
205 * specified object ID (OID), &quot;criticality&quot; field, and
206 * data to be used by the control.
207 * <P>
208 *
209 * @param id the object ID (OID) identifying the control
210 * @param critical <CODE>true</CODE> if the LDAP operation should be
211 * cancelled when the server does not support this control (in other
212 * words, this control is critical to the LDAP operation)
213 * @param vals control-specific data
214 * @see org.ietf.ldap.LDAPConstraints#setControls
215 */
216 public LDAPControl( String id,
217 boolean critical,
218 byte vals[] ) {
219 _oid = id;
220 _critical = critical;
221 _value = vals;
222 }
223
224 /**
225 * Gets the object ID (OID) of the control.
226 * @return object ID (OID) of the control.
227 */
228 public String getID() {
229 return _oid;
230 }
231
232 /**
233 * Specifies whether or not the control is critical to the LDAP operation.
234 * @return <CODE>true</CODE> if the LDAP operation should be cancelled when
235 * the server does not support this control.
236 */
237 public boolean isCritical() {
238 return _critical;
239 }
240
241 /**
242 * Gets the data in the control.
243 * @return the data in the control as a byte array.
244 */
245 public byte[] getValue() {
246 return _value;
247 }
248
249 /**
250 * Gets the ber representation of control.
251 * @return ber representation of control.
252 */
253 BERElement getBERElement() {
254 BERSequence seq = new BERSequence();
255 seq.addElement(new BEROctetString (_oid));
256 seq.addElement(new BERBoolean (_critical));
257 if ( (_value == null) || (_value.length < 1) )
258 seq.addElement(new BEROctetString ((byte[])null));
259 else {
260 seq.addElement(new BEROctetString (_value, 0, _value.length));
261 }
262 return seq;
263 }
264
265 /**
266 * Associates a class with an oid. This class must be an extension of
267 * <CODE>LDAPControl</CODE>, and should implement the <CODE>LDAPControl(
268 * String oid, boolean critical, byte[] value)</CODE> constructor to
269 * instantiate the control.
270 * @param oid the string representation of the oid
271 * @param controlClass the class that instantatiates the control associated
272 * with oid
273 * @exception org.ietf.ldap.LDAPException If the class parameter is not
274 * a subclass of <CODE>LDAPControl</CODE> or the class parameter does not
275 * implement the <CODE>LDAPControl(String oid, boolean critical, byte[] value)
276 * </CODE> constructor.
277 */
278 public static void register( String oid, Class<?> controlClass )
279 throws LDAPException {
280
281 if (controlClass == null) {
282 return;
283 }
284
285 // 1. make sure controlClass is a subclass of LDAPControl
286 Class<?> superClass = controlClass;
287 while (superClass != LDAPControl.class && superClass != null) {
288 superClass = superClass.getSuperclass();
289 }
290
291 if (superClass == null)
292 throw new LDAPException("controlClass must be a subclass of " +
293 "LDAPControl", LDAPException.PARAM_ERROR);
294
295 // 2. make sure controlClass has the proper constructor
296 Class<?>[] cparams = { String.class, boolean.class, byte[].class };
297 try {
298 controlClass.getConstructor(cparams);
299 } catch (NoSuchMethodException e) {
300 throw new LDAPException("controlClass does not implement the " +
301 "correct contstructor",
302 LDAPException.PARAM_ERROR);
303 }
304
305 // 3. check if the hash table exists
306 if (_controlClassHash == null) {
307 _controlClassHash = new Hashtable<>();
308 }
309
310 // 4. add the controlClass
311 _controlClassHash.put(oid, controlClass);
312 }
313
314 /**
315 * Returns the <CODE>Class</CODE> that has been registered to oid.
316 * @param oid a String that associates the control class to a control
317 * @return a <CODE>Class</CODE> that can instantiate a control of the
318 * type specified by oid.
319 * @see org.ietf.ldap.LDAPControl#register
320 *
321 */
322 protected static Class<?> lookupControlClass( String oid ) {
323 if ( _controlClassHash == null ) {
324 return null;
325 }
326
327 return _controlClassHash.get(oid);
328 }
329
330 /**
331 * Returns a <CODE>LDAPControl</CODE> object instantiated by the Class
332 * associated by <CODE>LDAPControl.register</CODE> to the oid. If
333 * no Class is found for the given control, or an exception occurs when
334 * attempting to instantiate the control, a basic <CODE>LDAPControl</CODE>
335 * is instantiated using the parameters.
336 * @param oid the oid of the control to instantiate
337 * @param critical <CODE>true</CODE> if this is a critical control
338 * @param value the byte value for the control
339 * @return a newly instantiated <CODE>LDAPControl</CODE>.
340 * @see org.ietf.ldap.LDAPControl#register
341 */
342 protected static LDAPControl createControl( String oid,
343 boolean critical,
344 byte[] value ) {
345
346 Class<?> controlClass = lookupControlClass(oid);
347
348 if ( controlClass == null ) {
349 return new LDAPControl(oid, critical, value);
350 }
351
352 Class<?>[] cparams = { String.class, boolean.class, byte[].class };
353 Constructor<?> creator = null;
354 try {
355 creator = controlClass.getConstructor(cparams);
356 } catch (NoSuchMethodException e) {
357 //shouldn't happen, but...
358 System.err.println("Caught java.lang.NoSuchMethodException while" +
359 " attempting to instantiate a control of type " +
360 oid);
361 return new LDAPControl(oid, critical, value);
362 }
363
364 Object[] oparams = { oid, critical, value } ;
365 LDAPControl returnControl = null;
366 try {
367 returnControl = (LDAPControl)creator.newInstance(oparams);
368 } catch (Exception e) {
369 String eString = null;
370 if (e instanceof InvocationTargetException) {
371 eString = ((InvocationTargetException)
372 e).getTargetException().toString();
373 } else {
374 eString = e.toString();
375 }
376
377 System.err.println("Caught " + eString + " while attempting to" +
378 " instantiate a control of type " +
379 oid);
380 returnControl = new LDAPControl(oid, critical, value);
381 }
382
383 return returnControl;
384 }
385
386 /**
387 * Returns a <CODE>LDAPControl</CODE> object instantiated by the Class
388 * associated by <CODE>LDAPControl.register</CODE> to the oid. If
389 * no Class is found for the given control, or an exception occurs when
390 * attempting to instantiate the control, a basic <CODE>LDAPControl</CODE>
391 * is instantiated using the parameters.
392 * @param el the <CODE>BERElement</CODE> containing the control
393 * @return a newly instantiated <CODE>LDAPControl</CODE>.
394 * @see org.ietf.ldap.LPAPControl#register
395 *
396 * Note:
397 * This code was extracted from <CODE>JDAPControl(BERElement el)</CODE>
398 * constructor.
399 */
400 static LDAPControl parseControl( BERElement el ) {
401 BERSequence s = (BERSequence)el;
402 String oid = null;
403 boolean critical = false;
404 byte[] value = null;
405 try{
406 oid = new String(((BEROctetString)s.elementAt(0)).getValue(), "UTF8");
407 } catch(Throwable x) {}
408
409 Object obj = s.elementAt(1);
410 if (obj instanceof BERBoolean) {
411 critical = ((BERBoolean)obj).getValue();
412 }
413 else {
414 value = ((BEROctetString)obj).getValue();
415 }
416
417 if (s.size() >= 3) {
418 value = ((BEROctetString)s.elementAt(2)).getValue();
419 }
420
421 return createControl(oid, critical, value);
422 }
423
424
425 /**
426 * Instantiates all of the controls contained within the LDAP message
427 * fragment specified by data and returns them in an <CODE>LDAPControl</CODE>
428 * array. This fragment can be either the entire LDAP message or just the
429 * control section of the message.
430 * <P>
431 * If an exception occurs when instantiating a control, that control is
432 * returned as a basic <CODE>LDAPControl</CODE>.
433 * @param data the LDAP message fragment in raw BER format
434 * @return an <CODE>LDAPControl</CODE> array containing all of the controls
435 * from the message fragment.
436 * @exception java.lang.IOException If the data passed to this method
437 * is not a valid LDAP message fragment.
438 * @see org.ietf.ldap.LDAPControl#register
439 */
440 public static LDAPControl[] newInstance(byte[] data) throws IOException {
441
442 int[] bread = { 0 };
443
444 BERElement el = BERElement.getElement(new JDAPBERTagDecoder(),
445 new ByteArrayInputStream(data),
446 bread);
447
448 LDAPControl[] jc = null;
449 try {
450 // see if data is a LDAP message
451 LDAPMessage msg = LDAPMessage.parseMessage(el);
452 return msg.getControls();
453 } catch (IOException e) {
454 // that didn't work; let's see if its just the controls
455 BERTag tag = (BERTag)el;
456 if ( tag.getTag() == (BERTag.CONSTRUCTED|BERTag.CONTEXT|0) ) {
457 BERSequence controls = (BERSequence)tag.getValue();
458 jc = new LDAPControl[controls.size()];
459 for (int i = 0; i < controls.size(); i++) {
460 jc[i] = parseControl(controls.elementAt(i));
461 }
462 }
463 }
464
465 return jc;
466 }
467
468 /**
469 * Creates a copy of the control
470 *
471 * @return copy of the control
472 */
473 public Object clone() {
474 byte[] vals = null;
475 if ( _value != null ) {
476 vals = new byte[_value.length];
477 for( int i = 0; i < _value.length; i++ )
478 vals[i] = _value[i];
479 }
480 LDAPControl control = new LDAPControl( _oid, _critical, vals );
481
482 return control;
483 }
484
485 /**
486 * Create a "flattened" BER encoding from a BER,
487 * and return it as a byte array.
488 * @param ber a BER encoded sequence
489 * @return the byte array of encoded data.
490 */
491 protected byte[] flattenBER( BERSequence ber ) {
492 /* Suck out the data and return it */
493 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
494 try {
495 ber.write( outStream );
496 } catch ( IOException e ) {
497 return null;
498 }
499 return outStream.toByteArray();
500 }
501
502 /**
503 * Return a string representation of the control for debugging
504 *
505 * @return a string representation of the control.
506 */
507 public String toString() {
508 String s = getID() + ' ' + isCritical();
509 if ( _value != null ) {
510 s += ' ' + LDIF.toPrintableString( _value );
511 }
512 return "LDAPControl {" + s + '}';
513 }
514
515 private String _oid;
516 protected boolean _critical = false;
517 protected byte[] _value = null;
518 static private Hashtable<String, Class<?>> _controlClassHash = null;
519 static {
520 try {
521 LDAPControl.register( LDAPPasswordExpiringControl.EXPIRING,
522 LDAPPasswordExpiringControl.class );
523 LDAPControl.register( LDAPPasswordExpiredControl.EXPIRED,
524 LDAPPasswordExpiredControl.class );
525 LDAPControl.register( LDAPEntryChangeControl.ENTRYCHANGED,
526 LDAPEntryChangeControl.class );
527 LDAPControl.register( LDAPSortControl.SORTRESPONSE,
528 LDAPSortControl.class );
529 LDAPControl.register( LDAPVirtualListResponse.VIRTUALLISTRESPONSE,
530 LDAPVirtualListResponse.class );
531 } catch (LDAPException e) {
532 }
533 }
534 }
535