encode.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  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. // SetMaxDynamicTableSizeLimit changes the maximum value that can be
  106. // specified in SetMaxDynamicTableSize to v. By default, it is set to
  107. // 4096, which is the same size of the default dynamic header table
  108. // size described in HPACK specification. If the current maximum
  109. // dynamic header table size is strictly greater than v, "Header Table
  110. // Size Update" will be done in the next WriteField call and the
  111. // maximum dynamic header table size is truncated to v.
  112. func (e *Encoder) SetMaxDynamicTableSizeLimit(v uint32) {
  113. e.maxSizeLimit = v
  114. if e.dynTab.maxSize > v {
  115. e.tableSizeUpdate = true
  116. e.dynTab.setMaxSize(v)
  117. }
  118. }
  119. // shouldIndex reports whether f should be indexed.
  120. func (e *Encoder) shouldIndex(f HeaderField) bool {
  121. return !f.Sensitive && f.Size() <= e.dynTab.maxSize
  122. }
  123. // appendIndexed appends index i, as encoded in "Indexed Header Field"
  124. // representation, to dst and returns the extended buffer.
  125. func appendIndexed(dst []byte, i uint64) []byte {
  126. first := len(dst)
  127. dst = appendVarInt(dst, 7, i)
  128. dst[first] |= 0x80
  129. return dst
  130. }
  131. // appendNewName appends f, as encoded in one of "Literal Header field
  132. // - New Name" representation variants, to dst and returns the
  133. // extended buffer.
  134. //
  135. // If f.Sensitive is true, "Never Indexed" representation is used. If
  136. // f.Sensitive is false and indexing is true, "Incremental Indexing"
  137. // representation is used.
  138. func appendNewName(dst []byte, f HeaderField, indexing bool) []byte {
  139. dst = append(dst, encodeTypeByte(indexing, f.Sensitive))
  140. dst = appendHpackString(dst, f.Name)
  141. return appendHpackString(dst, f.Value)
  142. }
  143. // appendIndexedName appends f and index i referring indexed name
  144. // entry, as encoded in one of "Literal Header field - Indexed Name"
  145. // representation variants, to dst and returns the extended buffer.
  146. //
  147. // If f.Sensitive is true, "Never Indexed" representation is used. If
  148. // f.Sensitive is false and indexing is true, "Incremental Indexing"
  149. // representation is used.
  150. func appendIndexedName(dst []byte, f HeaderField, i uint64, indexing bool) []byte {
  151. first := len(dst)
  152. var n byte
  153. if indexing {
  154. n = 6
  155. } else {
  156. n = 4
  157. }
  158. dst = appendVarInt(dst, n, i)
  159. dst[first] |= encodeTypeByte(indexing, f.Sensitive)
  160. return appendHpackString(dst, f.Value)
  161. }
  162. // appendTableSize appends v, as encoded in "Header Table Size Update"
  163. // representation, to dst and returns the extended buffer.
  164. func appendTableSize(dst []byte, v uint32) []byte {
  165. first := len(dst)
  166. dst = appendVarInt(dst, 5, uint64(v))
  167. dst[first] |= 0x20
  168. return dst
  169. }
  170. // appendVarInt appends i, as encoded in variable integer form using n
  171. // bit prefix, to dst and returns the extended buffer.
  172. //
  173. // See
  174. // http://http2.github.io/http2-spec/compression.html#integer.representation
  175. func appendVarInt(dst []byte, n byte, i uint64) []byte {
  176. k := uint64((1 << n) - 1)
  177. if i < k {
  178. return append(dst, byte(i))
  179. }
  180. dst = append(dst, byte(k))
  181. i -= k
  182. for ; i >= 128; i >>= 7 {
  183. dst = append(dst, byte(0x80|(i&0x7f)))
  184. }
  185. return append(dst, byte(i))
  186. }
  187. // appendHpackString appends s, as encoded in "String Literal"
  188. // representation, to dst and returns the extended buffer.
  189. //
  190. // s will be encoded in Huffman codes only when it produces strictly
  191. // shorter byte string.
  192. func appendHpackString(dst []byte, s string) []byte {
  193. huffmanLength := HuffmanEncodeLength(s)
  194. if huffmanLength < uint64(len(s)) {
  195. first := len(dst)
  196. dst = appendVarInt(dst, 7, huffmanLength)
  197. dst = AppendHuffmanString(dst, s)
  198. dst[first] |= 0x80
  199. } else {
  200. dst = appendVarInt(dst, 7, uint64(len(s)))
  201. dst = append(dst, s...)
  202. }
  203. return dst
  204. }
  205. // encodeTypeByte returns type byte. If sensitive is true, type byte
  206. // for "Never Indexed" representation is returned. If sensitive is
  207. // false and indexing is true, type byte for "Incremental Indexing"
  208. // representation is returned. Otherwise, type byte for "Without
  209. // Indexing" is returned.
  210. func encodeTypeByte(indexing, sensitive bool) byte {
  211. if sensitive {
  212. return 0x10
  213. }
  214. if indexing {
  215. return 0x40
  216. }
  217. return 0
  218. }