encode.go 7.1 KB

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