hpack.go 13 KB

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