hpack.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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. // buf is the unparsed buffer. It's only written to
  56. // saveBuf if it was truncated in the middle of a header
  57. // block. Because it's usually not owned, we can only
  58. // process it under Write.
  59. buf []byte // usually not owned
  60. saveBuf bytes.Buffer
  61. }
  62. func NewDecoder(maxSize uint32, emitFunc func(f HeaderField)) *Decoder {
  63. d := &Decoder{
  64. emit: emitFunc,
  65. }
  66. d.dynTab.allowedMaxSize = maxSize
  67. d.dynTab.setMaxSize(maxSize)
  68. return d
  69. }
  70. // TODO: add method *Decoder.Reset(maxSize, emitFunc) to let callers re-use Decoders and their
  71. // underlying buffers for garbage reasons.
  72. func (d *Decoder) SetMaxDynamicTableSize(v uint32) {
  73. d.dynTab.setMaxSize(v)
  74. }
  75. // SetAllowedMaxDynamicTableSize sets the upper bound that the encoded
  76. // stream (via dynamic table size updates) may set the maximum size
  77. // to.
  78. func (d *Decoder) SetAllowedMaxDynamicTableSize(v uint32) {
  79. d.dynTab.allowedMaxSize = v
  80. }
  81. type dynamicTable struct {
  82. // s is the FIFO described at
  83. // http://http2.github.io/http2-spec/compression.html#rfc.section.2.3.2
  84. // The newest (low index) is append at the end, and items are
  85. // evicted from the front.
  86. ents []HeaderField
  87. size uint32
  88. maxSize uint32 // current maxSize
  89. allowedMaxSize uint32 // maxSize may go up to this, inclusive
  90. }
  91. func (dt *dynamicTable) setMaxSize(v uint32) {
  92. dt.maxSize = v
  93. dt.evict()
  94. }
  95. // TODO: change dynamicTable to be a struct with a slice and a size int field,
  96. // per http://http2.github.io/http2-spec/compression.html#rfc.section.4.1:
  97. //
  98. //
  99. // Then make add increment the size. maybe the max size should move from Decoder to
  100. // dynamicTable and add should return an ok bool if there was enough space.
  101. //
  102. // Later we'll need a remove operation on dynamicTable.
  103. func (dt *dynamicTable) add(f HeaderField) {
  104. dt.ents = append(dt.ents, f)
  105. dt.size += f.size()
  106. dt.evict()
  107. }
  108. // If we're too big, evict old stuff (front of the slice)
  109. func (dt *dynamicTable) evict() {
  110. base := dt.ents // keep base pointer of slice
  111. for dt.size > dt.maxSize {
  112. dt.size -= dt.ents[0].size()
  113. dt.ents = dt.ents[1:]
  114. }
  115. // Shift slice contents down if we evicted things.
  116. if len(dt.ents) != len(base) {
  117. copy(base, dt.ents)
  118. dt.ents = base[:len(dt.ents)]
  119. }
  120. }
  121. // constantTimeStringCompare compares string a and b in a constant
  122. // time manner.
  123. func constantTimeStringCompare(a, b string) bool {
  124. if len(a) != len(b) {
  125. return false
  126. }
  127. c := byte(0)
  128. for i := 0; i < len(a); i++ {
  129. c |= a[i] ^ b[i]
  130. }
  131. return c == 0
  132. }
  133. // Search searches f in the table. The return value i is 0 if there is
  134. // no name match. If there is name match or name/value match, i is the
  135. // index of that entry (1-based). If both name and value match,
  136. // nameValueMatch becomes true.
  137. func (dt *dynamicTable) search(f HeaderField) (i uint64, nameValueMatch bool) {
  138. l := len(dt.ents)
  139. for j := l - 1; j >= 0; j-- {
  140. ent := dt.ents[j]
  141. if !constantTimeStringCompare(ent.Name, f.Name) {
  142. continue
  143. }
  144. if i == 0 {
  145. i = uint64(l - j)
  146. }
  147. if f.Sensitive {
  148. continue
  149. }
  150. if !constantTimeStringCompare(ent.Value, f.Value) {
  151. continue
  152. }
  153. i = uint64(l - j)
  154. nameValueMatch = true
  155. return
  156. }
  157. return
  158. }
  159. func (d *Decoder) maxTableIndex() int {
  160. return len(d.dynTab.ents) + len(staticTable)
  161. }
  162. func (d *Decoder) at(i uint64) (hf HeaderField, ok bool) {
  163. if i < 1 {
  164. return
  165. }
  166. if i > uint64(d.maxTableIndex()) {
  167. return
  168. }
  169. if i <= uint64(len(staticTable)) {
  170. return staticTable[i-1], true
  171. }
  172. dents := d.dynTab.ents
  173. return dents[len(dents)-(int(i)-len(staticTable))], true
  174. }
  175. // Decode decodes an entire block.
  176. //
  177. // TODO: remove this method and make it incremental later? This is
  178. // easier for debugging now.
  179. func (d *Decoder) DecodeFull(p []byte) ([]HeaderField, error) {
  180. var hf []HeaderField
  181. saveFunc := d.emit
  182. defer func() { d.emit = saveFunc }()
  183. d.emit = func(f HeaderField) { hf = append(hf, f) }
  184. if _, err := d.Write(p); err != nil {
  185. return nil, err
  186. }
  187. if err := d.Close(); err != nil {
  188. return nil, err
  189. }
  190. return hf, nil
  191. }
  192. func (d *Decoder) Close() error {
  193. if d.saveBuf.Len() > 0 {
  194. d.saveBuf.Reset()
  195. return DecodingError{errors.New("truncated headers")}
  196. }
  197. return nil
  198. }
  199. func (d *Decoder) Write(p []byte) (n int, err error) {
  200. if len(p) == 0 {
  201. // Prevent state machine CPU attacks (making us redo
  202. // work up to the point of finding out we don't have
  203. // enough data)
  204. return
  205. }
  206. // Only copy the data if we have to. Optimistically assume
  207. // that p will contain a complete header block.
  208. if d.saveBuf.Len() == 0 {
  209. d.buf = p
  210. } else {
  211. d.saveBuf.Write(p)
  212. d.buf = d.saveBuf.Bytes()
  213. d.saveBuf.Reset()
  214. }
  215. for len(d.buf) > 0 {
  216. err = d.parseHeaderFieldRepr()
  217. if err != nil {
  218. if err == errNeedMore {
  219. err = nil
  220. d.saveBuf.Write(d.buf)
  221. }
  222. break
  223. }
  224. }
  225. return len(p), err
  226. }
  227. // errNeedMore is an internal sentinel error value that means the
  228. // buffer is truncated and we need to read more data before we can
  229. // continue parsing.
  230. var errNeedMore = errors.New("need more data")
  231. type indexType int
  232. const (
  233. indexedTrue indexType = iota
  234. indexedFalse
  235. indexedNever
  236. )
  237. func (v indexType) indexed() bool { return v == indexedTrue }
  238. func (v indexType) sensitive() bool { return v == indexedNever }
  239. // returns errNeedMore if there isn't enough data available.
  240. // any other error is atal.
  241. // consumes d.buf iff it returns nil.
  242. // precondition: must be called with len(d.buf) > 0
  243. func (d *Decoder) parseHeaderFieldRepr() error {
  244. b := d.buf[0]
  245. switch {
  246. case b&128 != 0:
  247. // Indexed representation.
  248. // High bit set?
  249. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.1
  250. return d.parseFieldIndexed()
  251. case b&192 == 64:
  252. // 6.2.1 Literal Header Field with Incremental Indexing
  253. // 0b10xxxxxx: top two bits are 10
  254. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.1
  255. return d.parseFieldLiteral(6, indexedTrue)
  256. case b&240 == 0:
  257. // 6.2.2 Literal Header Field without Indexing
  258. // 0b0000xxxx: top four bits are 0000
  259. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.2
  260. return d.parseFieldLiteral(4, indexedFalse)
  261. case b&240 == 16:
  262. // 6.2.3 Literal Header Field never Indexed
  263. // 0b0001xxxx: top four bits are 0001
  264. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.3
  265. return d.parseFieldLiteral(4, indexedNever)
  266. case b&224 == 32:
  267. // 6.3 Dynamic Table Size Update
  268. // Top three bits are '001'.
  269. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.3
  270. return d.parseDynamicTableSizeUpdate()
  271. }
  272. return DecodingError{errors.New("invalid encoding")}
  273. }
  274. // (same invariants and behavior as parseHeaderFieldRepr)
  275. func (d *Decoder) parseFieldIndexed() error {
  276. buf := d.buf
  277. idx, buf, err := readVarInt(7, buf)
  278. if err != nil {
  279. return err
  280. }
  281. hf, ok := d.at(idx)
  282. if !ok {
  283. return DecodingError{InvalidIndexError(idx)}
  284. }
  285. d.emit(HeaderField{Name: hf.Name, Value: hf.Value})
  286. d.buf = buf
  287. return nil
  288. }
  289. // (same invariants and behavior as parseHeaderFieldRepr)
  290. func (d *Decoder) parseFieldLiteral(n uint8, it indexType) error {
  291. buf := d.buf
  292. nameIdx, buf, err := readVarInt(n, buf)
  293. if err != nil {
  294. return err
  295. }
  296. var hf HeaderField
  297. if nameIdx > 0 {
  298. ihf, ok := d.at(nameIdx)
  299. if !ok {
  300. return DecodingError{InvalidIndexError(nameIdx)}
  301. }
  302. hf.Name = ihf.Name
  303. } else {
  304. hf.Name, buf, err = readString(buf)
  305. if err != nil {
  306. return err
  307. }
  308. }
  309. hf.Value, buf, err = readString(buf)
  310. if err != nil {
  311. return err
  312. }
  313. d.buf = buf
  314. if it.indexed() {
  315. d.dynTab.add(hf)
  316. }
  317. hf.Sensitive = it.sensitive()
  318. d.emit(hf)
  319. return nil
  320. }
  321. // (same invariants and behavior as parseHeaderFieldRepr)
  322. func (d *Decoder) parseDynamicTableSizeUpdate() error {
  323. buf := d.buf
  324. size, buf, err := readVarInt(5, buf)
  325. if err != nil {
  326. return err
  327. }
  328. if size > uint64(d.dynTab.allowedMaxSize) {
  329. return DecodingError{errors.New("dynamic table size update too large")}
  330. }
  331. d.dynTab.setMaxSize(uint32(size))
  332. d.buf = buf
  333. return nil
  334. }
  335. var errVarintOverflow = DecodingError{errors.New("varint integer overflow")}
  336. // readVarInt reads an unsigned variable length integer off the
  337. // beginning of p. n is the parameter as described in
  338. // http://http2.github.io/http2-spec/compression.html#rfc.section.5.1.
  339. //
  340. // n must always be between 1 and 8.
  341. //
  342. // The returned remain buffer is either a smaller suffix of p, or err != nil.
  343. // The error is errNeedMore if p doesn't contain a complete integer.
  344. func readVarInt(n byte, p []byte) (i uint64, remain []byte, err error) {
  345. if n < 1 || n > 8 {
  346. panic("bad n")
  347. }
  348. if len(p) == 0 {
  349. return 0, p, errNeedMore
  350. }
  351. i = uint64(p[0])
  352. if n < 8 {
  353. i &= (1 << uint64(n)) - 1
  354. }
  355. if i < (1<<uint64(n))-1 {
  356. return i, p[1:], nil
  357. }
  358. origP := p
  359. p = p[1:]
  360. var m uint64
  361. for len(p) > 0 {
  362. b := p[0]
  363. p = p[1:]
  364. i += uint64(b&127) << m
  365. if b&128 == 0 {
  366. return i, p, nil
  367. }
  368. m += 7
  369. if m >= 63 { // TODO: proper overflow check. making this up.
  370. return 0, origP, errVarintOverflow
  371. }
  372. }
  373. return 0, origP, errNeedMore
  374. }
  375. func readString(p []byte) (s string, remain []byte, err error) {
  376. if len(p) == 0 {
  377. return "", p, errNeedMore
  378. }
  379. isHuff := p[0]&128 != 0
  380. strLen, p, err := readVarInt(7, p)
  381. if err != nil {
  382. return "", p, err
  383. }
  384. if uint64(len(p)) < strLen {
  385. return "", p, errNeedMore
  386. }
  387. if !isHuff {
  388. return string(p[:strLen]), p[strLen:], nil
  389. }
  390. // TODO: optimize this garbage:
  391. var buf bytes.Buffer
  392. if _, err := HuffmanDecode(&buf, p[:strLen]); err != nil {
  393. return "", nil, err
  394. }
  395. return buf.String(), p[strLen:], nil
  396. }