-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
lisafs.go
1222 lines (1079 loc) · 36.5 KB
/
lisafs.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 2021 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 fsgofer provides a lisafs server implementation which gives access
// to local files.
package fsgofer
import (
"fmt"
"io"
"math"
"os"
"path"
"path/filepath"
"strconv"
"sync"
"golang.org/x/sys/unix"
"gvisor.dev/gvisor/pkg/abi/linux"
"gvisor.dev/gvisor/pkg/atomicbitops"
"gvisor.dev/gvisor/pkg/cleanup"
rwfd "gvisor.dev/gvisor/pkg/fd"
"gvisor.dev/gvisor/pkg/fsutil"
"gvisor.dev/gvisor/pkg/lisafs"
"gvisor.dev/gvisor/pkg/log"
"gvisor.dev/gvisor/pkg/marshal/primitive"
"gvisor.dev/gvisor/runsc/config"
)
// LINT.IfChange
const (
openFlags = unix.O_NOFOLLOW | unix.O_CLOEXEC
// UNIX_PATH_MAX as defined in include/uapi/linux/un.h.
unixPathMax = 108
)
// Config sets configuration options for each attach point.
type Config struct {
// ROMount is set to true if this is a readonly mount.
ROMount bool
// PanicOnWrite panics on attempts to write to RO mounts.
PanicOnWrite bool
// HostUDS signals whether the gofer can connect to host unix domain sockets.
HostUDS config.HostUDS
// HostFifo signals whether the gofer can connect to host FIFOs.
HostFifo config.HostFifo
// DonateMountPointFD indicates whether a host FD to the mount point should
// be donated to the client on Mount RPC.
DonateMountPointFD bool
}
var procSelfFD *rwfd.FD
// OpenProcSelfFD opens the /proc/self/fd directory, which will be used to
// reopen file descriptors.
func OpenProcSelfFD(path string) error {
d, err := unix.Open(path, unix.O_RDONLY|unix.O_DIRECTORY, 0)
if err != nil {
return fmt.Errorf("error opening /proc/self/fd: %v", err)
}
procSelfFD = rwfd.New(d)
return nil
}
// LisafsServer implements lisafs.ServerImpl for fsgofer.
type LisafsServer struct {
lisafs.Server
config Config
}
var _ lisafs.ServerImpl = (*LisafsServer)(nil)
// NewLisafsServer initializes a new lisafs server for fsgofer.
func NewLisafsServer(config Config) *LisafsServer {
s := &LisafsServer{config: config}
s.Server.Init(s, lisafs.ServerOpts{
WalkStatSupported: true,
SetAttrOnDeleted: true,
AllocateOnDeleted: true,
})
return s
}
// Mount implements lisafs.ServerImpl.Mount.
func (s *LisafsServer) Mount(c *lisafs.Connection, mountNode *lisafs.Node) (*lisafs.ControlFD, linux.Statx, int, error) {
mountPath := mountNode.FilePath()
rootHostFD, err := tryOpen(func(flags int) (int, error) {
return unix.Open(mountPath, flags, 0)
})
if err != nil {
return nil, linux.Statx{}, -1, err
}
cu := cleanup.Make(func() {
_ = unix.Close(rootHostFD)
})
defer cu.Clean()
stat, err := fstatTo(rootHostFD)
if err != nil {
return nil, linux.Statx{}, -1, err
}
if err := checkSupportedFileType(uint32(stat.Mode)); err != nil {
log.Warningf("Mount: checkSupportedFileType() failed for file %q with mode %o: %v", mountPath, stat.Mode, err)
return nil, linux.Statx{}, -1, err
}
clientHostFD := -1
if s.config.DonateMountPointFD {
clientHostFD, err = unix.Dup(rootHostFD)
if err != nil {
return nil, linux.Statx{}, -1, err
}
}
cu.Release()
rootFD := &controlFDLisa{
hostFD: rootHostFD,
writableHostFD: atomicbitops.FromInt32(-1),
isMountPoint: true,
}
mountNode.IncRef() // Ref is transferred to ControlFD.
rootFD.ControlFD.Init(c, mountNode, linux.FileMode(stat.Mode), rootFD)
return rootFD.FD(), stat, clientHostFD, nil
}
// MaxMessageSize implements lisafs.ServerImpl.MaxMessageSize.
func (s *LisafsServer) MaxMessageSize() uint32 {
return lisafs.MaxMessageSize()
}
// SupportedMessages implements lisafs.ServerImpl.SupportedMessages.
func (s *LisafsServer) SupportedMessages() []lisafs.MID {
// Note that Flush, FListXattr and FRemoveXattr are not supported.
return []lisafs.MID{
lisafs.Mount,
lisafs.Channel,
lisafs.FStat,
lisafs.SetStat,
lisafs.Walk,
lisafs.WalkStat,
lisafs.OpenAt,
lisafs.OpenCreateAt,
lisafs.Close,
lisafs.FSync,
lisafs.PWrite,
lisafs.PRead,
lisafs.MkdirAt,
lisafs.MknodAt,
lisafs.SymlinkAt,
lisafs.LinkAt,
lisafs.FStatFS,
lisafs.FAllocate,
lisafs.ReadLinkAt,
lisafs.Connect,
lisafs.UnlinkAt,
lisafs.RenameAt,
lisafs.Getdents64,
lisafs.FGetXattr,
lisafs.FSetXattr,
lisafs.BindAt,
lisafs.Listen,
lisafs.Accept,
}
}
// controlFDLisa implements lisafs.ControlFDImpl.
type controlFDLisa struct {
lisafs.ControlFD
// hostFD is the file descriptor which can be used to make host syscalls.
hostFD int
// writableHostFD is the file descriptor number for a writable FD opened on
// the same FD as `hostFD`. It is initialized to -1, and can change in value
// exactly once.
writableHostFD atomicbitops.Int32
// isMountpoint indicates whether this FD represents the mount point for its
// owning connection. isMountPoint is immutable.
isMountPoint bool
}
var _ lisafs.ControlFDImpl = (*controlFDLisa)(nil)
func newControlFDLisa(hostFD int, parent *controlFDLisa, name string, mode linux.FileMode) *controlFDLisa {
var (
childFD *controlFDLisa
childNode *lisafs.Node
parentNode = parent.Node()
)
parentNode.WithChildrenMu(func() {
childNode = parentNode.LookupChildLocked(name)
if childNode == nil {
// Common case. Performance hack which is used to allocate the node and
// its control FD together in the heap. For a well-behaving client, there
// will be a 1:1 mapping between control FD and node and their lifecycle
// will be similar too. This will help reduce allocations and memory
// fragmentation. This is more cache friendly too.
temp := struct {
node lisafs.Node
fd controlFDLisa
}{}
childFD = &temp.fd
childNode = &temp.node
childNode.InitLocked(name, parentNode)
} else {
childNode.IncRef()
childFD = &controlFDLisa{}
}
})
childFD.hostFD = hostFD
childFD.writableHostFD = atomicbitops.FromInt32(-1)
childFD.ControlFD.Init(parent.Conn(), childNode, mode, childFD)
return childFD
}
func (fd *controlFDLisa) getWritableFD() (int, error) {
if writableFD := fd.writableHostFD.Load(); writableFD != -1 {
return int(writableFD), nil
}
writableFD, err := unix.Openat(int(procSelfFD.FD()), strconv.Itoa(fd.hostFD), (unix.O_WRONLY|openFlags)&^unix.O_NOFOLLOW, 0)
if err != nil {
return -1, err
}
if !fd.writableHostFD.CompareAndSwap(-1, int32(writableFD)) {
// Race detected, use the new value and clean this up.
unix.Close(writableFD)
return int(fd.writableHostFD.Load()), nil
}
return writableFD, nil
}
func (fd *controlFDLisa) getParentFD() (int, string, error) {
filePath := fd.Node().FilePath()
if filePath == "/" {
log.Warningf("getParentFD() call on the root")
return -1, "", unix.EINVAL
}
parent, err := unix.Open(path.Dir(filePath), openFlags|unix.O_PATH, 0)
return parent, path.Base(filePath), err
}
// FD implements lisafs.ControlFDImpl.FD.
func (fd *controlFDLisa) FD() *lisafs.ControlFD {
if fd == nil {
return nil
}
return &fd.ControlFD
}
// Close implements lisafs.ControlFDImpl.Close.
func (fd *controlFDLisa) Close() {
if fd.hostFD >= 0 {
_ = unix.Close(fd.hostFD)
fd.hostFD = -1
}
// No concurrent access is possible so no need to use atomics.
if fd.writableHostFD.RacyLoad() >= 0 {
_ = unix.Close(int(fd.writableHostFD.RacyLoad()))
fd.writableHostFD = atomicbitops.FromInt32(-1)
}
}
// Stat implements lisafs.ControlFDImpl.Stat.
func (fd *controlFDLisa) Stat() (linux.Statx, error) {
return fstatTo(fd.hostFD)
}
// SetStat implements lisafs.ControlFDImpl.SetStat.
func (fd *controlFDLisa) SetStat(stat lisafs.SetStatReq) (failureMask uint32, failureErr error) {
if stat.Mask&unix.STATX_MODE != 0 {
if fd.IsSocket() {
// fchmod(2) on socket files created via bind(2) fails. We need to
// fchmodat(2) it from its parent.
parent, sockName, err := fd.getParentFD()
if err == nil {
// Note that AT_SYMLINK_NOFOLLOW flag is not currently supported.
err = unix.Fchmodat(parent, sockName, stat.Mode&^unix.S_IFMT, 0 /* flags */)
unix.Close(parent)
}
if err != nil {
log.Warningf("SetStat fchmod failed on socket %q, err: %v", fd.Node().FilePath(), err)
failureMask |= unix.STATX_MODE
failureErr = err
}
} else {
if err := unix.Fchmod(fd.hostFD, stat.Mode&^unix.S_IFMT); err != nil {
log.Warningf("SetStat fchmod failed %q, err: %v", fd.Node().FilePath(), err)
failureMask |= unix.STATX_MODE
failureErr = err
}
}
}
if stat.Mask&unix.STATX_SIZE != 0 {
// ftruncate(2) requires the FD to be open for writing.
writableFD, err := fd.getWritableFD()
if err == nil {
err = unix.Ftruncate(writableFD, int64(stat.Size))
}
if err != nil {
log.Warningf("SetStat ftruncate failed %q, err: %v", fd.Node().FilePath(), err)
failureMask |= unix.STATX_SIZE
failureErr = err
}
}
if stat.Mask&(unix.STATX_ATIME|unix.STATX_MTIME) != 0 {
utimes := [2]unix.Timespec{
{Sec: 0, Nsec: unix.UTIME_OMIT},
{Sec: 0, Nsec: unix.UTIME_OMIT},
}
if stat.Mask&unix.STATX_ATIME != 0 {
utimes[0].Sec = stat.Atime.Sec
utimes[0].Nsec = stat.Atime.Nsec
}
if stat.Mask&unix.STATX_MTIME != 0 {
utimes[1].Sec = stat.Mtime.Sec
utimes[1].Nsec = stat.Mtime.Nsec
}
if fd.IsSymlink() {
// utimensat operates different that other syscalls. To operate on a
// symlink it *requires* AT_SYMLINK_NOFOLLOW with dirFD and a non-empty
// name. We need the parent FD.
parent, symlinkName, err := fd.getParentFD()
if err == nil {
err = fsutil.Utimensat(parent, symlinkName, utimes, unix.AT_SYMLINK_NOFOLLOW)
unix.Close(parent)
}
if err != nil {
failureMask |= (stat.Mask & (unix.STATX_ATIME | unix.STATX_MTIME))
failureErr = err
}
} else {
hostFD := fd.hostFD
if fd.IsRegular() {
// For regular files, utimensat(2) requires the FD to be open for
// writing, see BUGS section.
if writableFD, err := fd.getWritableFD(); err == nil {
hostFD = writableFD
} else {
log.Warningf("SetStat getWritableFD failed %q, err: %v", fd.Node().FilePath(), err)
}
}
// Directories and regular files can operate directly on the fd
// using empty name.
err := fsutil.Utimensat(hostFD, "", utimes, 0)
if err != nil {
log.Warningf("SetStat utimens failed %q, err: %v", fd.Node().FilePath(), err)
failureMask |= (stat.Mask & (unix.STATX_ATIME | unix.STATX_MTIME))
failureErr = err
}
}
}
if stat.Mask&(unix.STATX_UID|unix.STATX_GID) != 0 {
// "If the owner or group is specified as -1, then that ID is not changed"
// - chown(2)
uid := -1
if stat.Mask&unix.STATX_UID != 0 {
uid = int(stat.UID)
}
gid := -1
if stat.Mask&unix.STATX_GID != 0 {
gid = int(stat.GID)
}
if err := unix.Fchownat(fd.hostFD, "", uid, gid, unix.AT_EMPTY_PATH|unix.AT_SYMLINK_NOFOLLOW); err != nil {
log.Warningf("SetStat fchown failed %q, err: %v", fd.Node().FilePath(), err)
failureMask |= stat.Mask & (unix.STATX_UID | unix.STATX_GID)
failureErr = err
}
}
return
}
// Walk implements lisafs.ControlFDImpl.Walk.
func (fd *controlFDLisa) Walk(name string) (*lisafs.ControlFD, linux.Statx, error) {
childHostFD, err := tryOpen(func(flags int) (int, error) {
return unix.Openat(fd.hostFD, name, flags, 0)
})
if err != nil {
return nil, linux.Statx{}, err
}
stat, err := fstatTo(childHostFD)
if err != nil {
_ = unix.Close(childHostFD)
return nil, linux.Statx{}, err
}
if err := checkSupportedFileType(uint32(stat.Mode)); err != nil {
_ = unix.Close(childHostFD)
log.Warningf("Walk: checkSupportedFileType() failed for %q with mode %o: %v", name, stat.Mode, err)
return nil, linux.Statx{}, err
}
return newControlFDLisa(childHostFD, fd, name, linux.FileMode(stat.Mode)).FD(), stat, nil
}
// WalkStat implements lisafs.ControlFDImpl.WalkStat.
func (fd *controlFDLisa) WalkStat(path lisafs.StringArray, recordStat func(linux.Statx)) error {
// Note that while performing the walk below, we do not have read concurrency
// guarantee for any descendants. So files can be created/deleted inside fd
// while the walk is being performed. However, this should be fine from a
// security perspective as we are using host FDs to walk and checking that
// each opened path component is not a symlink.
curDirFD := fd.hostFD
closeCurDirFD := func() {
if curDirFD != fd.hostFD {
unix.Close(curDirFD)
}
}
defer closeCurDirFD()
if len(path) > 0 && len(path[0]) == 0 {
// Write stat results for dirFD if the first path component is "".
stat, err := fstatTo(fd.hostFD)
if err != nil {
return err
}
recordStat(stat)
path = path[1:]
}
// Don't attempt walking if parent is a symlink.
if fd.IsSymlink() {
return nil
}
for _, name := range path {
curFD, err := unix.Openat(curDirFD, name, unix.O_PATH|openFlags, 0)
if err == unix.ENOENT {
// No more path components exist on the filesystem. Return the partial
// walk to the client.
break
}
if err != nil {
return err
}
closeCurDirFD()
curDirFD = curFD
stat, err := fstatTo(curFD)
if err != nil {
return err
}
if err := checkSupportedFileType(uint32(stat.Mode)); err != nil {
log.Warningf("WalkStat: checkSupportedFileType() failed for file %q with mode %o while walking path %+v: %v", name, stat.Mode, path, err)
return err
}
recordStat(stat)
// Symlinks terminate walk. This client gets the symlink stat result, but
// will have to invoke Walk again with the resolved path.
if stat.Mode&unix.S_IFMT == unix.S_IFLNK {
break
}
}
return nil
}
// Used to log rejected fifo/uds operations, one time each.
var (
logRejectedFifoOpenOnce sync.Once
logRejectedUdsOpenOnce sync.Once
logRejectedUdsCreateOnce sync.Once
logRejectedUdsConnectOnce sync.Once
)
// Open implements lisafs.ControlFDImpl.Open.
func (fd *controlFDLisa) Open(flags uint32) (*lisafs.OpenFD, int, error) {
ftype := fd.FileType()
server := fd.Conn().ServerImpl().(*LisafsServer)
switch ftype {
case unix.S_IFIFO:
if !server.config.HostFifo.AllowOpen() {
logRejectedFifoOpenOnce.Do(func() {
log.Warningf("Rejecting attempt to open fifo/pipe from host filesystem: %q. If you want to allow this, set flag --host-fifo=open", fd.ControlFD.Node().FilePath())
})
return nil, -1, unix.EPERM
}
case unix.S_IFSOCK:
if !server.config.HostUDS.AllowOpen() {
logRejectedUdsOpenOnce.Do(func() {
log.Warningf("Rejecting attempt to open unix domain socket from host filesystem. If you want to allow this, set flag --host-uds=open", fd.ControlFD.Node().FilePath())
})
return nil, -1, unix.EPERM
}
}
flags |= openFlags
openHostFD, err := unix.Openat(int(procSelfFD.FD()), strconv.Itoa(fd.hostFD), int(flags)&^unix.O_NOFOLLOW, 0)
if err != nil {
return nil, -1, err
}
hostFDToDonate := -1
switch {
case ftype == unix.S_IFREG:
// Best effort to donate file to the Sentry (for performance only).
hostFDToDonate, _ = unix.Dup(openHostFD)
case ftype == unix.S_IFIFO,
ftype == unix.S_IFCHR,
fd.isMountPoint && fd.Conn().ServerImpl().(*LisafsServer).config.DonateMountPointFD:
// Character devices and pipes can block indefinitely during reads/writes,
// which is not allowed for gofer operations. Ensure that it donates an FD
// back to the caller, so it can wait on the FD when reads/writes return
// EWOULDBLOCK. For mount points, if DonateMountPointFD option is set, an
// FD must be donated.
var err error
hostFDToDonate, err = unix.Dup(openHostFD)
if err != nil {
return nil, 0, err
}
}
openFD := fd.newOpenFDLisa(openHostFD, flags)
return openFD.FD(), hostFDToDonate, nil
}
// OpenCreate implements lisafs.ControlFDImpl.OpenCreate.
func (fd *controlFDLisa) OpenCreate(mode linux.FileMode, uid lisafs.UID, gid lisafs.GID, name string, flags uint32) (*lisafs.ControlFD, linux.Statx, *lisafs.OpenFD, int, error) {
createFlags := unix.O_CREAT | unix.O_EXCL | unix.O_RDONLY | unix.O_NONBLOCK | openFlags
childHostFD, err := unix.Openat(fd.hostFD, name, createFlags, uint32(mode&^linux.FileTypeMask))
if err != nil {
return nil, linux.Statx{}, nil, -1, err
}
cu := cleanup.Make(func() {
// Best effort attempt to remove the file in case of failure.
if err := unix.Unlinkat(fd.hostFD, name, 0); err != nil {
log.Warningf("error unlinking file %q after failure: %v", path.Join(fd.Node().FilePath(), name), err)
}
unix.Close(childHostFD)
})
defer cu.Clean()
// Set the owners as requested by the client.
if err := unix.Fchownat(childHostFD, "", int(uid), int(gid), unix.AT_EMPTY_PATH|unix.AT_SYMLINK_NOFOLLOW); err != nil {
return nil, linux.Statx{}, nil, -1, err
}
// Get stat results.
childStat, err := fstatTo(childHostFD)
if err != nil {
return nil, linux.Statx{}, nil, -1, err
}
// Now open an FD to the newly created file with the flags requested by the client.
flags |= openFlags
newHostFD, err := unix.Openat(int(procSelfFD.FD()), strconv.Itoa(childHostFD), int(flags)&^unix.O_NOFOLLOW, 0)
if err != nil {
return nil, linux.Statx{}, nil, -1, err
}
cu.Release()
childFD := newControlFDLisa(childHostFD, fd, name, linux.ModeRegular)
newFD := childFD.newOpenFDLisa(newHostFD, uint32(flags))
// Donate FD because open(O_CREAT|O_EXCL) always creates a regular file.
// Since FD donation is a destructive operation, we should duplicate the
// to-be-donated FD. Eat the error if one occurs, it is better to have an FD
// without a host FD, than failing the Open attempt.
hostOpenFD := -1
if dupFD, err := unix.Dup(newFD.hostFD); err == nil {
hostOpenFD = dupFD
}
return childFD.FD(), childStat, newFD.FD(), hostOpenFD, nil
}
// Mkdir implements lisafs.ControlFDImpl.Mkdir.
func (fd *controlFDLisa) Mkdir(mode linux.FileMode, uid lisafs.UID, gid lisafs.GID, name string) (*lisafs.ControlFD, linux.Statx, error) {
if err := unix.Mkdirat(fd.hostFD, name, uint32(mode&^linux.FileTypeMask)); err != nil {
return nil, linux.Statx{}, err
}
cu := cleanup.Make(func() {
// Best effort attempt to remove the dir in case of failure.
if err := unix.Unlinkat(fd.hostFD, name, unix.AT_REMOVEDIR); err != nil {
log.Warningf("error unlinking dir %q after failure: %v", path.Join(fd.Node().FilePath(), name), err)
}
})
defer cu.Clean()
// Open directory to change ownership.
childDirFd, err := tryOpen(func(flags int) (int, error) {
return unix.Openat(fd.hostFD, name, flags|unix.O_DIRECTORY, 0)
})
if err != nil {
return nil, linux.Statx{}, err
}
if err := unix.Fchownat(childDirFd, "", int(uid), int(gid), unix.AT_EMPTY_PATH|unix.AT_SYMLINK_NOFOLLOW); err != nil {
unix.Close(childDirFd)
return nil, linux.Statx{}, err
}
// Get stat results.
childDirStat, err := fstatTo(childDirFd)
if err != nil {
unix.Close(childDirFd)
return nil, linux.Statx{}, err
}
cu.Release()
return newControlFDLisa(childDirFd, fd, name, linux.ModeDirectory).FD(), childDirStat, nil
}
// Mknod implements lisafs.ControlFDImpl.Mknod.
func (fd *controlFDLisa) Mknod(mode linux.FileMode, uid lisafs.UID, gid lisafs.GID, name string, minor uint32, major uint32) (*lisafs.ControlFD, linux.Statx, error) {
// From mknod(2) man page:
// "EPERM: [...] if the filesystem containing pathname does not support
// the type of node requested."
if mode.FileType() != linux.ModeRegular {
return nil, linux.Statx{}, unix.EPERM
}
if err := unix.Mknodat(fd.hostFD, name, uint32(mode), 0); err != nil {
return nil, linux.Statx{}, err
}
cu := cleanup.Make(func() {
// Best effort attempt to remove the file in case of failure.
if err := unix.Unlinkat(fd.hostFD, name, 0); err != nil {
log.Warningf("error unlinking file %q after failure: %v", path.Join(fd.Node().FilePath(), name), err)
}
})
defer cu.Clean()
// Open file to change ownership.
childFD, err := tryOpen(func(flags int) (int, error) {
return unix.Openat(fd.hostFD, name, flags, 0)
})
if err != nil {
return nil, linux.Statx{}, err
}
if err := unix.Fchownat(childFD, "", int(uid), int(gid), unix.AT_EMPTY_PATH|unix.AT_SYMLINK_NOFOLLOW); err != nil {
unix.Close(childFD)
return nil, linux.Statx{}, err
}
// Get stat results.
childStat, err := fstatTo(childFD)
if err != nil {
unix.Close(childFD)
return nil, linux.Statx{}, err
}
cu.Release()
return newControlFDLisa(childFD, fd, name, mode).FD(), childStat, nil
}
// Symlink implements lisafs.ControlFDImpl.Symlink.
func (fd *controlFDLisa) Symlink(name string, target string, uid lisafs.UID, gid lisafs.GID) (*lisafs.ControlFD, linux.Statx, error) {
if err := unix.Symlinkat(target, fd.hostFD, name); err != nil {
return nil, linux.Statx{}, err
}
cu := cleanup.Make(func() {
// Best effort attempt to remove the symlink in case of failure.
if err := unix.Unlinkat(fd.hostFD, name, 0); err != nil {
log.Warningf("error unlinking file %q after failure: %v", path.Join(fd.Node().FilePath(), name), err)
}
})
defer cu.Clean()
// Open symlink to change ownership.
symlinkFD, err := unix.Openat(fd.hostFD, name, unix.O_PATH|openFlags, 0)
if err != nil {
return nil, linux.Statx{}, err
}
if err := unix.Fchownat(symlinkFD, "", int(uid), int(gid), unix.AT_EMPTY_PATH|unix.AT_SYMLINK_NOFOLLOW); err != nil {
unix.Close(symlinkFD)
return nil, linux.Statx{}, err
}
symlinkStat, err := fstatTo(symlinkFD)
if err != nil {
unix.Close(symlinkFD)
return nil, linux.Statx{}, err
}
cu.Release()
return newControlFDLisa(symlinkFD, fd, name, linux.ModeSymlink).FD(), symlinkStat, nil
}
// Link implements lisafs.ControlFDImpl.Link.
func (fd *controlFDLisa) Link(dir lisafs.ControlFDImpl, name string) (*lisafs.ControlFD, linux.Statx, error) {
// Using linkat(targetFD, "", newdirfd, name, AT_EMPTY_PATH) requires
// CAP_DAC_READ_SEARCH in the *root* userns. The gofer process has
// CAP_DAC_READ_SEARCH in its own userns. But sometimes the gofer may be
// running in a different userns. So we can't use AT_EMPTY_PATH. Fallback
// to using olddirfd to call linkat(2).
oldDirFD, oldName, err := fd.getParentFD()
if err != nil {
return nil, linux.Statx{}, err
}
dirFD := dir.(*controlFDLisa)
if err := unix.Linkat(oldDirFD, oldName, dirFD.hostFD, name, 0); err != nil {
return nil, linux.Statx{}, err
}
cu := cleanup.Make(func() {
// Best effort attempt to remove the hard link in case of failure.
if err := unix.Unlinkat(dirFD.hostFD, name, 0); err != nil {
log.Warningf("error unlinking file %q after failure: %v", path.Join(dirFD.Node().FilePath(), name), err)
}
})
defer cu.Clean()
linkFD, err := tryOpen(func(flags int) (int, error) {
return unix.Openat(dirFD.hostFD, name, flags, 0)
})
if err != nil {
return nil, linux.Statx{}, err
}
linkStat, err := fstatTo(linkFD)
if err != nil {
return nil, linux.Statx{}, err
}
cu.Release()
return newControlFDLisa(linkFD, dirFD, name, linux.FileMode(linkStat.Mode)).FD(), linkStat, nil
}
// StatFS implements lisafs.ControlFDImpl.StatFS.
func (fd *controlFDLisa) StatFS() (lisafs.StatFS, error) {
var s unix.Statfs_t
if err := unix.Fstatfs(fd.hostFD, &s); err != nil {
return lisafs.StatFS{}, err
}
return lisafs.StatFS{
Type: uint64(s.Type),
BlockSize: s.Bsize,
Blocks: s.Blocks,
BlocksFree: s.Bfree,
BlocksAvailable: s.Bavail,
Files: s.Files,
FilesFree: s.Ffree,
NameLength: uint64(s.Namelen),
}, nil
}
// Readlink implements lisafs.ControlFDImpl.Readlink.
func (fd *controlFDLisa) Readlink(getLinkBuf func(uint32) []byte) (uint16, error) {
// This is similar to what os.Readlink does.
for linkLen := 128; linkLen < math.MaxUint16; linkLen *= 2 {
b := getLinkBuf(uint32(linkLen))
n, err := unix.Readlinkat(fd.hostFD, "", b)
if err != nil {
return 0, err
}
if n < int(linkLen) {
return uint16(n), nil
}
}
return 0, unix.ENOMEM
}
func isSockTypeSupported(sockType uint32) bool {
switch sockType {
case unix.SOCK_STREAM, unix.SOCK_DGRAM, unix.SOCK_SEQPACKET:
return true
default:
log.Debugf("socket type %d is not supported", sockType)
return false
}
}
// Connect implements lisafs.ControlFDImpl.Connect.
func (fd *controlFDLisa) Connect(sockType uint32) (int, error) {
if !fd.Conn().ServerImpl().(*LisafsServer).config.HostUDS.AllowOpen() {
logRejectedUdsConnectOnce.Do(func() {
log.Warningf("Rejecting attempt to connect to unix domain socket from host filesystem: %q. If you want to allow this, set flag --host-uds=open", fd.ControlFD.Node().FilePath())
})
return -1, unix.EPERM
}
// TODO(gvisor.dev/issue/1003): Due to different app vs replacement
// mappings, the app path may have fit in the sockaddr, but we can't fit
// hostPath in our sockaddr. We'd need to redirect through a shorter path
// in order to actually connect to this socket.
hostPath := fd.Node().FilePath()
if len(hostPath) >= linux.UnixPathMax {
return -1, unix.EINVAL
}
if !isSockTypeSupported(sockType) {
return -1, unix.ENXIO
}
sock, err := unix.Socket(unix.AF_UNIX, int(sockType), 0)
if err != nil {
return -1, err
}
sa := unix.SockaddrUnix{Name: hostPath}
if err := unix.Connect(sock, &sa); err != nil {
unix.Close(sock)
return -1, err
}
return sock, nil
}
// BindAt implements lisafs.ControlFDImpl.BindAt.
func (fd *controlFDLisa) BindAt(name string, sockType uint32, mode linux.FileMode, uid lisafs.UID, gid lisafs.GID) (*lisafs.ControlFD, linux.Statx, *lisafs.BoundSocketFD, int, error) {
if !fd.Conn().ServerImpl().(*LisafsServer).config.HostUDS.AllowCreate() {
logRejectedUdsCreateOnce.Do(func() {
log.Warningf("Rejecting attempt to create unix domain socket from host filesystem: %q. If you want to allow this, set flag --host-uds=create", name)
})
return nil, linux.Statx{}, nil, -1, unix.EPERM
}
// Because there is no "bindat" syscall in Linux, we must create an
// absolute path to the socket we are creating,
socketPath := filepath.Join(fd.Node().FilePath(), name)
// TODO(gvisor.dev/issue/1003): Due to different app vs replacement
// mappings, the app path may have fit in the sockaddr, but we can't fit
// hostPath in our sockaddr. We'd need to redirect through a shorter path
// in order to actually connect to this socket.
if len(socketPath) >= linux.UnixPathMax {
log.Warningf("BindAt called with name too long: %q (len=%d)", socketPath, len(socketPath))
return nil, linux.Statx{}, nil, -1, unix.EINVAL
}
// Only the following types are supported.
if !isSockTypeSupported(sockType) {
return nil, linux.Statx{}, nil, -1, unix.ENXIO
}
// Create and bind the socket using the sockPath which may be a
// symlink.
sockFD, err := unix.Socket(unix.AF_UNIX, int(sockType), 0)
if err != nil {
return nil, linux.Statx{}, nil, -1, err
}
cu := cleanup.Make(func() {
_ = unix.Close(sockFD)
})
defer cu.Clean()
// fchmod(2) has to happen *before* the bind(2). sockFD's file mode will
// be used in creating the filesystem-object in bind(2).
if err := unix.Fchmod(sockFD, uint32(mode&^linux.FileTypeMask)); err != nil {
return nil, linux.Statx{}, nil, -1, err
}
if err := unix.Bind(sockFD, &unix.SockaddrUnix{Name: socketPath}); err != nil {
return nil, linux.Statx{}, nil, -1, err
}
cu.Add(func() {
_ = unix.Unlink(socketPath)
})
sockFileFD, err := tryOpen(func(flags int) (int, error) {
return unix.Openat(fd.hostFD, name, flags, 0)
})
if err != nil {
return nil, linux.Statx{}, nil, -1, err
}
cu.Add(func() {
_ = unix.Close(sockFileFD)
})
if err := unix.Fchownat(sockFileFD, "", int(uid), int(gid), unix.AT_EMPTY_PATH|unix.AT_SYMLINK_NOFOLLOW); err != nil {
return nil, linux.Statx{}, nil, -1, err
}
// Stat the socket.
sockStat, err := fstatTo(sockFileFD)
if err != nil {
return nil, linux.Statx{}, nil, -1, err
}
// Create an FD that will be donated to the sandbox.
sockFDToDonate, err := unix.Dup(sockFD)
if err != nil {
return nil, linux.Statx{}, nil, -1, err
}
cu.Release()
socketControlFD := newControlFDLisa(sockFD, fd, name, linux.ModeSocket)
boundSocketFD := &boundSocketFDLisa{
sock: os.NewFile(uintptr(sockFD), socketPath),
}
boundSocketFD.Init(socketControlFD.FD(), boundSocketFD)
return socketControlFD.FD(), sockStat, boundSocketFD.FD(), sockFDToDonate, nil
}
// Unlink implements lisafs.ControlFDImpl.Unlink.
func (fd *controlFDLisa) Unlink(name string, flags uint32) error {
return unix.Unlinkat(fd.hostFD, name, int(flags))
}
// RenameAt implements lisafs.ControlFDImpl.RenameAt.
func (fd *controlFDLisa) RenameAt(oldName string, newDir lisafs.ControlFDImpl, newName string) error {
return fsutil.RenameAt(fd.hostFD, oldName, newDir.(*controlFDLisa).hostFD, newName)
}
// Renamed implements lisafs.ControlFDImpl.Renamed.
func (fd *controlFDLisa) Renamed() {
// controlFDLisa does not have any state to update on rename.
}
// GetXattr implements lisafs.ControlFDImpl.GetXattr.
func (fd *controlFDLisa) GetXattr(name string, size uint32, getValueBuf func(uint32) []byte) (uint16, error) {
data := getValueBuf(size)
xattrSize, err := unix.Fgetxattr(fd.hostFD, name, data)
return uint16(xattrSize), err
}
// SetXattr implements lisafs.ControlFDImpl.SetXattr.
func (fd *controlFDLisa) SetXattr(name string, value string, flags uint32) error {
return unix.EOPNOTSUPP
}
// ListXattr implements lisafs.ControlFDImpl.ListXattr.
func (fd *controlFDLisa) ListXattr(size uint64) (lisafs.StringArray, error) {
return nil, unix.EOPNOTSUPP
}
// RemoveXattr implements lisafs.ControlFDImpl.RemoveXattr.
func (fd *controlFDLisa) RemoveXattr(name string) error {
return unix.EOPNOTSUPP
}
// openFDLisa implements lisafs.OpenFDImpl.
type openFDLisa struct {
lisafs.OpenFD
// hostFD is the host file descriptor which can be used to make syscalls.
hostFD int
}
var _ lisafs.OpenFDImpl = (*openFDLisa)(nil)
func (fd *controlFDLisa) newOpenFDLisa(hostFD int, flags uint32) *openFDLisa {
newFD := &openFDLisa{
hostFD: hostFD,
}
newFD.OpenFD.Init(fd.FD(), flags, newFD)
return newFD
}
// FD implements lisafs.OpenFDImpl.FD.
func (fd *openFDLisa) FD() *lisafs.OpenFD {
if fd == nil {
return nil
}
return &fd.OpenFD
}
// Close implements lisafs.OpenFDImpl.Close.
func (fd *openFDLisa) Close() {
if fd.hostFD >= 0 {
_ = unix.Close(fd.hostFD)
fd.hostFD = -1
}
}
// Stat implements lisafs.OpenFDImpl.Stat.
func (fd *openFDLisa) Stat() (linux.Statx, error) {
return fstatTo(fd.hostFD)
}
// Sync implements lisafs.OpenFDImpl.Sync.
func (fd *openFDLisa) Sync() error {
return unix.Fsync(fd.hostFD)
}
// Write implements lisafs.OpenFDImpl.Write.
func (fd *openFDLisa) Write(buf []byte, off uint64) (uint64, error) {
rw := rwfd.NewReadWriter(fd.hostFD)
n, err := rw.WriteAt(buf, int64(off))
return uint64(n), err
}
// Read implements lisafs.OpenFDImpl.Read.
func (fd *openFDLisa) Read(buf []byte, off uint64) (uint64, error) {
rw := rwfd.NewReadWriter(fd.hostFD)
n, err := rw.ReadAt(buf, int64(off))
if err != nil && err != io.EOF {