decode.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. // 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. for end := d + length; d != end; d++ {
  118. dst[d] = dst[d-offset]
  119. }
  120. }
  121. if d != dLen {
  122. return nil, ErrCorrupt
  123. }
  124. return dst[:d], nil
  125. }
  126. // NewReader returns a new Reader that decompresses from r, using the framing
  127. // format described at
  128. // https://github.com/google/snappy/blob/master/framing_format.txt
  129. func NewReader(r io.Reader) *Reader {
  130. return &Reader{
  131. r: r,
  132. decoded: make([]byte, maxBlockSize),
  133. buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize),
  134. }
  135. }
  136. // Reader is an io.Reader that can read Snappy-compressed bytes.
  137. type Reader struct {
  138. r io.Reader
  139. err error
  140. decoded []byte
  141. buf []byte
  142. // decoded[i:j] contains decoded bytes that have not yet been passed on.
  143. i, j int
  144. readHeader bool
  145. }
  146. // Reset discards any buffered data, resets all state, and switches the Snappy
  147. // reader to read from r. This permits reusing a Reader rather than allocating
  148. // a new one.
  149. func (r *Reader) Reset(reader io.Reader) {
  150. r.r = reader
  151. r.err = nil
  152. r.i = 0
  153. r.j = 0
  154. r.readHeader = false
  155. }
  156. func (r *Reader) readFull(p []byte) (ok bool) {
  157. if _, r.err = io.ReadFull(r.r, p); r.err != nil {
  158. if r.err == io.ErrUnexpectedEOF {
  159. r.err = ErrCorrupt
  160. }
  161. return false
  162. }
  163. return true
  164. }
  165. // Read satisfies the io.Reader interface.
  166. func (r *Reader) Read(p []byte) (int, error) {
  167. if r.err != nil {
  168. return 0, r.err
  169. }
  170. for {
  171. if r.i < r.j {
  172. n := copy(p, r.decoded[r.i:r.j])
  173. r.i += n
  174. return n, nil
  175. }
  176. if !r.readFull(r.buf[:4]) {
  177. return 0, r.err
  178. }
  179. chunkType := r.buf[0]
  180. if !r.readHeader {
  181. if chunkType != chunkTypeStreamIdentifier {
  182. r.err = ErrCorrupt
  183. return 0, r.err
  184. }
  185. r.readHeader = true
  186. }
  187. chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16
  188. if chunkLen > len(r.buf) {
  189. r.err = ErrUnsupported
  190. return 0, r.err
  191. }
  192. // The chunk types are specified at
  193. // https://github.com/google/snappy/blob/master/framing_format.txt
  194. switch chunkType {
  195. case chunkTypeCompressedData:
  196. // Section 4.2. Compressed data (chunk type 0x00).
  197. if chunkLen < checksumSize {
  198. r.err = ErrCorrupt
  199. return 0, r.err
  200. }
  201. buf := r.buf[:chunkLen]
  202. if !r.readFull(buf) {
  203. return 0, r.err
  204. }
  205. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  206. buf = buf[checksumSize:]
  207. n, err := DecodedLen(buf)
  208. if err != nil {
  209. r.err = err
  210. return 0, r.err
  211. }
  212. if n > len(r.decoded) {
  213. r.err = ErrCorrupt
  214. return 0, r.err
  215. }
  216. if _, err := Decode(r.decoded, buf); err != nil {
  217. r.err = err
  218. return 0, r.err
  219. }
  220. if crc(r.decoded[:n]) != checksum {
  221. r.err = ErrCorrupt
  222. return 0, r.err
  223. }
  224. r.i, r.j = 0, n
  225. continue
  226. case chunkTypeUncompressedData:
  227. // Section 4.3. Uncompressed data (chunk type 0x01).
  228. if chunkLen < checksumSize {
  229. r.err = ErrCorrupt
  230. return 0, r.err
  231. }
  232. buf := r.buf[:checksumSize]
  233. if !r.readFull(buf) {
  234. return 0, r.err
  235. }
  236. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  237. // Read directly into r.decoded instead of via r.buf.
  238. n := chunkLen - checksumSize
  239. if !r.readFull(r.decoded[:n]) {
  240. return 0, r.err
  241. }
  242. if crc(r.decoded[:n]) != checksum {
  243. r.err = ErrCorrupt
  244. return 0, r.err
  245. }
  246. r.i, r.j = 0, n
  247. continue
  248. case chunkTypeStreamIdentifier:
  249. // Section 4.1. Stream identifier (chunk type 0xff).
  250. if chunkLen != len(magicBody) {
  251. r.err = ErrCorrupt
  252. return 0, r.err
  253. }
  254. if !r.readFull(r.buf[:len(magicBody)]) {
  255. return 0, r.err
  256. }
  257. for i := 0; i < len(magicBody); i++ {
  258. if r.buf[i] != magicBody[i] {
  259. r.err = ErrCorrupt
  260. return 0, r.err
  261. }
  262. }
  263. continue
  264. }
  265. if chunkType <= 0x7f {
  266. // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f).
  267. r.err = ErrUnsupported
  268. return 0, r.err
  269. }
  270. // Section 4.4 Padding (chunk type 0xfe).
  271. // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd).
  272. if !r.readFull(r.buf[:chunkLen]) {
  273. return 0, r.err
  274. }
  275. }
  276. }