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

Jean-Noel Rouvignac
31.30.2014 2f01ee4d569022fff64691323b9bbcedc4285d98
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
/*
 * 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 2012-2014 ForgeRock AS
 */
package org.opends.server.protocols.asn1;
 
import static org.opends.messages.ProtocolMessages.*;
import static org.opends.server.protocols.ldap.LDAPConstants.*;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.ByteStringBuilder;
import org.opends.server.util.SizeLimitInputStream;
 
/**
 * An ASN1Reader that reads from an input stream.
 */
final class ASN1InputStreamReader implements ASN1Reader
{
 
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  private int state = ELEMENT_READ_STATE_NEED_TYPE;
  private byte peekType = 0;
  private int peekLength = -1;
  private int lengthBytesNeeded = 0;
  private final int maxElementSize;
 
  private InputStream in;
  private final LinkedList<InputStream> streamStack;
  private byte[] buffer;
 
  /**
   * Creates a new ASN1 reader whose source is the provided input
   * stream and having a user defined maximum BER element size.
   *
   * @param stream
   *          The input stream to be read.
   * @param maxElementSize
   *          The maximum BER element size, or <code>0</code> to
   *          indicate that there is no limit.
   */
  ASN1InputStreamReader(InputStream stream, int maxElementSize)
  {
    this.in = stream;
    this.streamStack = new LinkedList<InputStream>();
    this.buffer = new byte[512];
    this.maxElementSize = maxElementSize;
  }
 
  /**
   * Determines if a complete ASN.1 element is ready to be read from the
   * input stream without blocking.
   *
   * @return <code>true</code> if another complete element is available or
   *         <code>false</code> otherwise.
   * @throws ASN1Exception If an error occurs while trying to decode
   *                       an ASN1 element.
   */
  public boolean elementAvailable() throws ASN1Exception
  {
    try
    {
      if(state == ELEMENT_READ_STATE_NEED_TYPE &&
          !needTypeState(false, false)) {
        return false;
      }
      if(state == ELEMENT_READ_STATE_NEED_FIRST_LENGTH_BYTE &&
          !needFirstLengthByteState(false, false)) {
        return false;
      }
      if(state == ELEMENT_READ_STATE_NEED_ADDITIONAL_LENGTH_BYTES &&
          !needAdditionalLengthBytesState(false, false)) {
        return false;
      }
 
      return peekLength <= in.available();
    }
    catch(IOException ioe)
    {
      throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
    }
  }
 
  /**
   * Determines if the input stream contains at least one ASN.1 element to
   * be read. This method will block until enough data is available on the
   * stream to determine if an element is available.
   *
   * @return <code>true</code> if another element is available or
   *         <code>false</code> otherwise.
   * @throws ASN1Exception If an error occurs while trying to decode
   *                       an ASN1 element.
   */
  public boolean hasNextElement() throws ASN1Exception
  {
    try
    {
      if(!streamStack.isEmpty())
      {
        // We are reading a sub sequence. Return true as long as we haven't
        // exausted the size limit for the sub sequence sub input stream.
        SizeLimitInputStream subSq = (SizeLimitInputStream)in;
        return (subSq.getSizeLimit() - subSq.getBytesRead() > 0);
      }
 
      return state != ELEMENT_READ_STATE_NEED_TYPE ||
          needTypeState(true, false);
    }
    catch(IOException ioe)
    {
      throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
    }
  }
 
  /**
   * Internal helper method reading the ASN.1 type byte and transition to
   * the next state if successful.
   *
   * @param isBlocking <code>true</code> to block if the type byte is not
   *                   available or <code>false</code> to check for
   *                   availability first.
   * @param throwEofException <code>true</code> to throw an exception when
   *                          an EOF is encountered or <code>false</code> to
   *                          return false.
   * @return <code>true</code> if the type byte was successfully read
   * @throws IOException If an error occurs while reading from the stream.
   * @throws ASN1Exception If an error occurs while trying to decode
   *                       an ASN1 element.
   */
  private boolean needTypeState(boolean isBlocking, boolean throwEofException)
      throws IOException, ASN1Exception
  {
    // Read just the type.
    if(!isBlocking && in.available() <= 0)
    {
      return false;
    }
 
    int type = in.read();
    if(type == -1)
    {
      if(throwEofException)
      {
        LocalizableMessage message =
            ERR_ASN1_TRUCATED_TYPE_BYTE.get();
        throw new ASN1Exception(message);
      }
      return false;
    }
 
    peekType = (byte)type;
    state = ELEMENT_READ_STATE_NEED_FIRST_LENGTH_BYTE;
    return true;
  }
 
  /**
   * Internal helper method reading the first length bytes and transition to
   * the next state if successful.
   *
   * @param isBlocking <code>true</code> to block if the type byte is not
   *                   available or <code>false</code> to check for
   *                   availability first.
   * @param throwEofException <code>true</code> to throw an exception when
   *                          an EOF is encountered or <code>false</code> to
   *                          return false.
   * @return <code>true</code> if the length bytes was successfully read
   * @throws IOException If an error occurs while reading from the stream.
   * @throws ASN1Exception If an error occurs while trying to decode
   *                       an ASN1 element.
   */
  private boolean needFirstLengthByteState(boolean isBlocking,
                                           boolean throwEofException)
      throws IOException, ASN1Exception
  {
    if(!isBlocking && in.available() <= 0)
    {
      return false;
    }
 
    int readByte = in.read();
    if(readByte == -1)
    {
      if(throwEofException)
      {
        LocalizableMessage message =
            ERR_ASN1_TRUNCATED_LENGTH_BYTE.get();
        throw new ASN1Exception(message);
      }
      return false;
    }
    peekLength = (readByte & 0x7F);
    if (peekLength != readByte)
    {
      lengthBytesNeeded = peekLength;
      if (lengthBytesNeeded > 4)
      {
        LocalizableMessage message =
            ERR_ASN1_INVALID_NUM_LENGTH_BYTES.get(lengthBytesNeeded);
        throw new ASN1Exception(message);
      }
      peekLength = 0x00;
 
      if(!isBlocking && in.available() < lengthBytesNeeded)
      {
        state = ELEMENT_READ_STATE_NEED_ADDITIONAL_LENGTH_BYTES;
        return false;
      }
 
      while(lengthBytesNeeded > 0)
      {
        readByte = in.read();
        if(readByte == -1)
        {
          state = ELEMENT_READ_STATE_NEED_ADDITIONAL_LENGTH_BYTES;
          if(throwEofException)
          {
            LocalizableMessage message =
                ERR_ASN1_TRUNCATED_LENGTH_BYTES.get(lengthBytesNeeded);
            throw new ASN1Exception(message);
          }
          return false;
        }
        peekLength = (peekLength << 8) | (readByte & 0xFF);
        lengthBytesNeeded--;
      }
    }
 
    // Make sure that the element is not larger than the maximum allowed
    // message size.
    if ((maxElementSize > 0) && (peekLength > maxElementSize))
    {
      LocalizableMessage m = ERR_LDAP_CLIENT_DECODE_MAX_REQUEST_SIZE_EXCEEDED.get(
          peekLength, maxElementSize);
      throw new ASN1Exception(m);
    }
    state = ELEMENT_READ_STATE_NEED_VALUE_BYTES;
    return true;
  }
 
  /**
   * Internal helper method reading the additional ASN.1 length bytes and
   * transition to the next state if successful.
   *
   * @param isBlocking <code>true</code> to block if the type byte is not
   *                   available or <code>false</code> to check for
   *                   availability first.
   * @param throwEofException <code>true</code> to throw an exception when
   *                          an EOF is encountered or <code>false</code> to
   *                          return false.
   * @return <code>true</code> if the length bytes was successfully read.
   * @throws IOException If an error occurs while reading from the stream.
   * @throws ASN1Exception If an error occurs while trying to decode
   *                       an ASN1 element.
   */
  private boolean needAdditionalLengthBytesState(boolean isBlocking,
                                                 boolean throwEofException)
      throws IOException, ASN1Exception
  {
    if(!isBlocking && in.available() < lengthBytesNeeded)
    {
      return false;
    }
 
    int readByte;
    while(lengthBytesNeeded > 0)
    {
      readByte = in.read();
      if(readByte == -1)
      {
        state = ELEMENT_READ_STATE_NEED_ADDITIONAL_LENGTH_BYTES;
        if(throwEofException)
        {
          LocalizableMessage message =
              ERR_ASN1_TRUNCATED_LENGTH_BYTES.get(lengthBytesNeeded);
          throw new ASN1Exception(message);
        }
        return false;
      }
      peekLength = (peekLength << 8) | (readByte & 0xFF);
      lengthBytesNeeded--;
    }
 
    // Make sure that the element is not larger than the maximum allowed
    // message size.
    if ((maxElementSize > 0) && (peekLength > maxElementSize))
    {
      LocalizableMessage m = ERR_LDAP_CLIENT_DECODE_MAX_REQUEST_SIZE_EXCEEDED.get(
          peekLength, maxElementSize);
      throw new ASN1Exception(m);
    }
    state = ELEMENT_READ_STATE_NEED_VALUE_BYTES;
    return true;
  }
 
  /**
   * {@inheritDoc}
   */
  public byte peekType() throws ASN1Exception
  {
    try
    {
      if(state == ELEMENT_READ_STATE_NEED_TYPE)
      {
        needTypeState(true, true);
      }
 
      return peekType;
    }
    catch(IOException ioe)
    {
      throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
    }
  }
 
  /**
   * {@inheritDoc}
   */
  public int peekLength() throws ASN1Exception
  {
    peekType();
 
    try
    {
      switch(state)
      {
        case ELEMENT_READ_STATE_NEED_FIRST_LENGTH_BYTE:
          needFirstLengthByteState(true, true);
          break;
 
        case ELEMENT_READ_STATE_NEED_ADDITIONAL_LENGTH_BYTES:
          needAdditionalLengthBytesState(true, true);
      }
 
      return peekLength;
    }
    catch(IOException ioe)
    {
      throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
    }
  }
 
  /**
   * {@inheritDoc}
   */
  public boolean readBoolean() throws ASN1Exception
  {
    // Read the header if haven't done so already
    peekLength();
 
    if (peekLength != 1)
    {
      LocalizableMessage message =
          ERR_ASN1_BOOLEAN_INVALID_LENGTH.get(peekLength);
      throw new ASN1Exception(message);
    }
 
    try
    {
      int readByte = in.read();
      if(readByte == -1)
      {
        LocalizableMessage message = ERR_ASN1_BOOLEAN_TRUNCATED_VALUE.get(peekLength);
        throw new ASN1Exception(message);
      }
 
      if(logger.isTraceEnabled())
      {
        logger.trace(
            String.format("READ ASN.1 BOOLEAN(type=0x%x, length=%d, value=%s)",
                peekType, peekLength, String.valueOf(readByte != 0x00)));
      }
 
      state = ELEMENT_READ_STATE_NEED_TYPE;
      return readByte != 0x00;
    }
    catch(IOException ioe)
    {
      throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
    }
  }
 
  /**
   * {@inheritDoc}
   */
  public int readEnumerated() throws ASN1Exception
  {
    // Read the header if haven't done so already
    peekLength();
 
    if ((peekLength < 1) || (peekLength > 4))
    {
      LocalizableMessage message = ERR_ASN1_INTEGER_INVALID_LENGTH.get(peekLength);
      throw new ASN1Exception(message);
    }
 
    // From an implementation point of view, an enumerated value is
    // equivalent to an integer.
    return (int) readInteger();
  }
 
  /**
   * {@inheritDoc}
   */
  public long readInteger() throws ASN1Exception
  {
    // Read the header if haven't done so already
    peekLength();
 
    if ((peekLength < 1) || (peekLength > 8))
    {
      LocalizableMessage message =
          ERR_ASN1_INTEGER_INVALID_LENGTH.get(peekLength);
      throw new ASN1Exception(message);
    }
 
    try
    {
      if(peekLength > 4)
      {
        long longValue = 0;
        for (int i=0; i < peekLength; i++)
        {
          int readByte = in.read();
          if(readByte == -1)
          {
            LocalizableMessage message =
                ERR_ASN1_INTEGER_TRUNCATED_VALUE.get(peekLength);
            throw new ASN1Exception(message);
          }
          if(i == 0 && ((byte)readByte) < 0)
          {
            longValue = 0xFFFFFFFFFFFFFFFFL;
          }
          longValue = (longValue << 8) | (readByte & 0xFF);
        }
 
        state = ELEMENT_READ_STATE_NEED_TYPE;
        return longValue;
      }
      else
      {
        int intValue = 0;
        for (int i=0; i < peekLength; i++)
        {
          int readByte = in.read();
          if(readByte == -1)
          {
            LocalizableMessage message =
                ERR_ASN1_INTEGER_TRUNCATED_VALUE.get(peekLength);
            throw new ASN1Exception(message);
          }
          if (i == 0 && ((byte)readByte) < 0)
          {
            intValue = 0xFFFFFFFF;
          }
          intValue = (intValue << 8) | (readByte & 0xFF);
        }
 
        if(logger.isTraceEnabled())
        {
          logger.trace(
              String.format("READ ASN.1 INTEGER(type=0x%x, length=%d, " +
                  "value=%d)", peekType, peekLength, intValue));
        }
 
        state = ELEMENT_READ_STATE_NEED_TYPE;
        return intValue;
      }
    }
    catch(IOException ioe)
    {
      throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
    }
  }
 
  /**
   * {@inheritDoc}
   */
  public void readNull() throws ASN1Exception
  {
    // Read the header if haven't done so already
    peekLength();
 
    // Make sure that the decoded length is exactly zero byte.
    if (peekLength != 0)
    {
      LocalizableMessage message =
          ERR_ASN1_NULL_INVALID_LENGTH.get(peekLength);
      throw new ASN1Exception(message);
    }
 
    if(logger.isTraceEnabled())
    {
      logger.trace(
          String.format("READ ASN.1 NULL(type=0x%x, length=%d)",
              peekType, peekLength));
    }
 
    state = ELEMENT_READ_STATE_NEED_TYPE;
  }
 
  /**
   * {@inheritDoc}
   */
  public ByteString readOctetString() throws ASN1Exception {
    // Read the header if haven't done so already
    peekLength();
 
    if(peekLength == 0)
    {
      state = ELEMENT_READ_STATE_NEED_TYPE;
      return ByteString.empty();
    }
 
    try
    {
      // Copy the value and construct the element to return.
      byte[] value = new byte[peekLength];
      int bytesNeeded = peekLength;
      int bytesRead;
      while(bytesNeeded > 0)
      {
        bytesRead = in.read(value, peekLength - bytesNeeded, bytesNeeded);
        if(bytesRead < 0)
        {
          LocalizableMessage message =
            ERR_ASN1_OCTET_STRING_TRUNCATED_VALUE.get(peekLength);
          throw new ASN1Exception(message);
        }
 
        bytesNeeded -= bytesRead;
      }
 
      if(logger.isTraceEnabled())
      {
        logger.trace(
            String.format("READ ASN.1 OCTETSTRING(type=0x%x, length=%d)",
                peekType, peekLength));
      }
 
      state = ELEMENT_READ_STATE_NEED_TYPE;
      return ByteString.wrap(value);
    }
    catch(IOException ioe)
    {
      throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
    }
  }
 
  /**
   * {@inheritDoc}
   */
  public String readOctetStringAsString() throws ASN1Exception
  {
    // We could cache the UTF-8 CharSet if performance proves to be an
    // issue.
    return readOctetStringAsString("UTF-8");
  }
 
  /**
   * {@inheritDoc}
   */
  public String readOctetStringAsString(String charSet) throws ASN1Exception
  {
    // Read the header if haven't done so already
    peekLength();
 
    if(peekLength == 0)
    {
      state = ELEMENT_READ_STATE_NEED_TYPE;
      return "";
    }
 
    // Resize the temp buffer if needed
    if(peekLength > buffer.length)
    {
      buffer = new byte[peekLength];
    }
 
    try
    {
      int bytesNeeded = peekLength;
      int bytesRead;
      while(bytesNeeded > 0)
      {
        bytesRead = in.read(buffer, peekLength - bytesNeeded, bytesNeeded);
        if(bytesRead < 0)
        {
          LocalizableMessage message =
            ERR_ASN1_OCTET_STRING_TRUNCATED_VALUE.get(peekLength);
          throw new ASN1Exception(message);
        }
        bytesNeeded -= bytesRead;
      }
 
      state = ELEMENT_READ_STATE_NEED_TYPE;
    }
    catch(IOException ioe)
    {
      throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
    }
 
    String str;
    try
    {
      str = new String(buffer, 0, peekLength, charSet);
    }
    catch (Exception e)
    {
      logger.traceException(e);
 
      str = new String(buffer, 0, peekLength);
    }
 
    if(logger.isTraceEnabled())
    {
      logger.trace(
          String.format("READ ASN.1 OCTETSTRING(type=0x%x, length=%d, " +
              "value=%s)", peekType, peekLength, str));
    }
 
    return str;
  }
 
  /**
   * {@inheritDoc}
   */
  public void readOctetString(ByteStringBuilder buffer) throws ASN1Exception
  {
    // Read the header if haven't done so already
    peekLength();
 
    if(peekLength == 0)
    {
      state = ELEMENT_READ_STATE_NEED_TYPE;
      return;
    }
 
    try
    {
      // Copy the value and construct the element to return.
      int bytesNeeded = peekLength;
      int bytesRead;
      while(bytesNeeded > 0)
      {
        bytesRead = buffer.append(in, bytesNeeded);
        if(bytesRead < 0)
        {
          LocalizableMessage message =
            ERR_ASN1_OCTET_STRING_TRUNCATED_VALUE.get(peekLength);
          throw new ASN1Exception(message);
        }
        bytesNeeded -= bytesRead;
      }
 
      if(logger.isTraceEnabled())
      {
        logger.trace(
            String.format("READ ASN.1 OCTETSTRING(type=0x%x, length=%d)",
                peekType, peekLength));
      }
 
      state = ELEMENT_READ_STATE_NEED_TYPE;
    }
    catch(IOException ioe)
    {
      throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
    }
  }
 
  /**
   * {@inheritDoc}
   */
  public void readStartSequence() throws ASN1Exception
  {
    // Read the header if haven't done so already
    peekLength();
 
    SizeLimitInputStream subStream =
        new SizeLimitInputStream(in, peekLength);
 
    if(logger.isTraceEnabled())
    {
      logger.trace(
          String.format("READ ASN.1 SEQUENCE(type=0x%x, length=%d)",
              peekType, peekLength));
    }
 
    streamStack.addFirst(in);
    in = subStream;
 
    // Reset the state
    state = ELEMENT_READ_STATE_NEED_TYPE;
  }
 
  /**
   * {@inheritDoc}
   */
  public void readStartExplicitTag() throws ASN1Exception
  {
    // From an implementation point of view, an explicit tag is equivalent to a
    // sequence, as it is also a constructed type.
    readStartSequence();
  }
 
  /**
   * {@inheritDoc}
   */
  public void readStartSet() throws ASN1Exception
  {
    // From an implementation point of view, a set is equivalent to a
    // sequence.
    readStartSequence();
  }
 
  /**
   * {@inheritDoc}
   */
  public void readEndSequence() throws ASN1Exception
  {
    if(streamStack.isEmpty())
    {
      LocalizableMessage message = ERR_ASN1_SEQUENCE_READ_NOT_STARTED.get();
      throw new ASN1Exception(message);
    }
 
    // Ignore all unused trailing components.
    SizeLimitInputStream subSq = (SizeLimitInputStream)in;
    if(subSq.getSizeLimit() - subSq.getBytesRead() > 0)
    {
      if(logger.isTraceEnabled())
      {
        logger.trace("Ignoring %d unused trailing bytes in " +
            "ASN.1 SEQUENCE", subSq.getSizeLimit() - subSq.getBytesRead());
      }
 
      try
      {
        subSq.skip(subSq.getSizeLimit() - subSq.getBytesRead());
      }
      catch(IOException ioe)
      {
        throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
      }
    }
 
    in = streamStack.removeFirst();
 
    // Reset the state
    state = ELEMENT_READ_STATE_NEED_TYPE;
  }
 
  /**
   * {@inheritDoc}
   */
  public void readEndExplicitTag() throws ASN1Exception
  {
    // From an implementation point of view, an explicit tag is equivalent to a
    // sequence, as it is also a constructed type.
    readEndSequence();
  }
 
  /**
   * {@inheritDoc}
   */
  public void readEndSet() throws ASN1Exception
  {
    // From an implementation point of view, a set is equivalent to a
    // sequence.
    readEndSequence();
  }
 
  /**
   * {@inheritDoc}
   */
  public void skipElement() throws ASN1Exception
  {
    // Read the header if haven't done so already
    peekLength();
 
    try
    {
      long bytesSkipped = in.skip(peekLength);
      if(bytesSkipped != peekLength)
      {
        LocalizableMessage message =
            ERR_ASN1_SKIP_TRUNCATED_VALUE.get(peekLength);
        throw new ASN1Exception(message);
      }
      state = ELEMENT_READ_STATE_NEED_TYPE;
    }
    catch(IOException ioe)
    {
      throw new ASN1Exception(ERR_ASN1_READ_ERROR.get(ioe), ioe);
    }
  }
 
  /**
   * Closes this ASN.1 reader and the underlying stream.
   *
   * @throws IOException if an I/O error occurs
   */
  public void close() throws IOException
  {
    // Calling close of SizeLimitInputStream should close the parent stream.
    in.close();
    streamStack.clear();
  }
}