github.com/SagerNet/gvisor@v0.0.0-20210707092255-7731c139d75c/pkg/sentry/fs/host/control.go (about) 1 // Copyright 2018 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package host 16 17 import ( 18 "golang.org/x/sys/unix" 19 "github.com/SagerNet/gvisor/pkg/context" 20 "github.com/SagerNet/gvisor/pkg/sentry/fs" 21 "github.com/SagerNet/gvisor/pkg/sentry/socket/control" 22 "github.com/SagerNet/gvisor/pkg/sentry/socket/unix/transport" 23 ) 24 25 // LINT.IfChange 26 27 type scmRights struct { 28 fds []int 29 } 30 31 func newSCMRights(fds []int) control.SCMRights { 32 return &scmRights{fds} 33 } 34 35 // Files implements control.SCMRights.Files. 36 func (c *scmRights) Files(ctx context.Context, max int) (control.RightsFiles, bool) { 37 n := max 38 var trunc bool 39 if l := len(c.fds); n > l { 40 n = l 41 } else if n < l { 42 trunc = true 43 } 44 45 rf := control.RightsFiles(fdsToFiles(ctx, c.fds[:n])) 46 47 // Only consume converted FDs (fdsToFiles may convert fewer than n FDs). 48 c.fds = c.fds[len(rf):] 49 return rf, trunc 50 } 51 52 // Clone implements transport.RightsControlMessage.Clone. 53 func (c *scmRights) Clone() transport.RightsControlMessage { 54 // Host rights never need to be cloned. 55 return nil 56 } 57 58 // Release implements transport.RightsControlMessage.Release. 59 func (c *scmRights) Release(ctx context.Context) { 60 for _, fd := range c.fds { 61 unix.Close(fd) 62 } 63 c.fds = nil 64 } 65 66 // If an error is encountered, only files created before the error will be 67 // returned. This is what Linux does. 68 func fdsToFiles(ctx context.Context, fds []int) []*fs.File { 69 files := make([]*fs.File, 0, len(fds)) 70 for _, fd := range fds { 71 // Get flags. We do it here because they may be modified 72 // by subsequent functions. 73 fileFlags, _, errno := unix.Syscall(unix.SYS_FCNTL, uintptr(fd), unix.F_GETFL, 0) 74 if errno != 0 { 75 ctx.Warningf("Error retrieving host FD flags: %v", error(errno)) 76 break 77 } 78 79 // Create the file backed by hostFD. 80 file, err := NewFile(ctx, fd) 81 if err != nil { 82 ctx.Warningf("Error creating file from host FD: %v", err) 83 break 84 } 85 86 // Set known flags. 87 file.SetFlags(fs.SettableFileFlags{ 88 NonBlocking: fileFlags&unix.O_NONBLOCK != 0, 89 }) 90 91 files = append(files, file) 92 } 93 return files 94 } 95 96 // LINT.ThenChange(../../fsimpl/host/control.go)