-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdeserialize.go
1232 lines (921 loc) · 28.5 KB
/
deserialize.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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package jserial
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/hex"
"io"
"strings"
"time"
"github.com/pkg/errors"
)
// ParseSerializedObject parses a serialized java object.
func ParseSerializedObject(buf []byte) (content []interface{}, err error) {
option := SetMaxDataBlockSize(len(buf))
sop := NewSerializedObjectParser(bytes.NewReader(buf), option)
return sop.ParseSerializedObject()
}
// ParseSerializedObject parses a serialized java object from stream.
func (sop *SerializedObjectParser) ParseSerializedObject() (content []interface{}, err error) {
if err = sop.magic(); err != nil {
return
}
if err = sop.version(); err != nil {
return
}
for !sop.end() {
var nxt interface{}
if nxt, err = sop.content(nil); err != nil {
if errors.Cause(err).Error() == io.EOF.Error() {
err = errors.New("premature end of input")
}
return
}
content = append(content, nxt)
}
return
}
// ParseSerializedObjectMinimal parses a serialized java object and returns the minimal object representation
// (i.e. without all the class info, etc...).
func ParseSerializedObjectMinimal(buf []byte) (content []interface{}, err error) {
if content, err = ParseSerializedObject(buf); err == nil {
content = jsonFriendlyArray(content)
}
return
}
// ParseSerializedObjectMinimal parses a serialized java object from stream
// and returns the minimal object representation (i.e. without all the class info, etc...).
func (sop *SerializedObjectParser) ParseSerializedObjectMinimal() (content []interface{}, err error) {
if content, err = sop.ParseSerializedObject(); err == nil {
content = jsonFriendlyArray(content)
}
return
}
// jsonFriendlyObject recursively filters / formats object fields to be as simple / JSON-like as possible.
func jsonFriendlyObject(obj interface{}) (jsonObj interface{}) {
if m, isMap := obj.(map[string]interface{}); isMap {
jsonMap := jsonFriendlyMap(m)
jsonObj = jsonMap
// if we have a single "value" key or a post-processed value just promote the value
if mVal, mValExists := jsonMap["value"]; mValExists {
_, mRawExists := jsonMap["@"]
if mRawExists || len(jsonMap) == 1 {
jsonObj = mVal
}
}
return
}
if arr, isArray := obj.([]interface{}); isArray {
jsonObj = jsonFriendlyArray(arr)
return
}
// default for raw / primitive fields
return obj
}
// jsonFriendlyArray recursively filters / formats a deserialized array.
func jsonFriendlyArray(arrayObj []interface{}) (jsonArray []interface{}) {
jsonArray = make([]interface{}, len(arrayObj))
for idx, arrayMember := range arrayObj {
jsonArray[idx] = jsonFriendlyObject(arrayMember)
}
return
}
// jsonFriendlyMap recursively filters / formats a deserialized map.
func jsonFriendlyMap(mapObj map[string]interface{}) (jsonMap map[string]interface{}) {
jsonMap = make(map[string]interface{})
for k, v := range mapObj {
// filter out `extends` keyword which just contains internal inheritance hierarchy
if k == "extends" {
continue
}
// filter out internal class definitions
if _, isClazz := v.(*clazz); !isClazz {
jsonMap[k] = jsonFriendlyObject(v)
}
}
return
}
func init() {
knownParsers = map[string]parser{
"Enum": parseEnum,
"BlockDataLong": parseBlockDataLong,
"BlockData": parseBlockData,
"EndBlockData": parseEndBlockData,
"ClassDesc": parseClassDesc,
"Class": parseClass,
"Array": parseArray,
"LongString": parseLongString,
"String": parseString,
"Null": parseNull,
"Object": parseObject,
"Reference": parseReference,
}
}
// typeNames includes all known type names.
var typeNames = []string{
"Null",
"Reference",
"ClassDesc",
"Object",
"String",
"Array",
"Class",
"BlockData",
"EndBlockData",
"Reset",
"BlockDataLong",
"Exception",
"LongString",
"ProxyClassDesc",
"Enum",
}
// typeNameMax is used to ensure an encountered type is known.
var typeNameMax = uint8(len(typeNames) - 1)
// allowedClazzNames includes all allowed names when parsing a class descriptor.
var allowedClazzNames = map[string]bool{
"ClassDesc": true,
"ProxyClassDesc": true,
"Null": true,
"Reference": true,
}
// parser is a func capable of reading a single serialized type.
type parser func(sop *SerializedObjectParser) (interface{}, error)
// knownParsers maps serialized names to corresponding parser implementations.
var knownParsers map[string]parser
// PostProc handlers are used to format deserialized objects for easier consumption.
type PostProc func(map[string]interface{}, []interface{}) (map[string]interface{}, error)
// KnownPostProcs maps serialized object signatures to PostProc implementations.
var KnownPostProcs = map[string]PostProc{
"java.util.ArrayList@7881d21d99c7619d": listPostProc,
"java.util.ArrayDeque@207cda2e240da08b": listPostProc,
"java.util.Hashtable@13bb0f25214ae4b8": mapPostProc,
"java.util.HashMap@0507dac1c31660d1": mapPostProc,
"java.util.EnumMap@065d7df7be907ca1": enumMapPostProc,
"java.util.HashSet@ba44859596b8b734": hashSetPostProc,
"java.util.Date@686a81014b597419": datePostProc,
}
// primitiveHandler are used to read primitive values.
type primitiveHandler func(sop *SerializedObjectParser) (interface{}, error)
// primitiveHandlers maps serialized primitive identifiers to a corresponding primitiveHandler.
var primitiveHandlers = map[string]primitiveHandler{
"B": func(sop *SerializedObjectParser) (b interface{}, err error) {
if b, err = sop.readInt8(); err != nil {
err = errors.Wrap(err, "error reading byte primitive")
}
return
},
"C": func(sop *SerializedObjectParser) (char interface{}, err error) {
var charCode uint16
if charCode, err = sop.readUInt16(); err != nil {
err = errors.Wrap(err, "error reading char primitive")
} else {
char = string(rune(charCode))
}
return
},
"D": func(sop *SerializedObjectParser) (double interface{}, err error) {
if double, err = sop.readFloat64(); err != nil {
err = errors.Wrap(err, "error reading double primitive")
}
return
},
"F": func(sop *SerializedObjectParser) (f32 interface{}, err error) {
if f32, err = sop.readFloat32(); err != nil {
err = errors.Wrap(err, "error reading float primitive")
}
return
},
"I": func(sop *SerializedObjectParser) (i32 interface{}, err error) {
if i32, err = sop.readInt32(); err != nil {
err = errors.Wrap(err, "error reading int primitive")
}
return
},
"J": func(sop *SerializedObjectParser) (long interface{}, err error) {
if long, err = sop.readInt64(); err != nil {
err = errors.Wrap(err, "error reading long primitive")
}
return
},
"S": func(sop *SerializedObjectParser) (short interface{}, err error) {
if short, err = sop.readInt16(); err != nil {
err = errors.Wrap(err, "error reading short primitive")
}
return
},
"Z": func(sop *SerializedObjectParser) (b interface{}, err error) {
var x int8
if x, err = sop.readInt8(); err != nil {
err = errors.Wrap(err, "error reading boolean primitive")
} else {
b = x != 0
}
return
},
"L": func(sop *SerializedObjectParser) (obj interface{}, err error) {
if obj, err = sop.content(nil); err != nil {
err = errors.Wrap(err, "error reading object primitive")
}
return
},
"[": func(sop *SerializedObjectParser) (arr interface{}, err error) {
if arr, err = sop.content(nil); err != nil {
err = errors.Wrap(err, "error reading array primitive")
}
return
},
}
// SerializedObjectParser reads serialized java objects
// see: https://docs.oracle.com/javase/8/docs/platform/serialization/spec/protocol.html
type SerializedObjectParser struct {
buf bytes.Buffer
rd *bufio.Reader
handles []interface{}
maxDataBlockSize int
}
const bufferSize = 1024
type Option func(sop *SerializedObjectParser)
// SetMaxDataBlockSize set the maximum size of the parsed data block,
// by default it is equal to the value of the buffer size bufio.Reader or size of bytes.Reader.
func SetMaxDataBlockSize(maxSize int) Option {
return func(sop *SerializedObjectParser) {
sop.maxDataBlockSize = maxSize
}
}
// NewSerializedObjectParser reads serialized java objects from stream.
func NewSerializedObjectParser(rd io.Reader, options ...Option) *SerializedObjectParser {
buf := bufio.NewReaderSize(rd, bufferSize)
sop := &SerializedObjectParser{
rd: buf,
maxDataBlockSize: buf.Size(),
}
for _, option := range options {
option(sop)
}
return sop
}
// newHandle adds a parsed object to the existing indexed handles which can be used later to lookup references to
// existing objects.
func (sop *SerializedObjectParser) newHandle(obj interface{}) interface{} {
sop.handles = append(sop.handles, obj)
return obj
}
// content reads the next object in the stream and parses it.
func (sop *SerializedObjectParser) content(allowedNames map[string]bool) (content interface{}, err error) {
var tc uint8
if tc, err = sop.readUInt8(); err != nil {
return
}
const typeMask = 0x70
tc -= typeMask
if tc > typeNameMax {
// prevents reading unknown ("foreign") byte from the stream
sop.rd.UnreadByte() //nolint:errcheck
err = errors.Errorf("unknown type %#x", tc+typeMask)
return
}
name := typeNames[tc]
if allowedNames != nil && !allowedNames[name] {
err = errors.Errorf("%s not allowed here", name)
return
}
parse, exists := knownParsers[name]
if !exists {
err = errors.Errorf("parsing %s is currently not supported", name)
return
}
return parse(sop)
}
// end check has next byte in stream.
func (sop *SerializedObjectParser) end() bool {
if sop.rd.Buffered() == 0 {
_, eof := sop.rd.Peek(1)
return eof != nil
}
return false
}
// readString reads a string of length cnt bytes.
func (sop *SerializedObjectParser) readString(cnt int, asHex bool) (s string, err error) {
sop.buf.Reset()
// Prevented to allocate an extremely large block of memory.
if cnt > sop.maxDataBlockSize {
err = errors.Errorf("block data exceeds size of reader buffer. " +
"To increase the size, use the method SetMaxDataBlockSize or use bufio.Reader with a larger buffer size")
return
}
if _, err = io.CopyN(&sop.buf, sop.rd, int64(cnt)); err != nil {
err = errors.Wrap(err, "error reading string")
return
}
if asHex {
s = hex.EncodeToString(sop.buf.Bytes())
} else {
s = sop.buf.String()
}
return
}
func (sop *SerializedObjectParser) readUInt8() (x uint8, err error) {
if err = binary.Read(sop.rd, binary.BigEndian, &x); err != nil {
err = errors.Wrap(err, "error reading uint8")
}
return
}
func (sop *SerializedObjectParser) readInt8() (x int8, err error) {
if err = binary.Read(sop.rd, binary.BigEndian, &x); err != nil {
err = errors.Wrap(err, "error reading int8")
}
return
}
func (sop *SerializedObjectParser) readUInt16() (x uint16, err error) {
if err = binary.Read(sop.rd, binary.BigEndian, &x); err != nil {
err = errors.Wrap(err, "error reading uint16")
}
return
}
func (sop *SerializedObjectParser) readInt16() (x int16, err error) {
if err = binary.Read(sop.rd, binary.BigEndian, &x); err != nil {
err = errors.Wrap(err, "error reading int16")
}
return
}
func (sop *SerializedObjectParser) readUInt32() (x uint32, err error) {
if err = binary.Read(sop.rd, binary.BigEndian, &x); err != nil {
err = errors.Wrap(err, "error reading uint32")
}
return
}
func (sop *SerializedObjectParser) readInt32() (x int32, err error) {
if err = binary.Read(sop.rd, binary.BigEndian, &x); err != nil {
err = errors.Wrap(err, "error reading int32")
}
return
}
func (sop *SerializedObjectParser) readFloat32() (x float32, err error) {
if err = binary.Read(sop.rd, binary.BigEndian, &x); err != nil {
err = errors.Wrap(err, "error reading float32")
}
return
}
func (sop *SerializedObjectParser) readInt64() (x int64, err error) {
if err = binary.Read(sop.rd, binary.BigEndian, &x); err != nil {
err = errors.Wrap(err, "error reading int64")
}
return
}
func (sop *SerializedObjectParser) readFloat64() (x float64, err error) {
if err = binary.Read(sop.rd, binary.BigEndian, &x); err != nil {
err = errors.Wrap(err, "error reading float64")
}
return
}
// utf reads a variable length string.
func (sop *SerializedObjectParser) utf() (s string, err error) {
var offset uint16
if offset, err = sop.readUInt16(); err != nil {
err = errors.Wrap(err, "error reading utf: unable to read segment length")
return
}
if s, err = sop.readString(int(offset), false); err != nil {
err = errors.Wrap(err, "error reading utf: unable to read segment")
}
return
}
// utf reads a large (up to 2^32 bytes) variable length string.
func (sop *SerializedObjectParser) utfLong() (s string, err error) {
var offset uint32
if offset, err = sop.readUInt32(); err != nil {
err = errors.Wrap(err, "error reading utf: unable to read first segment length")
return
}
if offset != 0 {
err = errors.New("unable to read string larger than 2^32 bytes")
return
}
if offset, err = sop.readUInt32(); err != nil {
err = errors.Wrap(err, "error reading utf long: unable to read second segment length")
return
}
if s, err = sop.readString(int(offset), false); err != nil {
err = errors.Wrap(err, "error reading utf long: unable to read segment")
}
return
}
// magic checks for the presence of the STREAM_MAGIC value.
func (sop *SerializedObjectParser) magic() error {
magicVal, err := sop.readUInt16()
if err == nil && magicVal != 0xaced {
return errors.New("magic value STREAM_MAGIC not found")
}
return err
}
// version checks to be sure the serialized object is using a supported protocol version.
func (sop *SerializedObjectParser) version() error {
ver, err := sop.readUInt16()
if err != nil {
return err
}
const protocolVersion = 5
if ver != protocolVersion {
return errors.Errorf("protocol version not recognized: wanted 5 got %d", ver)
}
return nil
}
// field contains info about a single class member.
type field struct {
className string
typeName string
name string
}
// fieldDesc reads a single field descriptor.
func (sop *SerializedObjectParser) fieldDesc() (f *field, err error) {
var typeDec uint8
if typeDec, err = sop.readUInt8(); err != nil {
err = errors.Wrap(err, "error reading field type")
return
}
var name string
if name, err = sop.utf(); err != nil {
err = errors.Wrap(err, "error reading field name")
return
}
typeName := string(typeDec)
f = &field{
typeName: typeName,
name: name,
}
if strings.Contains("[L", typeName) { //nolint
var className interface{}
if className, err = sop.content(nil); err != nil {
err = errors.Wrap(err, "error reading field class name")
return
}
var isString bool
if f.className, isString = className.(string); !isString {
err = errors.New("unexpected field class name type")
}
}
return
}
// annotations reads all class annotations.
func (sop *SerializedObjectParser) annotations(allowedNames map[string]bool) (anns []interface{}, err error) {
for {
var ann interface{}
if ann, err = sop.content(allowedNames); err != nil {
err = errors.Wrap(err, "error reading class annotation")
return
}
if _, isEndBlock := ann.(endBlockT); isEndBlock {
break
}
anns = append(anns, ann)
}
return
}
// clazz contains java class info.
type clazz struct {
super *clazz
annotations []interface{}
fields []*field
serialVersionUID string
name string
flags uint8
isEnum bool
}
// classDesc reads a class descriptor.
func (sop *SerializedObjectParser) classDesc() (cls *clazz, err error) {
var x interface{}
if x, err = sop.content(allowedClazzNames); err != nil {
err = errors.Wrap(err, "error reading class description")
return
}
if x == nil {
return
}
var isClazz bool
if cls, isClazz = x.(*clazz); !isClazz {
err = errors.New("unexpected type returned while reading class description")
}
return
}
// parseClassDesc parses a class descriptor.
//nolint:funlen
func parseClassDesc(sop *SerializedObjectParser) (x interface{}, err error) {
cls := &clazz{}
if cls.name, err = sop.utf(); err != nil {
err = errors.Wrap(err, "error reading class name")
return
}
const minClassNameLength = 2
if len(cls.name) < minClassNameLength {
err = errors.Wrapf(err, "invalid class name: '%s'", cls.name)
return
}
const serialVersionUIDLength = 8
if cls.serialVersionUID, err = sop.readString(serialVersionUIDLength, true); err != nil {
err = errors.Wrap(err, "error reading class serialVersionUID")
return
}
sop.newHandle(cls)
if cls.flags, err = sop.readUInt8(); err != nil {
err = errors.Wrap(err, "error reading class flags")
return
}
cls.isEnum = (cls.flags & 0x10) != 0
var fieldCount uint16
if fieldCount, err = sop.readUInt16(); err != nil {
err = errors.Wrap(err, "error reading class field count")
return
}
for i := 0; i < int(fieldCount); i++ {
var f *field
if f, err = sop.fieldDesc(); err != nil {
err = errors.Wrap(err, "error reading class field")
return
}
cls.fields = append(cls.fields, f)
}
if cls.annotations, err = sop.annotations(nil); err != nil {
err = errors.Wrap(err, "error reading class annotations")
return
}
if cls.super, err = sop.classDesc(); err != nil {
err = errors.Wrap(err, "error reading class super")
return
}
x = cls
return
}
func parseClass(sop *SerializedObjectParser) (cd interface{}, err error) {
if cd, err = sop.classDesc(); err != nil {
err = errors.Wrap(err, "error parsing class")
return
}
cd = sop.newHandle(cd)
return
}
func parseReference(sop *SerializedObjectParser) (ref interface{}, err error) {
var refIdx int32
if refIdx, err = sop.readInt32(); err != nil {
err = errors.Wrap(err, "error reading reference index")
return
}
const refIDMask = 0x7e0000
i := int(refIdx - refIDMask)
if i > -1 && i < len(sop.handles) {
ref = sop.handles[i]
}
return
}
func parseArray(sop *SerializedObjectParser) (arr interface{}, err error) {
var cls *clazz
if cls, err = sop.classDesc(); err != nil {
err = errors.Wrap(err, "error parsing array class")
return
}
res := map[string]interface{}{
"class": cls,
}
sop.newHandle(res)
var size int32
if size, err = sop.readInt32(); err != nil {
err = errors.Wrap(err, "error reading array size")
return
}
res["length"] = size
if cls == nil {
return
}
primHandler, exists := primitiveHandlers[string(cls.name[1])]
if !exists {
err = errors.Errorf("unknown field type '%s'", string(cls.name[1]))
return
}
var array []interface{}
for i := 0; i < int(size); i++ {
var nxt interface{}
if nxt, err = primHandler(sop); err != nil {
err = errors.Wrap(err, "error reading primitive array member")
return
}
array = append(array, nxt)
}
arr = array
return
}
// newDeferredHandle reserves an object handle slot and returns a func which can set the slot value at a later time.
func (sop *SerializedObjectParser) newDeferredHandle() func(interface{}) interface{} {
idx := len(sop.handles)
sop.handles = append(sop.handles, nil)
return func(obj interface{}) interface{} {
sop.handles[idx] = obj
return obj
}
}
func parseEnum(sop *SerializedObjectParser) (enum interface{}, err error) {
var cls *clazz
if cls, err = sop.classDesc(); err != nil {
err = errors.Wrap(err, "error parsing enum class")
return
}
deferredHandle := sop.newDeferredHandle()
var enumConstant interface{}
if enumConstant, err = sop.content(nil); err != nil {
err = errors.Wrap(err, "error parsing enum constant")
return
}
res := map[string]interface{}{
"value": enumConstant,
"class": cls,
}
enum = deferredHandle(res)
return
}
func parseBlockData(sop *SerializedObjectParser) (bd interface{}, err error) {
var size uint8
if size, err = sop.readUInt8(); err != nil {
err = errors.Wrap(err, "error parsing block data size")
return
}
data := make([]byte, size)
if _, err = io.ReadFull(sop.rd, data); err == nil {
bd = data
}
return
}
func parseBlockDataLong(sop *SerializedObjectParser) (bdl interface{}, err error) {
var size uint32
if size, err = sop.readUInt32(); err != nil {
err = errors.Wrap(err, "error parsing block data long size")
return
}
// Prevented to allocate an extremely large block of memory.
if int(size) > sop.maxDataBlockSize {
err = errors.Errorf("block data exceeds size of reader buffer. " +
"To increase the size, use the method SetMaxDataBlockSize or use bufio.Reader with a larger buffer size")
return
}
data := make([]byte, size)
if _, err = io.ReadFull(sop.rd, data); err == nil {
bdl = data
return
}
return
}
func parseString(sop *SerializedObjectParser) (str interface{}, err error) {
if str, err = sop.utf(); err != nil {
err = errors.Wrap(err, "error parsing string")
} else {
str = sop.newHandle(str)
}
return
}
func parseLongString(sop *SerializedObjectParser) (longStr interface{}, err error) {
if longStr, err = sop.utfLong(); err != nil {
err = errors.Wrap(err, "error parsing long string")
} else {
sop.newHandle(longStr)
}
return
}
func parseNull(_ *SerializedObjectParser) (interface{}, error) {
return nil, nil
}
type endBlockT string
const endBlock endBlockT = "endBlock"
func parseEndBlockData(_ *SerializedObjectParser) (interface{}, error) {
return endBlock, nil
}
// values reads primitive field values.
func (sop *SerializedObjectParser) values(cls *clazz) (vals map[string]interface{}, err error) {
var exists bool
var handler primitiveHandler
vals = make(map[string]interface{})
for _, field := range cls.fields {
if field == nil {
continue
}
if handler, exists = primitiveHandlers[field.typeName]; !exists {
err = errors.Errorf("unknown field type '%s'", field.typeName)
return
}
if vals[field.name], err = handler(sop); err != nil {
err = errors.Wrap(err, "error reading primitive field value")
return
}
}
return
}
// annotationsAsMap reads values (when isBlock is false) and merges annotations then calls any relevant post processor.
func (sop *SerializedObjectParser) annotationsAsMap(cls *clazz, isBlock bool) (data map[string]interface{}, err error) {
if isBlock {
data = make(map[string]interface{})
} else if data, err = sop.values(cls); err != nil {
err = errors.Wrap(err, "error reading class data field values")
return
}
var anns []interface{}
if anns, err = sop.annotations(nil); err != nil {
err = errors.Wrap(err, "error reading annotations")
return
}
data["@"] = anns
if !isBlock {
if postproc, exists := KnownPostProcs[cls.name+"@"+cls.serialVersionUID]; exists {
data, err = postproc(data, anns)
}
}
return
}
// classData reads a serialized class into a generic data structure.
func (sop *SerializedObjectParser) classData(cls *clazz) (data map[string]interface{}, err error) {
if cls == nil {
return nil, errors.New("invalid class definition: nil")
}
const (
ScSerializableWithoutWriteMethod = 0x02
ScSerializableWithWriteMethod = 0x03
ScExternalizeWithBlockData = 0x04
ScExternalizeWithoutBlockData = 0x0c
)
switch cls.flags & 0x0f {
case ScSerializableWithoutWriteMethod: // SC_SERIALIZABLE without SC_WRITE_METHOD
return sop.values(cls)
case ScSerializableWithWriteMethod: // SC_SERIALIZABLE with SC_WRITE_METHOD
return sop.annotationsAsMap(cls, false)
case ScExternalizeWithBlockData: // SC_EXTERNALIZABLE without SC_BLOCKDATA
return nil, errors.New("unable to parse version 1 external content")
case ScExternalizeWithoutBlockData: // SC_EXTERNALIZABLE with SC_BLOCKDATA