forked from rclone/gofakes3
-
Notifications
You must be signed in to change notification settings - Fork 1
/
hash.go
78 lines (67 loc) · 1.62 KB
/
hash.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
package gofakes3
import (
"bytes"
"crypto/md5"
"encoding/base64"
"fmt"
"hash"
"io"
)
// hashingReader proxies an existing io.Reader, passing each read block to the
// given hash.Hash.
//
// If the expected hash is not empty, once the underlying reader returns EOF,
// the hash is checked.
type hashingReader struct {
inner io.Reader
expected []byte
hash hash.Hash
sum []byte
}
func newHashingReader(inner io.Reader, expectedMD5Base64 string) (*hashingReader, error) {
var md5Bytes []byte
var err error
if expectedMD5Base64 != "" {
md5Bytes, err = base64.StdEncoding.DecodeString(expectedMD5Base64)
if err != nil {
return nil, ErrInvalidDigest
}
if len(md5Bytes) != 16 {
return nil, ErrInvalidDigest
}
}
return &hashingReader{
inner: inner,
expected: md5Bytes,
hash: md5.New(),
}, nil
}
// Sum returns the hash of the data read from the inner reader so far.
// If into is passed, it may be used if the hash needs to be computed.
func (h *hashingReader) Sum(into []byte) []byte {
if h.sum != nil {
return h.sum
}
return h.hash.Sum(into)
}
func (h *hashingReader) Read(p []byte) (n int, err error) {
n, err = h.inner.Read(p)
if n != 0 {
wn, _ := h.hash.Write(p[:n]) // Hash.Write never returns an error.
if wn != n {
return n, fmt.Errorf("short write to hasher")
}
}
if err != nil {
if err == io.EOF {
h.sum = h.hash.Sum(nil)
if h.expected != nil && !bytes.Equal(h.sum, h.expected) {
// FIXME: some more context here would be useful; need to flush out
// what S3 responds with in this case.
return n, ErrBadDigest
}
}
return n, err
}
return n, nil
}