-
Notifications
You must be signed in to change notification settings - Fork 0
/
fs_utils.go
480 lines (406 loc) · 12 KB
/
fs_utils.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
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
package backupfs
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"strings"
"syscall"
)
var (
errSymlinkInfoExpected = errors.New("expecting a symlink file-info")
errDirInfoExpected = errors.New("expecting a directory file-info")
errFileInfoExpected = errors.New("expecting a file file-info")
// internal package does not expose these errors
errCopyFileFailed = errors.New("failed to copy file")
errCopyDirFailed = errors.New("failed to copy directory")
errCopySymlinkFailed = errors.New("failed to copy symlink")
)
// / -> /a -> /a/b -> /a/b/c -> /a/b/c/d
// IterateDirTree does not clean the passed file name.
func IterateDirTree(name string, visitor func(string) (proceed bool, err error)) (aborted bool, err error) {
var (
create = false
lastIndex = 0
proceed = true
)
for i, r := range name {
create = false
if r == '/' || r == filepath.Separator {
create = true
lastIndex = max(i, 1) // root element should be visible
}
if i == len(name)-1 {
create = true
lastIndex = i + 1
}
if create {
// /path -> /path/subpath -> /path/subpath/subsubpath etc.
dirPath := name[:lastIndex]
proceed, err = visitor(dirPath)
if err != nil {
return false, err
}
if !proceed {
return true, nil
}
}
}
return false, nil
}
// ignoreChownError is solely used in Chown
func ignoreChownError(err error) error {
// first check os-specific ignorable errors, like on windoes not implemented
err = ignorableChownError(err)
// check is permission for chown is denied
// if no permission for chown, we don't chown
switch {
case errors.Is(err, fs.ErrPermission):
return nil
default:
return err
}
}
// ignoreChtimesError is solely used for Chtimes
func ignoreChtimesError(err error) error {
err = ignorableChtimesError(err)
if err == nil {
return nil
}
// check is permission for chown is denied
// if no permission for chown, we don't chtimes
switch {
case errors.Is(err, fs.ErrPermission):
return nil
default:
return err
}
}
func copyDir(fs FS, name string, info fs.FileInfo) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("%w: %s: %v", errCopyDirFailed, name, err)
}
}()
if !info.IsDir() {
return fmt.Errorf("%w: %s", errDirInfoExpected, name)
}
// do not touch the root directory
// this is either the OS root directory, which we do not want to change, as
// on for example redhat it's a read only directory which is not modifiable.
// on the other hand it is the root directory of the backup folder which has already its permissions
// set correctly.
pathWithoutVolume := TrimVolume(name)
if pathWithoutVolume == separator || pathWithoutVolume == "/" {
// windows supports both path separators, which is why we check for both
return nil
}
// try to create all dirs as somone might have tempered with the file system
targetMode := info.Mode()
err = fs.MkdirAll(name, targetMode.Perm())
if err != nil {
return err
}
newDirInfo, err := fs.Lstat(name)
if err != nil {
return fmt.Errorf("%w: %v", errCopyDirFailed, err)
}
currentMode := newDirInfo.Mode()
if !equalMode(currentMode, targetMode) {
err = fs.Chmod(name, targetMode)
if err != nil {
// TODO: do we want to fail here?
return err
}
}
targetModTime := info.ModTime()
currentModTime := newDirInfo.ModTime()
if !currentModTime.Equal(targetModTime) {
err = ignoreChtimesError(fs.Chtimes(name, targetModTime, targetModTime))
if err != nil {
return err
}
}
// https://pkg.go.dev/os#Chown
// Windows & Plan9 not supported
err = ignoreChownError(chown(info, name, fs))
if err != nil {
return err
}
return nil
}
func copyFile(fs FS, name string, info fs.FileInfo, sourceFile File) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("%w: %s: %v", errCopyFileFailed, name, err)
}
}()
if !info.Mode().IsRegular() {
return fmt.Errorf("%w: %s", errFileInfoExpected, name)
}
//
targetMode := info.Mode()
err = writeFile(fs, name, targetMode.Perm(), sourceFile)
if err != nil {
return err
}
newFileInfo, err := fs.Lstat(name)
if err != nil {
return err
}
if !equalMode(newFileInfo.Mode(), targetMode) {
// not equal, update it
err = fs.Chmod(name, targetMode)
if err != nil {
return err
}
}
targetModTime := info.ModTime()
currentModTime := newFileInfo.ModTime()
if !currentModTime.Equal(targetModTime) {
err = ignoreChtimesError(fs.Chtimes(name, targetModTime, targetModTime))
if err != nil {
return err
}
}
// might cause a windows error that this function is not implemented by the OS
// in a unix fassion
// permission and not implemented errors are ignored
err = ignoreChownError(chown(info, name, fs))
if err != nil {
return err
}
return nil
}
func writeFile(fs FS, name string, perm fs.FileMode, content io.Reader) (err error) {
// same as create but with custom permissions
file, err := fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, perm.Perm())
if err != nil {
return err
}
defer func() {
err = errors.Join(err, file.Close())
}()
_, err = io.Copy(file, content)
if err != nil {
return err
}
return nil
}
func copySymlink(source, target FS, name string, info fs.FileInfo) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("%w: %s: %v", errCopySymlinkFailed, name, err)
}
}()
if info.Mode()&os.ModeType&os.ModeSymlink == 0 {
return fmt.Errorf("%w: %s", errSymlinkInfoExpected, name)
}
pointsAt, err := source.Readlink(name)
if err != nil {
return err
}
err = target.Symlink(pointsAt, name)
if err != nil {
return err
}
return ignoreChownError(target.Lchown(name, toUID(info), toGID(info)))
}
// Chown is an operating system dependent implementation.
// only tries to change owner in cas ethat the owner differs
func chown(from fs.FileInfo, toName string, fs FS) error {
oldOwnerFi, err := fs.Lstat(toName)
if err != nil {
return fmt.Errorf("lstat for chown failed: %w", err)
}
oldUid := toUID(oldOwnerFi)
oldGid := toGID(oldOwnerFi)
newUid := toUID(from)
newGid := toGID(from)
// only update when something changed
if oldUid != newUid || oldGid != newGid {
err = fs.Chown(toName, toUID(from), toGID(from))
if err != nil {
return err
}
}
return nil
}
func restoreFile(name string, backupFi fs.FileInfo, base, backup FS) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("failed to restore file: %s: %w", name, err)
}
}()
f, err := backup.Open(name)
if err != nil {
// best effort, if backup was tempered with, we cannot restore the file.
return nil
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
// best effort, see above
return nil
}
if !fi.Mode().IsRegular() {
// remove dir/symlink/etc and create a file there
err = base.RemoveAll(name)
if err != nil {
// we failed to remove the directory
// supposedly we cannot restore the file, as the directory still exists
return nil
}
}
// in case that the application dooes not hold any backup data in memory anymore
// we fallback to using the file permissions of the actual backed up file
if backupFi != nil {
fi = backupFi
}
// move file back to base system
err = copyFile(base, name, backupFi, f)
if err != nil {
// failed to restore file
// critical error, most likely due to network problems
return err
}
return nil
}
func restoreSymlink(name string, backupFi fs.FileInfo, base, backup FS) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("failed to restore symlink: %s: %w", name, err)
}
}()
_, exists, err := lexists(backup, name)
if err != nil || !exists {
// best effort, if backup broken, we cannot restore
return nil
}
_, newFileExists, err := lexists(base, name)
if err == nil && newFileExists {
// remove dir/symlink/etc and create a new symlink there
err = base.RemoveAll(name)
if err != nil {
// in case we fail to remove the new file,
// we cannot restore the symlink
// best effort, fail silently
return nil
}
}
// try to restore symlink
return copySymlink(backup, base, name, backupFi)
}
// Check if a symlin, file or directory exists.
func lexists(fsys FS, path string) (fs.FileInfo, bool, error) {
fi, err := fsys.Lstat(path)
if isNotFoundError(err) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
return fi, true, nil
}
// equalMode is os-Dependent
func equalMode(a, b fs.FileMode) bool {
// mask with os-specific masks
a &= chmodBits
b &= chmodBits
return a == b
}
// toAbsSymlink always returns the absolute path to a symlink.
// newname is the symlink location, oldname is the location that
// the symlink is supposed point at. If oldname is a relative path,
// then the absolute path is calculated and returned instead.
func toAbsSymlink(oldname, newname string) string {
if !isAbs(oldname) {
return filepath.Join(filepath.Dir(newname), oldname)
}
return oldname
}
// toRelSymlink always returns the relative path to a symlink.
// newname is the symlink location, oldname is the location that
// the symlink is supposed point at. If oldname is an absolute path,
// then the relative path is calculated and returned instead.
//func toRelSymlink(oldname, newname string) (string, error) {
// if isAbs(oldname) {
// return filepath.Rel(filepath.Dir(newname), oldname)
// }
// return oldname, nil
//}
func isAbs(name string) bool {
return path.IsAbs(filepath.ToSlash(name)) || filepath.IsAbs(filepath.FromSlash(name))
}
type resolverFS interface {
Lstat(name string) (fs.FileInfo, error)
Readlink(name string) (string, error)
}
func resolvePath(fsys resolverFS, filePath string) (resolvedFilePath string, err error) {
resolvedFilePath, _, err = resolvePathWithInfo(fsys, filePath)
return resolvedFilePath, err
}
func resolvePathWithFound(fsys resolverFS, filePath string) (resolvedFilePath string, found bool, err error) {
resolvedFilePath, fi, err := resolvePathWithInfo(fsys, filePath)
return resolvedFilePath, fi != nil, err
}
// resolvePath resolves a path that contains symlinks.
// The returned path is the resolved path.
// In case that the returned path is not equal to the path that was passed to this function
// then there was a symlink somewhere along the way to that file or directory.
// WARNING: The last element of the path is NOT resolved.
// Returns the file info of the last unresolved element.
// In case that the file path was not found, the returned FileInfo is nil.
func resolvePathWithInfo(fsys resolverFS, filePath string) (resolvedFilePath string, fi fs.FileInfo, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("failed to resolve path: %s: %w", filePath, err)
}
}()
if filePath == "" {
return "", nil, errors.New("empty file path")
}
accPaths := make([]string, 0, strings.Count(filePath, separator))
// collect all subdir segmrents
_, _ = IterateDirTree(filePath, func(subdirPath string) (bool, error) {
accPaths = append(accPaths, subdirPath)
return true, nil
})
// do not use range here
for i := 0; i < len(accPaths); i++ {
p := accPaths[i]
// iterate over all accumulated path segments /a -> /a/b -> /a/b/c.txt etc.
fi, err = fsys.Lstat(p)
if err != nil {
if isNotFoundError(err) {
// return current resolved path state even if it was not found
// e.g. /a/symlink/test.txt with /a/symlink pointing to /a/folder, then the resolved nam ewill be /a/folder/test.txt
return accPaths[len(accPaths)-1], nil, nil
}
return "", nil, err
}
// check if symlink
if fi.Mode()&os.ModeSymlink != 0 {
// resolve symlink
linkedPath, err := fsys.Readlink(p)
if err != nil {
return "", nil, err
}
linkedPath = toAbsSymlink(linkedPath, p)
// update slice in place for all following paths after the symlink
replacePathPrefix(accPaths[i+1:], p, linkedPath)
}
}
return accPaths[len(accPaths)-1], fi, nil
}
func replacePathPrefix(paths []string, oldPrefix, newPrefix string) {
for idx, path := range paths {
paths[idx] = filepath.Join(newPrefix, strings.TrimPrefix(path, oldPrefix))
}
}
func isNotFoundError(err error) bool {
return errors.Is(err, fs.ErrNotExist) || errors.Is(err, syscall.ENOENT) || errors.Is(err, syscall.ENOTDIR)
}