hpack.go 15 KB

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