-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
decoder.go
275 lines (245 loc) · 6.27 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
package qpack
import (
"bytes"
"errors"
"fmt"
"sync"
"golang.org/x/net/http2/hpack"
)
// A decodingError is something the spec defines as a decoding error.
type decodingError struct {
err error
}
func (de decodingError) Error() string {
return fmt.Sprintf("decoding error: %v", de.err)
}
// An invalidIndexError is returned when an encoder references a table
// entry before the static table or after the end of the dynamic table.
type invalidIndexError int
func (e invalidIndexError) Error() string {
return fmt.Sprintf("invalid indexed representation index %d", int(e))
}
var errNoDynamicTable = decodingError{errors.New("no dynamic table")}
// errNeedMore is an internal sentinel error value that means the
// buffer is truncated and we need to read more data before we can
// continue parsing.
var errNeedMore = errors.New("need more data")
// A Decoder is the decoding context for incremental processing of
// header blocks.
type Decoder struct {
mutex sync.Mutex
emitFunc func(f HeaderField)
readRequiredInsertCount bool
readDeltaBase bool
// buf is the unparsed buffer. It's only written to
// saveBuf if it was truncated in the middle of a header
// block. Because it's usually not owned, we can only
// process it under Write.
buf []byte // not owned; only valid during Write
// saveBuf is previous data passed to Write which we weren't able
// to fully parse before. Unlike buf, we own this data.
saveBuf bytes.Buffer
}
// NewDecoder returns a new decoder
// The emitFunc will be called for each valid field parsed,
// in the same goroutine as calls to Write, before Write returns.
func NewDecoder(emitFunc func(f HeaderField)) *Decoder {
return &Decoder{emitFunc: emitFunc}
}
func (d *Decoder) Write(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
d.mutex.Lock()
n, err := d.writeLocked(p)
d.mutex.Unlock()
return n, err
}
func (d *Decoder) writeLocked(p []byte) (int, error) {
// Only copy the data if we have to. Optimistically assume
// that p will contain a complete header block.
if d.saveBuf.Len() == 0 {
d.buf = p
} else {
d.saveBuf.Write(p)
d.buf = d.saveBuf.Bytes()
d.saveBuf.Reset()
}
if err := d.decode(); err != nil {
if err != errNeedMore {
return 0, err
}
// TODO: limit the size of the buffer
d.saveBuf.Write(d.buf)
}
return len(p), nil
}
// DecodeFull decodes an entire block.
func (d *Decoder) DecodeFull(p []byte) ([]HeaderField, error) {
if len(p) == 0 {
return []HeaderField{}, nil
}
d.mutex.Lock()
defer d.mutex.Unlock()
saveFunc := d.emitFunc
defer func() { d.emitFunc = saveFunc }()
var hf []HeaderField
d.emitFunc = func(f HeaderField) { hf = append(hf, f) }
if _, err := d.writeLocked(p); err != nil {
return nil, err
}
if err := d.Close(); err != nil {
return nil, err
}
return hf, nil
}
// Close declares that the decoding is complete and resets the Decoder
// to be reused again for a new header block. If there is any remaining
// data in the decoder's buffer, Close returns an error.
func (d *Decoder) Close() error {
if d.saveBuf.Len() > 0 {
d.saveBuf.Reset()
return decodingError{errors.New("truncated headers")}
}
d.readRequiredInsertCount = false
d.readDeltaBase = false
return nil
}
func (d *Decoder) decode() error {
if !d.readRequiredInsertCount {
requiredInsertCount, rest, err := readVarInt(8, d.buf)
if err != nil {
return err
}
d.readRequiredInsertCount = true
if requiredInsertCount != 0 {
return decodingError{errors.New("expected Required Insert Count to be zero")}
}
d.buf = rest
}
if !d.readDeltaBase {
base, rest, err := readVarInt(7, d.buf)
if err != nil {
return err
}
d.readDeltaBase = true
if base != 0 {
return decodingError{errors.New("expected Base to be zero")}
}
d.buf = rest
}
if len(d.buf) == 0 {
return errNeedMore
}
for len(d.buf) > 0 {
b := d.buf[0]
var err error
switch {
case b&0x80 > 0: // 1xxxxxxx
err = d.parseIndexedHeaderField()
case b&0xc0 == 0x40: // 01xxxxxx
err = d.parseLiteralHeaderField()
case b&0xe0 == 0x20: // 001xxxxx
err = d.parseLiteralHeaderFieldWithoutNameReference()
default:
err = fmt.Errorf("unexpected type byte: %#x", b)
}
if err != nil {
return err
}
}
return nil
}
func (d *Decoder) parseIndexedHeaderField() error {
buf := d.buf
if buf[0]&0x40 == 0 {
return errNoDynamicTable
}
index, buf, err := readVarInt(6, buf)
if err != nil {
return err
}
hf, ok := d.at(index)
if !ok {
return decodingError{invalidIndexError(index)}
}
d.emitFunc(hf)
d.buf = buf
return nil
}
func (d *Decoder) parseLiteralHeaderField() error {
buf := d.buf
if buf[0]&0x10 == 0 {
return errNoDynamicTable
}
// We don't need to check the value of the N-bit here.
// It's only relevant when re-encoding header fields,
// and determines whether the header field can be added to the dynamic table.
// Since we don't support the dynamic table, we can ignore it.
index, buf, err := readVarInt(4, buf)
if err != nil {
return err
}
hf, ok := d.at(index)
if !ok {
return decodingError{invalidIndexError(index)}
}
if len(buf) == 0 {
return errNeedMore
}
usesHuffman := buf[0]&0x80 > 0
val, buf, err := d.readString(buf, 7, usesHuffman)
if err != nil {
return err
}
hf.Value = val
d.emitFunc(hf)
d.buf = buf
return nil
}
func (d *Decoder) parseLiteralHeaderFieldWithoutNameReference() error {
buf := d.buf
usesHuffmanForName := buf[0]&0x8 > 0
name, buf, err := d.readString(buf, 3, usesHuffmanForName)
if err != nil {
return err
}
if len(buf) == 0 {
return errNeedMore
}
usesHuffmanForVal := buf[0]&0x80 > 0
val, buf, err := d.readString(buf, 7, usesHuffmanForVal)
if err != nil {
return err
}
d.emitFunc(HeaderField{Name: name, Value: val})
d.buf = buf
return nil
}
func (d *Decoder) readString(buf []byte, n uint8, usesHuffman bool) (string, []byte, error) {
l, buf, err := readVarInt(n, buf)
if err != nil {
return "", nil, err
}
if uint64(len(buf)) < l {
return "", nil, errNeedMore
}
var val string
if usesHuffman {
var err error
val, err = hpack.HuffmanDecodeToString(buf[:l])
if err != nil {
return "", nil, err
}
} else {
val = string(buf[:l])
}
buf = buf[l:]
return val, buf, nil
}
func (d *Decoder) at(i uint64) (hf HeaderField, ok bool) {
if i >= uint64(len(staticTableEntries)) {
return
}
return staticTableEntries[i], true
}