-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMDer.cs
2627 lines (2527 loc) · 66.1 KB
/
MDer.cs
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using BigInt;
namespace Asn1 {
/*
* This class implements a custom syntax for building and parsing ASN.1
* objects. The syntax describes the object elements and accepts dynamic
* parameters. When building an object (MDer.Build()), the parameter
* values are used to populate the object fields at the places
* referenced in the syntax (similar in concept the the C printf()
* call). When parsing an object (MDer.Parse()), the parameter values
* are populated with values found in the source object.
*
* An "ASN.1 object" is any instance that implements IAsn1 and can thus
* be represented as an AsnElt instance; when an ASN.1 object is returned
* during a parsing process, it is an AsnElt instance. This class does not
* handle low-level (DER) encoding or decoding.
*
*
* Syntax:
* -------
*
* A semicolon (';') outside of a literal string introduces a comment that
* spans until the end of the current line (i.e. up to the next LF character).
* A comment counts as whitespace.
*
* 'param-ref' is %nnn with 'nnn' being a decimal number that is the index
* of the parameter in the provided array (starting at 0). There must be at
* least one decimal digit; all consecutive decimal digits are used.
*
*
* param-ref
* (param-ref)
* ([tagvalue] param-ref)
* ([tagclass tagvalue] param-ref)
*
* Uses the parameter as an object.
*
* When building: parameter can be null, in which case the whole object
* is considered optional and missing. Otherwise, it MUST be an IAsn1.
* If a tag is specified, and the parameter is not null, then the tag
* replaces the one of the parameter object (this is implicit tagging).
*
* When parsing: the tag, if present, is checked to match the object.
* The parameter slot is set to the object value.
*
* tagclass: one of:
* univ universal
* app application
* priv private
* context
*
* tagvalue: either a decimal integer, or one of:
* bool boolean
* int integer
* bits bitstring bit-string
* bytes blob octet-string
* null
* oid object-identifier
* enum enumerated
* utf8 utf-8 utf8string
* sequence
* set
* numeric numericstring
* printable printablestring
* ia5 ia5string
* teletex telextexstring
* genstring generalstring
* utf8 utf-8 utf8string
* utf16 utf-16 bmp bmpstring
* utf32 utf-32 universal universalstring
* utc utctime
* gentime generalizedtime
*
* Either or both of tagvalue and tagclass may be a parameter
* reference.
* Building:
* - tagclass must be a string or an int; valid range is 0 to 3
* - tagvalue must be a string or an int; valid range is 0 to
* 2147483647
* Parsing:
* - tagclass and/or tagvalue parameter is set to an int
* When the tagclass is not provided, CONTEXT is assumed.
*
* When tagvalue is provided, but not tagclass, then:
* - if tagvalue is one of the symbolic strings above, then the
* tag class is UNIVERSAL;
* - otherwise, the tag class is CONTEXT.
*
*
* (type value)
* ([tagvalue] type value)
* ([tagclass tagvalue] type value)
*
* 'type' is a keyword that specifies the object type. 'value'
* depends on the object type, and may be a parameter ref.
*
* When building: If the value is a parameter and the parameter is
* null, then the whole object is considered optional and missing.
*
* When parsing: the value may be '.', in which case its contents
* are ignored. Otherwise, the contents are (recursively) matched with
* the input.
*
* Type keywords are not case-sensitive.
* Object types and corresponding rules for values:
*
* bool
* boolean
* BOOLEAN object. Value is one of:
* true on yes 1 -> value is TRUE
* false off no 0 -> value is FALSE
* parameter of .NET type Boolean
* Parsing: produces a Boolean value.
*
* int
* integer
* INTEGER object. Value is either a string representation as
* accepted by ZInt.Parse(), or a parameter with type ZInt or
* one of the core .NET integer types (sbyte, byte, short, ushort,
* int, uint, long or ulong).
* Parsing: produces a ZInt value.
*
* enum
* enumerated
* ENUMERATED object. Rules are the same as for INTEGER; only the
* produced tag value changes (if not overridden).
*
* bits
* BIT STRING object. Two sub-values are expected: the number of
* ignored bits, and the bits themselves.
* Ignored bits value (must be between 0 and 7):
* int literal integer
* param-ref parameter must be of type int, or null
* Value bits:
* hex hexadecimal data blob
* (...) nested object (bits are its DER encoding)
* param-ref parameter must be byte[], IAsn1 or null
*
* Building:
* - If either the number of ignored bits or the value bits are
* a parameter reference and the parameter is null, then the
* object is considered absent.
* - When the bits are a parameter of type IAsn1, the DER encoding
* of the object is used as value.
* - When the bits are specified as a nested object or as a
* parameter of type IAsn1, then the number of ignored bits
* is verified to be zero. Otherwise, the number of ignored bits
* is verified to be between 0 and 7, and the ignored bits in the
* provided hex value are verified to have value 0.
*
* Parsing:
* - If the number of ignored bits is a parameter ref, then the
* parameter is set to a value of type int containing that
* number.
* - If the value bits are a parameter reference, then the parameter
* is set to a byte[]. The ignored bits are forced to 0.
* - If the value bits are a nested object, then the number of ignored
* bits are verified to be 0, and the value bits are decoded as
* a DER object which is explored recursively.
*
* blob
* bytes
* OCTET STRING object.
* Value depends on the next non-whitespace character:
* hex digit hexadecimal data blob
* '(' nested object
* '%' parameter ref; must be byte[], IAsn1 or null
* If the value is IAsn1, then its DER-encoding is used.
* Parsing:
* - hex blob: matched with the object
* - parameter ref: set to a byte[]
* - nested object: explored recursively
*
* null
* NULL object. Value is empty.
*
* oid
* OBJECT IDENTIFIER object. Value is one of:
* decimal-dotted notation for an OID
* symbolic identifier for a well-known OID
* parameter ref; must be string or null
* When a parameter of type string is used, the string value must
* be a correctly formed decimal-dotted notation, or a well-known
* OID identifier.
* Parsing:
* - literal OID (or symbolic identifier): matched with the object
* - parameter ref: set to a string (decimal-dotted)
*
* numeric numericstring
* printable printablestring
* ia5 ia5string
* teletex telextexstring
* genstring generalstring
* utf8 utf-8 utf8string
* utf16 utf-16 bmp bmpstring
* utf32 utf-32 universal universalstring
* utc utctime
* gentime generalizedtime
* Character string object (including time objects). Value is one of:
* literal string (in double-quotes)
* parameter ref; must be string or null
* In a literal string, a backslash introduces an escape sequence:
* \\ backslash
* \" double-quote character
* \n LF (character value 0x0A)
* \r CR (character value 0x0D)
* \t tabulation (character value 0x09)
* \xNN character with value 'NN' (two hexadecimal digits)
* \uNNNN character with value 'NNNN' (four hexadecimal digits)
* \UNNNNNN character with value 'NNNNNN' (six hexadecimal digits)
* The string value is verified to match the specified type, with the
* following caveats:
* - For UTCTime and GeneralizedTime, only verification is that all
* characters are within the 'PrintableString' charset.
* - For TeletexString and GeneralString, "latin-1" semantics are
* used (all characters should be in the 0..255 range).
*
* Parsing:
* - literal string: matched with the object (ordinal match)
* - parameter ref: set to a string, except for UTCTime and
* GeneralizedTime, in which case the date is parsed and the
* parameter is set to a DateTime (UTC)
*
* set
* sequence
* Value is a sequence of sub-objects.
*
* Building:
* (...) a sub-object spec (explored recursively)
* *(...) multiple sub-objects (see below)
* param-ref a parameter reference; should be IAsn1 or null
* *param-ref shorthand for *(param-ref)
* When using the '*' or '+' operators, the sub-specification should
* include at least one parameter reference with a parameter value
* which implements IEnumerable; if there is none, then this sub-object
* is omitted. Sub-objects are built for each element in the
* IEnumerable (except where null values imply omission). If the
* sub-specification uses several IEnumerable parameters, then
* the building of the list of sub-objects stops as soon as one of
* these enumerations is exhausted.
*
* Additional rules for building:
* - Sub-objects are included in the order they appear. There is
* no sorting step for SETs.
* - null/omitted sub-objects are skipped.
* - The only difference between 'set' and 'sequence' here is the
* tag value (if the tag is overriden with an explicit
* specification, then this difference has no impact).
*
* Parsing: each sub-value may be:
* (...) a sub-object spec (explored recursively)
* ?(...) an optional sub-object spec (explored recursively
* if present)
* ?(...):repl an optional sub-object spec with a replacement
* action if not present (see below)
* param-ref parameter is set to the sub-object (AsnElt)
* ?param-ref parameter is set to the sub-object (AsnElt), if
* present; null otherwise. This matches any
* sub-object; use a sub-object spec with explicit
* tagging to match specific sub-objects.
* *spec all remaining objects are explored with the spec
* +spec all remaining objects are explored with the spec
* (there must be at least one remaining object)
* When using '*' or '+', the recursive operation applies the spec
* repeatedly; whenever a parameter value is gathered, the parameter
* array slot is set to a list of the specifie type (List<string>,...)
* (created if necessary) and the value is added to it.
* The '+' operator is similar to '*' except that it enforces the
* presence of at least one sub-object.
*
* Replacement actions are sequences of store values into parameters.
* This is meant to provide for default values, in particular when
* accumulating elements from a sequence. Syntax of 'repl' is:
* - an opening parenthesis
* - one or several pairs:
* param-ref (type value)
* - a closing parenthesis
*
* setof
* This behaves like a 'set', except that after all sub-object values
* are gathered, they are sorted by lexicographic ordering of their
* respective encodings (exact duplicates are removed).
* Parsing: no check is done on order.
*
* setder
* This behaves like a 'set', except that after all sub-object values
* are gathered, they are sorted by tag class and value (as mandated
* by DER for SETs which are not SET OF). If two sub-objects have the
* same tag class and value, then an error is reported.
* Parsing: no check is done on order.
*
* set-nz
* sequence-nz
* setof-nz
* setder-nz
* These are equivalent to set, sequence, setof and setder,
* respectively, except that an empty resulting object is suppressed
* and treated as optional and absent instead.
* Parsing: input is verified not to be empty.
*
* tag
* Value is a single sub-object; if that sub-object is null, then
* the tag object is removed as well. An error is reported if this
* type is used without specifying a tag class and value.
* Parsing: similar to parsing a 'sequence' with a single element.
*
*
* Usage:
* ------
*
* MDer.Build() for building, MDer.Parse() for parsing. The syntax can
* be provided as either a string or a TextReader.
*
* Errors in the format syntax are reported with a FormatException.
*
* When building, a FormatException may also be thrown if a parameter
* value has a type which is not compatible with the context in which
* it is used (e.g. the value is used in a BOOLEAN but is not a bool
* or null).
*
* When parsing, errors in the source object (including values that can
* be decoded as ASN.1/DER but do not match the provided format) are
* reported with an AsnException (which extends IOException).
*
* MDer.Build() only reads parameter values. MDer.Parse() only writes
* parameter values. When parsing, the provided array is not cleared
* first; the caller is responsible for that task. Moreover, in case of
* a parse error, parameter values that were set prior to detecting the
* error are still set.
*/
public class MDer {
TextReader input;
int lookAhead;
object[] pp;
bool paramAccumulate;
MDer(TextReader input, object[] pp)
{
this.input = input;
lookAhead = -1;
if (pp == null) {
pp = new object[0];
}
this.pp = pp;
paramAccumulate = false;
}
/*
* Build an ASN.1 object using the provided format string with
* optional parameters. null may be returned if the syntax
* specifies to use a parameter value which has value null.
*
* In case of trailing garbage (non-whitespace after the object
* specification), then this function throws a FormatException.
*/
public static AsnElt Build(string fmt, params object[] pp)
{
MDer md = new MDer(new StringReader(fmt), pp);
AsnElt ae = md.Build();
if (md.PeekNextChar() != -1) {
throw new FormatException("trailing garbage after object in format string");
}
return ae;
}
/*
* Build an ASN.1 object using the provided format string with
* optional parameters. null may be returned if the syntax
* specifies to use a parameter value which has value null.
*
* This function reads only as many characters as it requires
* for building purposes. Since specifications are normally
* self-terminated, this means that characters after the final
* ')' character remain unread.
*/
public static AsnElt Build(TextReader fmt, params object[] pp)
{
MDer md = new MDer(fmt, pp);
return md.Build();
}
/*
* Build an ASN.1 object using the provided format string with
* optional parameters. The object value is set in 'ae'. That
* value may be null if the syntax specifies to use a parameter
* value which has value null.
*
* This function reads only as many characters as it requires
* for building purposes. Since specifications are normally
* self-terminated, this means that characters after the final
* ')' character remain unread.
*
* This function sets the built object in 'ae' and returns true.
* If the input stream only contains whitespace, and no actual
* object specification, then 'ae' is set to null and the return
* value is false.
*/
public static bool TryBuild(TextReader fmt, out AsnElt ae,
params object[] pp)
{
MDer md = new MDer(fmt, pp);
bool eof;
ae = md.BuildNext(out eof);
if (eof) {
int c = md.PeekNextChar();
if (c != -1) {
throw new FormatException(string.Format("unexpected character in specification: U+{0:X4}", c));
}
return false;
}
return true;
}
/*
* Parse an ASN.1 object using the provided specification string,
* and output parameter array.
*
* In case of trailing garbage (non-whitespace after the
* specification string), then this function throws an Exception.
*/
public static void Parse(string fmt, AsnElt ae, params object[] pp)
{
MDer md = new MDer(new StringReader(fmt), pp);
md.Parse(ae);
if (md.PeekNextChar() != -1) {
throw new FormatException("trailing garbage after object in format string");
}
}
/*
* Parse an ASN.1 object using the provided specification text,
* and output parameter array.
*
* This function reads only as many characters as it requires
* for parsing purposes. Since specifications are normally
* self-terminated, this means that characters after the final
* ')' character remain unread.
*/
public static void Parse(TextReader fmt, AsnElt ae, params object[] pp)
{
MDer md = new MDer(fmt, pp);
md.Parse(ae);
}
AsnElt Build()
{
bool eof;
AsnElt ae = BuildNext(out eof);
if (eof) {
throw new FormatException("no valid object at start of format string");
}
return ae;
}
void Parse(AsnElt d)
{
int c = PeekNextChar();
switch (c) {
case '(':
case '%':
case '.':
Parse(new AsnElt[] { d }, 0);
break;
default:
throw new FormatException("no valid object at start of format string");
}
}
/*
* Check whether a character is whitespace. Whitespace is all ASCII
* control characters (0x00 to 0x1F), ASCII space (0x20), and
* latin-1 unbreakable space (0xA0).
*/
static bool IsWS(int c)
{
return c <= 32 || c == 160;
}
/*
* Check whether a character is a decimal digit ('0' to '9').
*/
static bool IsDigit(int c)
{
return c >= '0' && c <= '9';
}
/*
* Check whether a character is an hexadecimal digit.
*/
static bool IsHexDigit(int c)
{
return (c >= '0' && c <= '9')
|| (c >= 'A' && c <= 'F')
|| (c >= 'a' && c <= 'f');
}
static bool[] WORD_CHAR = new bool[128];
const string WORD_EXTRA_CHARS = "$_-+.,";
/*
* Check whether a character is a "word character". Words consist
* of ASCII letters (lowercase and uppercase), ASCII digits, and
* the characters: $ _ - + . ,
*/
static bool IsWordChar(int c)
{
return c >= 0 && c < 128 && WORD_CHAR[c];
}
/*
* Peek at the next character in the source stream (without
* skipping whitespace).
*/
int LowPeek()
{
if (lookAhead < 0) {
lookAhead = input.Read();
}
return lookAhead;
}
/*
* Read the next character from the source stream (without skipping
* whitespace).
*/
int LowRead()
{
int v = LowPeek();
lookAhead = -1;
return v;
}
/*
* Read the next character from the source stream; each sequence of
* consecutive whitespace is coalesced into a single space character.
*/
int NextCharWS()
{
int c = LowPeek();
if (c < 0) {
return -1;
} else if (IsWS(c) || c == ';') {
for (;;) {
c = LowPeek();
if (c < 0) {
break;
} else if (IsWS(c)) {
LowRead();
continue;
} else if (c == ';') {
do {
c = LowRead();
} while (c >= 0 && c != '\n');
continue;
} else {
break;
}
}
return ' ';
} else {
LowRead();
return c;
}
}
/*
* Peek at the next non-whitespace character. Whitespace is skipped
* (including comments).
*/
int PeekNextChar()
{
for (;;) {
int c = LowPeek();
if (c < 0) {
return -1;
}
if (IsWS(c)) {
LowRead();
continue;
}
/*
* Semicolon introduces a comment that spans to
* the end of the current line.
*/
if (c == ';') {
do {
c = LowRead();
if (c < 0) {
return -1;
}
} while (c != '\n');
continue;
}
/*
* An opening brace starts a comment that stops
* on the matching closing brace. We must take
* care of nested semicolon-comments and string
* literals: braces in those don't count.
*/
if (c == '{') {
LowRead();
int count = 1;
while (count > 0) {
c = LowRead();
if (c < 0) {
return -1;
}
if (c == ';') {
do {
c = LowRead();
if (c < 0) {
return -1;
}
} while (c != '\n');
continue;
}
if (c == '"') {
bool lcwb = false;
for (;;) {
c = LowRead();
if (c < 0) {
return -1;
}
if (lcwb) {
lcwb = false;
} else if (c == '\\') {
lcwb = true;
} else if (c == '"') {
break;
}
}
continue;
}
if (c == '{') {
count ++;
} else if (c == '}') {
count --;
}
}
continue;
}
return c;
}
}
/*
* Read the next non-whitespace character. Whitespace is skipped
* (including comments).
*/
int NextChar()
{
int c = PeekNextChar();
if (c >= 0) {
LowRead();
}
return c;
}
/*
* Find the closing parenthesis for the current context. If
* 'sb' is not null, then read characters are accumulated in it
* (whitespace sequences are replaced with a single space).
*/
void FindClosingParenthesis(StringBuilder sb)
{
int nump = 1;
while (nump > 0) {
int c = NextCharWS();
if (c < 0) {
throw new FormatException("unmatched opening parenthesis");
}
if (sb != null) {
sb.Append((char)c);
}
switch (c) {
case '(':
nump ++;
break;
case ')':
nump --;
break;
case '"':
// for a literal string, we must use LowRead()
// to avoid whitespace/comment processing.
bool lwb = false;
for (;;) {
c = LowRead();
if (c < 0) {
throw new FormatException("unfinished literal string");
}
if (sb != null) {
sb.Append((char)c);
}
if (lwb) {
lwb = false;
} else if (c == '\\') {
lwb = true;
} else if (c == '"') {
break;
}
}
break;
}
}
}
/*
* Read a word (sequence of word characters). The first character
* has already been read, and is provided as 'fc'.
*/
string ReadWord(int fc)
{
StringBuilder sb = new StringBuilder();
sb.Append((char)fc);
for (;;) {
int c = LowPeek();
if (!IsWordChar(c)) {
return sb.ToString();
}
sb.Append((char)LowRead());
}
}
/*
* Read a word (sequence of word characters). Whitespace before
* the word is skipped. An exception is thrown if there is no
* remaining non-whitespace character (end-of-stream reached) or
* if the next non-whitespace character is not a word character.
*/
string ReadWord()
{
int fc = NextChar();
if (fc < 0) {
throw new FormatException("truncated input");
}
if (!IsWordChar(fc)) {
throw new FormatException(string.Format("unexpected U+{0:X4} character", fc));
}
return ReadWord(fc);
}
/*
* Read a parameter reference. It is assumed that the first
* reference character ('%') has been peeked at but not read.
* Returned value is parameter index (which has been verified
* to be within range of the parameter array).
*/
int ReadParamRef()
{
if (NextChar() != '%') {
throw new FormatException("expected parameter reference");
}
bool first = true;
int x = 0;
for (;;) {
int c = LowPeek();
if (!IsDigit(c)) {
break;
}
first = false;
LowRead();
if (x > 214748364) {
throw new FormatException("parameter number overflow");
}
x *= 10;
c -= '0';
if (x > 2147483647 - c) {
throw new FormatException("parameter number overflow");
}
x += c;
}
if (first) {
throw new FormatException("missing parameter number");
}
if (x >= pp.Length) {
throw new FormatException(string.Format("invalid parameter number: {0} (max: {1})", x, pp.Length - 1));
}
return x;
}
/*
* Read a parameter reference. It is assumed that the first
* reference character ('%') has been peeked at but not read.
* Returned value is the parameter value (which may be null).
*/
object ReadParamVal()
{
return pp[ReadParamRef()];
}
/*
* Get the value of a character as an hexadecimal digit. If the
* character is not an hex digit, then -1 is returned.
*/
int HexValue(int c)
{
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
} else if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
} else {
return -1;
}
}
/*
* Return the next source character (no whitespace skipping) and
* obtain its value as an hexadecimal digit; an exception is thrown
* if there is no such character (end-of-stream) or if the next
* character is not an hex digit.
*/
int ReadHexChar()
{
int c = LowRead();
if (c < 0) {
throw new FormatException("truncated input: unfinished string literal");
}
int d = HexValue(c);
if (d < 0) {
throw new FormatException(string.Format("invalid character U+{0:X4}, expecting hex digit", c));
}
return d;
}
/*
* Read a literal string value. Leading whitespace is skipped.
*/
string ReadLiteralString()
{
int c = PeekNextChar();
if (c != '"') {
throw new FormatException("expected literal string");
}
LowRead();
StringBuilder sb = new StringBuilder();
bool lwb = false;
for (;;) {
c = LowRead();
if (c < 0) {
throw new FormatException("truncated input: unfinished string literal");
}
if (lwb) {
switch ((char)c) {
case 'n': c = '\n'; break;
case 't': c = '\t'; break;
case 'r': c = '\r'; break;
case 'x':
c = ReadHexChar();
c = (c << 4) + ReadHexChar();
break;
case 'u':
c = ReadHexChar();
c = (c << 4) + ReadHexChar();
c = (c << 4) + ReadHexChar();
c = (c << 4) + ReadHexChar();
break;
case 'U':
c = ReadHexChar();
c = (c << 4) + ReadHexChar();
c = (c << 4) + ReadHexChar();
c = (c << 4) + ReadHexChar();
c = (c << 4) + ReadHexChar();
c = (c << 4) + ReadHexChar();
break;
}
if (c > 0x10FFFF) {
throw new FormatException("invalid Unicode codepoint: " + c);
} else if (c > 0xFFFF) {
c -= 0x10000;
sb.Append((char)(0xD800 + (c >> 10)));
sb.Append((char)(0xDC00 + (c & 0x3FF)));
} else {
sb.Append((char)c);
}
lwb = false;
} else {
switch ((char)c) {
case '\\':
lwb = true;
continue;
case '"':
return sb.ToString();
}
sb.Append((char)c);
}
}
}
/*
* Read a string value. Leading whitespace is skipped. Expected
* value is either a double-quoted literal string, or a parameter
* reference. If a parameter is found, it must be a string, or null.
* An exception is thrown if no literal string or parameter reference
* is found.
*/
string ReadString()
{
int c = PeekNextChar();
if (c < 0) {
throw new FormatException("truncated input");
}
if (c == '%') {
object obj = ReadParamVal();
if (obj == null) {
return null;
} else if (obj is string) {
return (string)obj;
} else {
throw new FormatException("unexpected parameter type: " + obj.GetType().FullName);
}
}
if (c != '"') {
throw new FormatException("not a string literal");
}
return ReadLiteralString();
}
/*
* Read a literal BOOLEAN value.
*/
bool ReadLiteralBoolean()
{
return ReadLiteralBoolean(ReadWord());
}
bool ReadLiteralBoolean(string w)
{
switch (w.ToLowerInvariant()) {
case "true":
case "on":
case "yes":
case "1":
return true;
case "false":
case "off":
case "no":
case "0":
return false;
default:
throw new FormatException("unexpected BOOLEAN value: " + w);
}
}
/*
* Read a BOOLEAN value.
*/
AsnElt ReadBoolean()
{
int c = PeekNextChar();
if (c == '%') {
object obj = ReadParamVal();
if (obj == null) {
return null;
} else if (obj is Boolean) {
if ((bool)obj) {
return AsnElt.BOOL_TRUE;
} else {
return AsnElt.BOOL_FALSE;
}
} else if (obj is string) {
return ReadLiteralBoolean((string)obj)
? AsnElt.BOOL_TRUE : AsnElt.BOOL_FALSE;
} else {
throw new FormatException("unexpected parameter type: " + obj.GetType().FullName);
}
}
bool v = ReadLiteralBoolean();
return v ? AsnElt.BOOL_TRUE : AsnElt.BOOL_FALSE;
}
/*
* Read a literal INTEGER value.
*/
ZInt ReadLiteralInteger()
{
return ReadLiteralInteger(ReadWord());
}
ZInt ReadLiteralInteger(string w)
{
// If the word is not a valid integer value, a proper
// FormatException is thrown.
return ZInt.Parse(w);
}
/*