decode.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. // Copyright 2011 The Snappy-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 snappy
  5. import (
  6. "encoding/binary"
  7. "errors"
  8. "io"
  9. )
  10. var (
  11. // ErrCorrupt reports that the input is invalid.
  12. ErrCorrupt = errors.New("snappy: corrupt input")
  13. // ErrTooLarge reports that the uncompressed length is too large.
  14. ErrTooLarge = errors.New("snappy: decoded block is too large")
  15. // ErrUnsupported reports that the input isn't supported.
  16. ErrUnsupported = errors.New("snappy: unsupported input")
  17. errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length")
  18. )
  19. // DecodedLen returns the length of the decoded block.
  20. func DecodedLen(src []byte) (int, error) {
  21. v, _, err := decodedLen(src)
  22. return v, err
  23. }
  24. // decodedLen returns the length of the decoded block and the number of bytes
  25. // that the length header occupied.
  26. func decodedLen(src []byte) (blockLen, headerLen int, err error) {
  27. v, n := binary.Uvarint(src)
  28. if n <= 0 || v > 0xffffffff {
  29. return 0, 0, ErrCorrupt
  30. }
  31. const wordSize = 32 << (^uint(0) >> 32 & 1)
  32. if wordSize == 32 && v > 0x7fffffff {
  33. return 0, 0, ErrTooLarge
  34. }
  35. return int(v), n, nil
  36. }
  37. const (
  38. decodeErrCodeCorrupt = 1
  39. decodeErrCodeUnsupportedLiteralLength = 2
  40. )
  41. // Decode returns the decoded form of src. The returned slice may be a sub-
  42. // slice of dst if dst was large enough to hold the entire decoded block.
  43. // Otherwise, a newly allocated slice will be returned.
  44. //
  45. // The dst and src must not overlap. It is valid to pass a nil dst.
  46. //
  47. // Decode handles the Snappy block format, not the Snappy stream format.
  48. func Decode(dst, src []byte) ([]byte, error) {
  49. dLen, s, err := decodedLen(src)
  50. if err != nil {
  51. return nil, err
  52. }
  53. if dLen <= len(dst) {
  54. dst = dst[:dLen]
  55. } else {
  56. dst = make([]byte, dLen)
  57. }
  58. switch decode(dst, src[s:]) {
  59. case 0:
  60. return dst, nil
  61. case decodeErrCodeUnsupportedLiteralLength:
  62. return nil, errUnsupportedLiteralLength
  63. }
  64. return nil, ErrCorrupt
  65. }
  66. // NewReader returns a new Reader that decompresses from r, using the framing
  67. // format described at
  68. // https://github.com/google/snappy/blob/master/framing_format.txt
  69. func NewReader(r io.Reader) *Reader {
  70. return &Reader{
  71. r: r,
  72. decoded: make([]byte, maxBlockSize),
  73. buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize),
  74. }
  75. }
  76. // Reader is an io.Reader that can read Snappy-compressed bytes.
  77. //
  78. // Reader handles the Snappy stream format, not the Snappy block format.
  79. type Reader struct {
  80. r io.Reader
  81. err error
  82. decoded []byte
  83. buf []byte
  84. // decoded[i:j] contains decoded bytes that have not yet been passed on.
  85. i, j int
  86. readHeader bool
  87. }
  88. // Reset discards any buffered data, resets all state, and switches the Snappy
  89. // reader to read from r. This permits reusing a Reader rather than allocating
  90. // a new one.
  91. func (r *Reader) Reset(reader io.Reader) {
  92. r.r = reader
  93. r.err = nil
  94. r.i = 0
  95. r.j = 0
  96. r.readHeader = false
  97. }
  98. func (r *Reader) readFull(p []byte, allowEOF bool) (ok bool) {
  99. if _, r.err = io.ReadFull(r.r, p); r.err != nil {
  100. if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) {
  101. r.err = ErrCorrupt
  102. }
  103. return false
  104. }
  105. return true
  106. }
  107. func (r *Reader) fill() error {
  108. for r.i >= r.j {
  109. if !r.readFull(r.buf[:4], true) {
  110. return r.err
  111. }
  112. chunkType := r.buf[0]
  113. if !r.readHeader {
  114. if chunkType != chunkTypeStreamIdentifier {
  115. r.err = ErrCorrupt
  116. return r.err
  117. }
  118. r.readHeader = true
  119. }
  120. chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16
  121. if chunkLen > len(r.buf) {
  122. r.err = ErrUnsupported
  123. return r.err
  124. }
  125. // The chunk types are specified at
  126. // https://github.com/google/snappy/blob/master/framing_format.txt
  127. switch chunkType {
  128. case chunkTypeCompressedData:
  129. // Section 4.2. Compressed data (chunk type 0x00).
  130. if chunkLen < checksumSize {
  131. r.err = ErrCorrupt
  132. return r.err
  133. }
  134. buf := r.buf[:chunkLen]
  135. if !r.readFull(buf, false) {
  136. return r.err
  137. }
  138. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  139. buf = buf[checksumSize:]
  140. n, err := DecodedLen(buf)
  141. if err != nil {
  142. r.err = err
  143. return r.err
  144. }
  145. if n > len(r.decoded) {
  146. r.err = ErrCorrupt
  147. return r.err
  148. }
  149. if _, err := Decode(r.decoded, buf); err != nil {
  150. r.err = err
  151. return r.err
  152. }
  153. if crc(r.decoded[:n]) != checksum {
  154. r.err = ErrCorrupt
  155. return r.err
  156. }
  157. r.i, r.j = 0, n
  158. continue
  159. case chunkTypeUncompressedData:
  160. // Section 4.3. Uncompressed data (chunk type 0x01).
  161. if chunkLen < checksumSize {
  162. r.err = ErrCorrupt
  163. return r.err
  164. }
  165. buf := r.buf[:checksumSize]
  166. if !r.readFull(buf, false) {
  167. return r.err
  168. }
  169. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  170. // Read directly into r.decoded instead of via r.buf.
  171. n := chunkLen - checksumSize
  172. if n > len(r.decoded) {
  173. r.err = ErrCorrupt
  174. return r.err
  175. }
  176. if !r.readFull(r.decoded[:n], false) {
  177. return r.err
  178. }
  179. if crc(r.decoded[:n]) != checksum {
  180. r.err = ErrCorrupt
  181. return r.err
  182. }
  183. r.i, r.j = 0, n
  184. continue
  185. case chunkTypeStreamIdentifier:
  186. // Section 4.1. Stream identifier (chunk type 0xff).
  187. if chunkLen != len(magicBody) {
  188. r.err = ErrCorrupt
  189. return r.err
  190. }
  191. if !r.readFull(r.buf[:len(magicBody)], false) {
  192. return r.err
  193. }
  194. for i := 0; i < len(magicBody); i++ {
  195. if r.buf[i] != magicBody[i] {
  196. r.err = ErrCorrupt
  197. return r.err
  198. }
  199. }
  200. continue
  201. }
  202. if chunkType <= 0x7f {
  203. // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f).
  204. r.err = ErrUnsupported
  205. return r.err
  206. }
  207. // Section 4.4 Padding (chunk type 0xfe).
  208. // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd).
  209. if !r.readFull(r.buf[:chunkLen], false) {
  210. return r.err
  211. }
  212. }
  213. return nil
  214. }
  215. // Read satisfies the io.Reader interface.
  216. func (r *Reader) Read(p []byte) (int, error) {
  217. if r.err != nil {
  218. return 0, r.err
  219. }
  220. if err := r.fill(); err != nil {
  221. return 0, err
  222. }
  223. n := copy(p, r.decoded[r.i:r.j])
  224. r.i += n
  225. return n, nil
  226. }
  227. // ReadByte satisfies the io.ByteReader interface.
  228. func (r *Reader) ReadByte() (byte, error) {
  229. if r.err != nil {
  230. return 0, r.err
  231. }
  232. if err := r.fill(); err != nil {
  233. return 0, err
  234. }
  235. c := r.decoded[r.i]
  236. r.i++
  237. return c, nil
  238. }