You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

223 lines
5.3 KiB

  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. "bytes"
  7. "errors"
  8. "io"
  9. "sync"
  10. )
  11. var bufPool = sync.Pool{
  12. New: func() interface{} { return new(bytes.Buffer) },
  13. }
  14. // HuffmanDecode decodes the string in v and writes the expanded
  15. // result to w, returning the number of bytes written to w and the
  16. // Write call's return value. At most one Write call is made.
  17. func HuffmanDecode(w io.Writer, v []byte) (int, error) {
  18. buf := bufPool.Get().(*bytes.Buffer)
  19. buf.Reset()
  20. defer bufPool.Put(buf)
  21. if err := huffmanDecode(buf, 0, v); err != nil {
  22. return 0, err
  23. }
  24. return w.Write(buf.Bytes())
  25. }
  26. // HuffmanDecodeToString decodes the string in v.
  27. func HuffmanDecodeToString(v []byte) (string, error) {
  28. buf := bufPool.Get().(*bytes.Buffer)
  29. buf.Reset()
  30. defer bufPool.Put(buf)
  31. if err := huffmanDecode(buf, 0, v); err != nil {
  32. return "", err
  33. }
  34. return buf.String(), nil
  35. }
  36. // ErrInvalidHuffman is returned for errors found decoding
  37. // Huffman-encoded strings.
  38. var ErrInvalidHuffman = errors.New("hpack: invalid Huffman-encoded data")
  39. // huffmanDecode decodes v to buf.
  40. // If maxLen is greater than 0, attempts to write more to buf than
  41. // maxLen bytes will return ErrStringLength.
  42. func huffmanDecode(buf *bytes.Buffer, maxLen int, v []byte) error {
  43. rootHuffmanNode := getRootHuffmanNode()
  44. n := rootHuffmanNode
  45. // cur is the bit buffer that has not been fed into n.
  46. // cbits is the number of low order bits in cur that are valid.
  47. // sbits is the number of bits of the symbol prefix being decoded.
  48. cur, cbits, sbits := uint(0), uint8(0), uint8(0)
  49. for _, b := range v {
  50. cur = cur<<8 | uint(b)
  51. cbits += 8
  52. sbits += 8
  53. for cbits >= 8 {
  54. idx := byte(cur >> (cbits - 8))
  55. n = n.children[idx]
  56. if n == nil {
  57. return ErrInvalidHuffman
  58. }
  59. if n.children == nil {
  60. if maxLen != 0 && buf.Len() == maxLen {
  61. return ErrStringLength
  62. }
  63. buf.WriteByte(n.sym)
  64. cbits -= n.codeLen
  65. n = rootHuffmanNode
  66. sbits = cbits
  67. } else {
  68. cbits -= 8
  69. }
  70. }
  71. }
  72. for cbits > 0 {
  73. n = n.children[byte(cur<<(8-cbits))]
  74. if n == nil {
  75. return ErrInvalidHuffman
  76. }
  77. if n.children != nil || n.codeLen > cbits {
  78. break
  79. }
  80. if maxLen != 0 && buf.Len() == maxLen {
  81. return ErrStringLength
  82. }
  83. buf.WriteByte(n.sym)
  84. cbits -= n.codeLen
  85. n = rootHuffmanNode
  86. sbits = cbits
  87. }
  88. if sbits > 7 {
  89. // Either there was an incomplete symbol, or overlong padding.
  90. // Both are decoding errors per RFC 7541 section 5.2.
  91. return ErrInvalidHuffman
  92. }
  93. if mask := uint(1<<cbits - 1); cur&mask != mask {
  94. // Trailing bits must be a prefix of EOS per RFC 7541 section 5.2.
  95. return ErrInvalidHuffman
  96. }
  97. return nil
  98. }
  99. type node struct {
  100. // children is non-nil for internal nodes
  101. children *[256]*node
  102. // The following are only valid if children is nil:
  103. codeLen uint8 // number of bits that led to the output of sym
  104. sym byte // output symbol
  105. }
  106. func newInternalNode() *node {
  107. return &node{children: new([256]*node)}
  108. }
  109. var (
  110. buildRootOnce sync.Once
  111. lazyRootHuffmanNode *node
  112. )
  113. func getRootHuffmanNode() *node {
  114. buildRootOnce.Do(buildRootHuffmanNode)
  115. return lazyRootHuffmanNode
  116. }
  117. func buildRootHuffmanNode() {
  118. if len(huffmanCodes) != 256 {
  119. panic("unexpected size")
  120. }
  121. lazyRootHuffmanNode = newInternalNode()
  122. for i, code := range huffmanCodes {
  123. addDecoderNode(byte(i), code, huffmanCodeLen[i])
  124. }
  125. }
  126. func addDecoderNode(sym byte, code uint32, codeLen uint8) {
  127. cur := lazyRootHuffmanNode
  128. for codeLen > 8 {
  129. codeLen -= 8
  130. i := uint8(code >> codeLen)
  131. if cur.children[i] == nil {
  132. cur.children[i] = newInternalNode()
  133. }
  134. cur = cur.children[i]
  135. }
  136. shift := 8 - codeLen
  137. start, end := int(uint8(code<<shift)), int(1<<shift)
  138. for i := start; i < start+end; i++ {
  139. cur.children[i] = &node{sym: sym, codeLen: codeLen}
  140. }
  141. }
  142. // AppendHuffmanString appends s, as encoded in Huffman codes, to dst
  143. // and returns the extended buffer.
  144. func AppendHuffmanString(dst []byte, s string) []byte {
  145. rembits := uint8(8)
  146. for i := 0; i < len(s); i++ {
  147. if rembits == 8 {
  148. dst = append(dst, 0)
  149. }
  150. dst, rembits = appendByteToHuffmanCode(dst, rembits, s[i])
  151. }
  152. if rembits < 8 {
  153. // special EOS symbol
  154. code := uint32(0x3fffffff)
  155. nbits := uint8(30)
  156. t := uint8(code >> (nbits - rembits))
  157. dst[len(dst)-1] |= t
  158. }
  159. return dst
  160. }
  161. // HuffmanEncodeLength returns the number of bytes required to encode
  162. // s in Huffman codes. The result is round up to byte boundary.
  163. func HuffmanEncodeLength(s string) uint64 {
  164. n := uint64(0)
  165. for i := 0; i < len(s); i++ {
  166. n += uint64(huffmanCodeLen[s[i]])
  167. }
  168. return (n + 7) / 8
  169. }
  170. // appendByteToHuffmanCode appends Huffman code for c to dst and
  171. // returns the extended buffer and the remaining bits in the last
  172. // element. The appending is not byte aligned and the remaining bits
  173. // in the last element of dst is given in rembits.
  174. func appendByteToHuffmanCode(dst []byte, rembits uint8, c byte) ([]byte, uint8) {
  175. code := huffmanCodes[c]
  176. nbits := huffmanCodeLen[c]
  177. for {
  178. if rembits > nbits {
  179. t := uint8(code << (rembits - nbits))
  180. dst[len(dst)-1] |= t
  181. rembits -= nbits
  182. break
  183. }
  184. t := uint8(code >> (nbits - rembits))
  185. dst[len(dst)-1] |= t
  186. nbits -= rembits
  187. rembits = 8
  188. if nbits == 0 {
  189. break
  190. }
  191. dst = append(dst, 0)
  192. }
  193. return dst, rembits
  194. }