-
Notifications
You must be signed in to change notification settings - Fork 1
/
manifest.go
110 lines (87 loc) · 2.03 KB
/
manifest.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
package eagle
import (
"bytes"
"encoding/binary"
"errors"
"io/ioutil"
"os"
"github.com/ostafen/eagle/crypto"
)
func decryptFileIfNeeded(data []byte) ([]byte, error) {
if !dbOptions.UseEncryption() {
return data, nil
}
iv, encryptedData := data[:16], data[16:]
cipher := crypto.NewCipher(dbOptions.EncryptKey, iv)
return cipher.Decrypt(encryptedData)
}
func readFile(filename string, value interface{}) error {
if _, err := os.Stat(filename); errors.Is(err, os.ErrNotExist) {
return nil
}
data, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
data, err = decryptFileIfNeeded(data)
if err != nil {
return err
}
err = binary.Read(bytes.NewBuffer(data), binary.BigEndian, value)
return err
}
func encryptFileIfNeeded(bytes []byte) ([]byte, error) {
if !dbOptions.UseEncryption() {
return bytes, nil
}
iv, err := crypto.GenerateIV()
if err != nil {
return bytes, err
}
cipher := crypto.NewCipher(dbOptions.EncryptKey, iv)
encrypted, err := cipher.Encrypt(bytes)
if err != nil {
return nil, err
}
withIV := make([]byte, len(encrypted)+len(iv))
copy(withIV, iv)
copy(withIV[len(iv):], encrypted)
return withIV, nil
}
const manifestFilename = "MANIFEST"
func SaveToFile(filename string, value interface{}) error {
var buf bytes.Buffer
binary.Write(&buf, binary.BigEndian, value)
bytes, err := encryptFileIfNeeded(buf.Bytes())
if err != nil {
return err
}
file, err := ioutil.TempFile("", manifestFilename)
if err != nil {
return err
}
defer os.Remove(file.Name())
defer file.Close()
if _, err = file.Write(bytes); err != nil {
return err
}
if err := file.Sync(); err != nil {
return err
}
return os.Rename(file.Name(), filename)
}
type manifest struct {
DBOpen bool
IOError bool
}
func openManifestFile(path string) (*manifest, error) {
manifest := &manifest{
DBOpen: false,
IOError: false,
}
err := readFile(path+"/"+manifestFilename, manifest)
return manifest, err
}
func (m *manifest) Save(path string) error {
return SaveToFile(path+"/"+manifestFilename, m)
}