hpack.go 14 KB

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