-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdecoder.go
More file actions
305 lines (267 loc) · 7.29 KB
/
Copy pathdecoder.go
File metadata and controls
305 lines (267 loc) · 7.29 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
// Copyright (C) 2021 Storj Labs, Inc.
// See LICENSE for copying information.
package picobuf
import (
"bytes"
"storj.io/picobuf/internal/protowire"
)
const (
fieldDecodingErrored = FieldNumber(-1)
fieldDecodingDone = FieldNumber(-2)
)
// Decoder implements decoding of protobuf messages.
type Decoder struct {
messageDecodeState
stack []messageDecodeState
init bool
aliasInput bool
allowInvalidUTF8 bool
maxRecursionDepth int
maxRepeatedElements int
repeatedElements int
err error
}
type messageDecodeState struct {
pendingField FieldNumber //nolint: structcheck
pendingWire protowire.Type //nolint: structcheck
buffer []byte
}
// NewDecoder returns a new Decoder.
func NewDecoder(data []byte) *Decoder {
dec := new(Decoder)
dec.buffer = data
return dec
}
// PendingField returns the next field number in the stream.
func (dec *Decoder) PendingField() FieldNumber { return dec.pendingField }
// Err returns error that occurred during decoding.
func (dec *Decoder) Err() error {
return dec.err
}
func (dec *Decoder) pushState(message []byte) {
// Nesting is bounded by the input for a self-referential message, so
// refuse to descend further rather than exhausting the stack. Still push,
// so that the caller's matching popState stays balanced.
limit := dec.maxRecursionDepth
if limit <= 0 {
limit = protowire.DefaultRecursionLimit
}
tooDeep := len(dec.stack) >= limit
if tooDeep {
message = nil
}
dec.stack = append(dec.stack, dec.messageDecodeState)
dec.messageDecodeState = messageDecodeState{
buffer: message,
}
dec.nextField(0)
if tooDeep {
dec.fail(0, "exceeded maximum recursion depth")
}
}
func (dec *Decoder) popState() {
if len(dec.stack) == 0 {
dec.fail(0, "stack mangled")
return
}
dec.messageDecodeState = dec.stack[len(dec.stack)-1]
dec.stack = dec.stack[:len(dec.stack)-1]
}
// RepeatedMessage decodes a message.
func (dec *Decoder) RepeatedMessage(field FieldNumber, fn func(c *Decoder)) {
for field == dec.pendingField {
if !dec.takeRepeated(field) {
return
}
if dec.pendingWire != protowire.BytesType {
dec.fail(field, "expected wire type Bytes")
return
}
message, n := protowire.ConsumeBytes(dec.buffer)
dec.pushState(message)
fn(dec)
dec.popState()
dec.nextField(n)
}
}
// RepeatedEnum decodes a repeated enumeration.
func (dec *Decoder) RepeatedEnum(field FieldNumber, add func(x int32)) {
for field == dec.pendingField {
switch dec.pendingWire {
case protowire.BytesType:
packed, n := protowire.ConsumeBytes(dec.buffer)
for len(packed) > 0 {
if !dec.takeRepeated(field) {
return
}
x, xn := protowire.ConsumeVarint(packed)
if xn < 0 {
dec.fail(field, "unable to parse Varint")
return
}
add(int32(x))
packed = packed[xn:]
}
dec.nextField(n)
case protowire.VarintType:
if !dec.takeRepeated(field) {
return
}
x, n := protowire.ConsumeVarint(dec.buffer)
if n < 0 {
dec.fail(field, "unable to parse Varint")
return
}
add(int32(x))
dec.nextField(n)
default:
dec.fail(field, "expected wire type Varint")
return
}
}
}
func (dec *Decoder) takeRepeated(field FieldNumber) bool {
if dec.maxRepeatedElements <= 0 {
return true
}
dec.repeatedElements++
if dec.repeatedElements > dec.maxRepeatedElements {
dec.fail(field, "exceeded maximum repeated elements")
return false
}
return true
}
// Message decodes a message.
func (dec *Decoder) Message(field FieldNumber, fn func(*Decoder)) {
if field != dec.pendingField {
return
}
if dec.pendingWire != protowire.BytesType {
dec.fail(field, "expected wire type Bytes")
return
}
message, n := protowire.ConsumeBytes(dec.buffer)
dec.pushState(message)
dec.Loop(fn)
dec.popState()
dec.nextField(n)
}
// PresentMessage decodes an always present message.
func (dec *Decoder) PresentMessage(field FieldNumber, fn func(*Decoder)) {
if field != dec.pendingField {
return
}
if dec.pendingWire != protowire.BytesType {
dec.fail(field, "expected wire type Bytes")
return
}
message, n := protowire.ConsumeBytes(dec.buffer)
dec.pushState(message)
dec.Loop(fn)
dec.popState()
dec.nextField(n)
}
// UnrecognizedFields decodes fields that are not in the provided set.
//
// Fields below 64 are excluded via the exclude bitmask, higher field numbers
// are listed in excludeHigh.
func (dec *Decoder) UnrecognizedFields(exclude uint64, out *[]byte, excludeHigh ...FieldNumber) {
for dec.pendingField >= 0 {
if field := dec.pendingField; field < 64 {
if exclude&(1<<uint64(field)) != 0 {
return
}
} else if containsField(excludeHigh, field) {
return
}
n := protowire.ConsumeFieldValue(protowire.Number(dec.pendingField), dec.pendingWire, dec.buffer)
if n < 0 {
dec.fail(dec.pendingField, "unable to parse unrecognized field")
return
}
*out = protowire.AppendTag(*out, protowire.Number(dec.pendingField), dec.pendingWire)
*out = append(*out, dec.buffer[:n]...)
dec.nextField(n)
}
}
// containsField reports whether fields contains field.
//
// It does a linear scan, because a message that captures unrecognized fields has
// few fields numbered 64 or above. Sort and binary search if that changes.
func containsField(fields []FieldNumber, field FieldNumber) bool {
for _, f := range fields {
if f == field {
return true
}
}
return false
}
// Loop loops fields until all messages have been processed.
func (dec *Decoder) Loop(fn func(*Decoder)) {
if !dec.init {
dec.nextField(0)
dec.init = true
}
for {
startingLength := len(dec.buffer)
fn(dec)
if !dec.pendingField.IsValid() {
break
}
if len(dec.buffer) == startingLength {
// we didn't process any of the fields
n := protowire.ConsumeFieldValue(protowire.Number(dec.pendingField), dec.pendingWire, dec.buffer)
dec.nextField(n)
}
}
}
// copyBytes returns x, copied out of the input unless the decoder was asked to
// alias it. See UnmarshalOptions.AliasInput.
func (dec *Decoder) copyBytes(x []byte) []byte {
if dec.aliasInput {
return x
}
return bytes.Clone(x)
}
// Fail fails the decoding process.
func (dec *Decoder) Fail(field FieldNumber, msg string) {
dec.fail(field, msg)
}
//go:noinline
func (dec *Decoder) fail(field FieldNumber, msg string) {
// TODO: use static error types
dec.pendingField = fieldDecodingErrored
dec.err = parseError{field: field, message: msg}
}
type parseError struct {
field FieldNumber
message string
}
func (e parseError) Error() string {
return "failed while parsing " + e.field.String() + ": " + e.message
}
func (dec *Decoder) nextField(advance int) {
if advance < 0 || advance > len(dec.buffer) {
dec.fail(0, "advance outside buffer")
return
}
dec.buffer = dec.buffer[advance:]
if len(dec.buffer) == 0 {
dec.pendingField = fieldDecodingDone
return
}
field, wire, n := protowire.ConsumeTag(dec.buffer)
if n < 0 {
dec.fail(0, "failed to parse") // TODO: better error message
return
}
// ConsumeTag only rejects field numbers below the minimum, so numbers
// between MaxValidNumber and MaxInt32 arrive here. Loop treats those as
// invalid and stops, which would silently discard the rest of the message.
if !FieldNumber(field).IsValid() {
dec.fail(FieldNumber(field), "invalid field number")
return
}
dec.buffer = dec.buffer[n:]
dec.pendingField, dec.pendingWire = FieldNumber(field), wire
}