forked from mreiferson/go-snappystream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader_test.go
650 lines (588 loc) · 16.2 KB
/
reader_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
package snappystream
import (
"bytes"
"crypto/rand"
"fmt"
"io"
"io/ioutil"
"strings"
"testing"
"github.com/mreiferson/go-snappystream/snappy-go"
)
// This test checks that padding and reserved skippable blocks are ignored by
// the reader.
func TestReader_skippable(t *testing.T) {
var buf bytes.Buffer
// write some blocks with injected padding/skippable blocks
w := NewWriter(&buf)
write := func(p []byte) (int, error) {
return w.Write(p)
}
writepad := func(b byte, n int) (int, error) {
return buf.Write(opaqueChunk(b, n))
}
_, err := write([]byte("hello"))
if err != nil {
t.Fatalf("write error: %v", err)
}
_, err = writepad(0xfe, 100) // normal padding
if err != nil {
t.Fatalf("write error: %v", err)
}
_, err = write([]byte(" "))
if err != nil {
t.Fatalf("write error: %v", err)
}
_, err = writepad(0xa0, 100) // reserved skippable block
if err != nil {
t.Fatalf("write error: %v", err)
}
_, err = writepad(0xfe, MaxBlockSize) // normal padding
if err != nil {
t.Fatalf("write error: %v", err)
}
_, err = write([]byte("padding"))
if err != nil {
t.Fatalf("write error: %v", err)
}
p, err := ioutil.ReadAll(NewReader(&buf, true))
if err != nil {
t.Fatalf("read error: %v", err)
}
if string(p) != "hello padding" {
t.Fatalf("read: unexpected content %q", string(p))
}
}
// This test checks that reserved unskippable blocks are cause decoder errors.
func TestReader_unskippable(t *testing.T) {
var buf bytes.Buffer
// write some blocks with injected padding/skippable blocks
w := NewWriter(&buf)
write := func(p []byte) (int, error) {
return w.Write(p)
}
writepad := func(b byte, n int) (int, error) {
return buf.Write(opaqueChunk(b, n))
}
_, err := write([]byte("unskippable"))
if err != nil {
t.Fatalf("write error: %v", err)
}
_, err = writepad(0x50, 100) // unskippable reserved block
if err != nil {
t.Fatalf("write error: %v", err)
}
_, err = write([]byte(" blocks"))
if err != nil {
t.Fatalf("write error: %v", err)
}
_, err = ioutil.ReadAll(NewReader(&buf, true))
if err == nil {
t.Fatalf("read success")
}
}
func TestReaderStreamID(t *testing.T) {
data := []byte("a snappy-framed data stream")
var buf bytes.Buffer
w := NewWriter(&buf)
_, err := w.Write(data)
if err != nil {
t.Fatal(err)
}
stream := buf.Bytes()
// sanity check: the stream can be decoded and starts with streamID
r := NewReader(bytes.NewReader(stream), true)
_, err = ioutil.ReadAll(r)
if err != nil {
t.Fatalf("read: %v", err)
}
if !bytes.HasPrefix(stream, streamID) {
t.Fatal("missing stream id")
}
// streamNoID is valid except for a missing the streamID block
streamNoID := bytes.TrimPrefix(stream, streamID)
r = NewReader(bytes.NewReader(streamNoID), true)
n, err := r.Read(make([]byte, 1))
if err == nil {
t.Fatalf("read: expected an error reading input missing a stream identifier block")
}
if n != 0 {
t.Fatalf("read: read non-zero number of bytes %d", n)
}
n, err = r.Read(make([]byte, 1))
if err == nil {
t.Fatalf("read: successful read after missing stream id error")
}
if n != 0 {
t.Fatalf("read: read non-zero number of bytes %d after missing stream id error", n)
}
}
// This test validates the reader successfully decods a padding of maximal
// size, 2^24 - 1.
func TestReader_maxPad(t *testing.T) {
buf := bytes.NewReader(bytes.Join([][]byte{
streamID,
compressedChunk(t, []byte("a maximal padding chunk")),
opaqueChunk(0xfe, (1<<24)-1), // normal padding
compressedChunk(t, []byte(" is decoded successfully")),
}, nil))
r := NewReader(buf, true)
p, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("read error: %v", err)
}
if string(p) != "a maximal padding chunk is decoded successfully" {
t.Fatalf("read: unexpected content %q", string(p))
}
}
// This test validates the reader successfully decodes a skippable chunk of
// maximal size, 2^24 - 1.
func TestReader_maxSkippable(t *testing.T) {
buf := bytes.NewReader(bytes.Join([][]byte{
streamID,
compressedChunk(t, []byte("a maximal skippable chunk")),
opaqueChunk(0xce, (1<<24)-1), // reserved skippable chunk
compressedChunk(t, []byte(" is decoded successfully")),
}, nil))
r := NewReader(buf, true)
p, err := ioutil.ReadAll(r)
if err != nil {
t.Fatalf("read error: %v", err)
}
if string(p) != "a maximal skippable chunk is decoded successfully" {
t.Fatalf("read: unexpected content %q", string(p))
}
}
// TestReader_maxBlock validates bounds checking on encoded and decoded data
// (4.2 Compressed Data).
func TestReader_maxBlock(t *testing.T) {
// decompressing a block with compressed length greater than MaxBlockSize
// should succeed.
buf := bytes.NewReader(bytes.Join([][]byte{
streamID,
compressedChunkGreaterN(t, MaxBlockSize),
}, nil))
r := NewReader(buf, true)
b, err := ioutil.ReadAll(r)
if err != nil {
t.Fatal(err)
}
if len(b) != MaxBlockSize {
t.Fatalf("bad read (%d bytes)", len(b))
}
// decompressing should fail if the block with decompressed length greater
// than MaxBlockSize.
buf = bytes.NewReader(bytes.Join([][]byte{
streamID,
compressedChunk(t, make([]byte, MaxBlockSize+1)),
}, nil))
r = NewReader(buf, true)
b, err = ioutil.ReadAll(r)
if err == nil {
t.Fatal("unexpected success")
}
if len(b) > 0 {
t.Fatalf("unexpected read %q", b)
}
}
// This test validates the reader's behavior encountering unskippable chunks of
// maximal size, 2^24 - 1. The desired error to in this case is one reporting
// an unskippable chunk, not a length error.
func TestReader_maxUnskippable(t *testing.T) {
// the first block should be decoded successfully.
prefix := "a maximal unskippable chunk"
buf := bytes.NewReader(bytes.Join([][]byte{
streamID,
compressedChunk(t, []byte(prefix)),
opaqueChunk(0x03, (1<<24)-1), // low end of the unskippable range
compressedChunk(t, []byte(" failure must be reported as such")),
}, nil))
p := make([]byte, len(prefix))
r := NewReader(buf, true)
n, err := r.Read(p)
if err != nil {
t.Fatalf("read error: %v", err)
}
if n != len(p) {
t.Fatalf("read: short read %d", n)
}
if string(p) != prefix {
t.Fatalf("read: bad value %q", p)
}
n, err = r.Read(p)
if err == nil {
t.Fatalf("read: expected error")
}
if n > 0 {
t.Fatalf("read: read %d more bytes than expected", n)
}
if !strings.Contains(err.Error(), "unskippable") {
t.Fatalf("read error: %v", err)
}
}
// This test validates errors returned when data blocks exceed size limits.
func TestReader_blockTooLarge(t *testing.T) {
// the compressed chunk size is within the allowed encoding size
// (maxEncodedBlockSize). but the uncompressed data is larger than allowed.
badstream := bytes.Join([][]byte{
streamID,
compressedChunk(t, make([]byte, (1<<24)-5)),
}, nil)
r := NewReader(bytes.NewBuffer(badstream), true)
p := make([]byte, 1)
n, err := r.Read(p)
if err == nil {
t.Fatalf("read: expected error")
}
if n != 0 {
t.Fatalf("read: read data from the stream")
}
// the compressed chunk size is within the allowed encoding size
// (maxEncodedBlockSize). but the uncompressed data is larger than allowed.
badstream = bytes.Join([][]byte{
streamID,
uncompressedChunk(t, make([]byte, (1<<24)-5)),
}, nil)
r = NewReader(bytes.NewBuffer(badstream), true)
p = make([]byte, 1)
n, err = r.Read(p)
if err == nil {
t.Fatalf("read: expected error")
}
if n != 0 {
t.Fatalf("read: read data from the stream")
}
}
// This test validates the reader's handling of corrupt chunks.
func TestReader_corruption(t *testing.T) {
// corruptID is a corrupt stream identifier
corruptID := append([]byte(nil), streamID...)
corruptID = bytes.Replace(streamID, []byte("p"), []byte("P"), -1) // corrupt "sNaPpY" data
badstream := corruptID
r := NewReader(bytes.NewBuffer(badstream), true)
p := make([]byte, 1)
n, err := r.Read(p)
if err == nil {
t.Fatalf("read: expected error")
}
if err == io.EOF {
t.Fatalf("read: unexpected eof")
}
if n != 0 {
t.Fatalf("read: read data from the stream")
}
corruptID = append([]byte(nil), streamID...) // corrupt the length
corruptID[1] = 0x00
badstream = corruptID
r = NewReader(bytes.NewBuffer(badstream), true)
p = make([]byte, 1)
n, err = r.Read(p)
if err == nil {
t.Fatalf("read: expected error")
}
if err == io.EOF {
t.Fatalf("read: unexpected eof")
}
if n != 0 {
t.Fatalf("read: read data from the stream")
}
// chunk is a valid compressed block
chunk := compressedChunk(t, []byte("a data block"))
// corrupt is a corrupt chunk
corrupt := append([]byte(nil), chunk...)
copy(corrupt[8:], make([]byte, 10)) // corrupt snappy-encoded data
badstream = bytes.Join([][]byte{
streamID,
corrupt,
}, nil)
r = NewReader(bytes.NewBuffer(badstream), true)
p = make([]byte, 1)
n, err = r.Read(p)
if err == nil {
t.Fatalf("read: expected error")
}
if err == io.EOF {
t.Fatalf("read: unexpected eof")
}
if n != 0 {
t.Fatalf("read: read data from the stream")
}
corrupt = append([]byte(nil), chunk...)
copy(corrupt[4:8], make([]byte, 4)) // crc checksum failure
badstream = bytes.Join([][]byte{
streamID,
corrupt,
}, nil)
r = NewReader(bytes.NewBuffer(badstream), true)
p = make([]byte, 1)
n, err = r.Read(p)
if err == nil {
t.Fatalf("read: expected error")
}
if err == io.EOF {
t.Fatalf("read: unexpected eof")
}
if n != 0 {
t.Fatalf("read: read data from the stream")
}
}
// This test ensures that reader returns io.ErrUnexpectedEOF at the appropriate
// times. io.EOF must be reserved for the case when all data has been
// successfully decoded.
func TestReader_unexpectedEOF(t *testing.T) {
var decodeBuffer [64 << 10]byte
for _, test := range [][]byte{
// truncated streamIDs
streamID[:4],
streamID[:len(streamID)-1],
// truncated data blocks
bytes.Join([][]byte{
streamID,
compressedChunk(t, bytes.Repeat([]byte("abc"), 100))[:2],
}, nil),
bytes.Join([][]byte{
streamID,
compressedChunk(t, bytes.Repeat([]byte("abc"), 100))[:7],
}, nil),
// truncated padding
bytes.Join([][]byte{
streamID,
opaqueChunk(0xfe, 100)[:1],
}, nil),
bytes.Join([][]byte{
streamID,
opaqueChunk(0xfe, 100)[:8],
}, nil),
// truncated skippable chunk
bytes.Join([][]byte{
streamID,
opaqueChunk(0xcf, 100)[:3],
}, nil),
bytes.Join([][]byte{
streamID,
opaqueChunk(0xcf, 100)[:7],
}, nil),
// truncated unskippable chunk
bytes.Join([][]byte{
streamID,
opaqueChunk(0x03, 100)[:3],
}, nil),
bytes.Join([][]byte{
streamID,
opaqueChunk(0x03, 100)[:5],
}, nil),
} {
r := NewReader(bytes.NewReader(test), true)
n, err := r.Read(decodeBuffer[:])
if err == nil {
t.Errorf("read bad streamID: expected error")
}
if err != io.ErrUnexpectedEOF {
t.Errorf("read bad streamID: %v", err)
}
if n != 0 {
t.Errorf("read bad streamID: expected read length %d", n)
}
}
}
var errNotEnoughEntropy = fmt.Errorf("inadequate entropy in PRNG")
// compressedChunkGreaterN like compressedChunk produces a single, compressed,
// snappy-framed block. The returned block will have decoded length at most n
// and encoded length greater than n.
func compressedChunkGreaterN(t *testing.T, n int) []byte {
decoded := make([]byte, n)
var numTries int
var encoded []byte
for len(encoded) <= n && numTries < 3 {
numTries++
nrd, err := io.ReadFull(rand.Reader, decoded)
if err != nil {
t.Errorf("crypto/rand: %v", err)
return nil
}
if nrd != n {
t.Errorf("crypto/rand: bad read (%d bytes)", nrd)
return nil
}
encoded, err = snappy.Encode(encoded[:cap(encoded)], decoded)
if err != nil {
t.Errorf("snappy: %v", err)
return nil
}
}
if len(encoded) <= n {
t.Error(errNotEnoughEntropy)
return nil
}
return compressedChunk(t, decoded)
}
// compressedChunk encodes b returning a single, compressed, snappy-framed
// block. compressedChunk can encode source data larger than allowed in the
// specification.
func compressedChunk(t *testing.T, src []byte) []byte {
encoded, err := snappy.Encode(nil, src)
if err != nil {
t.Errorf("snappy: %v", err)
return nil
}
if len(encoded) > (1<<24)-5 { // account for the 4-byte checksum
t.Errorf("block data too large %d", len(src))
return nil
}
chunk := make([]byte, len(encoded)+8)
writeHeader(chunk[:8], blockCompressed, encoded, src)
copy(chunk[8:], encoded)
return chunk
}
// uncompressedChunk encodes b returning a single, uncompressed, snappy-framed
// block. uncompressedChunk can encode chunks larger than allowed by the
// specification.
func uncompressedChunk(t *testing.T, src []byte) []byte {
if len(src) > (1<<24)-5 { // account for the 4-byte checksum
t.Errorf("block data too large %d", len(src))
return nil
}
chunk := make([]byte, len(src)+8)
writeHeader(chunk[:8], blockUncompressed, src, src)
copy(chunk[8:], src)
return chunk
}
// opaqueChunk returns an opaque b chunk (e.g. padding 0xfe) with length n
// (total length, n+4 bytes). practically useless but good enough for testing.
// the first 4-bytes of data are random to ensure checksums are not being
// verified.
func opaqueChunk(b byte, n int) []byte {
if b == 0 {
b = 0xfe
}
length := uint32(n)
lengthle := []byte{byte(length), byte(length >> 8), byte(length >> 16)}
checksum := make([]byte, 4)
_, err := rand.Read(checksum)
if err != nil {
panic(err)
}
padbytes := make([]byte, n-4) // let this panic if n < 4
_, err = rand.Read(padbytes)
if err != nil {
panic(err)
}
var h []byte
h = append(h, b)
h = append(h, lengthle...)
h = append(h, checksum...)
h = append(h, padbytes...)
return h
}
func TestReaderWriteTo(t *testing.T) {
var encbuf bytes.Buffer
var decbuf bytes.Buffer
msg := "hello copy interface"
w := NewWriter(&encbuf)
n, err := io.WriteString(w, msg)
if err != nil {
t.Fatalf("encode: %v", err)
}
if n != len(msg) {
t.Fatalf("encode: %v", err)
}
r := NewReader(&encbuf, true)
n64, err := r.(*reader).WriteTo(&decbuf)
if err != nil {
t.Fatalf("decode: %v", err)
}
if n64 != int64(len(msg)) {
t.Fatalf("decode: decoded %d bytes %q", n64, decbuf.Bytes())
}
decmsg := decbuf.String()
if decmsg != msg {
t.Fatalf("decode: %q", decmsg)
}
}
func TestReaderWriteToPreviousError(t *testing.T) {
// construct an io.Reader that returns an error on the first read and a
// valid snappy-framed stream on subsequent reads.
var stream io.Reader
stream = encodedString("hello")
stream = readErrorFirst(stream, fmt.Errorf("one time error"))
stream = NewReader(stream, true)
var buf bytes.Buffer
// attempt the first read from the stream.
n, err := stream.(*reader).WriteTo(&buf)
if err == nil {
t.Fatalf("error expected")
}
if n != 0 {
t.Fatalf("bytes written to buffer: %q", buf.Bytes())
}
// attempt a second read from the stream.
n, err = stream.(*reader).WriteTo(&buf)
if err == nil {
t.Fatalf("error expected")
}
if n != 0 {
t.Fatalf("bytes written to buffer: %q", buf.Bytes())
}
}
// readerErrorFirst is an io.Reader that returns an error on the first read.
// readerErrorFirst is used to test that a reader does not attempt to read
// after a read error occurs.
type readerErrorFirst struct {
r io.Reader
err error
count int
}
func readErrorFirst(r io.Reader, err error) io.Reader {
return &readerErrorFirst{
r: r,
err: err,
}
}
func (r *readerErrorFirst) Read(b []byte) (int, error) {
r.count++
if r.count == 1 {
return 0, r.err
}
return r.r.Read(b)
}
func TestReaderWriteToWriteError(t *testing.T) {
origmsg := "hello"
stream := NewReader(encodedString(origmsg), true)
// attempt to write the stream to an io.Writer that will not accept input.
n, err := stream.(*reader).WriteTo(unwritable(fmt.Errorf("cannot write to this writer")))
if err == nil {
t.Fatalf("error expected")
}
if n != 0 {
t.Fatalf("reported %d written to an unwritable writer", n)
}
// the decoded message can still be read successfully because the encoded
// stream was not corrupt/broken.
var buf bytes.Buffer
n, err = stream.(*reader).WriteTo(&buf)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if n != int64(len(origmsg)) {
t.Errorf("read %d bytes", n)
}
if buf.String() != origmsg {
t.Errorf("read %q", buf)
}
}
// writerUnwritable is an io.Writer that always returns an error.
type writerUnwritable struct {
err error
}
func (w *writerUnwritable) Write([]byte) (int, error) {
return 0, w.err
}
func unwritable(err error) io.Writer {
return &writerUnwritable{err}
}
func encodedString(s string) io.Reader {
var buf bytes.Buffer
w := NewWriter(&buf)
io.WriteString(w, s)
return &buf
}