encode.go 7.1 KB

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