hpack.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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, after compression. If a string exceeds this length,
  82. // 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 != nil {
  246. if err == errNeedMore {
  247. err = nil
  248. const varIntOverhead = 8 // conservative
  249. if d.maxStrLen != 0 &&
  250. int64(len(d.buf))+int64(d.saveBuf.Len()) > 2*(int64(d.maxStrLen)+varIntOverhead) {
  251. return 0, ErrStringLength
  252. }
  253. d.saveBuf.Write(d.buf)
  254. }
  255. break
  256. }
  257. }
  258. return len(p), err
  259. }
  260. // errNeedMore is an internal sentinel error value that means the
  261. // buffer is truncated and we need to read more data before we can
  262. // continue parsing.
  263. var errNeedMore = errors.New("need more data")
  264. type indexType int
  265. const (
  266. indexedTrue indexType = iota
  267. indexedFalse
  268. indexedNever
  269. )
  270. func (v indexType) indexed() bool { return v == indexedTrue }
  271. func (v indexType) sensitive() bool { return v == indexedNever }
  272. // returns errNeedMore if there isn't enough data available.
  273. // any other error is fatal.
  274. // consumes d.buf iff it returns nil.
  275. // precondition: must be called with len(d.buf) > 0
  276. func (d *Decoder) parseHeaderFieldRepr() error {
  277. b := d.buf[0]
  278. switch {
  279. case b&128 != 0:
  280. // Indexed representation.
  281. // High bit set?
  282. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.1
  283. return d.parseFieldIndexed()
  284. case b&192 == 64:
  285. // 6.2.1 Literal Header Field with Incremental Indexing
  286. // 0b10xxxxxx: top two bits are 10
  287. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.1
  288. return d.parseFieldLiteral(6, indexedTrue)
  289. case b&240 == 0:
  290. // 6.2.2 Literal Header Field without Indexing
  291. // 0b0000xxxx: top four bits are 0000
  292. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.2
  293. return d.parseFieldLiteral(4, indexedFalse)
  294. case b&240 == 16:
  295. // 6.2.3 Literal Header Field never Indexed
  296. // 0b0001xxxx: top four bits are 0001
  297. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.3
  298. return d.parseFieldLiteral(4, indexedNever)
  299. case b&224 == 32:
  300. // 6.3 Dynamic Table Size Update
  301. // Top three bits are '001'.
  302. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.3
  303. return d.parseDynamicTableSizeUpdate()
  304. }
  305. return DecodingError{errors.New("invalid encoding")}
  306. }
  307. // (same invariants and behavior as parseHeaderFieldRepr)
  308. func (d *Decoder) parseFieldIndexed() error {
  309. buf := d.buf
  310. idx, buf, err := readVarInt(7, buf)
  311. if err != nil {
  312. return err
  313. }
  314. hf, ok := d.at(idx)
  315. if !ok {
  316. return DecodingError{InvalidIndexError(idx)}
  317. }
  318. d.buf = buf
  319. return d.callEmit(HeaderField{Name: hf.Name, Value: hf.Value})
  320. }
  321. // (same invariants and behavior as parseHeaderFieldRepr)
  322. func (d *Decoder) parseFieldLiteral(n uint8, it indexType) error {
  323. buf := d.buf
  324. nameIdx, buf, err := readVarInt(n, buf)
  325. if err != nil {
  326. return err
  327. }
  328. var hf HeaderField
  329. wantStr := d.emitEnabled || it.indexed()
  330. if nameIdx > 0 {
  331. ihf, ok := d.at(nameIdx)
  332. if !ok {
  333. return DecodingError{InvalidIndexError(nameIdx)}
  334. }
  335. hf.Name = ihf.Name
  336. } else {
  337. hf.Name, buf, err = readString(buf, wantStr)
  338. if err != nil {
  339. return err
  340. }
  341. }
  342. hf.Value, buf, err = readString(buf, wantStr)
  343. if err != nil {
  344. return err
  345. }
  346. d.buf = buf
  347. if it.indexed() {
  348. d.dynTab.add(hf)
  349. }
  350. hf.Sensitive = it.sensitive()
  351. return d.callEmit(hf)
  352. }
  353. func (d *Decoder) callEmit(hf HeaderField) error {
  354. if d.maxStrLen != 0 {
  355. if len(hf.Name) > d.maxStrLen || len(hf.Value) > d.maxStrLen {
  356. return ErrStringLength
  357. }
  358. }
  359. if d.emitEnabled {
  360. d.emit(hf)
  361. }
  362. return nil
  363. }
  364. // (same invariants and behavior as parseHeaderFieldRepr)
  365. func (d *Decoder) parseDynamicTableSizeUpdate() error {
  366. buf := d.buf
  367. size, buf, err := readVarInt(5, buf)
  368. if err != nil {
  369. return err
  370. }
  371. if size > uint64(d.dynTab.allowedMaxSize) {
  372. return DecodingError{errors.New("dynamic table size update too large")}
  373. }
  374. d.dynTab.setMaxSize(uint32(size))
  375. d.buf = buf
  376. return nil
  377. }
  378. var errVarintOverflow = DecodingError{errors.New("varint integer overflow")}
  379. // readVarInt reads an unsigned variable length integer off the
  380. // beginning of p. n is the parameter as described in
  381. // http://http2.github.io/http2-spec/compression.html#rfc.section.5.1.
  382. //
  383. // n must always be between 1 and 8.
  384. //
  385. // The returned remain buffer is either a smaller suffix of p, or err != nil.
  386. // The error is errNeedMore if p doesn't contain a complete integer.
  387. func readVarInt(n byte, p []byte) (i uint64, remain []byte, err error) {
  388. if n < 1 || n > 8 {
  389. panic("bad n")
  390. }
  391. if len(p) == 0 {
  392. return 0, p, errNeedMore
  393. }
  394. i = uint64(p[0])
  395. if n < 8 {
  396. i &= (1 << uint64(n)) - 1
  397. }
  398. if i < (1<<uint64(n))-1 {
  399. return i, p[1:], nil
  400. }
  401. origP := p
  402. p = p[1:]
  403. var m uint64
  404. for len(p) > 0 {
  405. b := p[0]
  406. p = p[1:]
  407. i += uint64(b&127) << m
  408. if b&128 == 0 {
  409. return i, p, nil
  410. }
  411. m += 7
  412. if m >= 63 { // TODO: proper overflow check. making this up.
  413. return 0, origP, errVarintOverflow
  414. }
  415. }
  416. return 0, origP, errNeedMore
  417. }
  418. // readString decodes an hpack string from p.
  419. //
  420. // wantStr is whether s will be used. If false, decompression and
  421. // []byte->string garbage are skipped if s will be ignored
  422. // anyway. This does mean that huffman decoding errors for non-indexed
  423. // strings past the MAX_HEADER_LIST_SIZE are ignored, but the server
  424. // is returning an error anyway, and because they're not indexed, the error
  425. // won't affect the decoding state.
  426. func readString(p []byte, wantStr bool) (s string, remain []byte, err error) {
  427. if len(p) == 0 {
  428. return "", p, errNeedMore
  429. }
  430. isHuff := p[0]&128 != 0
  431. strLen, p, err := readVarInt(7, p)
  432. if err != nil {
  433. return "", p, err
  434. }
  435. if uint64(len(p)) < strLen {
  436. return "", p, errNeedMore
  437. }
  438. if !isHuff {
  439. if wantStr {
  440. s = string(p[:strLen])
  441. }
  442. return s, p[strLen:], nil
  443. }
  444. if wantStr {
  445. s, err = HuffmanDecodeToString(p[:strLen])
  446. if err != nil {
  447. return "", nil, err
  448. }
  449. }
  450. return s, p[strLen:], nil
  451. }