-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathtlv.go
More file actions
executable file
·364 lines (302 loc) · 9.19 KB
/
tlv.go
File metadata and controls
executable file
·364 lines (302 loc) · 9.19 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
package bertlv
import (
"encoding/hex"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
)
// Tag represents a BER-TLV tag identifier.
// It combines class, construction, and tag number according to ITU-T X.690.
type Tag uint32
// Length represents the length component in a BER-TLV structure.
type Length uint32
// Class represents the tag class in BER-TLV encoding.
// The four classes are Universal, Application, Context-specific, and Private.
type Class byte
const (
// Universal class for types defined in the standard
Universal Class = 0x00
// Application class for application-specific types
Application Class = 0x40
// ContextSpecific class for context-specific types within a constructed type
ContextSpecific Class = 0x80
// Private class for private use
Private Class = 0xC0
)
// MaxTagNumber is the maximum allowed tag number (14 bits)
const MaxTagNumber = 0x3FFF
const (
// Tag parsing constants
tagSkipMarker = "-"
bertlvTagKey = "bertlv"
)
// TagInfo holds complete metadata about a BER-TLV tag.
type TagInfo struct {
Class Class
Constructed bool
Number uint16
}
// tagKey is used for map lookups, matching on class and number only (ignoring constructed bit).
type tagKey struct {
Class Class
Number uint16
}
func (t TagInfo) key() tagKey {
return tagKey{Class: t.Class, Number: t.Number}
}
// String returns a human-readable representation of the tag.
func (t TagInfo) String() string {
return fmt.Sprintf("[%s %s %d]", t.getClassString(), t.getConstructionString(), t.Number)
}
// getClassString returns the string representation of the tag class
func (t TagInfo) getClassString() string {
switch t.Class {
case Universal:
return "Universal"
case Application:
return "Application"
case ContextSpecific:
return "Context"
case Private:
return "Private"
default:
return "Unknown"
}
}
// getConstructionString returns the string representation of the construction bit
func (t TagInfo) getConstructionString() string {
if t.Constructed {
return "Constructed"
}
return "Primitive"
}
// structField contains information about how to encode/decode a specific struct field.
type structField struct {
name string
tagInfo TagInfo
index []int
typ reflect.Type
omitEmpty bool
required bool
}
// structFields maintains a cache of struct field mappings for efficient encoding/decoding.
type structFields struct {
fields []structField
tagToField map[tagKey]int
}
// fieldCache provides thread-safe caching of struct field analysis
var fieldCache = struct {
sync.RWMutex
m map[reflect.Type]structFields
}{
m: make(map[reflect.Type]structFields),
}
// tagOptions contains parsed tag options from struct field tags.
type tagOptions struct {
options []string
}
// contains checks if a specific option is present.
func (o tagOptions) contains(option string) bool {
for _, opt := range o.options {
if opt == option {
return true
}
}
return false
}
// parseGoTag parses a struct field tag into tag number, class, constructed flag, and options.
// Supports both formats:
// - Hex format: "0x81" or "81" (automatically infers class and construction)
// - Explicit format: "1,application,omitempty" (requires explicit class specification)
func parseGoTag(structTag string) (TagInfo, tagOptions, error) {
if structTag == "" {
return TagInfo{}, tagOptions{}, fmt.Errorf("empty tag")
}
parts := strings.Split(structTag, ",")
tagStr := strings.TrimSpace(parts[0])
// Check if this is hex format
if isHexTag(tagStr) {
return parseHexTag(tagStr, parts[1:])
}
// Explicit decimal format - requires class specification for non-universal
return parseExplicitTag(parts)
}
// isHexTag determines if a tag string is in hexadecimal format.
// Requires the 0x prefix for unambiguous declaration.
func isHexTag(tagStr string) bool {
return strings.HasPrefix(tagStr, "0x")
}
// parseHexTag parses a hexadecimal tag using the existing decoder logic
func parseHexTag(tagStr string, remainingParts []string) (TagInfo, tagOptions, error) {
// Remove 0x prefix
hexStr := strings.TrimPrefix(tagStr, "0x")
// Convert hex string to bytes
tagBytes, err := hex.DecodeString(hexStr)
if err != nil {
return TagInfo{}, tagOptions{}, fmt.Errorf("invalid hex tag %q: %w", tagStr, err)
}
// Use existing decoder to parse the tag bytes
decoder := &Decoder{data: tagBytes, off: 0}
tagInfo, err := decoder.readTag()
if err != nil {
return TagInfo{}, tagOptions{}, fmt.Errorf("decoding hex tag %q: %w", tagStr, err)
}
// Parse remaining options (no class allowed in hex format)
opts := extractOptions(remainingParts, 0)
return tagInfo, opts, nil
}
// parseExplicitTag parses the explicit decimal format with required class specification
func parseExplicitTag(parts []string) (TagInfo, tagOptions, error) {
if len(parts) < 1 {
return TagInfo{}, tagOptions{}, fmt.Errorf("missing tag number")
}
// Parse tag number
tagNum, err := parseTagNumber(parts[0])
if err != nil {
return TagInfo{}, tagOptions{}, err
}
// For explicit format, require class specification for non-universal tags
class, optionStart := parseTagClass(parts)
// Validate that non-universal classes are explicitly specified
if class != Universal && len(parts) < 2 {
return TagInfo{}, tagOptions{}, fmt.Errorf("explicit class required for non-universal tags (use hex format for automatic inference)")
}
opts := extractOptions(parts, optionStart)
// Explicit format defaults to primitive (no construction info available)
return TagInfo{
Class: class,
Constructed: false,
Number: tagNum,
}, opts, nil
}
// parseTagNumber extracts and validates the tag number from the first part
func parseTagNumber(tagStr string) (uint16, error) {
tagStr = strings.TrimSpace(tagStr)
tagNum, err := strconv.ParseUint(tagStr, 10, 16)
if err != nil {
return 0, fmt.Errorf("invalid tag number %q: %w", tagStr, err)
}
err = validateTagNumber(uint16(tagNum))
if err != nil {
return 0, err
}
return uint16(tagNum), nil
}
// parseTagClass determines the class from the tag parts and returns class and option start index
func parseTagClass(parts []string) (Class, int) {
if len(parts) <= 1 {
return Universal, 1
}
classStr := strings.TrimSpace(strings.ToLower(parts[1]))
switch classStr {
case "application":
return Application, 2
case "context":
return ContextSpecific, 2
case "private":
return Private, 2
case "universal":
return Universal, 2
default:
return Universal, 1
}
}
// extractOptions gets the remaining options from the specified start index
func extractOptions(parts []string, optionStart int) tagOptions {
if len(parts) <= optionStart {
return tagOptions{}
}
return tagOptions{options: parts[optionStart:]}
}
// validateTagNumber ensures the tag number is within the allowed range.
func validateTagNumber(n uint16) error {
if n > MaxTagNumber {
return fmt.Errorf("tag number %d exceeds maximum %d", n, MaxTagNumber)
}
return nil
}
// cachedTypeFields returns cached struct field information, computing it if necessary.
func cachedTypeFields(t reflect.Type) structFields {
fieldCache.RLock()
fields, exists := fieldCache.m[t]
fieldCache.RUnlock()
if exists {
return fields
}
return computeAndCacheFields(t)
}
// computeAndCacheFields computes field information and stores it in cache
func computeAndCacheFields(t reflect.Type) structFields {
fields := analyzeStructType(t)
fieldCache.Lock()
fieldCache.m[t] = fields
fieldCache.Unlock()
return fields
}
// analyzeStructType analyzes a struct type and returns field mapping information.
func analyzeStructType(t reflect.Type) structFields {
var fields []structField
tagToField := make(map[tagKey]int)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
if shouldSkipField(field) {
continue
}
sf, err := createStructField(field)
if err != nil {
continue
}
fieldIndex := len(fields)
fields = append(fields, sf)
tagToField[sf.tagInfo.key()] = fieldIndex
}
return structFields{
fields: fields,
tagToField: tagToField,
}
}
// shouldSkipField determines if a struct field should be skipped during analysis
func shouldSkipField(field reflect.StructField) bool {
// Skip unexported fields
if field.PkgPath != "" {
return true
}
tag := field.Tag.Get(bertlvTagKey)
// Skip explicitly marked fields or fields without tags
return tag == tagSkipMarker || tag == ""
}
// createStructField creates a structField from a reflect.StructField
func createStructField(field reflect.StructField) (structField, error) {
tag := field.Tag.Get(bertlvTagKey)
tagInfo, opts, err := parseGoTag(tag)
if err != nil {
return structField{}, fmt.Errorf("parsing tag for field %s: %w", field.Name, err)
}
var typ reflect.Type
if field.Type.Kind() == reflect.Slice && field.Type.Elem().Kind() != reflect.Uint8 {
typ = field.Type.Elem()
}
return structField{
name: field.Name,
tagInfo: tagInfo,
index: field.Index,
typ: typ,
omitEmpty: opts.contains("omitempty"),
required: opts.contains("required"),
}, nil
}
// clearCache clears the field cache
func clearCache() {
fieldCache.Lock()
fieldCache.m = make(map[reflect.Type]structFields)
fieldCache.Unlock()
}
// getCacheSize returns the current cache size
func getCacheSize() int {
fieldCache.RLock()
size := len(fieldCache.m)
fieldCache.RUnlock()
return size
}