forked from kolo/xmlrpc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decoder.go
563 lines (486 loc) · 12.4 KB
/
decoder.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
package xmlrpc
import (
"bytes"
"encoding/xml"
"errors"
"fmt"
"io"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"golang.org/x/text/encoding/charmap"
)
const (
iso8601 = "20060102T15:04:05"
iso8601hyphen = "2006-01-02T15:04:05Z"
iso8601hyphenTZ = "2006-01-02T15:04:05-07:00"
iso8601Z = "20060102T15:04:05Z07:00"
iso8601Hyphen = "2006-01-02T15:04:05"
iso8601HyphenZ = "2006-01-02T15:04:05Z07:00"
)
var (
// CharsetReader is a function to generate reader which converts a non UTF-8
// charset into UTF-8.
CharsetReader func(string, io.Reader) (io.Reader, error)
timeLayouts = []string{iso8601, iso8601hyphen, iso8601hyphenTZ, iso8601Z, iso8601Hyphen, iso8601HyphenZ}
invalidXmlError = errors.New("invalid xml")
// This Regex exists to detect repsponses that contain an array. Which is required because the SoftLayer API
// will say it is returning an array, but actually return a struct if there is only one element.
topArrayRE = regexp.MustCompile(`^<\?xml version="1.0" encoding=".+"\?>\s*<params>\s*<param>\s*<value>\s*<array>`)
)
type TypeMismatchError string
func (e TypeMismatchError) Error() string { return string(e) }
type decoder struct {
*xml.Decoder
}
func unmarshal(data []byte, v interface{}) (err error) {
dec := &decoder{xml.NewDecoder(bytes.NewBuffer(data))}
if CharsetReader != nil {
dec.CharsetReader = CharsetReader
} else {
dec.CharsetReader = defaultCharsetReader
}
var tok xml.Token
for {
if tok, err = dec.Token(); err != nil {
return err
}
if t, ok := tok.(xml.StartElement); ok {
if t.Name.Local == "value" {
val := reflect.ValueOf(v)
if val.Kind() != reflect.Ptr {
return errors.New("non-pointer value passed to unmarshal")
}
val = val.Elem()
// Some APIs that normally return a collection, omit the []'s when
// the API returns a single value.
if val.Kind() == reflect.Slice && !topArrayRE.MatchString(string(data)) {
val.Set(reflect.MakeSlice(val.Type(), 1, 1))
val = val.Index(0)
}
if err = dec.decodeValue(val); err != nil {
return err
}
break
}
}
}
// read until end of document
err = dec.Skip()
if err != nil && err != io.EOF {
return err
}
return nil
}
func (dec *decoder) decodeValue(val reflect.Value) error {
var tok xml.Token
var err error
if val.Kind() == reflect.Ptr {
if val.IsNil() {
val.Set(reflect.New(val.Type().Elem()))
}
val = val.Elem()
}
var typeName string
for {
if tok, err = dec.Token(); err != nil {
return err
}
if t, ok := tok.(xml.EndElement); ok {
if t.Name.Local == "value" {
return nil
} else {
return invalidXmlError
}
}
if t, ok := tok.(xml.StartElement); ok {
typeName = t.Name.Local
break
}
// Treat value data without type identifier as string
if t, ok := tok.(xml.CharData); ok {
if value := strings.TrimSpace(string(t)); value != "" {
if err = checkType(val, reflect.String); err != nil {
return err
}
val.SetString(value)
return nil
}
}
}
switch typeName {
case "struct":
ismap := false
pmap := val
valType := val.Type()
if err = checkType(val, reflect.Struct); err != nil {
if checkType(val, reflect.Map) == nil {
if valType.Key().Kind() != reflect.String {
return fmt.Errorf("only maps with string key type can be unmarshalled")
}
ismap = true
} else if checkType(val, reflect.Interface) == nil && val.IsNil() {
var dummy map[string]interface{}
valType = reflect.TypeOf(dummy)
pmap = reflect.New(valType).Elem()
val.Set(pmap)
ismap = true
} else {
return err
}
}
var fields map[string]reflect.Value
if !ismap {
fields = make(map[string]reflect.Value)
buildStructFieldMap(&fields, val)
} else {
// Create initial empty map
pmap.Set(reflect.MakeMap(valType))
}
// Process struct members.
StructLoop:
for {
if tok, err = dec.Token(); err != nil {
return err
}
switch t := tok.(type) {
case xml.StartElement:
if t.Name.Local != "member" {
return invalidXmlError
}
tagName, fieldName, err := dec.readTag()
if err != nil {
return err
}
if tagName != "name" {
return invalidXmlError
}
var fv reflect.Value
ok := true
if !ismap {
fv, ok = fields[string(fieldName)]
} else {
fv = reflect.New(valType.Elem())
}
if ok {
for {
if tok, err = dec.Token(); err != nil {
return err
}
if t, ok := tok.(xml.StartElement); ok && t.Name.Local == "value" {
if err = dec.decodeValue(fv); err != nil {
return err
}
// </value>
if err = dec.Skip(); err != nil {
return err
}
break
}
}
}
// </member>
if err = dec.Skip(); err != nil {
return err
}
if ismap {
pmap.SetMapIndex(reflect.ValueOf(string(fieldName)), reflect.Indirect(fv))
val.Set(pmap)
}
case xml.EndElement:
break StructLoop
}
}
case "array":
slice := val
if checkType(val, reflect.Interface) == nil && val.IsNil() {
slice = reflect.ValueOf([]interface{}{})
} else if err = checkType(val, reflect.Slice); err != nil {
// Check to see if we have an unexpected array when we expect
// a struct. Adjust by expecting an array of the struct type
// and see if things still work.
// https://github.com/renier/xmlrpc/pull/2
if val.Kind() == reflect.Struct {
slice = reflect.New(reflect.SliceOf(reflect.TypeOf(val.Interface()))).Elem()
val = slice
} else {
return err
}
}
ArrayLoop:
for {
if tok, err = dec.Token(); err != nil {
return err
}
switch t := tok.(type) {
case xml.StartElement:
var index int
if t.Name.Local != "data" {
return invalidXmlError
}
DataLoop:
for {
if tok, err = dec.Token(); err != nil {
return err
}
switch tt := tok.(type) {
case xml.StartElement:
if tt.Name.Local != "value" {
return invalidXmlError
}
// Incase the incoming val is already defined.
if index < slice.Len() {
v := slice.Index(index)
if v.Kind() == reflect.Interface {
v = v.Elem()
}
if v.Kind() != reflect.Ptr {
return errors.New("error: cannot write to non-pointer array element")
}
if err = dec.decodeValue(v); err != nil {
return err
}
} else {
v := reflect.New(slice.Type().Elem())
if err = dec.decodeValue(v); err != nil {
return err
}
slice = reflect.Append(slice, v.Elem())
}
// </value>
if err = dec.Skip(); err != nil {
return err
}
index++
case xml.EndElement:
val.Set(slice)
break DataLoop
}
}
case xml.EndElement:
break ArrayLoop
}
}
default:
if tok, err = dec.Token(); err != nil {
return err
}
var data []byte
switch t := tok.(type) {
case xml.EndElement:
return nil
case xml.CharData:
data = []byte(t.Copy())
default:
return invalidXmlError
}
ParseValue:
switch typeName {
case "int", "i4", "i8":
if checkType(val, reflect.Interface) == nil && val.IsNil() {
i, err := strconv.ParseInt(string(data), 10, 64)
if err != nil {
return err
}
pi := reflect.New(reflect.TypeOf(i)).Elem()
pi.SetInt(i)
val.Set(pi)
} else if err = checkType(val, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64); err != nil {
return err
} else {
k := val.Kind()
isInt := k == reflect.Int || k == reflect.Int8 || k == reflect.Int16 || k == reflect.Int32 || k == reflect.Int64
if isInt {
i, err := strconv.ParseInt(string(data), 10, val.Type().Bits())
if err != nil {
return err
}
val.SetInt(i)
} else {
i, err := strconv.ParseUint(string(data), 10, val.Type().Bits())
if err != nil {
return err
}
val.SetUint(i)
}
}
case "string", "base64":
str := string(data)
if checkType(val, reflect.Interface) == nil && val.IsNil() {
pstr := reflect.New(reflect.TypeOf(str)).Elem()
pstr.SetString(str)
val.Set(pstr)
} else if err = checkType(val, reflect.String); err != nil {
valName := val.Type().Name()
if valName == "" {
valName = reflect.Indirect(val).Type().Name()
}
if valName == "Time" {
timeField := val.FieldByName(valName)
if timeField.IsValid() {
val = timeField
}
typeName = "dateTime.iso8601"
goto ParseValue
} else if strings.HasPrefix(strings.ToLower(valName), "float") {
typeName = "double"
goto ParseValue
}
return err
} else {
val.SetString(str)
}
case "dateTime.iso8601":
var t time.Time
var err error
for _, df := range timeLayouts {
t, err = time.Parse(df, string(data))
if err == nil {
break
}
}
if err != nil {
return err
}
if checkType(val, reflect.Interface) == nil && val.IsNil() {
ptime := reflect.New(reflect.TypeOf(t)).Elem()
ptime.Set(reflect.ValueOf(t))
val.Set(ptime)
} else if !reflect.TypeOf((time.Time)(t)).ConvertibleTo(val.Type()) {
return TypeMismatchError(
fmt.Sprintf(
"error: type mismatch error - can't decode %v (%s.%s) to time",
val.Kind(),
val.Type().PkgPath(),
val.Type().Name(),
),
)
} else {
val.Set(reflect.ValueOf(t).Convert(val.Type()))
}
case "boolean":
v, err := strconv.ParseBool(string(data))
if err != nil {
return err
}
if checkType(val, reflect.Interface) == nil && val.IsNil() {
pv := reflect.New(reflect.TypeOf(v)).Elem()
pv.SetBool(v)
val.Set(pv)
} else if err = checkType(val, reflect.Bool); err != nil {
return err
} else {
val.SetBool(v)
}
case "double":
if checkType(val, reflect.Interface) == nil && val.IsNil() {
i, err := strconv.ParseFloat(string(data), 64)
if err != nil {
return err
}
pdouble := reflect.New(reflect.TypeOf(i)).Elem()
pdouble.SetFloat(i)
val.Set(pdouble)
} else if err = checkType(val, reflect.Float32, reflect.Float64); err != nil {
return err
} else {
i, err := strconv.ParseFloat(string(data), val.Type().Bits())
if err != nil {
return err
}
val.SetFloat(i)
}
default:
return errors.New("unsupported type")
}
// </type>
if err = dec.Skip(); err != nil {
return err
}
}
return nil
}
func (dec *decoder) readTag() (string, []byte, error) {
var tok xml.Token
var err error
var name string
for {
if tok, err = dec.Token(); err != nil {
return "", nil, err
}
if t, ok := tok.(xml.StartElement); ok {
name = t.Name.Local
break
}
}
value, err := dec.readCharData()
if err != nil {
return "", nil, err
}
return name, value, dec.Skip()
}
func (dec *decoder) readCharData() ([]byte, error) {
var tok xml.Token
var err error
if tok, err = dec.Token(); err != nil {
return nil, err
}
if t, ok := tok.(xml.CharData); ok {
return []byte(t.Copy()), nil
} else {
return nil, invalidXmlError
}
}
func checkType(val reflect.Value, kinds ...reflect.Kind) error {
if len(kinds) == 0 {
return nil
}
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
match := false
for _, kind := range kinds {
if val.Kind() == kind {
match = true
break
}
}
if !match {
return TypeMismatchError(fmt.Sprintf("error: type mismatch - can't unmarshal %v to %v",
val.Kind(), kinds[0]))
}
return nil
}
func buildStructFieldMap(fieldMap *map[string]reflect.Value, val reflect.Value) {
valType := val.Type()
valFieldNum := valType.NumField()
for i := 0; i < valFieldNum; i++ {
field := valType.Field(i)
fieldVal := val.FieldByName(field.Name)
if field.Anonymous {
// Drill down into embedded structs
buildStructFieldMap(fieldMap, fieldVal)
continue
}
if fieldVal.CanSet() {
if fn := field.Tag.Get("xmlrpc"); fn != "" {
fn = strings.Split(fn, ",")[0]
(*fieldMap)[fn] = fieldVal
} else {
(*fieldMap)[field.Name] = fieldVal
}
}
}
}
// http://stackoverflow.com/a/34712322/3160958
// https://groups.google.com/forum/#!topic/golang-nuts/VudK_05B62k
func defaultCharsetReader(charset string, input io.Reader) (io.Reader, error) {
if charset == "iso-8859-1" || charset == "ISO-8859-1" {
return charmap.ISO8859_1.NewDecoder().Reader(input), nil
} else if strings.HasPrefix(charset, "utf") || strings.HasPrefix(charset, "UTF") {
return input, nil
}
return nil, fmt.Errorf("Unknown charset: %s", charset)
}