Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 

1047 linhas
26 KiB

  1. // Copyright 2011 The Snappy-Go Authors. All rights reserved.
  2. // Copyright (c) 2019 Klaus Post. All rights reserved.
  3. // Use of this source code is governed by a BSD-style
  4. // license that can be found in the LICENSE file.
  5. package s2
  6. import (
  7. "encoding/binary"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "math"
  13. "runtime"
  14. "sync"
  15. )
  16. var (
  17. // ErrCorrupt reports that the input is invalid.
  18. ErrCorrupt = errors.New("s2: corrupt input")
  19. // ErrCRC reports that the input failed CRC validation (streams only)
  20. ErrCRC = errors.New("s2: corrupt input, crc mismatch")
  21. // ErrTooLarge reports that the uncompressed length is too large.
  22. ErrTooLarge = errors.New("s2: decoded block is too large")
  23. // ErrUnsupported reports that the input isn't supported.
  24. ErrUnsupported = errors.New("s2: unsupported input")
  25. )
  26. // ErrCantSeek is returned if the stream cannot be seeked.
  27. type ErrCantSeek struct {
  28. Reason string
  29. }
  30. // Error returns the error as string.
  31. func (e ErrCantSeek) Error() string {
  32. return fmt.Sprintf("s2: Can't seek because %s", e.Reason)
  33. }
  34. // DecodedLen returns the length of the decoded block.
  35. func DecodedLen(src []byte) (int, error) {
  36. v, _, err := decodedLen(src)
  37. return v, err
  38. }
  39. // decodedLen returns the length of the decoded block and the number of bytes
  40. // that the length header occupied.
  41. func decodedLen(src []byte) (blockLen, headerLen int, err error) {
  42. v, n := binary.Uvarint(src)
  43. if n <= 0 || v > 0xffffffff {
  44. return 0, 0, ErrCorrupt
  45. }
  46. const wordSize = 32 << (^uint(0) >> 32 & 1)
  47. if wordSize == 32 && v > 0x7fffffff {
  48. return 0, 0, ErrTooLarge
  49. }
  50. return int(v), n, nil
  51. }
  52. const (
  53. decodeErrCodeCorrupt = 1
  54. )
  55. // Decode returns the decoded form of src. The returned slice may be a sub-
  56. // slice of dst if dst was large enough to hold the entire decoded block.
  57. // Otherwise, a newly allocated slice will be returned.
  58. //
  59. // The dst and src must not overlap. It is valid to pass a nil dst.
  60. func Decode(dst, src []byte) ([]byte, error) {
  61. dLen, s, err := decodedLen(src)
  62. if err != nil {
  63. return nil, err
  64. }
  65. if dLen <= cap(dst) {
  66. dst = dst[:dLen]
  67. } else {
  68. dst = make([]byte, dLen)
  69. }
  70. if s2Decode(dst, src[s:]) != 0 {
  71. return nil, ErrCorrupt
  72. }
  73. return dst, nil
  74. }
  75. // NewReader returns a new Reader that decompresses from r, using the framing
  76. // format described at
  77. // https://github.com/google/snappy/blob/master/framing_format.txt with S2 changes.
  78. func NewReader(r io.Reader, opts ...ReaderOption) *Reader {
  79. nr := Reader{
  80. r: r,
  81. maxBlock: maxBlockSize,
  82. }
  83. for _, opt := range opts {
  84. if err := opt(&nr); err != nil {
  85. nr.err = err
  86. return &nr
  87. }
  88. }
  89. nr.maxBufSize = MaxEncodedLen(nr.maxBlock) + checksumSize
  90. if nr.lazyBuf > 0 {
  91. nr.buf = make([]byte, MaxEncodedLen(nr.lazyBuf)+checksumSize)
  92. } else {
  93. nr.buf = make([]byte, MaxEncodedLen(defaultBlockSize)+checksumSize)
  94. }
  95. nr.readHeader = nr.ignoreStreamID
  96. nr.paramsOK = true
  97. return &nr
  98. }
  99. // ReaderOption is an option for creating a decoder.
  100. type ReaderOption func(*Reader) error
  101. // ReaderMaxBlockSize allows to control allocations if the stream
  102. // has been compressed with a smaller WriterBlockSize, or with the default 1MB.
  103. // Blocks must be this size or smaller to decompress,
  104. // otherwise the decoder will return ErrUnsupported.
  105. //
  106. // For streams compressed with Snappy this can safely be set to 64KB (64 << 10).
  107. //
  108. // Default is the maximum limit of 4MB.
  109. func ReaderMaxBlockSize(blockSize int) ReaderOption {
  110. return func(r *Reader) error {
  111. if blockSize > maxBlockSize || blockSize <= 0 {
  112. return errors.New("s2: block size too large. Must be <= 4MB and > 0")
  113. }
  114. if r.lazyBuf == 0 && blockSize < defaultBlockSize {
  115. r.lazyBuf = blockSize
  116. }
  117. r.maxBlock = blockSize
  118. return nil
  119. }
  120. }
  121. // ReaderAllocBlock allows to control upfront stream allocations
  122. // and not allocate for frames bigger than this initially.
  123. // If frames bigger than this is seen a bigger buffer will be allocated.
  124. //
  125. // Default is 1MB, which is default output size.
  126. func ReaderAllocBlock(blockSize int) ReaderOption {
  127. return func(r *Reader) error {
  128. if blockSize > maxBlockSize || blockSize < 1024 {
  129. return errors.New("s2: invalid ReaderAllocBlock. Must be <= 4MB and >= 1024")
  130. }
  131. r.lazyBuf = blockSize
  132. return nil
  133. }
  134. }
  135. // ReaderIgnoreStreamIdentifier will make the reader skip the expected
  136. // stream identifier at the beginning of the stream.
  137. // This can be used when serving a stream that has been forwarded to a specific point.
  138. func ReaderIgnoreStreamIdentifier() ReaderOption {
  139. return func(r *Reader) error {
  140. r.ignoreStreamID = true
  141. return nil
  142. }
  143. }
  144. // ReaderSkippableCB will register a callback for chuncks with the specified ID.
  145. // ID must be a Reserved skippable chunks ID, 0x80-0xfd (inclusive).
  146. // For each chunk with the ID, the callback is called with the content.
  147. // Any returned non-nil error will abort decompression.
  148. // Only one callback per ID is supported, latest sent will be used.
  149. func ReaderSkippableCB(id uint8, fn func(r io.Reader) error) ReaderOption {
  150. return func(r *Reader) error {
  151. if id < 0x80 || id > 0xfd {
  152. return fmt.Errorf("ReaderSkippableCB: Invalid id provided, must be 0x80-0xfd (inclusive)")
  153. }
  154. r.skippableCB[id] = fn
  155. return nil
  156. }
  157. }
  158. // ReaderIgnoreCRC will make the reader skip CRC calculation and checks.
  159. func ReaderIgnoreCRC() ReaderOption {
  160. return func(r *Reader) error {
  161. r.ignoreCRC = true
  162. return nil
  163. }
  164. }
  165. // Reader is an io.Reader that can read Snappy-compressed bytes.
  166. type Reader struct {
  167. r io.Reader
  168. err error
  169. decoded []byte
  170. buf []byte
  171. skippableCB [0x80]func(r io.Reader) error
  172. blockStart int64 // Uncompressed offset at start of current.
  173. index *Index
  174. // decoded[i:j] contains decoded bytes that have not yet been passed on.
  175. i, j int
  176. // maximum block size allowed.
  177. maxBlock int
  178. // maximum expected buffer size.
  179. maxBufSize int
  180. // alloc a buffer this size if > 0.
  181. lazyBuf int
  182. readHeader bool
  183. paramsOK bool
  184. snappyFrame bool
  185. ignoreStreamID bool
  186. ignoreCRC bool
  187. }
  188. // ensureBufferSize will ensure that the buffer can take at least n bytes.
  189. // If false is returned the buffer exceeds maximum allowed size.
  190. func (r *Reader) ensureBufferSize(n int) bool {
  191. if n > r.maxBufSize {
  192. r.err = ErrCorrupt
  193. return false
  194. }
  195. if cap(r.buf) >= n {
  196. return true
  197. }
  198. // Realloc buffer.
  199. r.buf = make([]byte, n)
  200. return true
  201. }
  202. // Reset discards any buffered data, resets all state, and switches the Snappy
  203. // reader to read from r. This permits reusing a Reader rather than allocating
  204. // a new one.
  205. func (r *Reader) Reset(reader io.Reader) {
  206. if !r.paramsOK {
  207. return
  208. }
  209. r.index = nil
  210. r.r = reader
  211. r.err = nil
  212. r.i = 0
  213. r.j = 0
  214. r.blockStart = 0
  215. r.readHeader = r.ignoreStreamID
  216. }
  217. func (r *Reader) readFull(p []byte, allowEOF bool) (ok bool) {
  218. if _, r.err = io.ReadFull(r.r, p); r.err != nil {
  219. if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) {
  220. r.err = ErrCorrupt
  221. }
  222. return false
  223. }
  224. return true
  225. }
  226. // skippable will skip n bytes.
  227. // If the supplied reader supports seeking that is used.
  228. // tmp is used as a temporary buffer for reading.
  229. // The supplied slice does not need to be the size of the read.
  230. func (r *Reader) skippable(tmp []byte, n int, allowEOF bool, id uint8) (ok bool) {
  231. if id < 0x80 {
  232. r.err = fmt.Errorf("interbal error: skippable id < 0x80")
  233. return false
  234. }
  235. if fn := r.skippableCB[id-0x80]; fn != nil {
  236. rd := io.LimitReader(r.r, int64(n))
  237. r.err = fn(rd)
  238. if r.err != nil {
  239. return false
  240. }
  241. _, r.err = io.CopyBuffer(ioutil.Discard, rd, tmp)
  242. return r.err == nil
  243. }
  244. if rs, ok := r.r.(io.ReadSeeker); ok {
  245. _, err := rs.Seek(int64(n), io.SeekCurrent)
  246. if err == nil {
  247. return true
  248. }
  249. if err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) {
  250. r.err = ErrCorrupt
  251. return false
  252. }
  253. }
  254. for n > 0 {
  255. if n < len(tmp) {
  256. tmp = tmp[:n]
  257. }
  258. if _, r.err = io.ReadFull(r.r, tmp); r.err != nil {
  259. if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) {
  260. r.err = ErrCorrupt
  261. }
  262. return false
  263. }
  264. n -= len(tmp)
  265. }
  266. return true
  267. }
  268. // Read satisfies the io.Reader interface.
  269. func (r *Reader) Read(p []byte) (int, error) {
  270. if r.err != nil {
  271. return 0, r.err
  272. }
  273. for {
  274. if r.i < r.j {
  275. n := copy(p, r.decoded[r.i:r.j])
  276. r.i += n
  277. return n, nil
  278. }
  279. if !r.readFull(r.buf[:4], true) {
  280. return 0, r.err
  281. }
  282. chunkType := r.buf[0]
  283. if !r.readHeader {
  284. if chunkType != chunkTypeStreamIdentifier {
  285. r.err = ErrCorrupt
  286. return 0, r.err
  287. }
  288. r.readHeader = true
  289. }
  290. chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16
  291. // The chunk types are specified at
  292. // https://github.com/google/snappy/blob/master/framing_format.txt
  293. switch chunkType {
  294. case chunkTypeCompressedData:
  295. r.blockStart += int64(r.j)
  296. // Section 4.2. Compressed data (chunk type 0x00).
  297. if chunkLen < checksumSize {
  298. r.err = ErrCorrupt
  299. return 0, r.err
  300. }
  301. if !r.ensureBufferSize(chunkLen) {
  302. if r.err == nil {
  303. r.err = ErrUnsupported
  304. }
  305. return 0, r.err
  306. }
  307. buf := r.buf[:chunkLen]
  308. if !r.readFull(buf, false) {
  309. return 0, r.err
  310. }
  311. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  312. buf = buf[checksumSize:]
  313. n, err := DecodedLen(buf)
  314. if err != nil {
  315. r.err = err
  316. return 0, r.err
  317. }
  318. if r.snappyFrame && n > maxSnappyBlockSize {
  319. r.err = ErrCorrupt
  320. return 0, r.err
  321. }
  322. if n > len(r.decoded) {
  323. if n > r.maxBlock {
  324. r.err = ErrCorrupt
  325. return 0, r.err
  326. }
  327. r.decoded = make([]byte, n)
  328. }
  329. if _, err := Decode(r.decoded, buf); err != nil {
  330. r.err = err
  331. return 0, r.err
  332. }
  333. if !r.ignoreCRC && crc(r.decoded[:n]) != checksum {
  334. r.err = ErrCRC
  335. return 0, r.err
  336. }
  337. r.i, r.j = 0, n
  338. continue
  339. case chunkTypeUncompressedData:
  340. r.blockStart += int64(r.j)
  341. // Section 4.3. Uncompressed data (chunk type 0x01).
  342. if chunkLen < checksumSize {
  343. r.err = ErrCorrupt
  344. return 0, r.err
  345. }
  346. if !r.ensureBufferSize(chunkLen) {
  347. if r.err == nil {
  348. r.err = ErrUnsupported
  349. }
  350. return 0, r.err
  351. }
  352. buf := r.buf[:checksumSize]
  353. if !r.readFull(buf, false) {
  354. return 0, r.err
  355. }
  356. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  357. // Read directly into r.decoded instead of via r.buf.
  358. n := chunkLen - checksumSize
  359. if r.snappyFrame && n > maxSnappyBlockSize {
  360. r.err = ErrCorrupt
  361. return 0, r.err
  362. }
  363. if n > len(r.decoded) {
  364. if n > r.maxBlock {
  365. r.err = ErrCorrupt
  366. return 0, r.err
  367. }
  368. r.decoded = make([]byte, n)
  369. }
  370. if !r.readFull(r.decoded[:n], false) {
  371. return 0, r.err
  372. }
  373. if !r.ignoreCRC && crc(r.decoded[:n]) != checksum {
  374. r.err = ErrCRC
  375. return 0, r.err
  376. }
  377. r.i, r.j = 0, n
  378. continue
  379. case chunkTypeStreamIdentifier:
  380. // Section 4.1. Stream identifier (chunk type 0xff).
  381. if chunkLen != len(magicBody) {
  382. r.err = ErrCorrupt
  383. return 0, r.err
  384. }
  385. if !r.readFull(r.buf[:len(magicBody)], false) {
  386. return 0, r.err
  387. }
  388. if string(r.buf[:len(magicBody)]) != magicBody {
  389. if string(r.buf[:len(magicBody)]) != magicBodySnappy {
  390. r.err = ErrCorrupt
  391. return 0, r.err
  392. } else {
  393. r.snappyFrame = true
  394. }
  395. } else {
  396. r.snappyFrame = false
  397. }
  398. continue
  399. }
  400. if chunkType <= 0x7f {
  401. // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f).
  402. // fmt.Printf("ERR chunktype: 0x%x\n", chunkType)
  403. r.err = ErrUnsupported
  404. return 0, r.err
  405. }
  406. // Section 4.4 Padding (chunk type 0xfe).
  407. // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd).
  408. if chunkLen > maxChunkSize {
  409. // fmt.Printf("ERR chunkLen: 0x%x\n", chunkLen)
  410. r.err = ErrUnsupported
  411. return 0, r.err
  412. }
  413. // fmt.Printf("skippable: ID: 0x%x, len: 0x%x\n", chunkType, chunkLen)
  414. if !r.skippable(r.buf, chunkLen, false, chunkType) {
  415. return 0, r.err
  416. }
  417. }
  418. }
  419. // DecodeConcurrent will decode the full stream to w.
  420. // This function should not be combined with reading, seeking or other operations.
  421. // Up to 'concurrent' goroutines will be used.
  422. // If <= 0, runtime.NumCPU will be used.
  423. // On success the number of bytes decompressed nil and is returned.
  424. // This is mainly intended for bigger streams.
  425. func (r *Reader) DecodeConcurrent(w io.Writer, concurrent int) (written int64, err error) {
  426. if r.i > 0 || r.j > 0 || r.blockStart > 0 {
  427. return 0, errors.New("DecodeConcurrent called after ")
  428. }
  429. if concurrent <= 0 {
  430. concurrent = runtime.NumCPU()
  431. }
  432. // Write to output
  433. var errMu sync.Mutex
  434. var aErr error
  435. setErr := func(e error) (ok bool) {
  436. errMu.Lock()
  437. defer errMu.Unlock()
  438. if e == nil {
  439. return aErr == nil
  440. }
  441. if aErr == nil {
  442. aErr = e
  443. }
  444. return false
  445. }
  446. hasErr := func() (ok bool) {
  447. errMu.Lock()
  448. v := aErr != nil
  449. errMu.Unlock()
  450. return v
  451. }
  452. var aWritten int64
  453. toRead := make(chan []byte, concurrent)
  454. writtenBlocks := make(chan []byte, concurrent)
  455. queue := make(chan chan []byte, concurrent)
  456. reUse := make(chan chan []byte, concurrent)
  457. for i := 0; i < concurrent; i++ {
  458. toRead <- make([]byte, 0, r.maxBufSize)
  459. writtenBlocks <- make([]byte, 0, r.maxBufSize)
  460. reUse <- make(chan []byte, 1)
  461. }
  462. // Writer
  463. var wg sync.WaitGroup
  464. wg.Add(1)
  465. go func() {
  466. defer wg.Done()
  467. for toWrite := range queue {
  468. entry := <-toWrite
  469. reUse <- toWrite
  470. if hasErr() {
  471. writtenBlocks <- entry
  472. continue
  473. }
  474. n, err := w.Write(entry)
  475. want := len(entry)
  476. writtenBlocks <- entry
  477. if err != nil {
  478. setErr(err)
  479. continue
  480. }
  481. if n != want {
  482. setErr(io.ErrShortWrite)
  483. continue
  484. }
  485. aWritten += int64(n)
  486. }
  487. }()
  488. // Reader
  489. defer func() {
  490. close(queue)
  491. if r.err != nil {
  492. err = r.err
  493. setErr(r.err)
  494. }
  495. wg.Wait()
  496. if err == nil {
  497. err = aErr
  498. }
  499. written = aWritten
  500. }()
  501. for !hasErr() {
  502. if !r.readFull(r.buf[:4], true) {
  503. if r.err == io.EOF {
  504. r.err = nil
  505. }
  506. return 0, r.err
  507. }
  508. chunkType := r.buf[0]
  509. if !r.readHeader {
  510. if chunkType != chunkTypeStreamIdentifier {
  511. r.err = ErrCorrupt
  512. return 0, r.err
  513. }
  514. r.readHeader = true
  515. }
  516. chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16
  517. // The chunk types are specified at
  518. // https://github.com/google/snappy/blob/master/framing_format.txt
  519. switch chunkType {
  520. case chunkTypeCompressedData:
  521. r.blockStart += int64(r.j)
  522. // Section 4.2. Compressed data (chunk type 0x00).
  523. if chunkLen < checksumSize {
  524. r.err = ErrCorrupt
  525. return 0, r.err
  526. }
  527. if chunkLen > r.maxBufSize {
  528. r.err = ErrCorrupt
  529. return 0, r.err
  530. }
  531. orgBuf := <-toRead
  532. buf := orgBuf[:chunkLen]
  533. if !r.readFull(buf, false) {
  534. return 0, r.err
  535. }
  536. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  537. buf = buf[checksumSize:]
  538. n, err := DecodedLen(buf)
  539. if err != nil {
  540. r.err = err
  541. return 0, r.err
  542. }
  543. if r.snappyFrame && n > maxSnappyBlockSize {
  544. r.err = ErrCorrupt
  545. return 0, r.err
  546. }
  547. if n > r.maxBlock {
  548. r.err = ErrCorrupt
  549. return 0, r.err
  550. }
  551. wg.Add(1)
  552. decoded := <-writtenBlocks
  553. entry := <-reUse
  554. queue <- entry
  555. go func() {
  556. defer wg.Done()
  557. decoded = decoded[:n]
  558. _, err := Decode(decoded, buf)
  559. toRead <- orgBuf
  560. if err != nil {
  561. writtenBlocks <- decoded
  562. setErr(err)
  563. return
  564. }
  565. if !r.ignoreCRC && crc(decoded) != checksum {
  566. writtenBlocks <- decoded
  567. setErr(ErrCRC)
  568. return
  569. }
  570. entry <- decoded
  571. }()
  572. continue
  573. case chunkTypeUncompressedData:
  574. // Section 4.3. Uncompressed data (chunk type 0x01).
  575. if chunkLen < checksumSize {
  576. r.err = ErrCorrupt
  577. return 0, r.err
  578. }
  579. if chunkLen > r.maxBufSize {
  580. r.err = ErrCorrupt
  581. return 0, r.err
  582. }
  583. // Grab write buffer
  584. orgBuf := <-writtenBlocks
  585. buf := orgBuf[:checksumSize]
  586. if !r.readFull(buf, false) {
  587. return 0, r.err
  588. }
  589. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  590. // Read content.
  591. n := chunkLen - checksumSize
  592. if r.snappyFrame && n > maxSnappyBlockSize {
  593. r.err = ErrCorrupt
  594. return 0, r.err
  595. }
  596. if n > r.maxBlock {
  597. r.err = ErrCorrupt
  598. return 0, r.err
  599. }
  600. // Read uncompressed
  601. buf = orgBuf[:n]
  602. if !r.readFull(buf, false) {
  603. return 0, r.err
  604. }
  605. if !r.ignoreCRC && crc(buf) != checksum {
  606. r.err = ErrCRC
  607. return 0, r.err
  608. }
  609. entry := <-reUse
  610. queue <- entry
  611. entry <- buf
  612. continue
  613. case chunkTypeStreamIdentifier:
  614. // Section 4.1. Stream identifier (chunk type 0xff).
  615. if chunkLen != len(magicBody) {
  616. r.err = ErrCorrupt
  617. return 0, r.err
  618. }
  619. if !r.readFull(r.buf[:len(magicBody)], false) {
  620. return 0, r.err
  621. }
  622. if string(r.buf[:len(magicBody)]) != magicBody {
  623. if string(r.buf[:len(magicBody)]) != magicBodySnappy {
  624. r.err = ErrCorrupt
  625. return 0, r.err
  626. } else {
  627. r.snappyFrame = true
  628. }
  629. } else {
  630. r.snappyFrame = false
  631. }
  632. continue
  633. }
  634. if chunkType <= 0x7f {
  635. // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f).
  636. // fmt.Printf("ERR chunktype: 0x%x\n", chunkType)
  637. r.err = ErrUnsupported
  638. return 0, r.err
  639. }
  640. // Section 4.4 Padding (chunk type 0xfe).
  641. // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd).
  642. if chunkLen > maxChunkSize {
  643. // fmt.Printf("ERR chunkLen: 0x%x\n", chunkLen)
  644. r.err = ErrUnsupported
  645. return 0, r.err
  646. }
  647. // fmt.Printf("skippable: ID: 0x%x, len: 0x%x\n", chunkType, chunkLen)
  648. if !r.skippable(r.buf, chunkLen, false, chunkType) {
  649. return 0, r.err
  650. }
  651. }
  652. return 0, r.err
  653. }
  654. // Skip will skip n bytes forward in the decompressed output.
  655. // For larger skips this consumes less CPU and is faster than reading output and discarding it.
  656. // CRC is not checked on skipped blocks.
  657. // io.ErrUnexpectedEOF is returned if the stream ends before all bytes have been skipped.
  658. // If a decoding error is encountered subsequent calls to Read will also fail.
  659. func (r *Reader) Skip(n int64) error {
  660. if n < 0 {
  661. return errors.New("attempted negative skip")
  662. }
  663. if r.err != nil {
  664. return r.err
  665. }
  666. for n > 0 {
  667. if r.i < r.j {
  668. // Skip in buffer.
  669. // decoded[i:j] contains decoded bytes that have not yet been passed on.
  670. left := int64(r.j - r.i)
  671. if left >= n {
  672. tmp := int64(r.i) + n
  673. if tmp > math.MaxInt32 {
  674. return errors.New("s2: internal overflow in skip")
  675. }
  676. r.i = int(tmp)
  677. return nil
  678. }
  679. n -= int64(r.j - r.i)
  680. r.i = r.j
  681. }
  682. // Buffer empty; read blocks until we have content.
  683. if !r.readFull(r.buf[:4], true) {
  684. if r.err == io.EOF {
  685. r.err = io.ErrUnexpectedEOF
  686. }
  687. return r.err
  688. }
  689. chunkType := r.buf[0]
  690. if !r.readHeader {
  691. if chunkType != chunkTypeStreamIdentifier {
  692. r.err = ErrCorrupt
  693. return r.err
  694. }
  695. r.readHeader = true
  696. }
  697. chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16
  698. // The chunk types are specified at
  699. // https://github.com/google/snappy/blob/master/framing_format.txt
  700. switch chunkType {
  701. case chunkTypeCompressedData:
  702. r.blockStart += int64(r.j)
  703. // Section 4.2. Compressed data (chunk type 0x00).
  704. if chunkLen < checksumSize {
  705. r.err = ErrCorrupt
  706. return r.err
  707. }
  708. if !r.ensureBufferSize(chunkLen) {
  709. if r.err == nil {
  710. r.err = ErrUnsupported
  711. }
  712. return r.err
  713. }
  714. buf := r.buf[:chunkLen]
  715. if !r.readFull(buf, false) {
  716. return r.err
  717. }
  718. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  719. buf = buf[checksumSize:]
  720. dLen, err := DecodedLen(buf)
  721. if err != nil {
  722. r.err = err
  723. return r.err
  724. }
  725. if dLen > r.maxBlock {
  726. r.err = ErrCorrupt
  727. return r.err
  728. }
  729. // Check if destination is within this block
  730. if int64(dLen) > n {
  731. if len(r.decoded) < dLen {
  732. r.decoded = make([]byte, dLen)
  733. }
  734. if _, err := Decode(r.decoded, buf); err != nil {
  735. r.err = err
  736. return r.err
  737. }
  738. if crc(r.decoded[:dLen]) != checksum {
  739. r.err = ErrCorrupt
  740. return r.err
  741. }
  742. } else {
  743. // Skip block completely
  744. n -= int64(dLen)
  745. r.blockStart += int64(dLen)
  746. dLen = 0
  747. }
  748. r.i, r.j = 0, dLen
  749. continue
  750. case chunkTypeUncompressedData:
  751. r.blockStart += int64(r.j)
  752. // Section 4.3. Uncompressed data (chunk type 0x01).
  753. if chunkLen < checksumSize {
  754. r.err = ErrCorrupt
  755. return r.err
  756. }
  757. if !r.ensureBufferSize(chunkLen) {
  758. if r.err != nil {
  759. r.err = ErrUnsupported
  760. }
  761. return r.err
  762. }
  763. buf := r.buf[:checksumSize]
  764. if !r.readFull(buf, false) {
  765. return r.err
  766. }
  767. checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
  768. // Read directly into r.decoded instead of via r.buf.
  769. n2 := chunkLen - checksumSize
  770. if n2 > len(r.decoded) {
  771. if n2 > r.maxBlock {
  772. r.err = ErrCorrupt
  773. return r.err
  774. }
  775. r.decoded = make([]byte, n2)
  776. }
  777. if !r.readFull(r.decoded[:n2], false) {
  778. return r.err
  779. }
  780. if int64(n2) < n {
  781. if crc(r.decoded[:n2]) != checksum {
  782. r.err = ErrCorrupt
  783. return r.err
  784. }
  785. }
  786. r.i, r.j = 0, n2
  787. continue
  788. case chunkTypeStreamIdentifier:
  789. // Section 4.1. Stream identifier (chunk type 0xff).
  790. if chunkLen != len(magicBody) {
  791. r.err = ErrCorrupt
  792. return r.err
  793. }
  794. if !r.readFull(r.buf[:len(magicBody)], false) {
  795. return r.err
  796. }
  797. if string(r.buf[:len(magicBody)]) != magicBody {
  798. if string(r.buf[:len(magicBody)]) != magicBodySnappy {
  799. r.err = ErrCorrupt
  800. return r.err
  801. }
  802. }
  803. continue
  804. }
  805. if chunkType <= 0x7f {
  806. // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f).
  807. r.err = ErrUnsupported
  808. return r.err
  809. }
  810. if chunkLen > maxChunkSize {
  811. r.err = ErrUnsupported
  812. return r.err
  813. }
  814. // Section 4.4 Padding (chunk type 0xfe).
  815. // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd).
  816. if !r.skippable(r.buf, chunkLen, false, chunkType) {
  817. return r.err
  818. }
  819. }
  820. return nil
  821. }
  822. // ReadSeeker provides random or forward seeking in compressed content.
  823. // See Reader.ReadSeeker
  824. type ReadSeeker struct {
  825. *Reader
  826. }
  827. // ReadSeeker will return an io.ReadSeeker compatible version of the reader.
  828. // If 'random' is specified the returned io.Seeker can be used for
  829. // random seeking, otherwise only forward seeking is supported.
  830. // Enabling random seeking requires the original input to support
  831. // the io.Seeker interface.
  832. // A custom index can be specified which will be used if supplied.
  833. // When using a custom index, it will not be read from the input stream.
  834. // The returned ReadSeeker contains a shallow reference to the existing Reader,
  835. // meaning changes performed to one is reflected in the other.
  836. func (r *Reader) ReadSeeker(random bool, index []byte) (*ReadSeeker, error) {
  837. // Read index if provided.
  838. if len(index) != 0 {
  839. if r.index == nil {
  840. r.index = &Index{}
  841. }
  842. if _, err := r.index.Load(index); err != nil {
  843. return nil, ErrCantSeek{Reason: "loading index returned: " + err.Error()}
  844. }
  845. }
  846. // Check if input is seekable
  847. rs, ok := r.r.(io.ReadSeeker)
  848. if !ok {
  849. if !random {
  850. return &ReadSeeker{Reader: r}, nil
  851. }
  852. return nil, ErrCantSeek{Reason: "input stream isn't seekable"}
  853. }
  854. if r.index != nil {
  855. // Seekable and index, ok...
  856. return &ReadSeeker{Reader: r}, nil
  857. }
  858. // Load from stream.
  859. r.index = &Index{}
  860. // Read current position.
  861. pos, err := rs.Seek(0, io.SeekCurrent)
  862. if err != nil {
  863. return nil, ErrCantSeek{Reason: "seeking input returned: " + err.Error()}
  864. }
  865. err = r.index.LoadStream(rs)
  866. if err != nil {
  867. if err == ErrUnsupported {
  868. // If we don't require random seeking, reset input and return.
  869. if !random {
  870. _, err = rs.Seek(pos, io.SeekStart)
  871. if err != nil {
  872. return nil, ErrCantSeek{Reason: "resetting stream returned: " + err.Error()}
  873. }
  874. r.index = nil
  875. return &ReadSeeker{Reader: r}, nil
  876. }
  877. return nil, ErrCantSeek{Reason: "input stream does not contain an index"}
  878. }
  879. return nil, ErrCantSeek{Reason: "reading index returned: " + err.Error()}
  880. }
  881. // reset position.
  882. _, err = rs.Seek(pos, io.SeekStart)
  883. if err != nil {
  884. return nil, ErrCantSeek{Reason: "seeking input returned: " + err.Error()}
  885. }
  886. return &ReadSeeker{Reader: r}, nil
  887. }
  888. // Seek allows seeking in compressed data.
  889. func (r *ReadSeeker) Seek(offset int64, whence int) (int64, error) {
  890. if r.err != nil {
  891. return 0, r.err
  892. }
  893. if offset == 0 && whence == io.SeekCurrent {
  894. return r.blockStart + int64(r.i), nil
  895. }
  896. if !r.readHeader {
  897. // Make sure we read the header.
  898. _, r.err = r.Read([]byte{})
  899. }
  900. rs, ok := r.r.(io.ReadSeeker)
  901. if r.index == nil || !ok {
  902. if whence == io.SeekCurrent && offset >= 0 {
  903. err := r.Skip(offset)
  904. return r.blockStart + int64(r.i), err
  905. }
  906. if whence == io.SeekStart && offset >= r.blockStart+int64(r.i) {
  907. err := r.Skip(offset - r.blockStart - int64(r.i))
  908. return r.blockStart + int64(r.i), err
  909. }
  910. return 0, ErrUnsupported
  911. }
  912. switch whence {
  913. case io.SeekCurrent:
  914. offset += r.blockStart + int64(r.i)
  915. case io.SeekEnd:
  916. if offset > 0 {
  917. return 0, errors.New("seek after end of file")
  918. }
  919. offset = r.index.TotalUncompressed + offset
  920. }
  921. if offset < 0 {
  922. return 0, errors.New("seek before start of file")
  923. }
  924. c, u, err := r.index.Find(offset)
  925. if err != nil {
  926. return r.blockStart + int64(r.i), err
  927. }
  928. // Seek to next block
  929. _, err = rs.Seek(c, io.SeekStart)
  930. if err != nil {
  931. return 0, err
  932. }
  933. r.i = r.j // Remove rest of current block.
  934. if u < offset {
  935. // Forward inside block
  936. return offset, r.Skip(offset - u)
  937. }
  938. return offset, nil
  939. }
  940. // ReadByte satisfies the io.ByteReader interface.
  941. func (r *Reader) ReadByte() (byte, error) {
  942. if r.err != nil {
  943. return 0, r.err
  944. }
  945. if r.i < r.j {
  946. c := r.decoded[r.i]
  947. r.i++
  948. return c, nil
  949. }
  950. var tmp [1]byte
  951. for i := 0; i < 10; i++ {
  952. n, err := r.Read(tmp[:])
  953. if err != nil {
  954. return 0, err
  955. }
  956. if n == 1 {
  957. return tmp[0], nil
  958. }
  959. }
  960. return 0, io.ErrNoProgress
  961. }
  962. // SkippableCB will register a callback for chunks with the specified ID.
  963. // ID must be a Reserved skippable chunks ID, 0x80-0xfe (inclusive).
  964. // For each chunk with the ID, the callback is called with the content.
  965. // Any returned non-nil error will abort decompression.
  966. // Only one callback per ID is supported, latest sent will be used.
  967. // Sending a nil function will disable previous callbacks.
  968. func (r *Reader) SkippableCB(id uint8, fn func(r io.Reader) error) error {
  969. if id < 0x80 || id > chunkTypePadding {
  970. return fmt.Errorf("ReaderSkippableCB: Invalid id provided, must be 0x80-0xfe (inclusive)")
  971. }
  972. r.skippableCB[id] = fn
  973. return nil
  974. }