-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdecode.go
More file actions
executable file
·582 lines (488 loc) · 13.9 KB
/
decode.go
File metadata and controls
executable file
·582 lines (488 loc) · 13.9 KB
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
package bertlv
import (
"fmt"
"reflect"
)
// Unmarshaler is the interface implemented by types that can unmarshal a BER-TLV value of themselves.
// The input is the value of a BER-TLV.
type Unmarshaler interface {
UnmarshalBERTLV(value []byte) error
}
// Options configures the behavior of encoding and decoding operations.
type Options struct {
// DisallowUnknownFields causes decoding to fail when encountering unknown tags
DisallowUnknownFields bool
}
// DefaultOptions returns the default options for encoding/decoding.
func DefaultOptions() Options {
return Options{
DisallowUnknownFields: false,
}
}
// Unmarshal parses the BER-TLV-encoded data and stores the result
// in the value pointed to by v. If v is nil or not a pointer,
// Unmarshal returns an InvalidUnmarshalError.
func Unmarshal(data []byte, v interface{}) error {
return UnmarshalWithOptions(data, v, DefaultOptions())
}
// UnmarshalWithOptions parses the BER-TLV-encoded data with custom options
// and stores the result in the value pointed to by v.
func UnmarshalWithOptions(data []byte, v interface{}, opts Options) error {
d := NewDecoderWithOptions(data, opts)
return d.Decode(v)
}
// UnmarshalWithTag unmarshals data expecting a specific tag
func UnmarshalWithTag(data []byte, v interface{}, tagStr string) error {
return UnmarshalWithTagAndOptions(data, v, tagStr, DefaultOptions())
}
// UnmarshalWithTagAndOptions unmarshals data with specific tag and options
func UnmarshalWithTagAndOptions(data []byte, v interface{}, tagStr string, opts Options) error {
tagInfo, _, err := parseGoTag(tagStr)
if err != nil {
return fmt.Errorf("parsing top-level tag: %w", err)
}
return NewDecoderWithOptions(data, opts).DecodeWithTag(v, tagInfo)
}
// Decoder represents the state while decoding a BER-TLV value.
type Decoder struct {
data []byte
off int
options Options
}
// NewDecoder creates a new decoder for the given data.
func NewDecoder(data []byte) *Decoder {
return NewDecoderWithOptions(data, DefaultOptions())
}
// NewDecoderWithOptions creates a new decoder with custom options.
func NewDecoderWithOptions(data []byte, opts Options) *Decoder {
return &Decoder{
data: data,
options: opts,
}
}
// Decode decodes the BER-TLV data into v.
func (d *Decoder) Decode(v interface{}) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
return &InvalidUnmarshalError{reflect.TypeOf(v)}
}
elem := rv.Elem()
if elem.Kind() == reflect.Struct {
return d.decodeStruct(elem)
}
return d.decodeValue(elem)
}
// DecodeWithTag decodes a single TLV element, verifying that its tag matches expectedTag,
// and stores the result in the value pointed to by v.
func (d *Decoder) DecodeWithTag(v interface{}, expectedTag TagInfo) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
return &InvalidUnmarshalError{reflect.TypeOf(v)}
}
tag, value, err := d.next()
if err != nil {
return err
}
if tag != expectedTag {
return &DecodeError{
Offset: 0,
Message: fmt.Sprintf("expected tag %d class %02x constructed=%v, got tag %d class %02x constructed=%v",
expectedTag.Number, expectedTag.Class, expectedTag.Constructed,
tag.Number, tag.Class, tag.Constructed),
}
}
elem := rv.Elem()
if shouldEncodePrimitive(elem) {
return d.decodePrimitive(elem, value)
}
if tag.Constructed {
subDecoder := NewDecoderWithOptions(value, d.options)
if elem.Kind() == reflect.Struct {
return subDecoder.decodeStruct(elem)
}
return subDecoder.decodeValue(elem)
}
return NewDecoderWithOptions(value, d.options).decodeValue(elem)
}
func shouldEncodePrimitive(v reflect.Value) bool {
t := v.Type()
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
switch t.Kind() {
case reflect.Bool,
reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64,
reflect.Float32, reflect.Float64,
reflect.String:
return true
case reflect.Slice:
// special case []byte
return t.Elem().Kind() == reflect.Uint8
default:
return false
}
}
// decodeStruct decodes TLV data into a struct by matching tags to fields
func (d *Decoder) decodeStruct(target reflect.Value) error {
if target.CanAddr() {
if u, ok := target.Addr().Interface().(Unmarshaler); ok {
remaining := d.data[d.off:]
d.off = len(d.data)
return u.UnmarshalBERTLV(remaining)
}
}
structType := target.Type()
fields := cachedTypeFields(structType)
// track fields that have been set for slices
sliceFields := make(map[int]reflect.Value)
// track fields for required options
foundFields := make(map[int]bool)
for d.hasMoreData() {
tagOffset := d.off
tag, value, err := d.next()
if err != nil {
return err
}
fieldIndex, exists := fields.tagToField[tag.key()]
if !exists {
if d.options.DisallowUnknownFields {
return &UnknownFieldError{
Tag: tag,
Offset: tagOffset,
}
}
continue
}
fieldInfo := fields.fields[fieldIndex]
field := target.FieldByIndex(fieldInfo.index)
if !field.CanSet() {
return &DecodeError{
Offset: tagOffset,
Field: fieldInfo.name,
Type: fieldInfo.typ,
Message: "field is unexported or read-only",
}
}
if fieldInfo.tagInfo.Class != Universal && fieldInfo.tagInfo.Class != tag.Class {
return &DecodeError{
Offset: tagOffset,
Field: fieldInfo.name,
Message: fmt.Sprintf("expected class %02x, got %02x", fieldInfo.tagInfo.Class, tag.Class),
}
}
// accumulate multiple TLVs with the same tag into a slice
if field.Kind() == reflect.Slice && field.Type().Elem().Kind() != reflect.Uint8 {
// Initialize slice if not already done
if _, known := sliceFields[fieldIndex]; !known {
sliceFields[fieldIndex] = reflect.MakeSlice(field.Type(), 0, 0)
}
elem := reflect.New(field.Type().Elem()).Elem()
if err = d.decodeFieldValue(elem, tag, value); err != nil {
return fmt.Errorf("decoding slice element for field %s: %w", fieldInfo.name, err)
}
sliceFields[fieldIndex] = reflect.Append(sliceFields[fieldIndex], elem)
} else {
// non-slice field - decode normally
err = d.decodeFieldValue(field, tag, value)
if err != nil {
return fmt.Errorf("decoding field %s: %w", fieldInfo.name, err)
}
}
foundFields[fieldIndex] = true
}
// After the loop
for i, fieldInfo := range fields.fields {
if fieldInfo.required && !foundFields[i] {
return &MissingRequiredFieldError{
Field: fieldInfo.name,
Tag: fieldInfo.tagInfo,
}
}
}
// Set all accumulated slice fields
for fieldIndex, sliceValue := range sliceFields {
fieldInfo := fields.fields[fieldIndex]
field := target.FieldByIndex(fieldInfo.index)
field.Set(sliceValue)
}
return nil
}
// decodeFieldValue decodes a single field value
func (d *Decoder) decodeFieldValue(field reflect.Value, tag TagInfo, value []byte) error {
// Check for unmarshaler
if field.CanAddr() {
if u, ok := field.Addr().Interface().(Unmarshaler); ok {
return u.UnmarshalBERTLV(value)
}
}
switch field.Kind() {
case reflect.Ptr:
// Create new value and decode into it
elemType := field.Type().Elem()
elem := reflect.New(elemType)
if err := d.decodeFieldValue(elem.Elem(), tag, value); err != nil {
return err
}
field.Set(elem)
return nil
case reflect.Struct:
// For struct fields, decode based on whether tag is constructed
if tag.Constructed {
subDecoder := NewDecoderWithOptions(value, d.options)
return subDecoder.decodeStruct(field)
}
// Primitive tag for struct is an error unless it has an unmarshaler
return &UnmarshalTypeError{
Value: "primitive tag for struct type",
Type: field.Type(),
Offset: int64(d.off - len(value)),
}
case reflect.Interface:
return d.decodeInterfaceValue(field, tag, value)
default:
return d.decodePrimitive(field, value)
}
}
// decodeValue decodes a single value (used when not matching struct fields)
func (d *Decoder) decodeValue(target reflect.Value) error {
if target.CanAddr() {
if u, ok := target.Addr().Interface().(Unmarshaler); ok {
remaining := d.data[d.off:]
d.off = len(d.data)
return u.UnmarshalBERTLV(remaining)
}
}
if !d.hasMoreData() {
return &DecodeError{
Offset: d.off,
Message: "no data available for decoding",
}
}
tag, value, err := d.next()
if err != nil {
return err
}
return d.decodeFieldValue(target, tag, value)
}
// decodeInterfaceValue handles interface{} field decoding
func (d *Decoder) decodeInterfaceValue(target reflect.Value, tag TagInfo, value []byte) error {
if target.NumMethod() != 0 {
return &UnmarshalTypeError{
Value: "interface with methods",
Type: target.Type(),
Offset: int64(d.off - len(value)),
}
}
// Store as a map with tag info and value
result := make(map[string]interface{})
result["tag"] = tag
if tag.Constructed {
// Recursively decode constructed content
subDecoder := NewDecoderWithOptions(value, d.options)
// Collect all nested TLVs
content := make([]interface{}, 0)
for subDecoder.hasMoreData() {
var elem interface{}
if err := subDecoder.decodeValue(reflect.ValueOf(&elem).Elem()); err != nil {
return err
}
content = append(content, elem)
}
result["value"] = content
} else {
// Store primitive value as bytes
valueCopy := make([]byte, len(value))
copy(valueCopy, value)
result["value"] = valueCopy
}
target.Set(reflect.ValueOf(result))
return nil
}
// decodePrimitive decodes primitive types from byte data
func (d *Decoder) decodePrimitive(v reflect.Value, data []byte) error {
switch v.Kind() {
case reflect.String:
v.SetString(string(data))
case reflect.Bool:
v.SetBool(len(data) > 0 && data[0] != 0)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return decodeSignedInt(v, data)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return decodeUnsignedInt(v, data)
case reflect.Slice:
if v.Type().Elem().Kind() != reflect.Uint8 {
return &UnmarshalTypeError{
Value: "primitive bytes",
Type: v.Type(),
Offset: int64(d.off),
}
}
// Make a copy of the data
dataCopy := make([]byte, len(data))
copy(dataCopy, data)
v.SetBytes(dataCopy)
default:
return &UnmarshalTypeError{
Value: "primitive",
Type: v.Type(),
Offset: int64(d.off),
}
}
return nil
}
// decodeSignedInt decodes a signed integer from BER-TLV format
func decodeSignedInt(v reflect.Value, data []byte) error {
if len(data) == 0 {
v.SetInt(0)
return nil
}
// BER-TLV integers are in two's complement form
negative := data[0]&0x80 != 0
n := int64(0)
for _, b := range data {
n = (n << 8) | int64(b)
}
// Sign extend if necessary
if negative && len(data) < 8 {
shiftAmount := uint(len(data) * 8)
n |= ^int64(0) << shiftAmount
}
v.SetInt(n)
return nil
}
// decodeUnsignedInt decodes an unsigned integer from BER-TLV format
func decodeUnsignedInt(v reflect.Value, data []byte) error {
if len(data) == 0 {
v.SetUint(0)
return nil
}
n := uint64(0)
for _, b := range data {
n = (n << 8) | uint64(b)
}
v.SetUint(n)
return nil
}
// hasMoreData checks if there's more data to decode
func (d *Decoder) hasMoreData() bool {
return d.off < len(d.data)
}
// next reads the next TLV element (tag, length, value) and updates the decoders offset.
func (d *Decoder) next() (TagInfo, []byte, error) {
tag, err := d.readTag()
if err != nil {
return TagInfo{}, nil, err
}
length, err := d.readLength()
if err != nil {
return TagInfo{}, nil, err
}
value, err := d.readValue(length)
if err != nil {
return TagInfo{}, nil, err
}
return tag, value, nil
}
// readTag reads and parses a BER-TLV tag and updates the decoders offset.
func (d *Decoder) readTag() (TagInfo, error) {
if d.off >= len(d.data) {
return TagInfo{}, &DecodeError{
Offset: d.off,
Message: "unexpected end of data while reading tag",
}
}
firstByte := d.data[d.off]
d.off++
tag := TagInfo{
Class: Class(firstByte & 0xC0),
Constructed: (firstByte & 0x20) != 0,
}
number := uint16(firstByte & 0x1F)
// Handle long form tag numbers
if number == 0x1F {
number = 0
for {
if d.off >= len(d.data) {
return TagInfo{}, &DecodeError{
Offset: d.off,
Message: "unexpected end of data while reading long form tag",
}
}
b := d.data[d.off]
d.off++
number = (number << 7) | uint16(b&0x7F)
if b&0x80 == 0 {
break
}
if number > MaxTagNumber {
return TagInfo{}, &DecodeError{
Offset: d.off,
Message: fmt.Sprintf("tag number %d exceeds maximum", number),
}
}
}
}
tag.Number = number
return tag, nil
}
// readLength reads and parses a BER-TLV length and updates the decoders offset.
func (d *Decoder) readLength() (int, error) {
if d.off >= len(d.data) {
return 0, &DecodeError{
Offset: d.off,
Message: "unexpected end of data while reading length",
}
}
b := d.data[d.off]
d.off++
// Short form
if b&0x80 == 0 {
return int(b), nil
}
// Long form
numBytes := int(b & 0x7F)
if numBytes == 0 {
return 0, &DecodeError{
Offset: d.off - 1,
Message: "indefinite length form not supported",
}
}
if numBytes > 4 {
return 0, &DecodeError{
Offset: d.off - 1,
Message: fmt.Sprintf("length requires %d bytes, maximum 4 supported", numBytes),
}
}
if d.off+numBytes > len(d.data) {
return 0, &DecodeError{
Offset: d.off,
Message: "unexpected end of data while reading long form length",
}
}
length := 0
for i := 0; i < numBytes; i++ {
length = (length << 8) | int(d.data[d.off])
d.off++
}
if length < 0 {
return 0, &DecodeError{
Offset: d.off - numBytes,
Message: "negative length",
}
}
return length, nil
}
// readValue reads the value bytes of specified length
func (d *Decoder) readValue(length int) ([]byte, error) {
if d.off+length > len(d.data) {
return nil, &DecodeError{
Offset: d.off,
Message: fmt.Sprintf("length %d extends beyond data bounds", length),
}
}
value := make([]byte, length)
copy(value, d.data[d.off:d.off+length])
d.off += length
return value, nil
}