decode.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. errUnsupportedCopy4Tag = errors.New("snappy: unsupported COPY_4 tag")
  18. errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length")
  19. )
  20. // DecodedLen returns the length of the decoded block.
  21. func DecodedLen(src []byte) (int, error) {
  22. v, _, err := decodedLen(src)
  23. return v, err
  24. }
  25. // decodedLen returns the length of the decoded block and the number of bytes
  26. // that the length header occupied.
  27. func decodedLen(src []byte) (blockLen, headerLen int, err error) {
  28. v, n := binary.Uvarint(src)
  29. if n <= 0 || v > 0xffffffff {
  30. return 0, 0, ErrCorrupt
  31. }
  32. const wordSize = 32 << (^uint(0) >> 32 & 1)
  33. if wordSize == 32 && v > 0x7fffffff {
  34. return 0, 0, ErrTooLarge
  35. }
  36. return int(v), n, nil
  37. }
  38. // Decode returns the decoded form of src. The returned slice may be a sub-
  39. // slice of dst if dst was large enough to hold the entire decoded block.
  40. // Otherwise, a newly allocated slice will be returned.
  41. //
  42. // The dst and src must not overlap. It is valid to pass a nil dst.
  43. func Decode(dst, src []byte) ([]byte, error) {
  44. dLen, s, err := decodedLen(src)
  45. if err != nil {
  46. return nil, err
  47. }
  48. if dLen <= len(dst) {
  49. dst = dst[:dLen]
  50. } else {
  51. dst = make([]byte, dLen)
  52. }
  53. var d, offset, length int
  54. for s < len(src) {
  55. switch src[s] & 0x03 {
  56. case tagLiteral:
  57. x := uint32(src[s] >> 2)
  58. switch {
  59. case x < 60:
  60. s++
  61. case x == 60:
  62. s += 2
  63. if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
  64. return nil, ErrCorrupt
  65. }
  66. x = uint32(src[s-1])
  67. case x == 61:
  68. s += 3
  69. if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
  70. return nil, ErrCorrupt
  71. }
  72. x = uint32(src[s-2]) | uint32(src[s-1])<<8
  73. case x == 62:
  74. s += 4
  75. if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
  76. return nil, ErrCorrupt
  77. }
  78. x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16
  79. case x == 63:
  80. s += 5
  81. if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
  82. return nil, ErrCorrupt
  83. }
  84. x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24
  85. }
  86. length = int(x) + 1
  87. if length <= 0 {
  88. return nil, errUnsupportedLiteralLength
  89. }
  90. if length > len(dst)-d || length > len(src)-s {
  91. return nil, ErrCorrupt
  92. }
  93. copy(dst[d:], src[s:s+length])
  94. d += length
  95. s += length
  96. continue
  97. case tagCopy1:
  98. s += 2
  99. if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
  100. return nil, ErrCorrupt
  101. }
  102. length = 4 + int(src[s-2])>>2&0x7
  103. offset = int(src[s-2])&0xe0<<3 | int(src[s-1])
  104. case tagCopy2:
  105. s += 3
  106. if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
  107. return nil, ErrCorrupt
  108. }
  109. length = 1 + int(src[s-3])>>2
  110. offset = int(src[s-2]) | int(src[s-1])<<8
  111. case tagCopy4:
  112. return nil, errUnsupportedCopy4Tag
  113. }
  114. if offset <= 0 || d < offset || length > len(dst)-d {
  115. return nil, ErrCorrupt
  116. }
  117. // Copy from an earlier sub-slice of dst to a later sub-slice. Unlike
  118. // the built-in copy function, this byte-by-byte copy always runs
  119. // forwards, even if the slices overlap. Conceptually, this is:
  120. //
  121. // d += forwardCopy(dst[d:d+length], dst[d-offset:])
  122. for end := d + length; d != end; d++ {
  123. dst[d] = dst[d-offset]
  124. }
  125. }
  126. if d != dLen {
  127. return nil, ErrCorrupt
  128. }
  129. return dst[:d], nil
  130. }
  131. // NewReader returns a new Reader that decompresses from r, using the framing
  132. // format described at
  133. // https://github.com/google/snappy/blob/master/framing_format.txt
  134. func NewReader(r io.Reader) *Reader {
  135. return &Reader{
  136. r: r,
  137. decoded: make([]byte, maxBlockSize),
  138. buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize),
  139. }
  140. }
  141. // Reader is an io.Reader that can read Snappy-compressed bytes.
  142. type Reader struct {
  143. r io.Reader
  144. err error
  145. decoded []byte
  146. buf []byte
  147. // decoded[i:j] contains decoded bytes that have not yet been passed on.
  148. i, j int
  149. readHeader bool
  150. }
  151. // Reset discards any buffered data, resets all state, and switches the Snappy
  152. // reader to read from r. This permits reusing a Reader rather than allocating
  153. // a new one.
  154. func (r *Reader) Reset(reader io.Reader) {
  155. r.r = reader
  156. r.err = nil
  157. r.i = 0
  158. r.j = 0
  159. r.readHeader = false
  160. }
  161. func (r *Reader) readFull(p []byte) (ok bool) {
  162. if _, r.err = io.ReadFull(r.r, p); r.err != nil {
  163. if r.err == io.ErrUnexpectedEOF {
  164. r.err = ErrCorrupt
  165. }
  166. return false
  167. }
  168. return true
  169. }
  170. // Read satisfies the io.Reader interface.
  171. func (r *Reader) Read(p []byte) (int, error) {
  172. if r.err != nil {
  173. return 0, r.err
  174. }
  175. for {
  176. if r.i < r.j {
  177. n := copy(p, r.decoded[r.i:r.j])
  178. r.i += n
  179. return n, nil
  180. }
  181. if !r.readFull(r.buf[:4]) {
  182. return 0, r.err
  183. }
  184. chunkType := r.buf[0]
  185. if !r.readHeader {
  186. if chunkType != chunkTypeStreamIdentifier {
  187. r.err = ErrCorrupt
  188. return 0, r.err
  189. }
  190. r.readHeader = true
  191. }
  192. chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16
  193. if chunkLen > len(r.buf) {
  194. r.err = ErrUnsupported
  195. return 0, r.err
  196. }
  197. // The chunk types are specified at
  198. // https://github.com/google/snappy/blob/master/framing_format.txt
  199. switch chunkType {
  200. case chunkTypeCompressedData:
  201. // Section 4.2. Compressed data (chunk type 0x00).
  202. if chunkLen < checksumSize {
  203. r.err = ErrCorrupt
  204. return 0, r.err
  205. }
  206. buf := r.buf[:chunkLen]
  207. if !r.readFull(buf) {
  208. return 0, r.err
  209. }
  210. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  211. buf = buf[checksumSize:]
  212. n, err := DecodedLen(buf)
  213. if err != nil {
  214. r.err = err
  215. return 0, r.err
  216. }
  217. if n > len(r.decoded) {
  218. r.err = ErrCorrupt
  219. return 0, r.err
  220. }
  221. if _, err := Decode(r.decoded, buf); err != nil {
  222. r.err = err
  223. return 0, r.err
  224. }
  225. if crc(r.decoded[:n]) != checksum {
  226. r.err = ErrCorrupt
  227. return 0, r.err
  228. }
  229. r.i, r.j = 0, n
  230. continue
  231. case chunkTypeUncompressedData:
  232. // Section 4.3. Uncompressed data (chunk type 0x01).
  233. if chunkLen < checksumSize {
  234. r.err = ErrCorrupt
  235. return 0, r.err
  236. }
  237. buf := r.buf[:checksumSize]
  238. if !r.readFull(buf) {
  239. return 0, r.err
  240. }
  241. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  242. // Read directly into r.decoded instead of via r.buf.
  243. n := chunkLen - checksumSize
  244. if !r.readFull(r.decoded[:n]) {
  245. return 0, r.err
  246. }
  247. if crc(r.decoded[:n]) != checksum {
  248. r.err = ErrCorrupt
  249. return 0, r.err
  250. }
  251. r.i, r.j = 0, n
  252. continue
  253. case chunkTypeStreamIdentifier:
  254. // Section 4.1. Stream identifier (chunk type 0xff).
  255. if chunkLen != len(magicBody) {
  256. r.err = ErrCorrupt
  257. return 0, r.err
  258. }
  259. if !r.readFull(r.buf[:len(magicBody)]) {
  260. return 0, r.err
  261. }
  262. for i := 0; i < len(magicBody); i++ {
  263. if r.buf[i] != magicBody[i] {
  264. r.err = ErrCorrupt
  265. return 0, r.err
  266. }
  267. }
  268. continue
  269. }
  270. if chunkType <= 0x7f {
  271. // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f).
  272. r.err = ErrUnsupported
  273. return 0, r.err
  274. }
  275. // Section 4.4 Padding (chunk type 0xfe).
  276. // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd).
  277. if !r.readFull(r.buf[:chunkLen]) {
  278. return 0, r.err
  279. }
  280. }
  281. }