1
2
3
4
5
6
7
8
9 package hpack
10
11 import (
12 "bytes"
13 "errors"
14 "fmt"
15 )
16
17
18 type DecodingError struct {
19 Err error
20 }
21
22 func (de DecodingError) Error() string {
23 return fmt.Sprintf("decoding error: %v", de.Err)
24 }
25
26
27
28 type InvalidIndexError int
29
30 func (e InvalidIndexError) Error() string {
31 return fmt.Sprintf("invalid indexed representation index %d", int(e))
32 }
33
34
35
36 type HeaderField struct {
37 Name, Value string
38
39
40
41 Sensitive bool
42 }
43
44
45
46
47
48 func (hf HeaderField) IsPseudo() bool {
49 return len(hf.Name) != 0 && hf.Name[0] == ':'
50 }
51
52 func (hf HeaderField) String() string {
53 var suffix string
54 if hf.Sensitive {
55 suffix = " (sensitive)"
56 }
57 return fmt.Sprintf("header field %q = %q%s", hf.Name, hf.Value, suffix)
58 }
59
60
61 func (hf HeaderField) Size() uint32 {
62
63
64
65
66
67
68
69
70
71
72
73
74 return uint32(len(hf.Name) + len(hf.Value) + 32)
75 }
76
77
78
79 type Decoder struct {
80 dynTab dynamicTable
81 emit func(f HeaderField)
82
83 emitEnabled bool
84 maxStrLen int
85
86
87
88
89
90 buf []byte
91
92
93
94 saveBuf bytes.Buffer
95
96 firstField bool
97 }
98
99
100
101
102 func NewDecoder(maxDynamicTableSize uint32, emitFunc func(f HeaderField)) *Decoder {
103 d := &Decoder{
104 emit: emitFunc,
105 emitEnabled: true,
106 firstField: true,
107 }
108 d.dynTab.table.init()
109 d.dynTab.allowedMaxSize = maxDynamicTableSize
110 d.dynTab.setMaxSize(maxDynamicTableSize)
111 return d
112 }
113
114
115
116 var ErrStringLength = errors.New("hpack: string too long")
117
118
119
120
121
122 func (d *Decoder) SetMaxStringLength(n int) {
123 d.maxStrLen = n
124 }
125
126
127
128
129 func (d *Decoder) SetEmitFunc(emitFunc func(f HeaderField)) {
130 d.emit = emitFunc
131 }
132
133
134
135
136
137
138
139
140 func (d *Decoder) SetEmitEnabled(v bool) { d.emitEnabled = v }
141
142
143
144 func (d *Decoder) EmitEnabled() bool { return d.emitEnabled }
145
146
147
148
149 func (d *Decoder) SetMaxDynamicTableSize(v uint32) {
150 d.dynTab.setMaxSize(v)
151 }
152
153
154
155
156 func (d *Decoder) SetAllowedMaxDynamicTableSize(v uint32) {
157 d.dynTab.allowedMaxSize = v
158 }
159
160 type dynamicTable struct {
161
162 table headerFieldTable
163 size uint32
164 maxSize uint32
165 allowedMaxSize uint32
166 }
167
168 func (dt *dynamicTable) setMaxSize(v uint32) {
169 dt.maxSize = v
170 dt.evict()
171 }
172
173 func (dt *dynamicTable) add(f HeaderField) {
174 dt.table.addEntry(f)
175 dt.size += f.Size()
176 dt.evict()
177 }
178
179
180 func (dt *dynamicTable) evict() {
181 var n int
182 for dt.size > dt.maxSize && n < dt.table.len() {
183 dt.size -= dt.table.ents[n].Size()
184 n++
185 }
186 dt.table.evictOldest(n)
187 }
188
189 func (d *Decoder) maxTableIndex() int {
190
191
192
193 return d.dynTab.table.len() + staticTable.len()
194 }
195
196 func (d *Decoder) at(i uint64) (hf HeaderField, ok bool) {
197
198 if i == 0 {
199 return
200 }
201 if i <= uint64(staticTable.len()) {
202 return staticTable.ents[i-1], true
203 }
204 if i > uint64(d.maxTableIndex()) {
205 return
206 }
207
208
209
210 dt := d.dynTab.table
211 return dt.ents[dt.len()-(int(i)-staticTable.len())], true
212 }
213
214
215
216
217
218 func (d *Decoder) DecodeFull(p []byte) ([]HeaderField, error) {
219 var hf []HeaderField
220 saveFunc := d.emit
221 defer func() { d.emit = saveFunc }()
222 d.emit = func(f HeaderField) { hf = append(hf, f) }
223 if _, err := d.Write(p); err != nil {
224 return nil, err
225 }
226 if err := d.Close(); err != nil {
227 return nil, err
228 }
229 return hf, nil
230 }
231
232
233
234
235 func (d *Decoder) Close() error {
236 if d.saveBuf.Len() > 0 {
237 d.saveBuf.Reset()
238 return DecodingError{errors.New("truncated headers")}
239 }
240 d.firstField = true
241 return nil
242 }
243
244 func (d *Decoder) Write(p []byte) (n int, err error) {
245 if len(p) == 0 {
246
247
248
249 return
250 }
251
252
253 if d.saveBuf.Len() == 0 {
254 d.buf = p
255 } else {
256 d.saveBuf.Write(p)
257 d.buf = d.saveBuf.Bytes()
258 d.saveBuf.Reset()
259 }
260
261 for len(d.buf) > 0 {
262 err = d.parseHeaderFieldRepr()
263 if err == errNeedMore {
264
265
266
267
268
269 const varIntOverhead = 8
270 if d.maxStrLen != 0 && int64(len(d.buf)) > 2*(int64(d.maxStrLen)+varIntOverhead) {
271 return 0, ErrStringLength
272 }
273 d.saveBuf.Write(d.buf)
274 return len(p), nil
275 }
276 d.firstField = false
277 if err != nil {
278 break
279 }
280 }
281 return len(p), err
282 }
283
284
285
286
287 var errNeedMore = errors.New("need more data")
288
289 type indexType int
290
291 const (
292 indexedTrue indexType = iota
293 indexedFalse
294 indexedNever
295 )
296
297 func (v indexType) indexed() bool { return v == indexedTrue }
298 func (v indexType) sensitive() bool { return v == indexedNever }
299
300
301
302
303
304 func (d *Decoder) parseHeaderFieldRepr() error {
305 b := d.buf[0]
306 switch {
307 case b&128 != 0:
308
309
310
311 return d.parseFieldIndexed()
312 case b&192 == 64:
313
314
315
316 return d.parseFieldLiteral(6, indexedTrue)
317 case b&240 == 0:
318
319
320
321 return d.parseFieldLiteral(4, indexedFalse)
322 case b&240 == 16:
323
324
325
326 return d.parseFieldLiteral(4, indexedNever)
327 case b&224 == 32:
328
329
330
331 return d.parseDynamicTableSizeUpdate()
332 }
333
334 return DecodingError{errors.New("invalid encoding")}
335 }
336
337
338 func (d *Decoder) parseFieldIndexed() error {
339 buf := d.buf
340 idx, buf, err := readVarInt(7, buf)
341 if err != nil {
342 return err
343 }
344 hf, ok := d.at(idx)
345 if !ok {
346 return DecodingError{InvalidIndexError(idx)}
347 }
348 d.buf = buf
349 return d.callEmit(HeaderField{Name: hf.Name, Value: hf.Value})
350 }
351
352
353 func (d *Decoder) parseFieldLiteral(n uint8, it indexType) error {
354 buf := d.buf
355 nameIdx, buf, err := readVarInt(n, buf)
356 if err != nil {
357 return err
358 }
359
360 var hf HeaderField
361 wantStr := d.emitEnabled || it.indexed()
362 var undecodedName undecodedString
363 if nameIdx > 0 {
364 ihf, ok := d.at(nameIdx)
365 if !ok {
366 return DecodingError{InvalidIndexError(nameIdx)}
367 }
368 hf.Name = ihf.Name
369 } else {
370 undecodedName, buf, err = d.readString(buf)
371 if err != nil {
372 return err
373 }
374 }
375 undecodedValue, buf, err := d.readString(buf)
376 if err != nil {
377 return err
378 }
379 if wantStr {
380 if nameIdx <= 0 {
381 hf.Name, err = d.decodeString(undecodedName)
382 if err != nil {
383 return err
384 }
385 }
386 hf.Value, err = d.decodeString(undecodedValue)
387 if err != nil {
388 return err
389 }
390 }
391 d.buf = buf
392 if it.indexed() {
393 d.dynTab.add(hf)
394 }
395 hf.Sensitive = it.sensitive()
396 return d.callEmit(hf)
397 }
398
399 func (d *Decoder) callEmit(hf HeaderField) error {
400 if d.maxStrLen != 0 {
401 if len(hf.Name) > d.maxStrLen || len(hf.Value) > d.maxStrLen {
402 return ErrStringLength
403 }
404 }
405 if d.emitEnabled {
406 d.emit(hf)
407 }
408 return nil
409 }
410
411
412 func (d *Decoder) parseDynamicTableSizeUpdate() error {
413
414
415 if !d.firstField && d.dynTab.size > 0 {
416 return DecodingError{errors.New("dynamic table size update MUST occur at the beginning of a header block")}
417 }
418
419 buf := d.buf
420 size, buf, err := readVarInt(5, buf)
421 if err != nil {
422 return err
423 }
424 if size > uint64(d.dynTab.allowedMaxSize) {
425 return DecodingError{errors.New("dynamic table size update too large")}
426 }
427 d.dynTab.setMaxSize(uint32(size))
428 d.buf = buf
429 return nil
430 }
431
432 var errVarintOverflow = DecodingError{errors.New("varint integer overflow")}
433
434
435
436
437
438
439
440
441
442 func readVarInt(n byte, p []byte) (i uint64, remain []byte, err error) {
443 if n < 1 || n > 8 {
444 panic("bad n")
445 }
446 if len(p) == 0 {
447 return 0, p, errNeedMore
448 }
449 i = uint64(p[0])
450 if n < 8 {
451 i &= (1 << uint64(n)) - 1
452 }
453 if i < (1<<uint64(n))-1 {
454 return i, p[1:], nil
455 }
456
457 origP := p
458 p = p[1:]
459 var m uint64
460 for len(p) > 0 {
461 b := p[0]
462 p = p[1:]
463 i += uint64(b&127) << m
464 if b&128 == 0 {
465 return i, p, nil
466 }
467 m += 7
468 if m >= 63 {
469 return 0, origP, errVarintOverflow
470 }
471 }
472 return 0, origP, errNeedMore
473 }
474
475
476
477
478
479 func (d *Decoder) readString(p []byte) (u undecodedString, remain []byte, err error) {
480 if len(p) == 0 {
481 return u, p, errNeedMore
482 }
483 isHuff := p[0]&128 != 0
484 strLen, p, err := readVarInt(7, p)
485 if err != nil {
486 return u, p, err
487 }
488 if d.maxStrLen != 0 && strLen > uint64(d.maxStrLen) {
489
490
491
492
493
494 return u, nil, ErrStringLength
495 }
496 if uint64(len(p)) < strLen {
497 return u, p, errNeedMore
498 }
499 u.isHuff = isHuff
500 u.b = p[:strLen]
501 return u, p[strLen:], nil
502 }
503
504 type undecodedString struct {
505 isHuff bool
506 b []byte
507 }
508
509 func (d *Decoder) decodeString(u undecodedString) (string, error) {
510 if !u.isHuff {
511 return string(u.b), nil
512 }
513 buf := bufPool.Get().(*bytes.Buffer)
514 buf.Reset()
515 var s string
516 err := huffmanDecode(buf, d.maxStrLen, u.b)
517 if err == nil {
518 s = buf.String()
519 }
520 buf.Reset()
521 bufPool.Put(buf)
522 return s, err
523 }
524
View as plain text