hpack.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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. func (d *Decoder) maxTableIndex() int {
  122. return len(d.dynTab.ents) + len(staticTable)
  123. }
  124. func (d *Decoder) at(i uint64) (hf HeaderField, ok bool) {
  125. if i < 1 {
  126. return
  127. }
  128. if i > uint64(d.maxTableIndex()) {
  129. return
  130. }
  131. if i <= uint64(len(staticTable)) {
  132. return staticTable[i-1], true
  133. }
  134. dents := d.dynTab.ents
  135. return dents[len(dents)-(int(i)-len(staticTable))], true
  136. }
  137. // Decode decodes an entire block.
  138. //
  139. // TODO: remove this method and make it incremental later? This is
  140. // easier for debugging now.
  141. func (d *Decoder) DecodeFull(p []byte) ([]HeaderField, error) {
  142. var hf []HeaderField
  143. saveFunc := d.emit
  144. defer func() { d.emit = saveFunc }()
  145. d.emit = func(f HeaderField) { hf = append(hf, f) }
  146. if _, err := d.Write(p); err != nil {
  147. return nil, err
  148. }
  149. if err := d.Close(); err != nil {
  150. return nil, err
  151. }
  152. return hf, nil
  153. }
  154. func (d *Decoder) Close() error {
  155. if d.saveBuf.Len() > 0 {
  156. d.saveBuf.Reset()
  157. return DecodingError{errors.New("truncated headers")}
  158. }
  159. return nil
  160. }
  161. func (d *Decoder) Write(p []byte) (n int, err error) {
  162. if len(p) == 0 {
  163. // Prevent state machine CPU attacks (making us redo
  164. // work up to the point of finding out we don't have
  165. // enough data)
  166. return
  167. }
  168. // Only copy the data if we have to. Optimistically assume
  169. // that p will contain a complete header block.
  170. if d.saveBuf.Len() == 0 {
  171. d.buf = p
  172. } else {
  173. d.saveBuf.Write(p)
  174. d.buf = d.saveBuf.Bytes()
  175. d.saveBuf.Reset()
  176. }
  177. for len(d.buf) > 0 {
  178. err = d.parseHeaderFieldRepr()
  179. if err != nil {
  180. if err == errNeedMore {
  181. err = nil
  182. d.saveBuf.Write(d.buf)
  183. }
  184. break
  185. }
  186. }
  187. return len(p), err
  188. }
  189. // errNeedMore is an internal sentinel error value that means the
  190. // buffer is truncated and we need to read more data before we can
  191. // continue parsing.
  192. var errNeedMore = errors.New("need more data")
  193. type indexType int
  194. const (
  195. indexedTrue indexType = iota
  196. indexedFalse
  197. indexedNever
  198. )
  199. func (v indexType) indexed() bool { return v == indexedTrue }
  200. func (v indexType) sensitive() bool { return v == indexedNever }
  201. // returns errNeedMore if there isn't enough data available.
  202. // any other error is atal.
  203. // consumes d.buf iff it returns nil.
  204. // precondition: must be called with len(d.buf) > 0
  205. func (d *Decoder) parseHeaderFieldRepr() error {
  206. b := d.buf[0]
  207. switch {
  208. case b&128 != 0:
  209. // Indexed representation.
  210. // High bit set?
  211. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.1
  212. return d.parseFieldIndexed()
  213. case b&192 == 64:
  214. // 6.2.1 Literal Header Field with Incremental Indexing
  215. // 0b10xxxxxx: top two bits are 10
  216. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.1
  217. return d.parseFieldLiteral(6, indexedTrue)
  218. case b&240 == 0:
  219. // 6.2.2 Literal Header Field without Indexing
  220. // 0b0000xxxx: top four bits are 0000
  221. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.2
  222. return d.parseFieldLiteral(4, indexedFalse)
  223. case b&240 == 16:
  224. // 6.2.3 Literal Header Field never Indexed
  225. // 0b0001xxxx: top four bits are 0001
  226. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.2.3
  227. return d.parseFieldLiteral(4, indexedNever)
  228. case b&224 == 32:
  229. // 6.3 Dynamic Table Size Update
  230. // Top three bits are '001'.
  231. // http://http2.github.io/http2-spec/compression.html#rfc.section.6.3
  232. return d.parseDynamicTableSizeUpdate()
  233. }
  234. return DecodingError{errors.New("invalid encoding")}
  235. }
  236. // (same invariants and behavior as parseHeaderFieldRepr)
  237. func (d *Decoder) parseFieldIndexed() error {
  238. buf := d.buf
  239. idx, buf, err := readVarInt(7, buf)
  240. if err != nil {
  241. return err
  242. }
  243. hf, ok := d.at(idx)
  244. if !ok {
  245. return DecodingError{InvalidIndexError(idx)}
  246. }
  247. d.emit(HeaderField{Name: hf.Name, Value: hf.Value})
  248. d.buf = buf
  249. return nil
  250. }
  251. // (same invariants and behavior as parseHeaderFieldRepr)
  252. func (d *Decoder) parseFieldLiteral(n uint8, it indexType) error {
  253. buf := d.buf
  254. nameIdx, buf, err := readVarInt(n, buf)
  255. if err != nil {
  256. return err
  257. }
  258. var hf HeaderField
  259. if nameIdx > 0 {
  260. ihf, ok := d.at(nameIdx)
  261. if !ok {
  262. return DecodingError{InvalidIndexError(nameIdx)}
  263. }
  264. hf.Name = ihf.Name
  265. } else {
  266. hf.Name, buf, err = readString(buf)
  267. if err != nil {
  268. return err
  269. }
  270. }
  271. hf.Value, buf, err = readString(buf)
  272. if err != nil {
  273. return err
  274. }
  275. d.buf = buf
  276. if it.indexed() {
  277. d.dynTab.add(hf)
  278. }
  279. hf.Sensitive = it.sensitive()
  280. d.emit(hf)
  281. return nil
  282. }
  283. // (same invariants and behavior as parseHeaderFieldRepr)
  284. func (d *Decoder) parseDynamicTableSizeUpdate() error {
  285. buf := d.buf
  286. size, buf, err := readVarInt(5, buf)
  287. if err != nil {
  288. return err
  289. }
  290. if size > uint64(d.dynTab.allowedMaxSize) {
  291. return DecodingError{errors.New("dynamic table size update too large")}
  292. }
  293. d.dynTab.setMaxSize(uint32(size))
  294. d.buf = buf
  295. return nil
  296. }
  297. var errVarintOverflow = DecodingError{errors.New("varint integer overflow")}
  298. // readVarInt reads an unsigned variable length integer off the
  299. // beginning of p. n is the parameter as described in
  300. // http://http2.github.io/http2-spec/compression.html#rfc.section.5.1.
  301. //
  302. // n must always be between 1 and 8.
  303. //
  304. // The returned remain buffer is either a smaller suffix of p, or err != nil.
  305. // The error is errNeedMore if p doesn't contain a complete integer.
  306. func readVarInt(n byte, p []byte) (i uint64, remain []byte, err error) {
  307. if n < 1 || n > 8 {
  308. panic("bad n")
  309. }
  310. if len(p) == 0 {
  311. return 0, p, errNeedMore
  312. }
  313. i = uint64(p[0])
  314. if n < 8 {
  315. i &= (1 << uint64(n)) - 1
  316. }
  317. if i < (1<<uint64(n))-1 {
  318. return i, p[1:], nil
  319. }
  320. origP := p
  321. p = p[1:]
  322. var m uint64
  323. for len(p) > 0 {
  324. b := p[0]
  325. p = p[1:]
  326. i += uint64(b&127) << m
  327. if b&128 == 0 {
  328. return i, p, nil
  329. }
  330. m += 7
  331. if m >= 63 { // TODO: proper overflow check. making this up.
  332. return 0, origP, errVarintOverflow
  333. }
  334. }
  335. return 0, origP, errNeedMore
  336. }
  337. func readString(p []byte) (s string, remain []byte, err error) {
  338. if len(p) == 0 {
  339. return "", p, errNeedMore
  340. }
  341. isHuff := p[0]&128 != 0
  342. strLen, p, err := readVarInt(7, p)
  343. if err != nil {
  344. return "", p, err
  345. }
  346. if uint64(len(p)) < strLen {
  347. return "", p, errNeedMore
  348. }
  349. if !isHuff {
  350. return string(p[:strLen]), p[strLen:], nil
  351. }
  352. // TODO: optimize this garbage:
  353. var buf bytes.Buffer
  354. if _, err := HuffmanDecode(&buf, p[:strLen]); err != nil {
  355. return "", nil, err
  356. }
  357. return buf.String(), p[strLen:], nil
  358. }