mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Jean-Noël Rouvignac
28.10.2015 07e7cb84f497a907074b5ca46f3147f65488d6ed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2006-2009 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2015 ForgeRock AS.
 */
package org.opends.server.protocols.ldap;
 
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.ReadableByteChannel;
 
import org.forgerock.opendj.io.ASN1;
import org.forgerock.opendj.io.ASN1Reader;
import org.forgerock.opendj.ldap.ByteSequenceReader;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteStringBuilder;
import org.forgerock.opendj.ldap.DecodeException;
 
/**
 * This class is for reading ASN.1 elements from a readable byte
 * channel. It will handle all partial element reads from the channel
 * and save any unread ASN.1 elements if required. All data read from
 * the channel will be ready to be read as ASN.1 elements no matter
 * how many times the channel is read. However, to minimize the the
 * amount of memory used by this reader, the client should read ASN.1
 * elements as soon as they are read off the channel.
 * <p>
 * {@code ASN1ByteChannelReader}s are created using the factory
 * methods in {@link ASN1}.
 * <p>
 * The client should use this class in the following manner:
 *<p>
 * When NIO signals new data is available in the channel, the client
 * should call {@link #processChannelData()}.
 *<p>
 * If bytes are read from the channel, the client should call
 * {@link #elementAvailable()} to see if a complete element is ready to
 * be read. However, if no data is actually read, the client should
 * wait for the next signal and try again.
 * <p>
 * As long as a complete element is ready, the client should read the
 * appropriate ASN.1 element(s). Once no more complete elements are
 * available, the client should call {@link #processChannelData()}
 * again to read more data (if available).
 * <p>
 * <b>NOTE:</b> Since this reader is non blocking, reading ASN.1
 * elements before making sure they are ready could result in
 * {@link IllegalBlockingModeException}s being thrown while reading
 * ASN.1 elements. Once an exception is thrown, the state of the reader
 * is no longer stable and can not be used again.
 */
final class ASN1ByteChannelReader implements ASN1Reader
{
  /** The byte channel to read from. */
  private final ReadableByteChannel byteChannel;
 
  /** The wrapped ASN.1 reader. */
  private final ASN1Reader reader;
 
  /**
   * The NIO ByteStringBuilder that stores any immediate data read off the
   * channel.
   */
  private final ByteBuffer byteBuffer;
 
  /**
   * The save buffer used to store any unprocessed data waiting to be read as
   * ASN.1 elements. (Usually due to reading incomplete elements from the
   * channel).
   */
  private final ByteStringBuilder saveBuffer;
 
  /** The save buffer reader. */
  private final ByteSequenceReader saveBufferReader;
 
  /**
   * An adaptor class for reading from a save buffer and the NIO byte buffer
   * sequentially using the InputStream interface.
   *
   * Since the NIO byte buffer is re-used when reading off the channel, any
   * unused data will be appended to the save buffer before reading off the
   * channel again. This reader will always read the save buffer first before
   * the actual NIO byte buffer to ensure bytes are read in the same order
   * as they are received.
   *
   * The read methods of this stream will throw an IllegalBlockingModeException
   * if invoked when there are no data to read from the save buffer or the
   * channel buffer.
   *
   * The stream will not support the mark or reset methods.
   */
  private final class CombinedBufferInputStream extends InputStream
  {
    /** {@inheritDoc} */
    @Override
    public int available()
    {
      // The number of available bytes is the sum of the save buffer
      // and the last read data in the NIO ByteStringBuilder.
      return saveBufferReader.remaining() + byteBuffer.remaining();
    }
 
    /**
     * Reads the next byte of data from the save buffer or channel buffer.
     * The value byte is returned as an int in the range 0 to 255.
     * If no byte is available in the save buffer or channel buffer,
     * IllegalBlockingModeException will be thrown.
     *
     * @return the next byte of data.
     * @throws IllegalBlockingModeException if there are more bytes available.
     */
    @Override
    public int read()
    {
      if(saveBufferReader.remaining() > 0)
      {
        // Try saved buffer first
        return 0xFF & saveBufferReader.get();
      }
      if(byteBuffer.remaining() > 0)
      {
        // Must still be on the channel buffer
        return 0xFF & byteBuffer.get();
      }
 
      throw new IllegalBlockingModeException();
    }
 
    /**
     * Reads up to len bytes of data from the save buffer or channel buffer
     * into an array of bytes. An attempt is made to read as many as len bytes,
     * but a smaller number may be read. The number of bytes actually read is
     * returned as an integer.
     *
     * If b is null, a NullPointerException is thrown.
     *
     * If the length of b is zero, then no bytes are read and 0 is returned;
     * otherwise, there is an attempt to read at least one byte. If no byte is
     * available in the save buffer or channel buffer,
     * IllegalBlockingModeException will be thrown; otherwise, at least one
     * byte is read and stored into b.
     *
     * The first byte read is stored into element b[0], the next one into
     * b[o1], and so on. The number of bytes read is, at most, equal to the
     * length of b. Let k be the number of bytes actually read; these bytes
     * will be stored in elements b[0] through b[k-1], leaving elements b[k]
     * through b[b.length-1] unaffected.
     *
     * @return the total number of bytes read into the buffer.
     * @throws IllegalBlockingModeException if there are more bytes available.
     */
    @Override
    public int read(byte[] b)
    {
      return read(b, 0, b.length);
    }
 
    /**
     * Reads up to len bytes of data from the save buffer or channel buffer
     * into an array of bytes. An attempt is made to read as many as len bytes,
     * but a smaller number may be read. The number of bytes actually read is
     * returned as an integer.
     *
     * If b is null, a NullPointerException is thrown.
     *
     * If off is negative, or len is negative, or off+len is greater than the
     * length of the array b, then an IndexOutOfBoundsException is thrown.
     *
     * If len is zero, then no bytes are read and 0 is returned; otherwise,
     * there is an attempt to read at least one byte. If no byte is available
     * in the save buffer or channel buffer, IllegalBlockingModeException will
     * be thrown; otherwise, at least one byte is read and stored into b.
     *
     * The first byte read is stored into element b[off], the next one into
     * b[off+1], and so on. The number of bytes read is, at most, equal to len.
     * Let k be the number of bytes actually read; these bytes will be stored
     * in elements b[off] through b[off+k-1], leaving elements b[off+k]
     * through b[off+len-1] unaffected.
     *
     * In every case, elements b[0] through b[off] and elements b[off+len]
     * through b[b.length-1] are unaffected.
     *
     * @return the total number of bytes read into the buffer.
     * @throws IllegalBlockingModeException if there are more bytes available.
     */
    @Override
    public int read(byte[] b, int off, int len)
    {
      if (off < 0 || len < 0 || off + len > b.length)
      {
        throw new IndexOutOfBoundsException();
      }
 
      if(len == 0)
      {
        return 0;
      }
 
      int bytesCopied=0;
      int getLen;
      if(saveBufferReader.remaining() > 0)
      {
        // Copy out of the last saved buffer first
        getLen = Math.min(saveBufferReader.remaining(), len);
        saveBufferReader.get(b, off, getLen);
        bytesCopied += getLen;
      }
      if(bytesCopied < len && byteBuffer.remaining() > 0)
      {
        // Copy out of the channel buffer if we haven't got
        // everything we needed.
        getLen = Math.min(byteBuffer.remaining(), len - bytesCopied);
        byteBuffer.get(b, off + bytesCopied, getLen);
        bytesCopied += getLen;
      }
      if(bytesCopied < len)
      {
        throw new IllegalBlockingModeException();
      }
 
      return bytesCopied;
    }
 
    /** {@inheritDoc} */
    @Override
    public long skip(long length)
    {
      int bytesSkipped=0;
      int len;
      if(saveBufferReader.remaining() > 0)
      {
        // Skip in the last saved buffer first
        len = Math.min(saveBufferReader.remaining(), (int)length);
        saveBufferReader.position(saveBufferReader.position() + len);
        bytesSkipped += len;
      }
      if(bytesSkipped < length && byteBuffer.remaining() > 0)
      {
        //Skip in the channel buffer if we haven't skipped enough.
        len = Math.min(byteBuffer.remaining(), (int)length - bytesSkipped);
        byteBuffer.position(byteBuffer.position() + len);
        bytesSkipped += len;
      }
      if(bytesSkipped < length)
      {
        throw new IllegalBlockingModeException();
      }
 
      return bytesSkipped;
    }
  }
 
  /**
   * Creates a new ASN.1 byte channel reader whose source is the
   * provided readable byte channel, having a user defined buffer
   * size, and user defined maximum BER element size.
   *
   * @param channel
   *          The readable byte channel to use.
   * @param bufferSize
   *          The buffer size to use when reading from the channel.
   * @param maxElementSize
   *          The max ASN.1 element size this reader will read.
   */
  ASN1ByteChannelReader(ReadableByteChannel channel, int bufferSize,
      int maxElementSize)
  {
    this.byteChannel = channel;
    this.byteBuffer = ByteBuffer.allocate(bufferSize);
    this.byteBuffer.flip();
    this.saveBuffer = new ByteStringBuilder();
    this.saveBufferReader = saveBuffer.asReader();
 
    CombinedBufferInputStream bufferStream = new CombinedBufferInputStream();
    this.reader = ASN1.getReader(bufferStream, maxElementSize);
  }
 
  /**
   * Process any new data on the channel so they can be read as ASN.1
   * elements. This method should only be called when there are no
   * more complete elements in the reader. Calling this method when
   * there are complete elements still in the reader will result in
   * unnecessary memory allocations to store any unread data. This
   * method will perform the following operations:
   * <ul>
   * <li>Clear the save buffer if everything was read.
   * <li>Append any unread data from the NIO byte buffer to the save
   * buffer.
   * <li>Clear the NIO byte buffer and read from the channel.
   * </ul>
   *
   * @return The number of bytes read from the channel or -1 if
   *         channel is closed.
   * @throws IOException
   *           If an exception occurs while reading from the channel.
   */
  public int processChannelData() throws IOException
  {
    // Clear the save buffer if we have read all of it
    if (saveBufferReader.remaining() == 0)
    {
      saveBuffer.clear();
      saveBufferReader.rewind();
    }
 
    // Append any unused data in the channel buffer to the save buffer
    if (byteBuffer.remaining() > 0)
    {
      saveBuffer.appendBytes(byteBuffer, byteBuffer.remaining());
    }
 
    byteBuffer.clear();
    try
    {
      return byteChannel.read(byteBuffer);
    }
    finally
    {
      // Make sure that the buffer is flipped even if the read fails in order to
      // ensure that subsequent calls which query the remaining data return
      // valid results.
      byteBuffer.flip();
    }
  }
 
  /**
   * Determines if a complete ASN.1 element is ready to be read from
   * channel.
   *
   * @return <code>true</code> if another complete element is available or
   *         <code>false</code> otherwise.
   * @throws IOException If an error occurs while trying to decode
   *                       an ASN1 element.
   */
  @Override
  public boolean elementAvailable() throws IOException
  {
    return reader.elementAvailable();
  }
 
  /**
   * Determines if the channel contains at least one ASN.1 element to be read.
   *
   * @return <code>true</code> if another element is available or
   *         <code>false</code> otherwise.
   * @throws IOException If an error occurs while trying to decode
   *                       an ASN1 element.
   */
  @Override
  public boolean hasNextElement() throws IOException {
    return reader.hasNextElement();
  }
 
  /**
   * Returns {@code true} if this ASN.1 reader contains unread data.
   *
   * @return {@code true} if this ASN.1 reader contains unread data.
   */
  public boolean hasRemainingData()
  {
    return saveBufferReader.remaining() != 0 || byteBuffer.remaining() != 0;
  }
 
  /** {@inheritDoc} */
  @Override
  public int peekLength() throws IOException {
    return reader.peekLength();
  }
 
  /** {@inheritDoc} */
  @Override
  public byte peekType() throws IOException {
    return reader.peekType();
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean readBoolean() throws IOException {
    return reader.readBoolean();
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean readBoolean(byte type) throws IOException {
    return reader.readBoolean(type);
  }
 
  /** {@inheritDoc} */
  @Override
  public void readEndExplicitTag() throws IOException {
    reader.readEndExplicitTag();
  }
 
  /** {@inheritDoc} */
  @Override
  public void readEndSequence() throws IOException {
    reader.readEndSequence();
  }
 
  /** {@inheritDoc} */
  @Override
  public void readEndSet() throws IOException {
    reader.readEndSet();
  }
 
  /** {@inheritDoc} */
  @Override
  public int readEnumerated() throws IOException {
    return reader.readEnumerated();
  }
 
  /** {@inheritDoc} */
  @Override
  public int readEnumerated(byte type) throws IOException {
    return reader.readEnumerated(type);
  }
 
  /** {@inheritDoc} */
  @Override
  public long readInteger() throws IOException {
    return reader.readInteger();
  }
 
  /** {@inheritDoc} */
  @Override
  public long readInteger(byte type) throws IOException {
    return reader.readInteger(type);
  }
 
  /** {@inheritDoc} */
  @Override
  public void readNull() throws IOException {
    reader.readNull();
  }
 
  /** {@inheritDoc} */
  @Override
  public void readNull(byte type) throws IOException {
    reader.readNull(type);
  }
 
  /** {@inheritDoc} */
  @Override
  public ByteString readOctetString() throws IOException {
    return reader.readOctetString();
  }
 
  /** {@inheritDoc} */
  @Override
  public ByteString readOctetString(byte type) throws IOException {
    return readOctetString(type);
  }
 
  /** {@inheritDoc} */
  @Override
  public ByteStringBuilder readOctetString(ByteStringBuilder buffer) throws IOException {
    return reader.readOctetString(buffer);
  }
 
  /** {@inheritDoc} */
  @Override
  public ByteStringBuilder readOctetString(byte type, ByteStringBuilder builder) throws IOException {
    return readOctetString(type, builder);
  }
 
  /** {@inheritDoc} */
  @Override
  public String readOctetStringAsString() throws IOException {
    return reader.readOctetStringAsString();
  }
 
  /** {@inheritDoc} */
  @Override
  public String readOctetStringAsString(byte type) throws IOException {
    return readOctetStringAsString(type);
  }
 
  /** {@inheritDoc} */
  @Override
  public void readStartExplicitTag() throws IOException {
    reader.readStartExplicitTag();
  }
 
  /** {@inheritDoc} */
  @Override
  public void readStartExplicitTag(byte type) throws IOException {
    reader.readStartExplicitTag(type);
  }
 
  /** {@inheritDoc} */
  @Override
  public void readStartSequence() throws IOException {
    reader.readStartSequence();
  }
 
  /** {@inheritDoc} */
  @Override
  public void readStartSequence(byte type) throws IOException {
    reader.readStartSequence(type);
  }
 
  /** {@inheritDoc} */
  @Override
  public void readStartSet() throws IOException {
    reader.readStartSet();
  }
 
  /** {@inheritDoc} */
  @Override
  public void readStartSet(byte type) throws IOException {
    reader.readStartSet(type);
  }
 
  /** {@inheritDoc} */
  @Override
  public void close() throws IOException {
    reader.close();
    byteChannel.close();
  }
 
  /** {@inheritDoc} */
  @Override
  public ASN1Reader skipElement() throws IOException {
    reader.skipElement();
    return this;
  }
 
  /** {@inheritDoc} */
  @Override
  public ASN1Reader skipElement(byte type) throws DecodeException, IOException
  {
    reader.skipElement(type);
    return this;
  }
}