encode.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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
  5. import (
  6. "io"
  7. )
  8. const (
  9. uint32Max = ^uint32(0)
  10. initialHeaderTableSize = 4096
  11. )
  12. type Encoder struct {
  13. dynTab dynamicTable
  14. // minSize is the minimum table size set by
  15. // SetMaxDynamicTableSize after the previous Header Table Size
  16. // Update.
  17. minSize uint32
  18. // maxSizeLimit is the maximum table size this encoder
  19. // supports. This will protect the encoder from too large
  20. // size.
  21. maxSizeLimit uint32
  22. // tableSizeUpdate indicates whether "Header Table Size
  23. // Update" is required.
  24. tableSizeUpdate bool
  25. w io.Writer
  26. buf []byte
  27. }
  28. // NewEncoder returns a new Encoder which performs HPACK encoding. An
  29. // encoded data is written to w.
  30. func NewEncoder(w io.Writer) *Encoder {
  31. e := &Encoder{
  32. minSize: uint32Max,
  33. maxSizeLimit: initialHeaderTableSize,
  34. tableSizeUpdate: false,
  35. w: w,
  36. }
  37. e.dynTab.setMaxSize(initialHeaderTableSize)
  38. return e
  39. }
  40. // WriteField encodes f into a single Write to e's underlying Writer.
  41. // This function may also produce bytes for "Header Table Size Update"
  42. // if necessary. If produced, it is done before encoding f.
  43. func (e *Encoder) WriteField(f HeaderField) error {
  44. e.buf = e.buf[:0]
  45. if e.tableSizeUpdate {
  46. e.tableSizeUpdate = false
  47. if e.minSize < e.dynTab.maxSize {
  48. e.buf = appendTableSize(e.buf, e.minSize)
  49. }
  50. e.minSize = uint32Max
  51. e.buf = appendTableSize(e.buf, e.dynTab.maxSize)
  52. }
  53. idx, nameValueMatch := e.searchTable(f)
  54. if nameValueMatch {
  55. e.buf = appendIndexed(e.buf, idx)
  56. } else {
  57. indexing := e.shouldIndex(f)
  58. if indexing {
  59. e.dynTab.add(f)
  60. }
  61. if idx == 0 {
  62. e.buf = appendNewName(e.buf, f, indexing)
  63. } else {
  64. e.buf = appendIndexedName(e.buf, f, idx, indexing)
  65. }
  66. }
  67. n, err := e.w.Write(e.buf)
  68. if err == nil && n != len(e.buf) {
  69. err = io.ErrShortWrite
  70. }
  71. return err
  72. }
  73. // searchTable searches f in both stable and dynamic header tables.
  74. // The static header table is searched first. Only when there is no
  75. // exact match for both name and value, the dynamic header table is
  76. // then searched. If there is no match, i is 0. If both name and value
  77. // match, i is the matched index and nameValueMatch becomes true. If
  78. // only name matches, i points to that index and nameValueMatch
  79. // becomes false.
  80. func (e *Encoder) searchTable(f HeaderField) (i uint64, nameValueMatch bool) {
  81. for idx, hf := range staticTable {
  82. if hf.Name != f.Name {
  83. continue
  84. }
  85. if i == 0 {
  86. i = uint64(idx + 1)
  87. }
  88. if f.Sensitive || hf.Value != f.Value {
  89. continue
  90. }
  91. return uint64(idx + 1), true
  92. }
  93. j, nameValueMatch := e.dynTab.search(f)
  94. if nameValueMatch || (i == 0 && j != 0) {
  95. i = j + uint64(len(staticTable))
  96. }
  97. return
  98. }
  99. // SetMaxDynamicTableSize changes the dynamic header table size to v.
  100. // The actual size is bounded by the value passed to
  101. // SetMaxDynamicTableSizeLimit.
  102. func (e *Encoder) SetMaxDynamicTableSize(v uint32) {
  103. if v > e.maxSizeLimit {
  104. v = e.maxSizeLimit
  105. }
  106. if v < e.minSize {
  107. e.minSize = v
  108. }
  109. e.tableSizeUpdate = true
  110. e.dynTab.setMaxSize(v)
  111. }
  112. // SetMaxDynamicTableSizeLimit changes the maximum value that can be
  113. // specified in SetMaxDynamicTableSize to v. By default, it is set to
  114. // 4096, which is the same size of the default dynamic header table
  115. // size described in HPACK specification. If the current maximum
  116. // dynamic header table size is strictly greater than v, "Header Table
  117. // Size Update" will be done in the next WriteField call and the
  118. // maximum dynamic header table size is truncated to v.
  119. func (e *Encoder) SetMaxDynamicTableSizeLimit(v uint32) {
  120. e.maxSizeLimit = v
  121. if e.dynTab.maxSize > v {
  122. e.tableSizeUpdate = true
  123. e.dynTab.setMaxSize(v)
  124. }
  125. }
  126. // shouldIndex reports whether f should be indexed.
  127. func (e *Encoder) shouldIndex(f HeaderField) bool {
  128. return !f.Sensitive && f.Size() <= e.dynTab.maxSize
  129. }
  130. // appendIndexed appends index i, as encoded in "Indexed Header Field"
  131. // representation, to dst and returns the extended buffer.
  132. func appendIndexed(dst []byte, i uint64) []byte {
  133. first := len(dst)
  134. dst = appendVarInt(dst, 7, i)
  135. dst[first] |= 0x80
  136. return dst
  137. }
  138. // appendNewName appends f, as encoded in one of "Literal Header field
  139. // - New Name" representation variants, to dst and returns the
  140. // extended buffer.
  141. //
  142. // If f.Sensitive is true, "Never Indexed" representation is used. If
  143. // f.Sensitive is false and indexing is true, "Inremental Indexing"
  144. // representation is used.
  145. func appendNewName(dst []byte, f HeaderField, indexing bool) []byte {
  146. dst = append(dst, encodeTypeByte(indexing, f.Sensitive))
  147. dst = appendHpackString(dst, f.Name)
  148. return appendHpackString(dst, f.Value)
  149. }
  150. // appendIndexedName appends f and index i referring indexed name
  151. // entry, as encoded in one of "Literal Header field - Indexed Name"
  152. // representation variants, to dst and returns the extended buffer.
  153. //
  154. // If f.Sensitive is true, "Never Indexed" representation is used. If
  155. // f.Sensitive is false and indexing is true, "Incremental Indexing"
  156. // representation is used.
  157. func appendIndexedName(dst []byte, f HeaderField, i uint64, indexing bool) []byte {
  158. first := len(dst)
  159. var n byte
  160. if indexing {
  161. n = 6
  162. } else {
  163. n = 4
  164. }
  165. dst = appendVarInt(dst, n, i)
  166. dst[first] |= encodeTypeByte(indexing, f.Sensitive)
  167. return appendHpackString(dst, f.Value)
  168. }
  169. // appendTableSize appends v, as encoded in "Header Table Size Update"
  170. // representation, to dst and returns the extended buffer.
  171. func appendTableSize(dst []byte, v uint32) []byte {
  172. first := len(dst)
  173. dst = appendVarInt(dst, 5, uint64(v))
  174. dst[first] |= 0x20
  175. return dst
  176. }
  177. // appendVarInt appends i, as encoded in variable integer form using n
  178. // bit prefix, to dst and returns the extended buffer.
  179. //
  180. // See
  181. // http://http2.github.io/http2-spec/compression.html#integer.representation
  182. func appendVarInt(dst []byte, n byte, i uint64) []byte {
  183. k := uint64((1 << n) - 1)
  184. if i < k {
  185. return append(dst, byte(i))
  186. }
  187. dst = append(dst, byte(k))
  188. i -= k
  189. for ; i >= 128; i >>= 7 {
  190. dst = append(dst, byte(0x80|(i&0x7f)))
  191. }
  192. return append(dst, byte(i))
  193. }
  194. // appendHpackString appends s, as encoded in "String Literal"
  195. // representation, to dst and returns the the extended buffer.
  196. //
  197. // s will be encoded in Huffman codes only when it produces strictly
  198. // shorter byte string.
  199. func appendHpackString(dst []byte, s string) []byte {
  200. huffmanLength := HuffmanEncodeLength(s)
  201. if huffmanLength < uint64(len(s)) {
  202. first := len(dst)
  203. dst = appendVarInt(dst, 7, huffmanLength)
  204. dst = AppendHuffmanString(dst, s)
  205. dst[first] |= 0x80
  206. } else {
  207. dst = appendVarInt(dst, 7, uint64(len(s)))
  208. dst = append(dst, s...)
  209. }
  210. return dst
  211. }
  212. // encodeTypeByte returns type byte. If sensitive is true, type byte
  213. // for "Never Indexed" representation is returned. If sensitive is
  214. // false and indexing is true, type byte for "Incremental Indexing"
  215. // representation is returned. Otherwise, type byte for "Without
  216. // Indexing" is returned.
  217. func encodeTypeByte(indexing, sensitive bool) byte {
  218. if sensitive {
  219. return 0x10
  220. }
  221. if indexing {
  222. return 0x40
  223. }
  224. return 0
  225. }