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