forked from MetaCubeX/gvisor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filesystem.go
1770 lines (1660 loc) · 54.1 KB
/
filesystem.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
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2019 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package gofer
import (
"fmt"
"math"
"strings"
"sync"
"golang.org/x/sys/unix"
"github.com/MerlinKodo/gvisor/pkg/abi/linux"
"github.com/MerlinKodo/gvisor/pkg/atomicbitops"
"github.com/MerlinKodo/gvisor/pkg/context"
"github.com/MerlinKodo/gvisor/pkg/errors/linuxerr"
"github.com/MerlinKodo/gvisor/pkg/fspath"
"github.com/MerlinKodo/gvisor/pkg/sentry/fsimpl/host"
"github.com/MerlinKodo/gvisor/pkg/sentry/fsmetric"
"github.com/MerlinKodo/gvisor/pkg/sentry/kernel"
"github.com/MerlinKodo/gvisor/pkg/sentry/kernel/auth"
"github.com/MerlinKodo/gvisor/pkg/sentry/kernel/pipe"
"github.com/MerlinKodo/gvisor/pkg/sentry/socket/unix/transport"
"github.com/MerlinKodo/gvisor/pkg/sentry/vfs"
)
// Sync implements vfs.FilesystemImpl.Sync.
func (fs *filesystem) Sync(ctx context.Context) error {
// Snapshot current syncable dentries and special file FDs.
fs.syncMu.Lock()
ds := make([]*dentry, 0, fs.syncableDentries.Len())
for elem := fs.syncableDentries.Front(); elem != nil; elem = elem.Next() {
ds = append(ds, elem.d)
}
sffds := make([]*specialFileFD, 0, fs.specialFileFDs.Len())
for sffd := fs.specialFileFDs.Front(); sffd != nil; sffd = sffd.Next() {
sffds = append(sffds, sffd)
}
fs.syncMu.Unlock()
// Return the first error we encounter, but sync everything we can
// regardless.
var retErr error
// Note that lisafs is capable of batching FSync RPCs. However, we can not
// batch all the FDIDs to be synced from ds and sffds. Because the error
// handling varies based on file type. FSync errors are only considered for
// regular file FDIDs that were opened for writing. We could do individual
// RPCs for such FDIDs and batch the rest, but it increases code complexity
// substantially. We could implement it in the future if need be.
// Sync syncable dentries.
for _, d := range ds {
if err := d.syncCachedFile(ctx, true /* forFilesystemSync */); err != nil {
ctx.Infof("gofer.filesystem.Sync: dentry.syncCachedFile failed: %v", err)
if retErr == nil {
retErr = err
}
}
}
// Sync special files, which may be writable but do not use dentry shared
// handles (so they won't be synced by the above).
for _, sffd := range sffds {
if err := sffd.sync(ctx, true /* forFilesystemSync */); err != nil {
ctx.Infof("gofer.filesystem.Sync: specialFileFD.sync failed: %v", err)
if retErr == nil {
retErr = err
}
}
}
return retErr
}
// MaxFilenameLen is the maximum length of a filename. This is dictated by 9P's
// encoding of strings, which uses 2 bytes for the length prefix.
const MaxFilenameLen = (1 << 16) - 1
// dentrySlicePool is a pool of *[]*dentry used to store dentries for which
// dentry.checkCachingLocked() must be called. The pool holds pointers to
// slices because Go lacks generics, so sync.Pool operates on any, so
// every call to (what should be) sync.Pool<[]*dentry>.Put() allocates a copy
// of the slice header on the heap.
var dentrySlicePool = sync.Pool{
New: func() any {
ds := make([]*dentry, 0, 4) // arbitrary non-zero initial capacity
return &ds
},
}
func appendDentry(ds *[]*dentry, d *dentry) *[]*dentry {
if ds == nil {
ds = dentrySlicePool.Get().(*[]*dentry)
}
*ds = append(*ds, d)
return ds
}
// Precondition: !parent.isSynthetic() && !child.isSynthetic().
func appendNewChildDentry(ds **[]*dentry, parent *dentry, child *dentry) {
// The new child was added to parent and took a ref on the parent (hence
// parent can be removed from cache). A new child has 0 refs for now. So
// checkCachingLocked() should be called on both. Call it first on the parent
// as it may create space in the cache for child to be inserted - hence
// avoiding a cache eviction.
*ds = appendDentry(*ds, parent)
*ds = appendDentry(*ds, child)
}
// Preconditions: ds != nil.
func putDentrySlice(ds *[]*dentry) {
// Allow dentries to be GC'd.
for i := range *ds {
(*ds)[i] = nil
}
*ds = (*ds)[:0]
dentrySlicePool.Put(ds)
}
// renameMuRUnlockAndCheckCaching calls fs.renameMu.RUnlock(), then calls
// dentry.checkCachingLocked on all dentries in *dsp with fs.renameMu locked
// for writing.
//
// dsp is a pointer-to-pointer since defer evaluates its arguments immediately,
// but dentry slices are allocated lazily, and it's much easier to say "defer
// fs.renameMuRUnlockAndCheckCaching(&ds)" than "defer func() {
// fs.renameMuRUnlockAndCheckCaching(ds) }()" to work around this.
// +checklocksreleaseread:fs.renameMu
func (fs *filesystem) renameMuRUnlockAndCheckCaching(ctx context.Context, dsp **[]*dentry) {
fs.renameMu.RUnlock()
if *dsp == nil {
return
}
ds := **dsp
for _, d := range ds {
d.checkCachingLocked(ctx, false /* renameMuWriteLocked */)
}
putDentrySlice(*dsp)
}
// +checklocksrelease:fs.renameMu
func (fs *filesystem) renameMuUnlockAndCheckCaching(ctx context.Context, ds **[]*dentry) {
if *ds == nil {
fs.renameMu.Unlock()
return
}
for _, d := range **ds {
d.checkCachingLocked(ctx, true /* renameMuWriteLocked */)
}
fs.renameMu.Unlock()
putDentrySlice(*ds)
}
// stepLocked resolves rp.Component() to an existing file, starting from the
// given directory.
//
// Dentries which may become cached as a result of the traversal are appended
// to *ds.
//
// Preconditions:
// - fs.renameMu must be locked.
// - d.opMu must be locked for reading.
// - !rp.Done().
// - If !d.cachedMetadataAuthoritative(), then d and all children that are
// part of rp must have been revalidated.
//
// +checklocksread:d.opMu
func (fs *filesystem) stepLocked(ctx context.Context, rp resolvingPath, d *dentry, mayFollowSymlinks bool, ds **[]*dentry) (*dentry, bool, error) {
if !d.isDir() {
return nil, false, linuxerr.ENOTDIR
}
if err := d.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {
return nil, false, err
}
name := rp.Component()
if name == "." {
rp.Advance()
return d, false, nil
}
if name == ".." {
if isRoot, err := rp.CheckRoot(ctx, &d.vfsd); err != nil {
return nil, false, err
} else if isRoot || d.parent == nil {
rp.Advance()
return d, false, nil
}
if err := rp.CheckMount(ctx, &d.parent.vfsd); err != nil {
return nil, false, err
}
rp.Advance()
return d.parent, false, nil
}
child, err := fs.getChildAndWalkPathLocked(ctx, d, rp, ds)
if err != nil {
return nil, false, err
}
if err := rp.CheckMount(ctx, &child.vfsd); err != nil {
return nil, false, err
}
if child.isSymlink() && mayFollowSymlinks && rp.ShouldFollowSymlink() {
target, err := child.readlink(ctx, rp.Mount())
if err != nil {
return nil, false, err
}
followedSymlink, err := rp.HandleSymlink(target)
return d, followedSymlink, err
}
rp.Advance()
return child, false, nil
}
// getChildLocked returns a dentry representing the child of parent with the
// given name. Returns ENOENT if the child doesn't exist.
//
// Preconditions:
// - fs.renameMu must be locked.
// - parent.opMu must be locked.
// - parent.isDir().
// - name is not "." or "..".
// - parent and the dentry at name have been revalidated.
//
// +checklocks:parent.opMu
func (fs *filesystem) getChildLocked(ctx context.Context, parent *dentry, name string, ds **[]*dentry) (*dentry, error) {
if child, err := parent.getCachedChildLocked(name); child != nil || err != nil {
return child, err
}
// We don't need to check for race here because parent.opMu is held for
// writing.
return fs.getRemoteChildLocked(ctx, parent, name, false /* checkForRace */, ds)
}
// getRemoteChildLocked is similar to getChildLocked, with the additional
// precondition that the child identified by name does not exist in cache.
//
// If checkForRace argument is true, then this method will check to see if the
// call has raced with another getRemoteChild call, and will handle the race if
// so.
//
// Preconditions:
// - If checkForRace is false, then parent.opMu must be held for writing.
// - Otherwise, parent.opMu must be held for reading.
//
// Postcondition: The returned dentry is already cached appropriately.
//
// +checklocksread:parent.opMu
func (fs *filesystem) getRemoteChildLocked(ctx context.Context, parent *dentry, name string, checkForRace bool, ds **[]*dentry) (*dentry, error) {
child, err := parent.getRemoteChild(ctx, name)
// Cache the result appropriately in the dentry tree.
if err != nil {
if linuxerr.Equals(linuxerr.ENOENT, err) {
parent.childrenMu.Lock()
defer parent.childrenMu.Unlock()
parent.cacheNegativeLookupLocked(name)
}
return nil, err
}
parent.childrenMu.Lock()
defer parent.childrenMu.Unlock()
if checkForRace {
// See if we raced with anoter getRemoteChild call that added
// to the cache.
if cachedChild, ok := parent.children[name]; ok && cachedChild != nil {
// We raced. Destroy our child and return the cached
// one. This child has no handles, no data, and has not
// been cached, so destruction is quick and painless.
child.destroyDisconnected(ctx)
// All good. Return the cached child.
return cachedChild, nil
}
// No race, continue with the child we got.
}
parent.cacheNewChildLocked(child, name)
appendNewChildDentry(ds, parent, child)
return child, nil
}
// getChildAndWalkPathLocked is the same as getChildLocked, except that it
// may prefetch the entire path represented by rp.
//
// +checklocksread:parent.opMu
func (fs *filesystem) getChildAndWalkPathLocked(ctx context.Context, parent *dentry, rp resolvingPath, ds **[]*dentry) (*dentry, error) {
if child, err := parent.getCachedChildLocked(rp.Component()); child != nil || err != nil {
return child, err
}
// dentry.getRemoteChildAndWalkPathLocked already handles dentry caching.
return parent.getRemoteChildAndWalkPathLocked(ctx, rp, ds)
}
// getCachedChildLocked returns a child dentry if it was cached earlier. If no
// cached child dentry exists, (nil, nil) is returned.
//
// Preconditions:
// - fs.renameMu must be locked.
// - d.opMu must be locked for reading.
// - d.isDir().
// - name is not "." or "..".
// - d and the dentry at name have been revalidated.
//
// +checklocksread:d.opMu
func (d *dentry) getCachedChildLocked(name string) (*dentry, error) {
if len(name) > MaxFilenameLen {
return nil, linuxerr.ENAMETOOLONG
}
d.childrenMu.Lock()
defer d.childrenMu.Unlock()
if child, ok := d.children[name]; ok || d.isSynthetic() {
if child == nil {
return nil, linuxerr.ENOENT
}
return child, nil
}
if d.childrenSet != nil {
// Is the child even there? Don't make RPC if not.
if _, ok := d.childrenSet[name]; !ok {
return nil, linuxerr.ENOENT
}
}
return nil, nil
}
// walkParentDirLocked resolves all but the last path component of rp to an
// existing directory, starting from the given directory (which is usually
// rp.Start().Impl().(*dentry)). It does not check that the returned directory
// is searchable by the provider of rp.
//
// Preconditions:
// - fs.renameMu must be locked.
// - !rp.Done().
// - If !d.cachedMetadataAuthoritative(), then d's cached metadata must be up
// to date.
func (fs *filesystem) walkParentDirLocked(ctx context.Context, vfsRP *vfs.ResolvingPath, d *dentry, ds **[]*dentry) (*dentry, error) {
rp := resolvingPathParent(vfsRP)
if err := fs.revalidatePath(ctx, rp, d, ds); err != nil {
return nil, err
}
for !rp.done() {
d.opMu.RLock()
next, followedSymlink, err := fs.stepLocked(ctx, rp, d, true /* mayFollowSymlinks */, ds)
d.opMu.RUnlock()
if err != nil {
return nil, err
}
d = next
if followedSymlink {
if err := fs.revalidatePath(ctx, rp, d, ds); err != nil {
return nil, err
}
}
}
if !d.isDir() {
return nil, linuxerr.ENOTDIR
}
return d, nil
}
// resolveLocked resolves rp to an existing file.
//
// Preconditions: fs.renameMu must be locked.
func (fs *filesystem) resolveLocked(ctx context.Context, vfsRP *vfs.ResolvingPath, ds **[]*dentry) (*dentry, error) {
rp := resolvingPathFull(vfsRP)
d := rp.Start().Impl().(*dentry)
if err := fs.revalidatePath(ctx, rp, d, ds); err != nil {
return nil, err
}
for !rp.done() {
d.opMu.RLock()
next, followedSymlink, err := fs.stepLocked(ctx, rp, d, true /* mayFollowSymlinks */, ds)
d.opMu.RUnlock()
if err != nil {
return nil, err
}
d = next
if followedSymlink {
if err := fs.revalidatePath(ctx, rp, d, ds); err != nil {
return nil, err
}
}
}
if rp.MustBeDir() && !d.isDir() {
return nil, linuxerr.ENOTDIR
}
return d, nil
}
// doCreateAt checks that creating a file at rp is permitted, then invokes
// createInRemoteDir (if the parent directory is a real remote directory) or
// createInSyntheticDir (if the parent directory is synthetic) to do so.
//
// Preconditions:
// - !rp.Done().
// - For the final path component in rp, !rp.ShouldFollowSymlink().
func (fs *filesystem) doCreateAt(ctx context.Context, rp *vfs.ResolvingPath, dir bool, createInRemoteDir func(parent *dentry, name string, ds **[]*dentry) (*dentry, error), createInSyntheticDir func(parent *dentry, name string) (*dentry, error)) error {
var ds *[]*dentry
fs.renameMu.RLock()
defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)
start := rp.Start().Impl().(*dentry)
parent, err := fs.walkParentDirLocked(ctx, rp, start, &ds)
if err != nil {
return err
}
// Order of checks is important. First check if parent directory can be
// executed, then check for existence, and lastly check if mount is writable.
if err := parent.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {
return err
}
name := rp.Component()
if name == "." || name == ".." {
return linuxerr.EEXIST
}
if parent.isDeleted() {
return linuxerr.ENOENT
}
if err := fs.revalidateOne(ctx, rp.VirtualFilesystem(), parent, name, &ds); err != nil {
return err
}
parent.opMu.Lock()
defer parent.opMu.Unlock()
if len(name) > MaxFilenameLen {
return linuxerr.ENAMETOOLONG
}
// Check for existence only if caching information is available. Otherwise,
// don't check for existence just yet. We will check for existence if the
// checks for writability fail below. Existence check is done by the creation
// RPCs themselves.
parent.childrenMu.Lock()
if child, ok := parent.children[name]; ok && child != nil {
parent.childrenMu.Unlock()
return linuxerr.EEXIST
}
if parent.childrenSet != nil {
if _, ok := parent.childrenSet[name]; ok {
parent.childrenMu.Unlock()
return linuxerr.EEXIST
}
}
parent.childrenMu.Unlock()
checkExistence := func() error {
if child, err := fs.getChildLocked(ctx, parent, name, &ds); err != nil && !linuxerr.Equals(linuxerr.ENOENT, err) {
return err
} else if child != nil {
return linuxerr.EEXIST
}
return nil
}
mnt := rp.Mount()
if err := mnt.CheckBeginWrite(); err != nil {
// Existence check takes precedence.
if existenceErr := checkExistence(); existenceErr != nil {
return existenceErr
}
return err
}
defer mnt.EndWrite()
if err := parent.checkPermissions(rp.Credentials(), vfs.MayWrite); err != nil {
// Existence check takes precedence.
if existenceErr := checkExistence(); existenceErr != nil {
return existenceErr
}
return err
}
if !dir && rp.MustBeDir() {
return linuxerr.ENOENT
}
if parent.isSynthetic() {
if createInSyntheticDir == nil {
return linuxerr.EPERM
}
child, err := createInSyntheticDir(parent, name)
if err != nil {
return err
}
parent.childrenMu.Lock()
parent.cacheNewChildLocked(child, name)
parent.syntheticChildren++
parent.clearDirentsLocked()
parent.childrenMu.Unlock()
parent.touchCMtime()
ev := linux.IN_CREATE
if dir {
ev |= linux.IN_ISDIR
}
parent.watches.Notify(ctx, name, uint32(ev), 0, vfs.InodeEvent, false /* unlinked */)
return nil
}
// No cached dentry exists; however, in InteropModeShared there might still be
// an existing file at name. Just attempt the file creation RPC anyways. If a
// file does exist, the RPC will fail with EEXIST like we would have.
child, err := createInRemoteDir(parent, name, &ds)
if err != nil {
return err
}
parent.childrenMu.Lock()
parent.cacheNewChildLocked(child, name)
if child.isSynthetic() {
parent.syntheticChildren++
ds = appendDentry(ds, parent)
} else {
appendNewChildDentry(&ds, parent, child)
}
if fs.opts.interop != InteropModeShared {
if child, ok := parent.children[name]; ok && child == nil {
// Delete the now-stale negative dentry.
delete(parent.children, name)
parent.negativeChildren--
}
parent.clearDirentsLocked()
parent.touchCMtime()
}
parent.childrenMu.Unlock()
ev := linux.IN_CREATE
if dir {
ev |= linux.IN_ISDIR
}
parent.watches.Notify(ctx, name, uint32(ev), 0, vfs.InodeEvent, false /* unlinked */)
return nil
}
// Preconditions: !rp.Done().
func (fs *filesystem) unlinkAt(ctx context.Context, rp *vfs.ResolvingPath, dir bool) error {
var ds *[]*dentry
fs.renameMu.RLock()
defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)
start := rp.Start().Impl().(*dentry)
parent, err := fs.walkParentDirLocked(ctx, rp, start, &ds)
if err != nil {
return err
}
if err := parent.checkPermissions(rp.Credentials(), vfs.MayWrite|vfs.MayExec); err != nil {
return err
}
if err := rp.Mount().CheckBeginWrite(); err != nil {
return err
}
defer rp.Mount().EndWrite()
name := rp.Component()
if dir {
if name == "." {
return linuxerr.EINVAL
}
if name == ".." {
return linuxerr.ENOTEMPTY
}
} else {
if name == "." || name == ".." {
return linuxerr.EISDIR
}
}
vfsObj := rp.VirtualFilesystem()
if err := fs.revalidateOne(ctx, vfsObj, parent, rp.Component(), &ds); err != nil {
return err
}
mntns := vfs.MountNamespaceFromContext(ctx)
defer mntns.DecRef(ctx)
parent.opMu.Lock()
defer parent.opMu.Unlock()
parent.childrenMu.Lock()
if parent.childrenSet != nil {
if _, ok := parent.childrenSet[name]; !ok {
parent.childrenMu.Unlock()
return linuxerr.ENOENT
}
}
parent.childrenMu.Unlock()
// Load child if sticky bit is set because we need to determine whether
// deletion is allowed.
var child *dentry
if parent.mode.Load()&linux.ModeSticky == 0 {
var ok bool
parent.childrenMu.Lock()
child, ok = parent.children[name]
parent.childrenMu.Unlock()
if ok && child == nil {
// Hit a negative cached entry, child doesn't exist.
return linuxerr.ENOENT
}
} else {
child, _, err = fs.stepLocked(ctx, resolvingPathFull(rp), parent, false /* mayFollowSymlinks */, &ds)
if err != nil {
return err
}
if err := parent.mayDelete(rp.Credentials(), child); err != nil {
return err
}
}
// If a child dentry exists, prepare to delete it. This should fail if it is
// a mount point. We detect mount points by speculatively calling
// PrepareDeleteDentry, which fails if child is a mount point.
//
// Also note that if child is nil, then it can't be a mount point.
if child != nil {
// Hold child.childrenMu so we can check child.children and
// child.syntheticChildren. We don't access these fields until a bit later,
// but locking child.childrenMu after calling vfs.PrepareDeleteDentry() would
// create an inconsistent lock ordering between dentry.childrenMu and
// vfs.Dentry.mu (in the VFS lock order, it would make dentry.childrenMu both "a
// FilesystemImpl lock" and "a lock acquired by a FilesystemImpl between
// PrepareDeleteDentry and CommitDeleteDentry). To avoid this, lock
// child.childrenMu before calling PrepareDeleteDentry.
child.childrenMu.Lock()
defer child.childrenMu.Unlock()
if err := vfsObj.PrepareDeleteDentry(mntns, &child.vfsd); err != nil {
return err
}
}
flags := uint32(0)
// If a dentry exists, use it for best-effort checks on its deletability.
if dir {
if child != nil {
// child must be an empty directory.
if child.syntheticChildren != 0 { // +checklocksforce: child.childrenMu is held if child != nil.
// This is definitely not an empty directory, irrespective of
// fs.opts.interop.
vfsObj.AbortDeleteDentry(&child.vfsd) // +checklocksforce: PrepareDeleteDentry called if child != nil.
return linuxerr.ENOTEMPTY
}
// If InteropModeShared is in effect and the first call to
// PrepareDeleteDentry above succeeded, then child wasn't
// revalidated (so we can't expect its file type to be correct) and
// individually revalidating its children (to confirm that they
// still exist) would be a waste of time.
if child.cachedMetadataAuthoritative() {
if !child.isDir() {
vfsObj.AbortDeleteDentry(&child.vfsd) // +checklocksforce: see above.
return linuxerr.ENOTDIR
}
for _, grandchild := range child.children { // +checklocksforce: child.childrenMu is held if child != nil.
if grandchild != nil {
vfsObj.AbortDeleteDentry(&child.vfsd) // +checklocksforce: see above.
return linuxerr.ENOTEMPTY
}
}
}
}
flags = linux.AT_REMOVEDIR
} else {
// child must be a non-directory file.
if child != nil && child.isDir() {
vfsObj.AbortDeleteDentry(&child.vfsd) // +checklocksforce: see above.
return linuxerr.EISDIR
}
if rp.MustBeDir() {
if child != nil {
vfsObj.AbortDeleteDentry(&child.vfsd) // +checklocksforce: see above.
}
return linuxerr.ENOTDIR
}
}
if parent.isSynthetic() {
if child == nil {
return linuxerr.ENOENT
}
} else if child == nil || !child.isSynthetic() {
if err := parent.unlink(ctx, name, flags); err != nil {
if child != nil {
vfsObj.AbortDeleteDentry(&child.vfsd) // +checklocksforce: see above.
}
return err
}
}
// Generate inotify events for rmdir or unlink.
if dir {
parent.watches.Notify(ctx, name, linux.IN_DELETE|linux.IN_ISDIR, 0, vfs.InodeEvent, true /* unlinked */)
} else {
var cw *vfs.Watches
if child != nil {
cw = &child.watches
}
vfs.InotifyRemoveChild(ctx, cw, &parent.watches, name)
}
parent.childrenMu.Lock()
defer parent.childrenMu.Unlock()
if child != nil {
vfsObj.CommitDeleteDentry(ctx, &child.vfsd) // +checklocksforce: see above.
child.setDeleted()
if child.isSynthetic() {
parent.syntheticChildren--
child.decRefNoCaching()
}
ds = appendDentry(ds, child)
}
parent.cacheNegativeLookupLocked(name)
if parent.cachedMetadataAuthoritative() {
parent.clearDirentsLocked()
parent.touchCMtime()
if dir {
parent.decLinks()
}
}
return nil
}
// AccessAt implements vfs.Filesystem.Impl.AccessAt.
func (fs *filesystem) AccessAt(ctx context.Context, rp *vfs.ResolvingPath, creds *auth.Credentials, ats vfs.AccessTypes) error {
var ds *[]*dentry
fs.renameMu.RLock()
defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)
d, err := fs.resolveLocked(ctx, rp, &ds)
if err != nil {
return err
}
if err := d.checkPermissions(creds, ats); err != nil {
return err
}
if ats.MayWrite() && rp.Mount().ReadOnly() {
return linuxerr.EROFS
}
return nil
}
// GetDentryAt implements vfs.FilesystemImpl.GetDentryAt.
func (fs *filesystem) GetDentryAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.GetDentryOptions) (*vfs.Dentry, error) {
var ds *[]*dentry
fs.renameMu.RLock()
defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)
d, err := fs.resolveLocked(ctx, rp, &ds)
if err != nil {
return nil, err
}
if opts.CheckSearchable {
if !d.isDir() {
return nil, linuxerr.ENOTDIR
}
if err := d.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {
return nil, err
}
}
d.IncRef()
// Call d.checkCachingLocked() so it can be removed from the cache if needed.
ds = appendDentry(ds, d)
return &d.vfsd, nil
}
// GetParentDentryAt implements vfs.FilesystemImpl.GetParentDentryAt.
func (fs *filesystem) GetParentDentryAt(ctx context.Context, rp *vfs.ResolvingPath) (*vfs.Dentry, error) {
var ds *[]*dentry
fs.renameMu.RLock()
defer fs.renameMuRUnlockAndCheckCaching(ctx, &ds)
start := rp.Start().Impl().(*dentry)
d, err := fs.walkParentDirLocked(ctx, rp, start, &ds)
if err != nil {
return nil, err
}
d.IncRef()
// Call d.checkCachingLocked() so it can be removed from the cache if needed.
ds = appendDentry(ds, d)
return &d.vfsd, nil
}
// LinkAt implements vfs.FilesystemImpl.LinkAt.
func (fs *filesystem) LinkAt(ctx context.Context, rp *vfs.ResolvingPath, vd vfs.VirtualDentry) error {
err := fs.doCreateAt(ctx, rp, false /* dir */, func(parent *dentry, name string, ds **[]*dentry) (*dentry, error) {
if rp.Mount() != vd.Mount() {
return nil, linuxerr.EXDEV
}
d := vd.Dentry().Impl().(*dentry)
if d.isDir() {
return nil, linuxerr.EPERM
}
gid := auth.KGID(d.gid.Load())
uid := auth.KUID(d.uid.Load())
mode := linux.FileMode(d.mode.Load())
if err := vfs.MayLink(rp.Credentials(), mode, uid, gid); err != nil {
return nil, err
}
if d.nlink.Load() == 0 {
return nil, linuxerr.ENOENT
}
if d.nlink.Load() == math.MaxUint32 {
return nil, linuxerr.EMLINK
}
return parent.link(ctx, d, name)
}, nil)
if err == nil {
// Success!
vd.Dentry().Impl().(*dentry).incLinks()
}
return err
}
// MkdirAt implements vfs.FilesystemImpl.MkdirAt.
func (fs *filesystem) MkdirAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MkdirOptions) error {
creds := rp.Credentials()
return fs.doCreateAt(ctx, rp, true /* dir */, func(parent *dentry, name string, ds **[]*dentry) (*dentry, error) {
// If the parent is a setgid directory, use the parent's GID
// rather than the caller's and enable setgid.
kgid := creds.EffectiveKGID
mode := opts.Mode
if parent.mode.Load()&linux.S_ISGID != 0 {
kgid = auth.KGID(parent.gid.Load())
mode |= linux.S_ISGID
}
child, err := parent.mkdir(ctx, name, mode, creds.EffectiveKUID, kgid)
if err == nil {
if fs.opts.interop != InteropModeShared {
parent.incLinks()
}
return child, nil
}
if !opts.ForSyntheticMountpoint || linuxerr.Equals(linuxerr.EEXIST, err) {
return nil, err
}
ctx.Infof("Failed to create remote directory %q: %v; falling back to synthetic directory", name, err)
child = fs.newSyntheticDentry(&createSyntheticOpts{
name: name,
mode: linux.S_IFDIR | opts.Mode,
kuid: creds.EffectiveKUID,
kgid: creds.EffectiveKGID,
})
if fs.opts.interop != InteropModeShared {
parent.incLinks()
}
return child, nil
}, func(parent *dentry, name string) (*dentry, error) {
if !opts.ForSyntheticMountpoint {
// Can't create non-synthetic files in synthetic directories.
return nil, linuxerr.EPERM
}
child := fs.newSyntheticDentry(&createSyntheticOpts{
name: name,
mode: linux.S_IFDIR | opts.Mode,
kuid: creds.EffectiveKUID,
kgid: creds.EffectiveKGID,
})
parent.incLinks()
return child, nil
})
}
// MknodAt implements vfs.FilesystemImpl.MknodAt.
func (fs *filesystem) MknodAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.MknodOptions) error {
return fs.doCreateAt(ctx, rp, false /* dir */, func(parent *dentry, name string, ds **[]*dentry) (*dentry, error) {
creds := rp.Credentials()
if child, err := parent.mknod(ctx, name, creds, &opts); err == nil {
return child, nil
} else if !linuxerr.Equals(linuxerr.EPERM, err) {
return nil, err
}
// EPERM means that gofer does not allow creating a socket or pipe. Fallback
// to creating a synthetic one, i.e. one that is kept entirely in memory.
// Check that we're not overriding an existing file with a synthetic one.
_, _, err := fs.stepLocked(ctx, resolvingPathFull(rp), parent, false /* mayFollowSymlinks */, ds) // +checklocksforce: parent.opMu taken by doCreateAt.
switch {
case err == nil:
// Step succeeded, another file exists.
return nil, linuxerr.EEXIST
case !linuxerr.Equals(linuxerr.ENOENT, err):
// Schrödinger. File/Cat may or may not exist.
return nil, err
}
switch opts.Mode.FileType() {
case linux.S_IFSOCK:
return fs.newSyntheticDentry(&createSyntheticOpts{
name: name,
mode: opts.Mode,
kuid: creds.EffectiveKUID,
kgid: creds.EffectiveKGID,
endpoint: opts.Endpoint,
}), nil
case linux.S_IFIFO:
return fs.newSyntheticDentry(&createSyntheticOpts{
name: name,
mode: opts.Mode,
kuid: creds.EffectiveKUID,
kgid: creds.EffectiveKGID,
pipe: pipe.NewVFSPipe(true /* isNamed */, pipe.DefaultPipeSize),
}), nil
}
// Retain error from gofer if synthetic file cannot be created internally.
return nil, linuxerr.EPERM
}, nil)
}
// OpenAt implements vfs.FilesystemImpl.OpenAt.
func (fs *filesystem) OpenAt(ctx context.Context, rp *vfs.ResolvingPath, opts vfs.OpenOptions) (*vfs.FileDescription, error) {
// Reject O_TMPFILE, which is not supported; supporting it correctly in the
// presence of other remote filesystem users requires remote filesystem
// support, and it isn't clear that there's any way to implement this in
// 9P.
if opts.Flags&linux.O_TMPFILE != 0 {
return nil, linuxerr.EOPNOTSUPP
}
mayCreate := opts.Flags&linux.O_CREAT != 0
mustCreate := opts.Flags&(linux.O_CREAT|linux.O_EXCL) == (linux.O_CREAT | linux.O_EXCL)
var ds *[]*dentry
fs.renameMu.RLock()
unlocked := false
unlock := func() {
if !unlocked {
fs.renameMuRUnlockAndCheckCaching(ctx, &ds)
unlocked = true
}
}
defer unlock()
start := rp.Start().Impl().(*dentry)
if rp.Done() {
// Reject attempts to open mount root directory with O_CREAT.
if mayCreate && rp.MustBeDir() {
return nil, linuxerr.EISDIR
}
if mustCreate {
return nil, linuxerr.EEXIST
}
if !start.cachedMetadataAuthoritative() {
// Refresh dentry's attributes before opening.
if err := start.updateMetadata(ctx); err != nil {
return nil, err
}
}
start.IncRef()
defer start.DecRef(ctx)
unlock()
// start is intentionally not added to ds (which would remove it from the
// cache) because doing so regresses performance in practice.
return start.open(ctx, rp, &opts)
}
afterTrailingSymlink:
parent, err := fs.walkParentDirLocked(ctx, rp, start, &ds)
if err != nil {
return nil, err
}
// Check for search permission in the parent directory.
if err := parent.checkPermissions(rp.Credentials(), vfs.MayExec); err != nil {
return nil, err
}
// Reject attempts to open directories with O_CREAT.
if mayCreate && rp.MustBeDir() {
return nil, linuxerr.EISDIR
}
if err := fs.revalidateOne(ctx, rp.VirtualFilesystem(), parent, rp.Component(), &ds); err != nil {
return nil, err
}
// Determine whether or not we need to create a file.
// NOTE(b/263297063): Don't hold opMu for writing here, to avoid
// serializing OpenAt calls in the same directory in the common case
// that the file exists.
parent.opMu.RLock()
child, followedSymlink, err := fs.stepLocked(ctx, resolvingPathFull(rp), parent, true /* mayFollowSymlinks */, &ds)
parent.opMu.RUnlock()
if followedSymlink {
if mustCreate {
// EEXIST must be returned if an existing symlink is opened with O_EXCL.
return nil, linuxerr.EEXIST
}
if err != nil {
// If followedSymlink && err != nil, then this symlink resolution error
// must be handled by the VFS layer.
return nil, err
}
start = parent
goto afterTrailingSymlink
}
if linuxerr.Equals(linuxerr.ENOENT, err) && mayCreate {
if parent.isSynthetic() {
return nil, linuxerr.EPERM
}
// Take opMu for writing, but note that the file may have been
// created by another goroutine since we checked for existence
// a few lines ago. We must handle that case.
parent.opMu.Lock()