forked from ipfs/kubo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwritable.go
More file actions
792 lines (711 loc) · 24.1 KB
/
writable.go
File metadata and controls
792 lines (711 loc) · 24.1 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
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
// Package writable implements FUSE filesystem types shared by the
// mutable /mfs and /ipns mounts. Both mounts expose MFS directories
// as writable POSIX filesystems; the only differences are how the
// root is created and how xattr names are published.
//
//go:build (linux || darwin || freebsd) && !nofuse
package writable
import (
"context"
"io"
"os"
"sync"
"syscall"
"time"
"github.com/hanwen/go-fuse/v2/fs"
"github.com/hanwen/go-fuse/v2/fuse"
"github.com/ipfs/boxo/files"
dag "github.com/ipfs/boxo/ipld/merkledag"
ft "github.com/ipfs/boxo/ipld/unixfs"
uio "github.com/ipfs/boxo/ipld/unixfs/io"
"github.com/ipfs/boxo/mfs"
ipld "github.com/ipfs/go-ipld-format"
logging "github.com/ipfs/go-log/v2"
fusemnt "github.com/ipfs/kubo/fuse/mount"
)
var log = logging.Logger("fuse/writable")
// Config controls write-side behavior for writable mounts.
type Config struct {
StoreMtime bool // persist mtime on create and open-for-write
StoreMode bool // persist mode on chmod
DAG ipld.DAGService // required: read-only opens use it to bypass MFS desclock
// RepoPath is the on-disk path of the IPFS repo (e.g. ~/.ipfs).
// Statfs calls syscall.Statfs on this path so that the FUSE mount
// reports how much free space is left on the volume that stores
// MFS data. Without it tools like macOS Finder see zero free space
// and refuse to copy files.
RepoPath string
}
// NewDir creates a Dir node backed by the given MFS directory.
// cfg.DAG is required: read-only file opens build a DagReader directly
// from it to avoid MFS's desclock (see FileInode.Open). Passing a nil
// DAG would silently re-introduce the rsync --inplace deadlock, so we
// fail loudly at construction time instead.
func NewDir(d *mfs.Directory, cfg *Config) *Dir {
if cfg == nil || cfg.DAG == nil {
panic("fuse/writable: Config.DAG is required")
}
return &Dir{MFSDir: d, Cfg: cfg}
}
// Dir is the FUSE adapter for MFS directories.
type Dir struct {
fs.Inode
MFSDir *mfs.Directory
Cfg *Config
}
func (d *Dir) fillAttr(a *fuse.Attr) {
a.Mode = uint32(fusemnt.DefaultDirModeRW.Perm())
if m, err := d.MFSDir.Mode(); err == nil && m != 0 {
a.Mode = files.ModePermsToUnixPerms(m)
}
if t, err := d.MFSDir.ModTime(); err == nil && !t.IsZero() {
a.SetTimes(nil, &t, nil)
}
}
func (d *Dir) Getattr(_ context.Context, _ fs.FileHandle, out *fuse.AttrOut) syscall.Errno {
d.fillAttr(&out.Attr)
return 0
}
// Statfs reports disk-space statistics for the underlying filesystem.
// macOS Finder checks free space before copying; without this it
// reports "not enough free space" because go-fuse returns zeroed stats.
func (d *Dir) Statfs(_ context.Context, out *fuse.StatfsOut) syscall.Errno {
if d.Cfg.RepoPath == "" {
return 0
}
var s syscall.Statfs_t
if err := syscall.Statfs(d.Cfg.RepoPath, &s); err != nil {
return fs.ToErrno(err)
}
out.FromStatfsT(&s)
return 0
}
// Setattr handles chmod and mtime changes on directories.
// Tools like tar and rsync set directory timestamps after extraction.
//
// Mode and mtime are stored as UnixFS optional metadata.
// The UnixFS spec supports all 12 permission bits, but boxo's MFS
// layer exposes only the lower 9 (ugo-rwx); setuid/setgid/sticky
// are silently dropped. FUSE mounts are always nosuid so these
// bits would have no execution effect anyway.
// See https://specs.ipfs.tech/unixfs/#dag-pb-optional-metadata
func (d *Dir) Setattr(_ context.Context, _ fs.FileHandle, in *fuse.SetAttrIn, out *fuse.AttrOut) syscall.Errno {
if mode, ok := in.GetMode(); ok && d.Cfg.StoreMode {
if err := d.MFSDir.SetMode(files.UnixPermsToModePerms(mode)); err != nil {
return fs.ToErrno(err)
}
}
if mtime, ok := in.GetMTime(); ok && d.Cfg.StoreMtime {
if err := d.MFSDir.SetModTime(mtime); err != nil {
return fs.ToErrno(err)
}
}
d.fillAttr(&out.Attr)
return 0
}
func (d *Dir) Lookup(ctx context.Context, name string, out *fuse.EntryOut) (*fs.Inode, syscall.Errno) {
mfsNode, err := d.MFSDir.Child(name)
if err != nil {
return nil, syscall.ENOENT
}
switch mfsNode.Type() {
case mfs.TDir:
child := &Dir{MFSDir: mfsNode.(*mfs.Directory), Cfg: d.Cfg}
child.fillAttr(&out.Attr)
return d.NewInode(ctx, child, fs.StableAttr{Mode: syscall.S_IFDIR}), 0
case mfs.TFile:
mfsFile := mfsNode.(*mfs.File)
if target := SymlinkTarget(mfsFile); target != "" {
child := &Symlink{Target: target, MFSFile: mfsFile, Cfg: d.Cfg}
child.fillAttr(&out.Attr)
return d.NewInode(ctx, child, fs.StableAttr{Mode: syscall.S_IFLNK}), 0
}
child := &FileInode{MFSFile: mfsFile, Cfg: d.Cfg}
child.fillAttr(&out.Attr)
return d.NewInode(ctx, child, fs.StableAttr{}), 0
default:
log.Errorf("unexpected MFS node type %d under directory", mfsNode.Type())
return nil, syscall.EIO
}
}
func (d *Dir) Readdir(ctx context.Context) (fs.DirStream, syscall.Errno) {
nodes, err := d.MFSDir.List(ctx)
if err != nil {
return nil, fs.ToErrno(err)
}
entries := make([]fuse.DirEntry, len(nodes))
for i, node := range nodes {
var mode uint32
switch {
case node.Type == int(mfs.TDir):
mode = syscall.S_IFDIR
case node.Type == int(mfs.TFile):
// MFS represents symlinks as TFile; check the DAG node.
if child, err := d.MFSDir.Child(node.Name); err == nil {
if f, ok := child.(*mfs.File); ok && SymlinkTarget(f) != "" {
mode = syscall.S_IFLNK
}
}
}
entries[i] = fuse.DirEntry{Name: node.Name, Mode: mode}
}
return fs.NewListDirStream(entries), 0
}
// Mkdir creates a new directory under d.
//
// TODO: boxo's mfs.Directory.Mkdir(name string) accepts no mode
// argument, so the caller's mode is silently dropped here. Tools
// that mkdir then chown without a follow-up chmod (some tar/rsync
// flows) see the default 0755 instead of the requested mode.
// Fixing this requires a boxo MFS API change.
func (d *Dir) Mkdir(ctx context.Context, name string, _ uint32, out *fuse.EntryOut) (*fs.Inode, syscall.Errno) {
mfsDir, err := d.MFSDir.Mkdir(name)
if err != nil {
return nil, fs.ToErrno(err)
}
child := &Dir{MFSDir: mfsDir, Cfg: d.Cfg}
// Fill the response attrs so the kernel doesn't cache zero values
// until AttrTimeout expires. Matches Dir.Create and FileInode.Setattr.
child.fillAttr(&out.Attr)
return d.NewInode(ctx, child, fs.StableAttr{Mode: syscall.S_IFDIR}), 0
}
func (d *Dir) Unlink(_ context.Context, name string) syscall.Errno {
if err := d.MFSDir.Unlink(name); err != nil {
return fs.ToErrno(err)
}
return fs.ToErrno(d.MFSDir.Flush())
}
func (d *Dir) Rmdir(ctx context.Context, name string) syscall.Errno {
child, err := d.MFSDir.Child(name)
if err != nil {
return fs.ToErrno(err)
}
target, ok := child.(*mfs.Directory)
if !ok {
return syscall.ENOTDIR
}
children, err := target.ListNames(ctx)
if err != nil {
return fs.ToErrno(err)
}
if len(children) > 0 {
return syscall.ENOTEMPTY
}
if err := d.MFSDir.Unlink(name); err != nil {
return fs.ToErrno(err)
}
return fs.ToErrno(d.MFSDir.Flush())
}
// Rename moves an entry across MFS directories.
//
// TODO: this is not atomic. The source is unlinked before the
// destination is added, so any failure between the two steps loses
// the source entry. Making it atomic requires changes to MFS rename
// semantics (boxo/mfs does not currently expose an atomic rename).
func (d *Dir) Rename(_ context.Context, oldName string, newParent fs.InodeEmbedder, newName string, _ uint32) syscall.Errno {
child, err := d.MFSDir.Child(oldName)
if err != nil {
return fs.ToErrno(err)
}
nd, err := child.GetNode()
if err != nil {
return fs.ToErrno(err)
}
// Unlink the source first. For same-directory renames, this clears
// the old name from the directory's entry cache before AddChild
// repopulates it with the new name. Without this ordering, Flush
// would sync the stale cache entry back into the DAG.
if err := d.MFSDir.Unlink(oldName); err != nil {
return fs.ToErrno(err)
}
targetDir, ok := newParent.EmbeddedInode().Operations().(*Dir)
if !ok {
return syscall.EINVAL
}
if err := targetDir.MFSDir.Unlink(newName); err != nil && err != os.ErrNotExist {
return fs.ToErrno(err)
}
if err := targetDir.MFSDir.AddChild(newName, nd); err != nil {
return fs.ToErrno(err)
}
return fs.ToErrno(d.MFSDir.Flush())
}
func (d *Dir) Create(ctx context.Context, name string, flags uint32, _ uint32, out *fuse.EntryOut) (*fs.Inode, fs.FileHandle, uint32, syscall.Errno) {
node := dag.NodeWithData(ft.FilePBData(nil, 0))
if err := node.SetCidBuilder(d.MFSDir.GetCidBuilder()); err != nil {
return nil, nil, 0, fs.ToErrno(err)
}
if err := d.MFSDir.AddChild(name, node); err != nil {
return nil, nil, 0, fs.ToErrno(err)
}
if err := d.MFSDir.Flush(); err != nil {
return nil, nil, 0, fs.ToErrno(err)
}
mfsNode, err := d.MFSDir.Child(name)
if err != nil {
return nil, nil, 0, fs.ToErrno(err)
}
if d.Cfg.StoreMtime {
if err := mfsNode.SetModTime(time.Now()); err != nil {
return nil, nil, 0, fs.ToErrno(err)
}
}
mfsFile, ok := mfsNode.(*mfs.File)
if !ok {
return nil, nil, 0, syscall.EIO
}
fileInode := &FileInode{MFSFile: mfsFile, Cfg: d.Cfg}
accessMode := flags & syscall.O_ACCMODE
fd, err := mfsFile.Open(mfs.Flags{
Read: accessMode == syscall.O_RDONLY || accessMode == syscall.O_RDWR,
Write: accessMode == syscall.O_WRONLY || accessMode == syscall.O_RDWR,
Sync: true,
})
if err != nil {
return nil, nil, 0, fs.ToErrno(err)
}
// Fill the response attrs so the kernel doesn't cache zero values
// (mode 0, size 0) for the new inode until AttrTimeout expires.
// fstat on the open file handle returned to the caller hits this
// cache, so leaving it empty makes f.Stat() report mode 0 right
// after open. Matches FileInode.Setattr and Dir.Mkdir.
fileInode.fillAttr(&out.Attr)
inode := d.NewInode(ctx, fileInode, fs.StableAttr{})
return inode, &FileHandle{inode: inode, fd: fd}, 0, 0
}
func (d *Dir) Listxattr(_ context.Context, dest []byte) (uint32, syscall.Errno) {
data := []byte(fusemnt.XattrCID + "\x00")
if len(dest) == 0 {
return uint32(len(data)), 0
}
if len(dest) < len(data) {
return 0, syscall.ERANGE
}
return uint32(copy(dest, data)), 0
}
func (d *Dir) Getxattr(_ context.Context, attr string, dest []byte) (uint32, syscall.Errno) {
if attr == fusemnt.XattrCIDDeprecated {
log.Errorf("xattr %q is deprecated, use %q instead", fusemnt.XattrCIDDeprecated, fusemnt.XattrCID)
attr = fusemnt.XattrCID
}
if attr != fusemnt.XattrCID {
return 0, fs.ENOATTR
}
nd, err := d.MFSDir.GetNode()
if err != nil {
return 0, fs.ToErrno(err)
}
data := []byte(nd.Cid().String())
if len(dest) == 0 {
return uint32(len(data)), 0
}
if len(dest) < len(data) {
return 0, syscall.ERANGE
}
return uint32(copy(dest, data)), 0
}
// Symlink creates a new symlink in this directory.
func (d *Dir) Symlink(ctx context.Context, target, name string, out *fuse.EntryOut) (*fs.Inode, syscall.Errno) {
data, err := ft.SymlinkData(target)
if err != nil {
return nil, fs.ToErrno(err)
}
nd := dag.NodeWithData(data)
if err := nd.SetCidBuilder(d.MFSDir.GetCidBuilder()); err != nil {
return nil, fs.ToErrno(err)
}
if err := d.MFSDir.AddChild(name, nd); err != nil {
return nil, fs.ToErrno(err)
}
if err := d.MFSDir.Flush(); err != nil {
return nil, fs.ToErrno(err)
}
// Retrieve the mfs.File so Setattr can persist mtime.
mfsNode, err := d.MFSDir.Child(name)
if err != nil {
return nil, fs.ToErrno(err)
}
mfsFile, _ := mfsNode.(*mfs.File)
sym := &Symlink{Target: target, MFSFile: mfsFile, Cfg: d.Cfg}
sym.fillAttr(&out.Attr)
return d.NewInode(ctx, sym, fs.StableAttr{Mode: syscall.S_IFLNK}), 0
}
// FileInode is the FUSE adapter for MFS file inodes.
type FileInode struct {
fs.Inode
MFSFile *mfs.File
Cfg *Config
}
func (fi *FileInode) fillAttr(a *fuse.Attr) {
size, _ := fi.MFSFile.Size()
a.Size = uint64(size)
a.Mode = uint32(fusemnt.DefaultFileModeRW.Perm())
if m, err := fi.MFSFile.Mode(); err == nil && m != 0 {
a.Mode = files.ModePermsToUnixPerms(m)
}
if t, _ := fi.MFSFile.ModTime(); !t.IsZero() {
a.SetTimes(nil, &t, nil)
}
}
func (fi *FileInode) Getattr(_ context.Context, _ fs.FileHandle, out *fuse.AttrOut) syscall.Errno {
fi.fillAttr(&out.Attr)
return 0
}
func (fi *FileInode) Open(ctx context.Context, flags uint32) (fs.FileHandle, uint32, syscall.Errno) {
accessMode := flags & syscall.O_ACCMODE
// Read-only opens bypass MFS's desclock by creating a DagReader
// directly from the current DAG node. MFS holds desclock.RLock
// for the lifetime of a read descriptor, which blocks any
// concurrent write open on the same file (desclock.Lock). Tools
// like rsync --inplace open the destination for reading and
// writing simultaneously, deadlocking on MFS's lock. Creating
// a DagReader here avoids the lock entirely: the reader gets a
// snapshot of the file at open time, and writers proceed through
// MFS independently. Cfg.DAG is required by NewDir.
if accessMode == syscall.O_RDONLY {
nd, err := fi.MFSFile.GetNode()
if err != nil {
return nil, 0, fs.ToErrno(err)
}
r, err := uio.NewDagReader(ctx, nd, fi.Cfg.DAG)
if err != nil {
return nil, 0, fusemnt.ReadErrno(err)
}
return &roFileHandle{r: r}, fuse.FOPEN_KEEP_CACHE, 0
}
mfsFlags := mfs.Flags{
Read: accessMode == syscall.O_RDONLY || accessMode == syscall.O_RDWR,
Write: accessMode == syscall.O_WRONLY || accessMode == syscall.O_RDWR,
Sync: true,
}
fd, err := fi.MFSFile.Open(mfsFlags)
if err != nil {
return nil, 0, fs.ToErrno(err)
}
if flags&syscall.O_TRUNC != 0 {
if !mfsFlags.Write {
fd.Close()
log.Error("tried to open a readonly file with truncate")
return nil, 0, syscall.ENOTSUP
}
if err := fd.Truncate(0); err != nil {
fd.Close()
return nil, 0, fs.ToErrno(err)
}
}
// O_APPEND is handled in FileHandle.Write by seeking to end.
if mfsFlags.Write && fi.Cfg.StoreMtime {
if err := fi.MFSFile.SetModTime(time.Now()); err != nil {
fd.Close()
return nil, 0, fs.ToErrno(err)
}
}
return &FileHandle{inode: fi.EmbeddedInode(), fd: fd, appendMode: flags&syscall.O_APPEND != 0}, 0, 0
}
// Setattr handles chmod, mtime changes (touch), and ftruncate.
//
// Mode and mtime are stored as UnixFS optional metadata.
// The UnixFS spec supports all 12 permission bits, but boxo's MFS
// layer exposes only the lower 9 (ugo-rwx); setuid/setgid/sticky
// are silently dropped. FUSE mounts are always nosuid so these
// bits would have no execution effect anyway.
// See https://specs.ipfs.tech/unixfs/#dag-pb-optional-metadata
//
// With hanwen/go-fuse, the kernel passes the open file handle (fh) when
// the caller uses ftruncate(fd, size). This lets us truncate through
// the existing write descriptor without opening a second one. For
// truncate(path, size) without a handle, a temporary descriptor is
// opened; this may block if another writer holds MFS's desclock.
func (fi *FileInode) Setattr(_ context.Context, fh fs.FileHandle, in *fuse.SetAttrIn, out *fuse.AttrOut) syscall.Errno {
if sz, ok := in.GetSize(); ok {
if f, ok := fh.(*FileHandle); ok {
// ftruncate(fd, size): use the existing write descriptor.
f.mu.Lock()
err := f.fd.Truncate(int64(sz))
f.mu.Unlock()
if err != nil {
return fs.ToErrno(err)
}
} else {
// truncate(path, size) without an open file descriptor.
// Open a temporary write descriptor, truncate, flush, and
// close. This may block if another writer holds MFS's
// desclock; the FUSE kernel timeout (30s) bounds the wait.
fd, err := fi.MFSFile.Open(mfs.Flags{Write: true, Sync: true})
if err != nil {
return fs.ToErrno(err)
}
if err := fd.Truncate(int64(sz)); err != nil {
fd.Close()
return fs.ToErrno(err)
}
if err := fd.Flush(); err != nil {
fd.Close()
return fs.ToErrno(err)
}
if err := fd.Close(); err != nil {
return fs.ToErrno(err)
}
}
}
if mode, ok := in.GetMode(); ok && fi.Cfg.StoreMode {
if err := fi.MFSFile.SetMode(files.UnixPermsToModePerms(mode)); err != nil {
return fs.ToErrno(err)
}
}
if mtime, ok := in.GetMTime(); ok && fi.Cfg.StoreMtime {
if err := fi.MFSFile.SetModTime(mtime); err != nil {
return fs.ToErrno(err)
}
}
// Fill the response attrs so the kernel doesn't cache stale zero
// values until AttrTimeout expires. Matches Dir.Setattr behavior.
fi.fillAttr(&out.Attr)
return 0
}
func (fi *FileInode) Listxattr(_ context.Context, dest []byte) (uint32, syscall.Errno) {
data := []byte(fusemnt.XattrCID + "\x00")
if len(dest) == 0 {
return uint32(len(data)), 0
}
if len(dest) < len(data) {
return 0, syscall.ERANGE
}
return uint32(copy(dest, data)), 0
}
func (fi *FileInode) Getxattr(_ context.Context, attr string, dest []byte) (uint32, syscall.Errno) {
if attr == fusemnt.XattrCIDDeprecated {
log.Errorf("xattr %q is deprecated, use %q instead", fusemnt.XattrCIDDeprecated, fusemnt.XattrCID)
attr = fusemnt.XattrCID
}
if attr != fusemnt.XattrCID {
return 0, fs.ENOATTR
}
nd, err := fi.MFSFile.GetNode()
if err != nil {
return 0, fs.ToErrno(err)
}
data := []byte(nd.Cid().String())
if len(dest) == 0 {
return uint32(len(data)), 0
}
if len(dest) < len(data) {
return 0, syscall.ERANGE
}
return uint32(copy(dest, data)), 0
}
// FileHandle wraps an MFS file descriptor for FUSE operations.
// All methods are serialized by mu because the FUSE server dispatches
// each request in its own goroutine and the underlying DagModifier
// is not safe for concurrent use.
type FileHandle struct {
inode *fs.Inode // back-pointer for kernel cache invalidation
fd mfs.FileDescriptor
mu sync.Mutex
appendMode bool // O_APPEND: writes always go to end of file
}
func (fh *FileHandle) Read(ctx context.Context, dest []byte, off int64) (fuse.ReadResult, syscall.Errno) {
fh.mu.Lock()
defer fh.mu.Unlock()
if _, err := fh.fd.Seek(off, io.SeekStart); err != nil {
return nil, fs.ToErrno(err)
}
size, err := fh.fd.Size()
if err != nil {
return nil, fs.ToErrno(err)
}
n := min(len(dest), int(size-off))
if n <= 0 {
return fuse.ReadResultData(nil), 0
}
got, err := fh.fd.CtxReadFull(ctx, dest[:n])
if err != nil {
return nil, fusemnt.ReadErrno(err)
}
return fuse.ReadResultData(dest[:got]), 0
}
func (fh *FileHandle) Write(_ context.Context, data []byte, off int64) (uint32, syscall.Errno) {
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.appendMode {
// O_APPEND: the kernel may send offset 0, but POSIX says
// writes must go to the end of the file.
if _, err := fh.fd.Seek(0, io.SeekEnd); err != nil {
return 0, fs.ToErrno(err)
}
n, err := fh.fd.Write(data)
if err != nil {
return 0, fs.ToErrno(err)
}
return uint32(n), 0
}
n, err := fh.fd.WriteAt(data, off)
if err != nil {
return 0, fs.ToErrno(err)
}
return uint32(n), 0
}
// Flush persists buffered writes to the DAG and invalidates the
// kernel's cached attrs so the next stat sees the updated size.
//
// We intentionally ignore ctx: the underlying MFS flush cannot be
// safely canceled mid-operation, and abandoning it would leak a
// background goroutine that races with the subsequent Release.
//
// Cache invalidation happens here (in addition to Release) because
// the kernel calls Flush synchronously inside close() but sends
// Release asynchronously after close() returns. Without this, a
// stat() immediately after close() could see stale cached attrs.
func (fh *FileHandle) Flush(_ context.Context) syscall.Errno {
fh.mu.Lock()
defer fh.mu.Unlock()
err := fh.fd.Flush()
if fh.inode != nil {
_ = fh.inode.NotifyContent(0, 0)
}
return fs.ToErrno(err)
}
// Release closes the descriptor and invalidates the kernel's cached
// content and attrs so readers opening the same path see the new data.
// Invalidation happens here (not in Flush) because fd.Close commits
// the final DAG node; Flush alone may not have the final size yet.
func (fh *FileHandle) Release(_ context.Context) syscall.Errno {
fh.mu.Lock()
defer fh.mu.Unlock()
err := fh.fd.Close()
if fh.inode != nil {
_ = fh.inode.NotifyContent(0, 0)
}
return fs.ToErrno(err)
}
// Fsync flushes the write buffer through the open file descriptor and
// invalidates the kernel's cached attrs and content for this inode.
// Editors (vim, emacs) and databases call fsync after writing to
// ensure data reaches persistent storage; a fresh reader on the same
// path must see the synced bytes immediately, not the size the kernel
// cached from the initial Create response.
func (fh *FileHandle) Fsync(_ context.Context, _ uint32) syscall.Errno {
fh.mu.Lock()
defer fh.mu.Unlock()
err := fh.fd.Flush()
if fh.inode != nil {
_ = fh.inode.NotifyContent(0, 0)
}
return fs.ToErrno(err)
}
// Symlink is the FUSE adapter for UnixFS TSymlink nodes on writable mounts.
// Target is resolved once at Lookup/Create time and never changes
// (POSIX symlinks are immutable; changing the target requires unlink + symlink).
type Symlink struct {
fs.Inode
Target string
MFSFile *mfs.File // backing MFS node for mtime persistence
Cfg *Config
}
func (s *Symlink) Readlink(_ context.Context) ([]byte, syscall.Errno) {
return []byte(s.Target), 0
}
func (s *Symlink) fillAttr(a *fuse.Attr) {
a.Mode = uint32(fusemnt.SymlinkMode.Perm())
a.Size = uint64(len(s.Target))
if s.MFSFile != nil {
if t, err := s.MFSFile.ModTime(); err == nil && !t.IsZero() {
a.SetTimes(nil, &t, nil)
}
}
}
func (s *Symlink) Getattr(_ context.Context, _ fs.FileHandle, out *fuse.AttrOut) syscall.Errno {
s.fillAttr(&out.Attr)
return 0
}
// Setattr handles mtime changes on symlinks.
// Tools like rsync call lutimes on symlinks after creating them and
// treat ENOTSUP as an error. Every major FUSE filesystem (gocryptfs,
// rclone, sshfs, s3fs) implements Setattr on symlinks for this reason.
//
// Mode is always 0777 per POSIX convention (access control uses the
// target's mode), so chmod requests are silently accepted but not stored.
func (s *Symlink) Setattr(_ context.Context, _ fs.FileHandle, in *fuse.SetAttrIn, out *fuse.AttrOut) syscall.Errno {
if s.MFSFile != nil {
if mtime, ok := in.GetMTime(); ok && s.Cfg.StoreMtime {
if err := s.MFSFile.SetModTime(mtime); err != nil {
return fs.ToErrno(err)
}
}
}
s.fillAttr(&out.Attr)
return 0
}
// roFileHandle is a read-only file handle backed by a DagReader.
// Used for O_RDONLY opens to bypass MFS's desclock (see FileInode.Open).
type roFileHandle struct {
r uio.DagReader
mu sync.Mutex
}
func (fh *roFileHandle) Read(ctx context.Context, dest []byte, off int64) (fuse.ReadResult, syscall.Errno) {
fh.mu.Lock()
defer fh.mu.Unlock()
if _, err := fh.r.Seek(off, io.SeekStart); err != nil {
return nil, fs.ToErrno(err)
}
n, err := fh.r.CtxReadFull(ctx, dest)
switch err {
case nil, io.EOF, io.ErrUnexpectedEOF:
default:
return nil, fusemnt.ReadErrno(err)
}
return fuse.ReadResultData(dest[:n]), 0
}
func (fh *roFileHandle) Release(_ context.Context) syscall.Errno {
fh.mu.Lock()
defer fh.mu.Unlock()
return fs.ToErrno(fh.r.Close())
}
// SymlinkTarget extracts the symlink target from an MFS file, or
// returns "" if the file is not a TSymlink node. MFS represents
// symlinks as *mfs.File, so the DAG node's UnixFS type must be checked.
func SymlinkTarget(f *mfs.File) string {
nd, err := f.GetNode()
if err != nil {
return ""
}
fsn, err := ft.ExtractFSNode(nd)
if err != nil {
return ""
}
if fsn.Type() != ft.TSymlink {
return ""
}
return string(fsn.Data())
}
// Interface compliance checks.
var (
_ fs.NodeGetattrer = (*Dir)(nil)
_ fs.NodeStatfser = (*Dir)(nil)
_ fs.NodeSetattrer = (*Dir)(nil)
_ fs.NodeLookuper = (*Dir)(nil)
_ fs.NodeReaddirer = (*Dir)(nil)
_ fs.NodeMkdirer = (*Dir)(nil)
_ fs.NodeUnlinker = (*Dir)(nil)
_ fs.NodeRmdirer = (*Dir)(nil)
_ fs.NodeRenamer = (*Dir)(nil)
_ fs.NodeCreater = (*Dir)(nil)
_ fs.NodeSymlinker = (*Dir)(nil)
_ fs.NodeGetxattrer = (*Dir)(nil)
_ fs.NodeListxattrer = (*Dir)(nil)
_ fs.NodeGetattrer = (*FileInode)(nil)
_ fs.NodeOpener = (*FileInode)(nil)
_ fs.NodeSetattrer = (*FileInode)(nil)
_ fs.NodeGetxattrer = (*FileInode)(nil)
_ fs.NodeListxattrer = (*FileInode)(nil)
_ fs.NodeGetattrer = (*Symlink)(nil)
_ fs.NodeSetattrer = (*Symlink)(nil)
_ fs.NodeReadlinker = (*Symlink)(nil)
_ fs.FileReader = (*FileHandle)(nil)
_ fs.FileWriter = (*FileHandle)(nil)
_ fs.FileFlusher = (*FileHandle)(nil)
_ fs.FileReleaser = (*FileHandle)(nil)
_ fs.FileFsyncer = (*FileHandle)(nil)
_ fs.FileReader = (*roFileHandle)(nil)
_ fs.FileReleaser = (*roFileHandle)(nil)
)