-
Notifications
You must be signed in to change notification settings - Fork 4
/
aper.go
937 lines (888 loc) · 27.7 KB
/
aper.go
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
// Copyright 2019 Communication Service/Software Laboratory, National Chiao Tung University (free5gc.org)
//
// SPDX-License-Identifier: Apache-2.0
package aper
import (
"fmt"
"path"
"reflect"
"runtime"
"github.com/omec-project/aper/logger"
)
type perBitData struct {
bytes []byte
byteOffset uint64
bitsOffset uint
}
func perTrace(level int, s string) {
logger.AperLog.Debugf("perTrace level is %d", level)
_, file, line, ok := runtime.Caller(1)
if !ok {
logger.AperLog.Debugln(s)
} else {
logger.AperLog.Debugf("%s (%s:%d)", s, path.Base(file), line)
}
}
func perBitLog(numBits uint64, byteOffset uint64, bitsOffset uint, value interface{}) string {
if reflect.TypeOf(value).Kind() == reflect.Uint64 {
return fmt.Sprintf(" [PER got %2d bits, byteOffset(after): %d, bitsOffset(after): %d, value: 0x%0x]",
numBits, byteOffset, bitsOffset, reflect.ValueOf(value).Uint())
}
return fmt.Sprintf(" [PER got %2d bits, byteOffset(after): %d, bitsOffset(after): %d, value: 0x%0x]",
numBits, byteOffset, bitsOffset, reflect.ValueOf(value).Bytes())
}
// GetBitString is to get BitString with desire size from source byte array with bit offset
func GetBitString(srcBytes []byte, bitsOffset uint, numBits uint) (dstBytes []byte, err error) {
bitsLeft := uint(len(srcBytes))*8 - bitsOffset
if numBits > bitsLeft {
err = fmt.Errorf("get bits overflow, requireBits: %d, leftBits: %d", numBits, bitsLeft)
return
}
byteLen := (bitsOffset + numBits + 7) >> 3
numBitsByteLen := (numBits + 7) >> 3
dstBytes = make([]byte, numBitsByteLen)
numBitsMask := byte(0xff)
if modEight := numBits & 0x7; modEight != 0 {
numBitsMask <<= uint8(8 - (modEight))
}
for i := 1; i < int(byteLen); i++ {
dstBytes[i-1] = srcBytes[i-1]<<bitsOffset | srcBytes[i]>>(8-bitsOffset)
}
if byteLen == numBitsByteLen {
dstBytes[byteLen-1] = srcBytes[byteLen-1] << bitsOffset
}
dstBytes[numBitsByteLen-1] &= numBitsMask
return
}
// GetFewBits is to get Value with desire few bits from source byte with bit offset
// func GetFewBits(srcByte byte, bitsOffset uint, numBits uint) (value uint64, err error) {
// if numBits == 0 {
// value = 0
// return
// }
// bitsLeft := 8 - bitsOffset
// if bitsLeft < numBits {
// err = fmt.Errorf("get bits overflow, requireBits: %d, leftBits: %d", numBits, bitsLeft)
// return
// }
// if bitsOffset == 0 {
// value = uint64(srcByte >> (8 - numBits))
// } else {
// value = uint64((srcByte << bitsOffset) >> (8 - numBits))
// }
// return
// }
// GetBitsValue is to get Value with desire bits from source byte array with bit offset
func GetBitsValue(srcBytes []byte, bitsOffset uint, numBits uint) (value uint64, err error) {
var dstBytes []byte
dstBytes, err = GetBitString(srcBytes, bitsOffset, numBits)
if err != nil {
return
}
for i, j := 0, numBits; j >= 8; i, j = i+1, j-8 {
value <<= 8
value |= uint64(uint(dstBytes[i]))
}
if numBitsOff := (numBits & 0x7); numBitsOff != 0 {
var mask uint = (1 << numBitsOff) - 1
value <<= numBitsOff
value |= uint64(uint(dstBytes[len(dstBytes)-1]>>(8-numBitsOff)) & mask)
}
return
}
func (pd *perBitData) bitCarry() {
pd.byteOffset += uint64(pd.bitsOffset >> 3)
pd.bitsOffset = pd.bitsOffset & 0x07
}
func (pd *perBitData) getBitString(numBits uint) (dstBytes []byte, err error) {
dstBytes, err = GetBitString(pd.bytes[pd.byteOffset:], pd.bitsOffset, numBits)
if err != nil {
return
}
pd.bitsOffset += numBits
pd.bitCarry()
perTrace(1, perBitLog(uint64(numBits), pd.byteOffset, pd.bitsOffset, dstBytes))
return
}
func (pd *perBitData) getBitsValue(numBits uint) (value uint64, err error) {
value, err = GetBitsValue(pd.bytes[pd.byteOffset:], pd.bitsOffset, numBits)
if err != nil {
return
}
pd.bitsOffset += numBits
pd.bitCarry()
perTrace(1, perBitLog(uint64(numBits), pd.byteOffset, pd.bitsOffset, value))
return
}
func (pd *perBitData) parseAlignBits() error {
if (pd.bitsOffset & 0x7) > 0 {
alignBits := 8 - ((pd.bitsOffset) & 0x7)
perTrace(2, fmt.Sprintf("Aligning %d bits", alignBits))
if val, err := pd.getBitsValue(alignBits); err != nil {
return err
} else if val != 0 {
return fmt.Errorf("align Bit is not zero")
}
} else if pd.bitsOffset != 0 {
pd.bitCarry()
}
return nil
}
func (pd *perBitData) parseConstraintValue(valueRange int64) (value uint64, err error) {
perTrace(3, fmt.Sprintf("Getting Constraint Value with range %d", valueRange))
var bytes uint
if valueRange <= 255 {
if valueRange < 0 {
return value, fmt.Errorf("value range is negative")
}
var i uint
// 1 ~ 8 bits
for i = 1; i <= 8; i++ {
upper := 1 << i
if int64(upper) >= valueRange {
break
}
}
value, err = pd.getBitsValue(i)
return value, err
} else if valueRange == 256 {
bytes = 1
} else if valueRange <= 65536 {
bytes = 2
} else {
return value, fmt.Errorf("constraint Value is large than 65536")
}
if err = pd.parseAlignBits(); err != nil {
return value, err
}
value, err = pd.getBitsValue(bytes * 8)
return value, err
}
func (pd *perBitData) parseSemiConstrainedWholeNumber(lb uint64) (value uint64, err error) {
var repeat bool
var length uint64
if length, err = pd.parseLength(-1, &repeat); err != nil {
return value, err
}
if length > 8 || repeat {
return value, fmt.Errorf("too long length: %d", length)
}
if value, err = pd.getBitsValue(uint(length) * 8); err != nil {
return value, err
}
value += lb
return value, err
}
func (pd *perBitData) parseNormallySmallNonNegativeWholeNumber() (value uint64, err error) {
var notSmallFlag uint64
if notSmallFlag, err = pd.getBitsValue(1); err != nil {
return
}
if notSmallFlag == 1 {
if value, err = pd.parseSemiConstrainedWholeNumber(0); err != nil {
return
}
} else {
if value, err = pd.getBitsValue(6); err != nil {
return
}
}
return
}
func (pd *perBitData) parseLength(sizeRange int64, repeat *bool) (value uint64, err error) {
*repeat = false
if sizeRange <= 65536 && sizeRange > 0 {
return pd.parseConstraintValue(sizeRange)
}
if err = pd.parseAlignBits(); err != nil {
return value, err
}
firstByte, err := pd.getBitsValue(8)
if err != nil {
return value, err
}
if (firstByte & 128) == 0 { // #10.9.3.6
value = firstByte & 0x7F
return value, err
} else if (firstByte & 64) == 0 { // #10.9.3.7
var secondByte uint64
if secondByte, err = pd.getBitsValue(8); err != nil {
return value, err
}
value = ((firstByte & 63) << 8) | secondByte
return value, err
}
firstByte &= 63
if firstByte < 1 || firstByte > 4 {
return value, fmt.Errorf("parse Length Out of Constraint")
}
*repeat = true
value = 16384 * firstByte
return value, err
}
func (pd *perBitData) parseBitString(extensed bool, lowerBoundPtr *int64, upperBoundPtr *int64) (BitString, error) {
var lb, ub, sizeRange int64 = 0, -1, -1
if !extensed {
if lowerBoundPtr != nil {
lb = *lowerBoundPtr
}
if upperBoundPtr != nil {
ub = *upperBoundPtr
sizeRange = ub - lb + 1
}
}
if ub > 65535 {
sizeRange = -1
}
// initailization
bitString := BitString{[]byte{}, 0}
// lowerbound == upperbound
if sizeRange == 1 {
sizes := uint64(ub+7) >> 3
bitString.BitLength = uint64(ub)
perTrace(2, fmt.Sprintf("Decoding BIT STRING size %d", ub))
if sizes > 2 {
if err := pd.parseAlignBits(); err != nil {
return bitString, err
}
if (pd.byteOffset + sizes) > uint64(len(pd.bytes)) {
return bitString, fmt.Errorf("per data out of range")
}
bitString.Bytes = pd.bytes[pd.byteOffset : pd.byteOffset+sizes]
pd.byteOffset += sizes
pd.bitsOffset = uint(ub & 0x7)
if pd.bitsOffset > 0 {
pd.byteOffset--
}
perTrace(1, perBitLog(uint64(ub), pd.byteOffset, pd.bitsOffset, bitString.Bytes))
} else {
if bytes, err := pd.getBitString(uint(ub)); err != nil {
logger.AperLog.Warnf("PD GetBitString error: %+v", err)
return bitString, err
} else {
bitString.Bytes = bytes
}
}
perTrace(2, fmt.Sprintf("Decoded BIT STRING (length = %d): %0.8b", ub, bitString.Bytes))
return bitString, nil
}
repeat := false
for {
var rawLength uint64
if length, err := pd.parseLength(sizeRange, &repeat); err != nil {
return bitString, err
} else {
rawLength = length
}
rawLength += uint64(lb)
perTrace(2, fmt.Sprintf("Decoding BIT STRING size %d", rawLength))
if rawLength == 0 {
return bitString, nil
}
sizes := (rawLength + 7) >> 3
if err := pd.parseAlignBits(); err != nil {
return bitString, err
}
if (pd.byteOffset + sizes) > uint64(len(pd.bytes)) {
return bitString, fmt.Errorf("per data out of range")
}
bitString.Bytes = append(bitString.Bytes, pd.bytes[pd.byteOffset:pd.byteOffset+sizes]...)
bitString.BitLength += rawLength
pd.byteOffset += sizes
pd.bitsOffset = uint(rawLength & 0x7)
if pd.bitsOffset != 0 {
pd.byteOffset--
}
perTrace(1, perBitLog(rawLength, pd.byteOffset, pd.bitsOffset, bitString.Bytes))
perTrace(2, fmt.Sprintf("Decoded BIT STRING (length = %d): %0.8b", rawLength, bitString.Bytes))
if !repeat {
// if err = pd.parseAlignBits(); err != nil {
// return
// }
break
}
}
return bitString, nil
}
func (pd *perBitData) parseOctetString(extensed bool, lowerBoundPtr *int64, upperBoundPtr *int64) (
OctetString, error,
) {
var lb, ub, sizeRange int64 = 0, -1, -1
if !extensed {
if lowerBoundPtr != nil {
lb = *lowerBoundPtr
}
if upperBoundPtr != nil {
ub = *upperBoundPtr
sizeRange = ub - lb + 1
}
}
if ub > 65535 {
sizeRange = -1
}
// initailization
octetString := OctetString("")
// lowerbound == upperbound
if sizeRange == 1 {
perTrace(2, fmt.Sprintf("Decoding OCTET STRING size %d", ub))
if ub > 2 {
unsignedUB := uint64(ub)
if err := pd.parseAlignBits(); err != nil {
return octetString, err
}
if (int64(pd.byteOffset) + ub) > int64(len(pd.bytes)) {
return octetString, fmt.Errorf("per data out of range")
}
octetString = pd.bytes[pd.byteOffset : pd.byteOffset+unsignedUB]
pd.byteOffset += uint64(ub)
perTrace(1, perBitLog(8*unsignedUB, pd.byteOffset, pd.bitsOffset, octetString))
} else {
if octet, err := pd.getBitString(uint(ub * 8)); err != nil {
return octetString, err
} else {
octetString = octet
}
}
perTrace(2, fmt.Sprintf("Decoded OCTET STRING (length = %d): 0x%0x", ub, octetString))
return octetString, nil
}
repeat := false
for {
var rawLength uint64
if length, err := pd.parseLength(sizeRange, &repeat); err != nil {
return octetString, err
} else {
rawLength = length
}
rawLength += uint64(lb)
perTrace(2, fmt.Sprintf("Decoding OCTET STRING size %d", rawLength))
if rawLength == 0 {
return octetString, nil
} else if err := pd.parseAlignBits(); err != nil {
return octetString, err
}
if (rawLength + pd.byteOffset) > uint64(len(pd.bytes)) {
return octetString, fmt.Errorf("per data out of range ")
}
octetString = append(octetString, pd.bytes[pd.byteOffset:pd.byteOffset+rawLength]...)
pd.byteOffset += rawLength
perTrace(1, perBitLog(8*rawLength, pd.byteOffset, pd.bitsOffset, octetString))
perTrace(2, fmt.Sprintf("Decoded OCTET STRING (length = %d): 0x%0x", rawLength, octetString))
if !repeat {
// if err = pd.parseAlignBits(); err != nil {
// return
// }
break
}
}
return octetString, nil
}
func (pd *perBitData) parseBool() (value bool, err error) {
perTrace(3, "Decoding BOOLEAN Value")
bit, err1 := pd.getBitsValue(1)
if err1 != nil {
err = err1
return
}
if bit == 1 {
value = true
perTrace(2, "Decoded BOOLEAN Value : ture")
} else {
value = false
perTrace(2, "Decoded BOOLEAN Value : false")
}
return
}
func (pd *perBitData) parseInteger(extensed bool, lowerBoundPtr *int64, upperBoundPtr *int64) (int64, error) {
var lb, ub, valueRange int64 = 0, -1, 0
if !extensed {
if lowerBoundPtr == nil {
perTrace(3, "Decoding INTEGER with Unconstraint Value")
valueRange = -1
} else {
lb = *lowerBoundPtr
if upperBoundPtr != nil {
ub = *upperBoundPtr
valueRange = ub - lb + 1
perTrace(3, fmt.Sprintf("Decoding INTEGER with Value Range(%d..%d)", lb, ub))
} else {
perTrace(3, fmt.Sprintf("Decoding INTEGER with Semi-Constraint Range(%d..)", lb))
}
}
} else {
valueRange = -1
perTrace(3, "Decoding INTEGER with Extensive Value")
}
var rawLength uint
if valueRange == 1 {
return ub, nil
} else if valueRange <= 0 {
// semi-constraint or unconstraint
if err := pd.parseAlignBits(); err != nil {
return int64(0), err
}
if pd.byteOffset >= uint64(len(pd.bytes)) {
return int64(0), fmt.Errorf("per data out of range")
}
rawLength = uint(pd.bytes[pd.byteOffset])
pd.byteOffset++
perTrace(1, perBitLog(8, pd.byteOffset, pd.bitsOffset, uint64(rawLength)))
} else if valueRange <= 65536 {
rawValue, err := pd.parseConstraintValue(valueRange)
if err != nil {
return int64(0), err
} else {
return int64(rawValue) + lb, nil
}
} else {
// valueRange > 65536
var byteLen uint
unsignedValueRange := uint64(valueRange - 1)
for byteLen = 1; byteLen <= 127; byteLen++ {
unsignedValueRange >>= 8
if unsignedValueRange == 0 {
break
}
}
var i, upper uint
// 1 ~ 8 bits
for i = 1; i <= 8; i++ {
upper = 1 << i
if upper >= byteLen {
break
}
}
if tempLength, err := pd.getBitsValue(i); err != nil {
return int64(0), err
} else {
rawLength = uint(tempLength)
}
rawLength++
if err := pd.parseAlignBits(); err != nil {
return int64(0), err
}
}
perTrace(2, fmt.Sprintf("Decoding INTEGER Length with %d bytes", rawLength))
if rawValue, err := pd.getBitsValue(rawLength * 8); err != nil {
return int64(0), err
} else if valueRange < 0 {
signedBitMask := uint64(1 << (rawLength*8 - 1))
valueMask := signedBitMask - 1
// negative
if rawValue&signedBitMask > 0 {
return int64((^rawValue)&valueMask+1) * -1, nil
}
return int64(rawValue) + lb, nil
} else {
return int64(rawValue) + lb, nil
}
}
func (pd *perBitData) parseEnumerated(extensed bool, lowerBoundPtr *int64, upperBoundPtr *int64) (value uint64,
err error,
) {
if lowerBoundPtr == nil || upperBoundPtr == nil {
err = fmt.Errorf("enumerated value constraint is error")
return
}
lb, ub := *lowerBoundPtr, *upperBoundPtr
if lb < 0 || lb > ub {
err = fmt.Errorf("enumerated value constraint is error")
return
}
if extensed {
perTrace(2, fmt.Sprintf("Decoding ENUMERATED with Extensive Value of Range(%d..)", ub+1))
if value, err = pd.parseNormallySmallNonNegativeWholeNumber(); err != nil {
return
}
value += uint64(ub) + 1
} else {
perTrace(2, fmt.Sprintf("Decoding ENUMERATED with Value Range(%d..%d)", lb, ub))
valueRange := ub - lb + 1
if valueRange > 1 {
value, err = pd.parseConstraintValue(valueRange)
}
}
perTrace(2, fmt.Sprintf("Decoded ENUMERATED Value : %d", value))
return
}
func (pd *perBitData) parseSequenceOf(sizeExtensed bool, params fieldParameters, sliceType reflect.Type) (
reflect.Value, error,
) {
var sliceContent reflect.Value
var lb int64 = 0
var sizeRange int64
if params.sizeLowerBound != nil && *params.sizeLowerBound < 65536 {
lb = *params.sizeLowerBound
}
if !sizeExtensed && params.sizeUpperBound != nil && *params.sizeUpperBound < 65536 {
ub := *params.sizeUpperBound
sizeRange = ub - lb + 1
perTrace(3, fmt.Sprintf("Decoding Length of \"SEQUENCE OF\" with Size Range(%d..%d)", lb, ub))
} else {
sizeRange = -1
perTrace(3, fmt.Sprintf("Decoding Length of \"SEQUENCE OF\" with Semi-Constraint Range(%d..)", lb))
}
var numElements uint64
if sizeRange > 1 {
if numElementsTmp, err := pd.parseConstraintValue(sizeRange); err != nil {
logger.AperLog.Warnf("Parse Constraint Value failed: %+v", err)
} else {
numElements = numElementsTmp
}
numElements += uint64(lb)
} else if sizeRange == 1 {
numElements += uint64(lb)
} else {
if err := pd.parseAlignBits(); err != nil {
return sliceContent, err
}
if pd.byteOffset >= uint64(len(pd.bytes)) {
return sliceContent, fmt.Errorf("per data out of range")
}
numElements = uint64(pd.bytes[pd.byteOffset])
pd.byteOffset++
perTrace(1, perBitLog(8, pd.byteOffset, pd.bitsOffset, numElements))
}
perTrace(2, fmt.Sprintf("Decoding \"SEQUENCE OF\" struct %s with len(%d)", sliceType.Elem().Name(), numElements))
params.sizeExtensible = false
params.sizeUpperBound = nil
params.sizeLowerBound = nil
intNumElements := int(numElements)
sliceContent = reflect.MakeSlice(sliceType, intNumElements, intNumElements)
for i := 0; i < intNumElements; i++ {
err := parseField(sliceContent.Index(i), pd, params)
if err != nil {
return sliceContent, err
}
}
return sliceContent, nil
}
func (pd *perBitData) getChoiceIndex(extensed bool, upperBoundPtr *int64) (present int, err error) {
if extensed {
err = fmt.Errorf("unsupport value of CHOICE type is in Extensed")
} else if upperBoundPtr == nil {
err = fmt.Errorf("the upper bound of CHIOCE is missing")
} else if ub := *upperBoundPtr; ub < 0 {
err = fmt.Errorf("the upper bound of CHIOCE is negative")
} else if rawChoice, err1 := pd.parseConstraintValue(ub + 1); err1 != nil {
err = err1
} else {
perTrace(2, fmt.Sprintf("Decoded Present index of CHOICE is %d + 1", rawChoice))
present = int(rawChoice) + 1
}
return
}
func getReferenceFieldValue(v reflect.Value) (value int64, err error) {
fieldType := v.Type()
switch v.Kind() {
case reflect.Int, reflect.Int32, reflect.Int64:
value = v.Int()
case reflect.Struct:
if fieldType.Field(0).Name == "Present" {
present := int(v.Field(0).Int())
if present == 0 {
err = fmt.Errorf("referenceField value present is 0 (present's field number)")
} else if present >= fieldType.NumField() {
err = fmt.Errorf("present is bigger than number of struct field")
} else {
value, err = getReferenceFieldValue(v.Field(present))
}
} else {
value, err = getReferenceFieldValue(v.Field(0))
}
default:
err = fmt.Errorf("openType reference only support INTEGER")
}
return
}
func (pd *perBitData) parseOpenType(skip bool, v reflect.Value, params fieldParameters) error {
pdOpenType := &perBitData{[]byte(""), 0, 0}
repeat := false
for {
var rawLength uint64
if rawLengthTmp, err := pd.parseLength(-1, &repeat); err != nil {
return err
} else {
rawLength = rawLengthTmp
}
if rawLength == 0 {
break
} else if err := pd.parseAlignBits(); err != nil {
return err
}
if (rawLength + pd.byteOffset) > uint64(len(pd.bytes)) {
return fmt.Errorf("per data out of range ")
}
pdOpenType.bytes = append(pdOpenType.bytes, pd.bytes[pd.byteOffset:pd.byteOffset+rawLength]...)
pd.byteOffset += rawLength
if !repeat {
if err := pd.parseAlignBits(); err != nil {
return err
}
break
}
}
if skip {
perTrace(2, fmt.Sprintf("Skip OpenType (len = %d byte)", len(pdOpenType.bytes)))
return nil
} else {
perTrace(2, fmt.Sprintf("Decoding OpenType %s with (len = %d byte)", v.Type().String(), len(pdOpenType.bytes)))
err := parseField(v, pdOpenType, params)
perTrace(2, fmt.Sprintf("Decoded OpenType %s", v.Type().String()))
return err
}
}
// parseField is the main parsing function. Given a byte slice and an offset
// into the array, it will try to parse a suitable ASN.1 value out and store it
// in the given Value. TODO : ObjectIdenfier, handle extension Field
func parseField(v reflect.Value, pd *perBitData, params fieldParameters) error {
fieldType := v.Type()
// If we have run out of data return error.
if pd.byteOffset == uint64(len(pd.bytes)) {
return fmt.Errorf("sequence truncated")
}
if v.Kind() == reflect.Ptr {
ptr := reflect.New(fieldType.Elem())
v.Set(ptr)
return parseField(v.Elem(), pd, params)
}
sizeExtensible := false
valueExtensible := false
if params.sizeExtensible {
if bitsValue, err1 := pd.getBitsValue(1); err1 != nil {
return err1
} else if bitsValue != 0 {
sizeExtensible = true
}
perTrace(2, fmt.Sprintf("Decoded Size Extensive Bit : %t", sizeExtensible))
}
if params.valueExtensible && v.Kind() != reflect.Slice {
if bitsValue, err1 := pd.getBitsValue(1); err1 != nil {
return err1
} else if bitsValue != 0 {
valueExtensible = true
}
perTrace(2, fmt.Sprintf("Decoded Value Extensive Bit : %t", valueExtensible))
}
// We deal with the structures defined in this package first.
switch fieldType {
case BitStringType:
bitString, err1 := pd.parseBitString(sizeExtensible, params.sizeLowerBound, params.sizeUpperBound)
if err1 != nil {
return err1
}
v.Set(reflect.ValueOf(bitString))
return nil
case ObjectIdentifierType:
return fmt.Errorf("unsupport ObjectIdenfier type")
case OctetStringType:
if octetString, err := pd.parseOctetString(sizeExtensible, params.sizeLowerBound, params.sizeUpperBound); err != nil {
return err
} else {
v.Set(reflect.ValueOf(octetString))
return nil
}
case EnumeratedType:
if parsedEnum, err := pd.parseEnumerated(valueExtensible, params.valueLowerBound,
params.valueUpperBound); err != nil {
return err
} else {
v.SetUint(parsedEnum)
return nil
}
}
switch val := v; val.Kind() {
case reflect.Bool:
if parsedBool, err := pd.parseBool(); err != nil {
return err
} else {
val.SetBool(parsedBool)
return nil
}
case reflect.Int, reflect.Int32, reflect.Int64:
if parsedInt, err := pd.parseInteger(valueExtensible, params.valueLowerBound, params.valueUpperBound); err != nil {
return err
} else {
val.SetInt(parsedInt)
perTrace(2, fmt.Sprintf("Decoded INTEGER Value: %d", parsedInt))
return nil
}
case reflect.Struct:
structType := fieldType
var structParams []fieldParameters
var optionalCount uint
var optionalPresents uint64
// pass tag for optional
for i := 0; i < structType.NumField(); i++ {
if structType.Field(i).PkgPath != "" {
return fmt.Errorf("struct contains unexported fields : %s", structType.Field(i).PkgPath)
}
tempParams := parseFieldParameters(structType.Field(i).Tag.Get("aper"))
// for optional flag
if tempParams.optional {
optionalCount++
}
structParams = append(structParams, tempParams)
}
if optionalCount > 0 {
if optionalPresentsTmp, err := pd.getBitsValue(optionalCount); err != nil {
return err
} else {
optionalPresents = optionalPresentsTmp
}
perTrace(2, fmt.Sprintf("optionalPresents is %0b", optionalPresents))
}
// CHOICE or OpenType
if structType.NumField() > 0 && structType.Field(0).Name == "Present" {
var present int = 0
if params.openType {
if params.referenceFieldValue == nil {
return fmt.Errorf("openType reference value is empty")
}
refValue := *params.referenceFieldValue
for j, param := range structParams {
if j == 0 {
continue
}
if param.referenceFieldValue != nil && *param.referenceFieldValue == refValue {
present = j
break
}
}
if present == 0 {
val.Field(0).SetInt(0)
perTrace(2, "OpenType reference value does not match any field")
return pd.parseOpenType(true, reflect.Value{}, fieldParameters{})
} else if present >= structType.NumField() {
return fmt.Errorf("openType Present is bigger than number of struct field")
} else {
val.Field(0).SetInt(int64(present))
perTrace(2, fmt.Sprintf("Decoded Present index of OpenType is %d ", present))
return pd.parseOpenType(false, val.Field(present), structParams[present])
}
} else {
if presentTmp, err := pd.getChoiceIndex(valueExtensible, params.valueUpperBound); err != nil {
logger.AperLog.Errorf("pd.getChoiceIndex Error")
} else {
present = presentTmp
}
val.Field(0).SetInt(int64(present))
if present == 0 {
return fmt.Errorf("choice present is 0 (present's field number)")
} else if present >= structType.NumField() {
return fmt.Errorf("choice present is bigger than number of struct field")
} else {
return parseField(val.Field(present), pd, structParams[present])
}
}
}
for i := 0; i < structType.NumField(); i++ {
if structParams[i].optional && optionalCount > 0 {
optionalCount--
if optionalPresents&(1<<optionalCount) == 0 {
perTrace(3, fmt.Sprintf("Field \"%s\" in %s is OPTIONAL and not present", structType.Field(i).Name, structType))
continue
} else {
perTrace(3, fmt.Sprintf("Field \"%s\" in %s is OPTIONAL and present", structType.Field(i).Name, structType))
}
}
// for open type reference
if structParams[i].openType {
fieldName := structParams[i].referenceFieldName
var index int
for index = 0; index < i; index++ {
if structType.Field(index).Name == fieldName {
break
}
}
if index == i {
return fmt.Errorf("open type is not reference to the other field in the struct")
}
structParams[i].referenceFieldValue = new(int64)
if referenceFieldValue, err := getReferenceFieldValue(val.Field(index)); err != nil {
return err
} else {
*structParams[i].referenceFieldValue = referenceFieldValue
}
}
if err := parseField(val.Field(i), pd, structParams[i]); err != nil {
return err
}
}
return nil
case reflect.Slice:
sliceType := fieldType
if newSlice, err := pd.parseSequenceOf(sizeExtensible, params, sliceType); err != nil {
return err
} else {
val.Set(newSlice)
return nil
}
case reflect.String:
perTrace(2, "Decoding PrintableString using Octet String decoding method")
if octetString, err := pd.parseOctetString(sizeExtensible, params.sizeLowerBound, params.sizeUpperBound); err != nil {
return err
} else {
printableString := string(octetString)
val.SetString(printableString)
perTrace(2, fmt.Sprintf("Decoded PrintableString : \"%s\"", printableString))
return nil
}
}
return fmt.Errorf("unsupported: %s", v.Type().String())
}
// Unmarshal parses the APER-encoded ASN.1 data structure b
// and uses the reflect package to fill in an arbitrary value pointed at by value.
// Because Unmarshal uses the reflect package, the structs
// being written to must use upper case field names.
//
// An ASN.1 INTEGER can be written to an int, int32, int64,
// If the encoded value does not fit in the Go type,
// Unmarshal returns a parse error.
//
// An ASN.1 BIT STRING can be written to a BitString.
//
// An ASN.1 OCTET STRING can be written to a []byte.
//
// An ASN.1 OBJECT IDENTIFIER can be written to an
// ObjectIdentifier.
//
// An ASN.1 ENUMERATED can be written to an Enumerated.
//
// Any of the above ASN.1 values can be written to an interface{}.
// The value stored in the interface has the corresponding Go type.
// For integers, that type is int64.
//
// An ASN.1 SEQUENCE OF x can be written
// to a slice if an x can be written to the slice's element type.
//
// An ASN.1 SEQUENCE can be written to a struct
// if each of the elements in the sequence can be
// written to the corresponding element in the struct.
//
// The following tags on struct fields have special meaning to Unmarshal:
//
// optional OPTIONAL tag in SEQUENCE
// sizeExt specifies that size is extensible
// valueExt specifies that value is extensible
// sizeLB set the minimum value of size constraint
// sizeUB set the maximum value of value constraint
// valueLB set the minimum value of size constraint
// valueUB set the maximum value of value constraint
// default sets the default value
// openType specifies the open Type
// referenceFieldName the string of the reference field for this type (only if openType used)
// referenceFieldValue the corresponding value of the reference field for this type (only if openType used)
//
// Other ASN.1 types are not supported; if it encounters them,
// Unmarshal returns a parse error.
func Unmarshal(b []byte, value interface{}) error {
return UnmarshalWithParams(b, value, "")
}
// UnmarshalWithParams allows field parameters to be specified for the
// top-level element. The form of the params is the same as the field tags.
func UnmarshalWithParams(b []byte, value interface{}, params string) error {
v := reflect.ValueOf(value).Elem()
pd := &perBitData{b, 0, 0}
return parseField(v, pd, parseFieldParameters(params))
}