gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/pkg/sentry/fdimport/fdimport.go (about)

     1  // Copyright 2020 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 fdimport provides the Import function.
    16  package fdimport
    17  
    18  import (
    19  	"fmt"
    20  
    21  	"golang.org/x/sys/unix"
    22  	"gvisor.dev/gvisor/pkg/context"
    23  	"gvisor.dev/gvisor/pkg/fd"
    24  	"gvisor.dev/gvisor/pkg/sentry/fsimpl/host"
    25  	"gvisor.dev/gvisor/pkg/sentry/kernel"
    26  	"gvisor.dev/gvisor/pkg/sentry/kernel/auth"
    27  	"gvisor.dev/gvisor/pkg/sentry/vfs"
    28  )
    29  
    30  // Import imports a map of FDs into the given FDTable. If console is true,
    31  // sets up TTY for sentry stdin, stdout, and stderr FDs. Used FDs are either
    32  // closed or released. It's safe for the caller to close any remaining files
    33  // upon return.
    34  func Import(ctx context.Context, fdTable *kernel.FDTable, console bool, uid auth.KUID, gid auth.KGID, fds map[int]*fd.FD, containerName string) (*host.TTYFileDescription, error) {
    35  	k := kernel.KernelFromContext(ctx)
    36  	if k == nil {
    37  		return nil, fmt.Errorf("cannot find kernel from context")
    38  	}
    39  	mnt := k.HostMount()
    40  
    41  	// Collect host fds and flags. Do this before importing any fds because
    42  	// multiple fds may refer to the same file, and importing fds may
    43  	// change flags.
    44  	fdFlags := make(map[*fd.FD]kernel.FDFlags)
    45  	for _, hostFD := range fds {
    46  		var err error
    47  		fdFlags[hostFD], err = getFDFlags(hostFD)
    48  		if err != nil {
    49  			return nil, err
    50  		}
    51  	}
    52  
    53  	var ttyFile *vfs.FileDescription
    54  	for appFD, hostFD := range fds {
    55  		fdOpts := host.NewFDOptions{
    56  			Savable: true,
    57  		}
    58  		if uid != auth.NoID || gid != auth.NoID {
    59  			fdOpts.VirtualOwner = true
    60  			fdOpts.UID = uid
    61  			fdOpts.GID = gid
    62  		}
    63  		var appFile *vfs.FileDescription
    64  
    65  		fdOpts.RestoreKey = host.MakeRestoreID(containerName, appFD)
    66  		if console && appFD < 3 {
    67  			// Import the file as a host TTY file.
    68  			if ttyFile == nil {
    69  				fdOpts.IsTTY = true
    70  				var err error
    71  				appFile, err = host.NewFD(ctx, mnt, hostFD.FD(), &fdOpts)
    72  				if err != nil {
    73  					return nil, err
    74  				}
    75  				defer appFile.DecRef(ctx)
    76  				hostFD.Release() // FD is transferred to host FD.
    77  
    78  				// Remember this in the TTY file, as we will use it for the other stdio
    79  				// FDs.
    80  				ttyFile = appFile
    81  			} else {
    82  				// Re-use the existing TTY file, as all three stdio FDs must point to
    83  				// the same fs.File in order to share TTY state, specifically the
    84  				// foreground process group id.
    85  				appFile = ttyFile
    86  			}
    87  		} else {
    88  			var err error
    89  			appFile, err = host.NewFD(ctx, mnt, hostFD.FD(), &fdOpts)
    90  			if err != nil {
    91  				return nil, err
    92  			}
    93  			defer appFile.DecRef(ctx)
    94  			hostFD.Release() // FD is transferred to host FD.
    95  		}
    96  
    97  		df, err := fdTable.NewFDAt(ctx, int32(appFD), appFile, fdFlags[hostFD])
    98  		if err != nil {
    99  			return nil, err
   100  		}
   101  		if df != nil {
   102  			df.DecRef(ctx)
   103  			return nil, fmt.Errorf("app FD %d displaced while importing FDs", appFD)
   104  		}
   105  	}
   106  	if ttyFile == nil {
   107  		return nil, nil
   108  	}
   109  	return ttyFile.Impl().(*host.TTYFileDescription), nil
   110  }
   111  
   112  func getFDFlags(f *fd.FD) (kernel.FDFlags, error) {
   113  	fdflags, _, errno := unix.Syscall(unix.SYS_FCNTL, uintptr(f.FD()), unix.F_GETFD, 0)
   114  	if errno != 0 {
   115  		return kernel.FDFlags{}, fmt.Errorf("failed to get fd flags for fd %d (errno=%d)", f, errno)
   116  	}
   117  	return kernel.FDFlags{
   118  		CloseOnExec: fdflags&unix.O_CLOEXEC != 0,
   119  	}, nil
   120  }