-
Notifications
You must be signed in to change notification settings - Fork 279
/
digest_reader.go
110 lines (99 loc) · 2.44 KB
/
digest_reader.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
/*
* Copyright 2020 The Dragonfly Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package digestutils
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"fmt"
"hash"
"io"
"strings"
"github.com/pkg/errors"
logger "d7y.io/dragonfly/v2/internal/dflog"
)
var (
ErrDigestNotMatch = errors.New("digest not match")
)
// digestReader reads stream with RateLimiter.
type digestReader struct {
r io.Reader
hash hash.Hash
digest string
*logger.SugaredLoggerOnWith
}
type DigestReader interface {
io.Reader
Digest() string
}
// TODO add AF_ALG digest https://github.com/golang/sys/commit/e24f485414aeafb646f6fca458b0bf869c0880a1
func NewDigestReader(log *logger.SugaredLoggerOnWith, reader io.Reader, digest ...string) (io.Reader, error) {
var (
d string
hashMethod hash.Hash
)
if len(digest) > 0 {
d = digest[0]
}
ds := strings.Split(d, ":")
if len(ds) == 2 {
d = ds[1]
switch ds[0] {
case "sha1":
hashMethod = sha1.New()
case "sha256":
hashMethod = sha256.New()
case "sha512":
hashMethod = sha512.New()
case "md5":
hashMethod = md5.New()
default:
return nil, fmt.Errorf("unsupport digest method: %s", ds[0])
}
} else {
hashMethod = md5.New()
}
return &digestReader{
SugaredLoggerOnWith: log,
digest: d,
hash: hashMethod,
r: reader,
}, nil
}
func (dr *digestReader) Read(p []byte) (int, error) {
n, err := dr.r.Read(p)
if err != nil && err != io.EOF {
return n, err
}
if n > 0 {
dr.hash.Write(p[:n])
}
if err == io.EOF && dr.digest != "" {
digest := dr.Digest()
if digest != dr.digest {
dr.Warnf("digest not match, desired: %s, actual: %s", dr.digest, digest)
return n, ErrDigestNotMatch
}
dr.Debugf("digest match: %s", digest)
}
return n, err
}
// Digest returns the digest of contents.
func (dr *digestReader) Digest() string {
return hex.EncodeToString(dr.hash.Sum(nil))
}