hpack.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. // Copyright 2014 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package hpack implements HPACK, a compression format for
  5. // efficiently representing HTTP header fields in the context of HTTP/2.
  6. //
  7. // See http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-09
  8. package hpack
  9. import (
  10. "bytes"
  11. "errors"
  12. "fmt"
  13. )
  14. // A DecodingError is something the spec defines as a decoding error.
  15. type DecodingError struct {
  16. Err error
  17. }
  18. func (de DecodingError) Error() string {
  19. return fmt.Sprintf("decoding error: %v", de.Err)
  20. }
  21. // An InvalidIndexError is returned when an encoder references a table
  22. // entry before the static table or after the end of the dynamic table.
  23. type InvalidIndexError int
  24. func (e InvalidIndexError) Error() string {
  25. return fmt.Sprintf("invalid indexed representation index %d", int(e))
  26. }
  27. // A HeaderField is a name-value pair. Both the name and value are
  28. // treated as opaque sequences of octets.
  29. type HeaderField struct {
  30. Name, Value string
  31. // Sensitive means that this header field should never be
  32. // indexed.
  33. Sensitive bool
  34. }
  35. func (hf *HeaderField) size() uint32 {
  36. // http://http2.github.io/http2-spec/compression.html#rfc.section.4.1
  37. // "The size of the dynamic table is the sum of the size of
  38. // its entries. The size of an entry is the sum of its name's
  39. // length in octets (as defined in Section 5.2), its value's
  40. // length in octets (see Section 5.2), plus 32. The size of
  41. // an entry is calculated using the length of the name and
  42. // value without any Huffman encoding applied."
  43. // This can overflow if somebody makes a large HeaderField
  44. // Name and/or Value by hand, but we don't care, because that
  45. // won't happen on the wire because the encoding doesn't allow
  46. // it.
  47. return uint32(len(hf.Name) + len(hf.Value) + 32)
  48. }
  49. // A Decoder is the decoding context for incremental processing of
  50. // header blocks.
  51. type Decoder struct {
  52. dynTab dynamicTable
  53. emit func(f HeaderField)
  54. emitEnabled bool // whether calls to emit are enabled
  55. maxStrLen int // 0 means unlimited
  56. // buf is the unparsed buffer. It's only written to
  57. // saveBuf if it was truncated in the middle of a header
  58. // block. Because it's usually not owned, we can only
  59. // process it under Write.
  60. buf []byte // not owned; only valid during Write
  61. // saveBuf is previous data passed to Write which we weren't able
  62. // to fully parse before. Unlike buf, we own this data.
  63. saveBuf bytes.Buffer
  64. }
  65. // NewDecoder returns a new decoder with the provided maximum dynamic
  66. // table size. The emitFunc will be called for each valid field
  67. // parsed, in the same goroutine as calls to Write, before Write returns.
  68. func NewDecoder(maxDynamicTableSize uint32, emitFunc func(f HeaderField)) *Decoder {
  69. d := &Decoder{
  70. emit: emitFunc,
  71. emitEnabled: true,
  72. }
  73. d.dynTab.allowedMaxSize = maxDynamicTableSize
  74. d.dynTab.setMaxSize(maxDynamicTableSize)
  75. return d
  76. }
  77. // ErrStringLength is returned by Decoder.Write when the max string length
  78. // (as configured by Decoder.SetMaxStringLength) would be violated.
  79. var ErrStringLength = errors.New("hpack: string too long")
  80. // SetMaxStringLength sets the maximum size of a HeaderField name or
  81. // value string. If a string exceeds this length (even after any
  82. // decompression), Write will return ErrStringLength.
  83. // A value of 0 means unlimited and is the default from NewDecoder.
  84. func (d *Decoder) SetMaxStringLength(n int) {
  85. d.maxStrLen = n
  86. }
  87. // SetEmitFunc changes the callback used when new header fields
  88. // are decoded.
  89. // It must be non-nil. It does not affect EmitEnabled.
  90. func (d *Decoder) SetEmitFunc(emitFunc func(f HeaderField)) {
  91. d.emit = emitFunc
  92. }
  93. // SetEmitEnabled controls whether the emitFunc provided to NewDecoder
  94. // should be called. The default is true.
  95. //
  96. // This facility exists to let servers enforce MAX_HEADER_LIST_SIZE
  97. // while still decoding and keeping in-sync with decoder state, but
  98. // without doing unnecessary decompression or generating unnecessary
  99. // garbage for header fields past the limit.
  100. func (d *Decoder) SetEmitEnabled(v bool) { d.emitEnabled = v }
  101. // EmitEnabled reports whether calls to the emitFunc provided to NewDecoder
  102. // are currently enabled. The default is true.
  103. func (d *Decoder) EmitEnabled() bool { return d.emitEnabled }
  104. // TODO: add method *Decoder.Reset(maxSize, emitFunc) to let callers re-use Decoders and their
  105. // underlying buffers for garbage reasons.
  106. func (d *Decoder) SetMaxDynamicTableSize(v uint32) {
  107. d.dynTab.setMaxSize(v)
  108. }
  109. // SetAllowedMaxDynamicTableSize sets the upper bound that the encoded
  110. // stream (via dynamic table size updates) may set the maximum size
  111. // to.
  112. func (d *Decoder) SetAllowedMaxDynamicTableSize(v uint32) {
  113. d.dynTab.allowedMaxSize = v
  114. }
  115. type dynamicTable struct {
  116. // ents is the FIFO described at
  117. // http://http2.github.io/http2-spec/compression.html#rfc.section.2.3.2
  118. // The newest (low index) is append at the end, and items are
  119. // evicted from the front.
  120. ents []HeaderField
  121. size uint32
  122. maxSize uint32 // current maxSize
  123. allowedMaxSize uint32 // maxSize may go up to this, inclusive
  124. }
  125. func (dt *dynamicTable) setMaxSize(v uint32) {
  126. dt.maxSize = v
  127. dt.evict()
  128. }
  129. // TODO: change dynamicTable to be a struct with a slice and a size int field,
  130. // per http://http2.github.io/http2-spec/compression.html#rfc.section.4.1:
  131. //
  132. //
  133. // Then make add increment the size. maybe the max size should move from Decoder to
  134. // dynamicTable and add should return an ok bool if there was enough space.
  135. //
  136. // Later we'll need a remove operation on dynamicTable.
  137. func (dt *dynamicTable) add(f HeaderField) {
  138. dt.ents = append(dt.ents, f)
  139. dt.size += f.size()
  140. dt.evict()
  141. }
  142. // If we're too big, evict old stuff (front of the slice)
  143. func (dt *dynamicTable) evict() {
  144. base := dt.ents // keep base pointer of slice
  145. for dt.size > dt.maxSize {
  146. dt.size -= dt.ents[0].size()
  147. dt.ents = dt.ents[1:]
  148. }
  149. // Shift slice contents down if we evicted things.
  150. if len(dt.ents) != len(base) {
  151. copy(base, dt.ents)
  152. dt.ents = base[:len(dt.ents)]
  153. }
  154. }
  155. // constantTimeStringCompare compares string a and b in a constant
  156. // time manner.
  157. func constantTimeStringCompare(a, b string) bool {
  158. if len(a) != len(b) {
  159. return false
  160. }
  161. c := byte(0)
  162. for i := 0; i < len(a); i++ {
  163. c |= a[i] ^ b[i]
  164. }
  165. return c == 0
  166. }
  167. // Search searches f in the table. The return value i is 0 if there is
  168. // no name match. If there is name match or name/value match, i is the
  169. // index of that entry (1-based). If both name and value match,
  170. // nameValueMatch becomes true.
  171. func (dt *dynamicTable) search(f HeaderField) (i uint64, nameValueMatch bool) {
  172. l := len(dt.ents)
  173. for j := l - 1; j >= 0; j-- {
  174. ent := dt.ents[j]
  175. if !constantTimeStringCompare(ent.Name, f.Name) {
  176. continue
  177. }
  178. if i == 0 {
  179. i = uint64(l - j)
  180. }
  181. if f.Sensitive {
  182. continue
  183. }
  184. if !constantTimeStringCompare(ent.Value, f.Value) {
  185. continue
  186. }
  187. i = uint64(l - j)
  188. nameValueMatch = true
  189. return
  190. }
  191. return
  192. }
  193. func (d *Decoder) maxTableIndex() int {
  194. return len(d.dynTab.ents) + len(staticTable)
  195. }
  196. func (d *Decoder) at(i uint64) (hf HeaderField, ok bool) {
  197. if i < 1 {
  198. return
  199. }
  200. if i > uint64(d.maxTableIndex()) {
  201. return
  202. }
  203. if i <= uint64(len(staticTable)) {
  204. return staticTable[i-1], true
  205. }
  206. dents := d.dynTab.ents
  207. return dents[len(dents)-(int(i)-len(staticTable))], true
  208. }
  209. // Decode decodes an entire block.
  210. //
  211. // TODO: remove this method and make it incremental later? This is
  212. // easier for debugging now.
  213. func (d *Decoder) DecodeFull(p []byte) ([]HeaderField, error) {
  214. var hf []HeaderField
  215. saveFunc := d.emit
  216. defer func() { d.emit = saveFunc }()
  217. d.emit = func(f HeaderField) { hf = append(hf, f) }
  218. if _, err := d.Write(p); err != nil {
  219. return nil, err
  220. }
  221. if err := d.Close(); err != nil {
  222. return nil, err
  223. }
  224. return hf, nil
  225. }
  226. func (d *Decoder) Close() error {
  227. if d.saveBuf.Len() > 0 {
  228. d.saveBuf.Reset()
  229. return DecodingError{errors.New("truncated headers")}
  230. }
  231. return nil
  232. }
  233. func (d *Decoder) Write(p []byte) (n int, err error) {
  234. if len(p) == 0 {
  235. // Prevent state machine CPU attacks (making us redo
  236. // work up to the point of finding out we don't have
  237. // enough data)
  238. return
  239. }
  240. // Only copy the data if we have to. Optimistically assume
  241. // that p will contain a complete header block.
  242. if d.saveBuf.Len() == 0 {
  243. d.buf = p
  244. } else {
  245. d.saveBuf.Write(p)
  246. d.buf = d.saveBuf.Bytes()
  247. d.saveBuf.Reset()
  248. }
  249. for len(d.buf) > 0 {
  250. err = d.parseHeaderFieldRepr()
  251. if err == errNeedMore {
  252. // Extra paranoia, making sure saveBuf won't
  253. // get too large. All the varint and string
  254. // reading code earlier should already catch
  255. // overlong things and return ErrStringLength,
  256. // but keep this as a last resort.
  257. const varIntOverhead = 8 // conservative
  258. if d.maxStrLen != 0 && int64(len(d.buf)) > 2*(int64(d.maxStrLen)+varIntOverhead) {
  259. return 0, ErrStringLength
  260. }
  261. d.saveBuf.Write(d.buf)
  262. return len(p), nil
  263. }
  264. if err != nil {
  265. break
  266. }
  267. }
  268. return len(p), err
  269. }
  270. // errNeedMore is an internal sentinel error value that means the
  271. // buffer is truncated and we need to read more data before we can
  272. // continue parsing.
  273. var errNeedMore = errors.New("need more data")
  274. type indexType int
  275. const (
  276. indexedTrue indexType = iota
  277. indexedFalse
  278. indexedNever
  279. )
  280. func (v indexType) indexed() bool { return v == indexedTrue }
  281. func (v indexType) sensitive() bool { return v == indexedNever }
  282. // returns errNeedMore if there isn't enough data available.
  283. // any other error is fatal.
  284. // consumes d.buf iff it returns nil.
  285. // precondition: must be called with len(d.buf) > 0
  286. func (d *Decoder) parseHeaderFieldRepr() error {
  287. b := d.buf[0]
  288. switch {
  289. case b&128 != 0:
  290. // Indexed representation.
  291. // High bit set?
  292. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.1
  293. return d.parseFieldIndexed()
  294. case b&192 == 64:
  295. // 6.2.1 Literal Header Field with Incremental Indexing
  296. // 0b10xxxxxx: top two bits are 10
  297. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.1
  298. return d.parseFieldLiteral(6, indexedTrue)
  299. case b&240 == 0:
  300. // 6.2.2 Literal Header Field without Indexing
  301. // 0b0000xxxx: top four bits are 0000
  302. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.2
  303. return d.parseFieldLiteral(4, indexedFalse)
  304. case b&240 == 16:
  305. // 6.2.3 Literal Header Field never Indexed
  306. // 0b0001xxxx: top four bits are 0001
  307. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.3
  308. return d.parseFieldLiteral(4, indexedNever)
  309. case b&224 == 32:
  310. // 6.3 Dynamic Table Size Update
  311. // Top three bits are '001'.
  312. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.3
  313. return d.parseDynamicTableSizeUpdate()
  314. }
  315. return DecodingError{errors.New("invalid encoding")}
  316. }
  317. // (same invariants and behavior as parseHeaderFieldRepr)
  318. func (d *Decoder) parseFieldIndexed() error {
  319. buf := d.buf
  320. idx, buf, err := readVarInt(7, buf)
  321. if err != nil {
  322. return err
  323. }
  324. hf, ok := d.at(idx)
  325. if !ok {
  326. return DecodingError{InvalidIndexError(idx)}
  327. }
  328. d.buf = buf
  329. return d.callEmit(HeaderField{Name: hf.Name, Value: hf.Value})
  330. }
  331. // (same invariants and behavior as parseHeaderFieldRepr)
  332. func (d *Decoder) parseFieldLiteral(n uint8, it indexType) error {
  333. buf := d.buf
  334. nameIdx, buf, err := readVarInt(n, buf)
  335. if err != nil {
  336. return err
  337. }
  338. var hf HeaderField
  339. wantStr := d.emitEnabled || it.indexed()
  340. if nameIdx > 0 {
  341. ihf, ok := d.at(nameIdx)
  342. if !ok {
  343. return DecodingError{InvalidIndexError(nameIdx)}
  344. }
  345. hf.Name = ihf.Name
  346. } else {
  347. hf.Name, buf, err = d.readString(buf, wantStr)
  348. if err != nil {
  349. return err
  350. }
  351. }
  352. hf.Value, buf, err = d.readString(buf, wantStr)
  353. if err != nil {
  354. return err
  355. }
  356. d.buf = buf
  357. if it.indexed() {
  358. d.dynTab.add(hf)
  359. }
  360. hf.Sensitive = it.sensitive()
  361. return d.callEmit(hf)
  362. }
  363. func (d *Decoder) callEmit(hf HeaderField) error {
  364. if d.maxStrLen != 0 {
  365. if len(hf.Name) > d.maxStrLen || len(hf.Value) > d.maxStrLen {
  366. return ErrStringLength
  367. }
  368. }
  369. if d.emitEnabled {
  370. d.emit(hf)
  371. }
  372. return nil
  373. }
  374. // (same invariants and behavior as parseHeaderFieldRepr)
  375. func (d *Decoder) parseDynamicTableSizeUpdate() error {
  376. buf := d.buf
  377. size, buf, err := readVarInt(5, buf)
  378. if err != nil {
  379. return err
  380. }
  381. if size > uint64(d.dynTab.allowedMaxSize) {
  382. return DecodingError{errors.New("dynamic table size update too large")}
  383. }
  384. d.dynTab.setMaxSize(uint32(size))
  385. d.buf = buf
  386. return nil
  387. }
  388. var errVarintOverflow = DecodingError{errors.New("varint integer overflow")}
  389. // readVarInt reads an unsigned variable length integer off the
  390. // beginning of p. n is the parameter as described in
  391. // http://http2.github.io/http2-spec/compression.html#rfc.section.5.1.
  392. //
  393. // n must always be between 1 and 8.
  394. //
  395. // The returned remain buffer is either a smaller suffix of p, or err != nil.
  396. // The error is errNeedMore if p doesn't contain a complete integer.
  397. func readVarInt(n byte, p []byte) (i uint64, remain []byte, err error) {
  398. if n < 1 || n > 8 {
  399. panic("bad n")
  400. }
  401. if len(p) == 0 {
  402. return 0, p, errNeedMore
  403. }
  404. i = uint64(p[0])
  405. if n < 8 {
  406. i &= (1 << uint64(n)) - 1
  407. }
  408. if i < (1<<uint64(n))-1 {
  409. return i, p[1:], nil
  410. }
  411. origP := p
  412. p = p[1:]
  413. var m uint64
  414. for len(p) > 0 {
  415. b := p[0]
  416. p = p[1:]
  417. i += uint64(b&127) << m
  418. if b&128 == 0 {
  419. return i, p, nil
  420. }
  421. m += 7
  422. if m >= 63 { // TODO: proper overflow check. making this up.
  423. return 0, origP, errVarintOverflow
  424. }
  425. }
  426. return 0, origP, errNeedMore
  427. }
  428. // readString decodes an hpack string from p.
  429. //
  430. // wantStr is whether s will be used. If false, decompression and
  431. // []byte->string garbage are skipped if s will be ignored
  432. // anyway. This does mean that huffman decoding errors for non-indexed
  433. // strings past the MAX_HEADER_LIST_SIZE are ignored, but the server
  434. // is returning an error anyway, and because they're not indexed, the error
  435. // won't affect the decoding state.
  436. func (d *Decoder) readString(p []byte, wantStr bool) (s string, remain []byte, err error) {
  437. if len(p) == 0 {
  438. return "", p, errNeedMore
  439. }
  440. isHuff := p[0]&128 != 0
  441. strLen, p, err := readVarInt(7, p)
  442. if err != nil {
  443. return "", p, err
  444. }
  445. if d.maxStrLen != 0 && strLen > uint64(d.maxStrLen) {
  446. return "", nil, ErrStringLength
  447. }
  448. if uint64(len(p)) < strLen {
  449. return "", p, errNeedMore
  450. }
  451. if !isHuff {
  452. if wantStr {
  453. s = string(p[:strLen])
  454. }
  455. return s, p[strLen:], nil
  456. }
  457. if wantStr {
  458. buf := bufPool.Get().(*bytes.Buffer)
  459. buf.Reset() // don't trust others
  460. defer bufPool.Put(buf)
  461. if err := huffmanDecode(buf, d.maxStrLen, p[:strLen]); err != nil {
  462. buf.Reset()
  463. return "", nil, err
  464. }
  465. s = buf.String()
  466. buf.Reset() // be nice to GC
  467. }
  468. return s, p[strLen:], nil
  469. }