Debian Codegraph @

syntax/decode.go

raw symbols SCIP
1 package syntax
2
3 import (
4 "bytes"
5 "fmt"
6 "reflect"
7 "runtime"
8 )
9
10 func Unmarshal(data []byte, v interface{}) (int, error) {
11 // Check for well-formedness.
12 // Avoids filling out half a data structure
13 // before discovering a JSON syntax error.
14 d := decodeState{}
15 d.Write(data)
16 return d.unmarshal(v)
17 }
18
19 // Unmarshaler is the interface implemented by types that can
20 // unmarshal a TLS description of themselves. Note that unlike the
21 // JSON unmarshaler interface, it is not known a priori how much of
22 // the input data will be consumed. So the Unmarshaler must state
23 // how much of the input data it consumed.
24 type Unmarshaler interface {
25 UnmarshalTLS([]byte) (int, error)
26 }
27
28 type decodeState struct {
29 bytes.Buffer
30 }
31
32 func (d *decodeState) unmarshal(v interface{}) (read int, err error) {
33 defer func() {
34 if r := recover(); r != nil {
35 if _, ok := r.(runtime.Error); ok {
36 panic(r)
37 }
38 if s, ok := r.(string); ok {
39 panic(s)
40 }
41 err = r.(error)
42 }
43 }()
44
45 rv := reflect.ValueOf(v)
46 if rv.Kind() != reflect.Ptr || rv.IsNil() {
47 return 0, fmt.Errorf("Invalid unmarshal target (non-pointer or nil)")
48 }
49
50 read = d.value(rv)
51 return read, nil
52 }
53
54 func (e *decodeState) value(v reflect.Value) int {
55 return valueDecoder(v)(e, v, fieldOptions{})
56 }
57
58 type decoderFunc func(e *decodeState, v reflect.Value, opts fieldOptions) int
59
60 func valueDecoder(v reflect.Value) decoderFunc {
61 return typeDecoder(v.Type().Elem())
62 }
63
64 func typeDecoder(t reflect.Type) decoderFunc {
65 // Note: Omits the caching / wait-group things that encoding/json uses
66 return newTypeDecoder(t)
67 }
68
69 var (
70 unmarshalerType = reflect.TypeOf(new(Unmarshaler)).Elem()
71 )
72
73 func newTypeDecoder(t reflect.Type) decoderFunc {
74 var dec decoderFunc
75 if t.Kind() != reflect.Ptr && reflect.PtrTo(t).Implements(unmarshalerType) {
76 dec = unmarshalerDecoder
77 } else {
78 switch t.Kind() {
79 case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
80 dec = uintDecoder
81 case reflect.Array:
82 dec = newArrayDecoder(t)
83 case reflect.Slice:
84 dec = newSliceDecoder(t)
85 case reflect.Map:
86 dec = newMapDecoder(t)
87 case reflect.Struct:
88 dec = newStructDecoder(t)
89 case reflect.Ptr:
90 dec = newPointerDecoder(t)
91 default:
92 panic(fmt.Errorf("Unsupported type (%s)", t))
93 }
94 }
95
96 if reflect.PtrTo(t).Implements(validatorType) {
97 dec = newValidatorDecoder(dec)
98 }
99
100 return dec
101 }
102
103 ///// Specific decoders below
104
105 func omitDecoder(d *decodeState, v reflect.Value, opts fieldOptions) int {
106 return 0
107 }
108
109 //////////
110
111 func unmarshalerDecoder(d *decodeState, v reflect.Value, opts fieldOptions) int {
112 um, ok := v.Interface().(Unmarshaler)
113 if !ok {
114 panic(fmt.Errorf("Non-Unmarshaler passed to unmarshalerEncoder"))
115 }
116
117 read, err := um.UnmarshalTLS(d.Bytes())
118 if err != nil {
119 panic(err)
120 }
121
122 if read > d.Len() {
123 panic(fmt.Errorf("Invalid return value from UnmarshalTLS"))
124 }
125
126 d.Next(read)
127 return read
128 }
129
130 //////////
131
132 func newValidatorDecoder(raw decoderFunc) decoderFunc {
133 return func(d *decodeState, v reflect.Value, opts fieldOptions) int {
134 read := raw(d, v, opts)
135
136 val, ok := v.Interface().(Validator)
137 if !ok {
138 panic(fmt.Errorf("Non-Validator passed to validatorDecoder"))
139 }
140
141 if err := val.ValidForTLS(); err != nil {
142 panic(fmt.Errorf("Decoded invalid TLS value: %v", err))
143 }
144
145 return read
146 }
147 }
148
149 //////////
150
151 func uintDecoder(d *decodeState, v reflect.Value, opts fieldOptions) int {
152 if opts.varint {
153 return varintDecoder(d, v, opts)
154 }
155
156 uintLen := int(v.Elem().Type().Size())
157 buf := d.Next(uintLen)
158 if len(buf) != uintLen {
159 panic(fmt.Errorf("Insufficient data to read uint"))
160 }
161
162 return setUintFromBuffer(v, buf)
163 }
164
165 func varintDecoder(d *decodeState, v reflect.Value, opts fieldOptions) int {
166 l, val := readVarint(d)
167
168 uintLen := int(v.Elem().Type().Size())
169 if uintLen < l {
170 panic(fmt.Errorf("Uint too small to fit varint: %d < %d", uintLen, l))
171 }
172
173 v.Elem().SetUint(val)
174
175 return l
176 }
177
178 func readVarint(d *decodeState) (int, uint64) {
179 // Read the first octet and decide the size of the presented varint
180 first := d.Next(1)
181 if len(first) != 1 {
182 panic(fmt.Errorf("Insufficient data to read varint length"))
183 }
184
185 twoBits := uint(first[0] >> 6)
186 varintLen := 1 << twoBits
187
188 rest := d.Next(varintLen - 1)
189 if len(rest) != varintLen-1 {
190 panic(fmt.Errorf("Insufficient data to read varint"))
191 }
192
193 buf := append(first, rest...)
194 buf[0] &= 0x3f
195
196 return len(buf), decodeUintFromBuffer(buf)
197 }
198
199 func decodeUintFromBuffer(buf []byte) uint64 {
200 val := uint64(0)
201 for _, b := range buf {
202 val = (val << 8) + uint64(b)
203 }
204
205 return val
206 }
207
208 func setUintFromBuffer(v reflect.Value, buf []byte) int {
209 v.Elem().SetUint(decodeUintFromBuffer(buf))
210 return len(buf)
211 }
212
213 //////////
214
215 type arrayDecoder struct {
216 elemDec decoderFunc
217 }
218
219 func (ad *arrayDecoder) decode(d *decodeState, v reflect.Value, opts fieldOptions) int {
220 n := v.Elem().Type().Len()
221 read := 0
222 for i := 0; i < n; i += 1 {
223 read += ad.elemDec(d, v.Elem().Index(i).Addr(), opts)
224 }
225 return read
226 }
227
228 func newArrayDecoder(t reflect.Type) decoderFunc {
229 dec := &arrayDecoder{typeDecoder(t.Elem())}
230 return dec.decode
231 }
232
233 //////////
234
235 func decodeLength(d *decodeState, opts fieldOptions) (int, int) {
236 read := 0
237 length := 0
238 switch {
239 case opts.omitHeader:
240 read = 0
241 length = d.Len()
242
243 case opts.varintHeader:
244 var length64 uint64
245 read, length64 = readVarint(d)
246 length = int(length64)
247
248 case opts.headerSize > 0:
249 lengthBytes := d.Next(int(opts.headerSize))
250 if len(lengthBytes) != int(opts.headerSize) {
251 panic(fmt.Errorf("Not enough data to read header"))
252 }
253 read = len(lengthBytes)
254 length = int(decodeUintFromBuffer(lengthBytes))
255
256 default:
257 panic(fmt.Errorf("Cannot decode a slice without a header length"))
258 }
259
260 // Check that the length is OK
261 if opts.maxSize > 0 && length > opts.maxSize {
262 panic(fmt.Errorf("Length of vector exceeds declared max"))
263 }
264 if length < opts.minSize {
265 panic(fmt.Errorf("Length of vector below declared min"))
266 }
267
268 return read, length
269 }
270
271 //////////
272
273 type sliceDecoder struct {
274 elementType reflect.Type
275 elementDec decoderFunc
276 }
277
278 func (sd *sliceDecoder) decode(d *decodeState, v reflect.Value, opts fieldOptions) int {
279 // Determine the length of the vector
280 read, length := decodeLength(d, opts)
281
282 // Decode elements
283 elemData := d.Next(length)
284 if len(elemData) != length {
285 panic(fmt.Errorf("Not enough data to read elements"))
286 }
287
288 elemBuf := &decodeState{}
289 elemBuf.Write(elemData)
290 elems := []reflect.Value{}
291 for elemBuf.Len() > 0 {
292 elem := reflect.New(sd.elementType)
293 read += sd.elementDec(elemBuf, elem, opts)
294 elems = append(elems, elem)
295 }
296
297 v.Elem().Set(reflect.MakeSlice(v.Elem().Type(), len(elems), len(elems)))
298 for i := 0; i < len(elems); i += 1 {
299 v.Elem().Index(i).Set(elems[i].Elem())
300 }
301 return read
302 }
303
304 func newSliceDecoder(t reflect.Type) decoderFunc {
305 dec := &sliceDecoder{
306 elementType: t.Elem(),
307 elementDec: typeDecoder(t.Elem()),
308 }
309 return dec.decode
310 }
311
312 //////////
313
314 type mapDecoder struct {
315 keyType reflect.Type
316 valType reflect.Type
317 keyDec decoderFunc
318 valDec decoderFunc
319 }
320
321 func (md mapDecoder) decode(d *decodeState, v reflect.Value, opts fieldOptions) int {
322 // Determine the length of the data
323 read, length := decodeLength(d, opts)
324
325 // Decode key/value pairs
326 elemData := d.Next(length)
327 if len(elemData) != length {
328 panic(fmt.Errorf("Not enough data to read elements"))
329 }
330
331 mapType := reflect.MapOf(md.keyType, md.valType)
332 v.Elem().Set(reflect.MakeMap(mapType))
333
334 nullOpts := fieldOptions{}
335 elemBuf := &decodeState{}
336 elemBuf.Write(elemData)
337 for elemBuf.Len() > 0 {
338 key := reflect.New(md.keyType)
339 read += md.keyDec(elemBuf, key, nullOpts)
340
341 val := reflect.New(md.valType)
342 read += md.valDec(elemBuf, val, nullOpts)
343
344 v.Elem().SetMapIndex(key.Elem(), val.Elem())
345 }
346
347 return read
348 }
349
350 func newMapDecoder(t reflect.Type) decoderFunc {
351 md := mapDecoder{
352 keyType: t.Key(),
353 valType: t.Elem(),
354 keyDec: typeDecoder(t.Key()),
355 valDec: typeDecoder(t.Elem()),
356 }
357
358 return md.decode
359 }
360
361 //////////
362
363 type structDecoder struct {
364 fieldOpts []fieldOptions
365 fieldDecs []decoderFunc
366 }
367
368 func (sd *structDecoder) decode(d *decodeState, v reflect.Value, opts fieldOptions) int {
369 read := 0
370 for i := range sd.fieldDecs {
371 read += sd.fieldDecs[i](d, v.Elem().Field(i).Addr(), sd.fieldOpts[i])
372 }
373 return read
374 }
375
376 func newStructDecoder(t reflect.Type) decoderFunc {
377 n := t.NumField()
378 sd := structDecoder{
379 fieldOpts: make([]fieldOptions, n),
380 fieldDecs: make([]decoderFunc, n),
381 }
382
383 for i := 0; i < n; i += 1 {
384 f := t.Field(i)
385
386 tag := f.Tag.Get("tls")
387 opts := parseTag(tag)
388
389 if !opts.ValidForType(f.Type) {
390 panic(fmt.Errorf("Tags invalid for field type"))
391 }
392
393 sd.fieldOpts[i] = opts
394 if sd.fieldOpts[i].omit {
395 sd.fieldDecs[i] = omitDecoder
396 } else {
397 sd.fieldDecs[i] = typeDecoder(f.Type)
398 }
399 }
400
401 return sd.decode
402 }
403
404 //////////
405
406 type pointerDecoder struct {
407 base decoderFunc
408 }
409
410 func (pd *pointerDecoder) decode(d *decodeState, v reflect.Value, opts fieldOptions) int {
411 readBase := 0
412 if opts.optional {
413 readBase = 1
414 flag := d.Next(1)
415 switch flag[0] {
416 case optionalFlagAbsent:
417 indir := v.Elem()
418 indir.Set(reflect.Zero(indir.Type()))
419 return 1
420
421 case optionalFlagPresent:
422 // No action; continue as normal
423
424 default:
425 panic(fmt.Errorf("Invalid flag byte for optional: [%x]", flag))
426 }
427 }
428
429 v.Elem().Set(reflect.New(v.Elem().Type().Elem()))
430 return readBase + pd.base(d, v.Elem(), opts)
431 }
432
433 func newPointerDecoder(t reflect.Type) decoderFunc {
434 baseDecoder := typeDecoder(t.Elem())
435 pd := pointerDecoder{base: baseDecoder}
436 return pd.decode
437 }