encode.go 7.2 KB

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