-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.go
More file actions
324 lines (272 loc) · 7.51 KB
/
Copy pathfile.go
File metadata and controls
324 lines (272 loc) · 7.51 KB
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
package password
import (
"bytes"
"encoding/json"
"fmt"
"github.com/image357/password/log"
"io/fs"
"os"
pathlib "path"
"path/filepath"
"sort"
"strings"
"sync"
"unicode/utf8"
)
// DefaultStorePath is the default relative storage path of a file storage backend.
const DefaultStorePath = "./password"
// DefaultFileEnding is the default file extension for password files.
const DefaultFileEnding string = "pwd"
// storageFileMode controls the file permission set by this package.
const storageFileMode os.FileMode = 0600
// storageDirMode controls the directory permission set by this package.
const storageDirMode os.FileMode = 0700
// FileStorage is a file based storage backend.
type FileStorage struct {
// storePath holds the absolute storage path.
storePath string
// storageTree holds an id to sync.Mutex map for thread-safe file access.
storageTree map[string]*sync.Mutex
// storageTreeLockCount holds an id to count map for cleaning up unused sync.Mutex entries in storageTree.
storageTreeLockCount map[string]int
// storageTreeMutex controls thread-safe access to the storageTree.
storageTreeMutex sync.Mutex
}
// NewFileStorage returns a default initialized storage backend for persistent files.
func NewFileStorage() *FileStorage {
f := new(FileStorage)
f.SetStorePath(DefaultStorePath)
f.storageTree = make(map[string]*sync.Mutex)
f.storageTreeLockCount = make(map[string]int)
return f
}
// GetStorePath returns the current storage path with system-specific path separators.
func (f *FileStorage) GetStorePath() string {
return filepath.FromSlash(f.storePath)
}
// SetStorePath accepts a new storage path with system-unspecific or mixed path separators.
func (f *FileStorage) SetStorePath(path string) {
temp, err := filepath.Abs(path)
if err != nil {
log.Warn("cannot resolve absolute storage path", "path", path)
} else {
path = temp
}
path = normalizeSeparator(path)
f.storePath = pathlib.Clean(path)
}
// FilePath returns the storage filepath of a given password-id with system-specific path separators.
// It accepts system-unspecific or mixed id separators, i.e. forward- and backward-slashes are treated as the same character.
func (f *FileStorage) FilePath(id string) string {
id = NormalizeId(id)
return filepath.FromSlash(pathlib.Join(f.storePath, id+"."+DefaultFileEnding))
}
// lockId locks a storage id mutex by first locking the storage tree and increasing lock count.
func (f *FileStorage) lockId(id string) {
id = NormalizeId(id)
// get mutex with side effects (create if necessary)
f.storageTreeMutex.Lock()
idMutex, ok := f.storageTree[id]
if !ok {
idMutex = &sync.Mutex{}
f.storageTree[id] = idMutex
}
f.storageTreeLockCount[id]++
f.storageTreeMutex.Unlock()
// lock mutex
idMutex.Lock()
}
// unlockId locks a storage id mutex by first locking the storage tree and decreasing lock count.
// The storage tree is cleaned from id if lock count is zero.
func (f *FileStorage) unlockId(id string) {
id = NormalizeId(id)
// try get mutex without side effects
f.storageTreeMutex.Lock()
idMutex, ok := f.storageTree[id]
if !ok {
delete(f.storageTree, id)
delete(f.storageTreeLockCount, id)
}
f.storageTreeMutex.Unlock()
if !ok {
// abort on missing mutex
return
} else {
// unlock mutex
idMutex.Unlock()
}
// cleanup if last lock
f.storageTreeMutex.Lock()
f.storageTreeLockCount[id]--
if f.storageTreeLockCount[id] <= 0 {
delete(f.storageTree, id)
delete(f.storageTreeLockCount, id)
}
f.storageTreeMutex.Unlock()
}
// Store (create/overwrite) the provided data in a file.
// id is converted to the corresponding filepath.
// If necessary, subfolders are created.
func (f *FileStorage) Store(id string, data string) error {
filePath := f.FilePath(id)
folderPath, _ := filepath.Split(filePath)
if folderPath != "" {
err := os.MkdirAll(folderPath, storageDirMode)
if err != nil {
return err
}
}
f.lockId(id)
defer f.unlockId(id)
err := os.WriteFile(filePath, []byte(data), storageFileMode)
if err != nil {
_ = os.Remove(filePath)
return err
}
return nil
}
// Retrieve data from an existing file.
// id is converted to the corresponding filepath.
func (f *FileStorage) Retrieve(id string) (string, error) {
f.lockId(id)
defer f.unlockId(id)
textBytes, err := os.ReadFile(f.FilePath(id))
if err != nil {
return "", err
}
if !utf8.Valid(textBytes) {
return "", fmt.Errorf("invalid utf8 character after file reading")
}
text := string(textBytes)
return text, nil
}
// Exists tests if a given id already exists in the storage backend.
func (f *FileStorage) Exists(id string) (bool, error) {
_, err := os.Stat(f.FilePath(id))
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return false, err
}
// List all stored password-ids.
func (f *FileStorage) List() ([]string, error) {
list := make([]string, 0, 16)
err := filepath.WalkDir(f.GetStorePath(), func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if !strings.HasSuffix(d.Name(), "."+DefaultFileEnding) {
return nil
}
path = strings.TrimSuffix(path, "."+DefaultFileEnding)
path, err = filepath.Rel(f.GetStorePath(), path)
if err != nil {
return err
}
path = NormalizeId(path)
list = append(list, path)
return nil
})
if err != nil {
return nil, err
}
sort.Strings(list)
return list, nil
}
// Delete an existing password.
func (f *FileStorage) Delete(id string) error {
f.lockId(id)
defer f.unlockId(id)
err := os.Remove(f.FilePath(id))
if err != nil {
return err
}
return nil
}
// Clean (delete) all stored passwords.
func (f *FileStorage) Clean() error {
list, err := f.List()
if err != nil {
return err
}
var lastErr error = nil
for _, l := range list {
err = f.Delete(l)
if err != nil {
lastErr = err
}
}
return lastErr
}
// DumpJSON serializes the storage backend to a JSON string.
// Warning: This method does not block operations on the underlying storage backend (read/write/create/delete).
// You should stop operations manually before usage or ignore the reported error.
// Data consistency is guaranteed.
func (f *FileStorage) DumpJSON() (string, error) {
// prepare encoder
temp := new(bytes.Buffer)
enc := json.NewEncoder(temp)
enc.SetEscapeHTML(false)
enc.SetIndent("", "")
// get ids
list, err := f.List()
if err != nil {
return "", err
}
// loop storage
var lastErr error = nil
var registry = make(map[string]string)
for _, id := range list {
data, err := f.Retrieve(id)
if err != nil {
lastErr = err
continue
}
registry[id] = data
}
// serialize
err = enc.Encode(registry)
if err != nil {
return "", err
}
return strings.ReplaceAll(temp.String(), "\n", ""), lastErr
}
// LoadJSON deserializes a JSON string into the storage backend.
// Warning: This method does not block operations on the underlying storage backend (read/write/create/delete).
// You should stop operations manually before usage or ignore the reported error.
// Data consistency is guaranteed.
func (f *FileStorage) LoadJSON(input string) error {
// prepare decoder
dec := json.NewDecoder(strings.NewReader(input))
dec.DisallowUnknownFields()
// deserialize
temp := make(map[string]interface{})
err := dec.Decode(&temp)
if err != nil {
return err
}
// check value types
for _, v := range temp {
switch v.(type) {
case string:
// pass
default:
return invalidStorageTypeErr
}
}
// write data files
var lastErr error = nil
for k, v := range temp {
err := f.Store(k, v.(string))
if err != nil {
lastErr = err
}
}
return lastErr
}