forked from couchbaselabs/cbfs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
142 lines (123 loc) · 2.4 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
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
package main
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"encoding/hex"
"fmt"
"hash"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
)
var hashBuilders = map[string]func() hash.Hash{
"sha1": sha1.New,
"sha256": sha256.New,
"sha512": sha512.New,
"md5": md5.New,
}
func getHash() hash.Hash {
h, ok := hashBuilders[globalConfig.Hash]
if !ok {
return nil
}
return h()
}
type hashRecord struct {
tmpf *os.File
sh hash.Hash
w io.Writer
hashin string
base string
written int64
}
func NewHashRecord(tmpdir, hashin string) (*hashRecord, error) {
tmpf, err := ioutil.TempFile(tmpdir, "tmp")
if err != nil {
return nil, err
}
sh := getHash()
return &hashRecord{
tmpf: tmpf,
sh: sh,
w: io.MultiWriter(tmpf, sh),
hashin: hashin,
base: *root,
}, nil
}
func (h *hashRecord) Write(p []byte) (n int, err error) {
n, err = h.w.Write(p)
if err == nil {
h.written += int64(n)
}
return
}
func (h *hashRecord) Finish() (string, error) {
err := h.tmpf.Close()
if err != nil {
return "", err
}
hs := hex.EncodeToString(h.sh.Sum([]byte{}))
fn := hashFilename(h.base, hs)
if h.hashin != "" && h.hashin != hs {
return "", fmt.Errorf("Invalid hash %v != %v",
h.hashin, hs)
}
err = os.Rename(h.tmpf.Name(), fn)
if err != nil {
os.MkdirAll(filepath.Dir(fn), 0777)
os.Remove(fn)
err = os.Rename(h.tmpf.Name(), fn)
if err != nil {
log.Printf("Error renaming %v to %v: %v",
h.tmpf.Name(), fn, err)
os.Remove(h.tmpf.Name())
return "", err
}
}
h.tmpf = nil
return hs, nil
}
func (h *hashRecord) Process(r io.Reader) (string, int64, error) {
length, err := io.Copy(h, r)
if err != nil {
return "", length, err
}
hs, err := h.Finish()
return hs, length, err
}
func (h *hashRecord) Close() error {
if h != nil && h.tmpf != nil {
os.Remove(h.tmpf.Name())
return h.tmpf.Close()
}
return nil
}
func cleanTmpFiles() error {
d, err := os.Open(*root)
if err != nil {
return err
}
fi, err := d.Readdir(0)
if err != nil {
return err
}
now := time.Now()
for _, fn := range fi {
cutoff := fn.ModTime().Add(1 * time.Hour)
if strings.HasPrefix(fn.Name(), "tmp") &&
cutoff.Before(now) {
log.Printf("Removing tmp file: %v", fn.Name())
err = os.Remove(filepath.Join(*root, fn.Name()))
if err != nil {
log.Printf("Error cleaning %v: %v",
fn.Name(), err)
}
}
}
return nil
}