github.com/moby/docker@v26.1.3+incompatible/daemon/graphdriver/copy/copy.go (about)

     1  //go:build linux
     2  
     3  package copy // import "github.com/docker/docker/daemon/graphdriver/copy"
     4  
     5  import (
     6  	"container/list"
     7  	"errors"
     8  	"fmt"
     9  	"io"
    10  	"os"
    11  	"path/filepath"
    12  	"syscall"
    13  	"time"
    14  
    15  	"github.com/containerd/containerd/pkg/userns"
    16  	"github.com/docker/docker/pkg/pools"
    17  	"github.com/docker/docker/pkg/system"
    18  	"golang.org/x/sys/unix"
    19  )
    20  
    21  // Mode indicates whether to use hardlink or copy content
    22  type Mode int
    23  
    24  const (
    25  	// Content creates a new file, and copies the content of the file
    26  	Content Mode = iota
    27  	// Hardlink creates a new hardlink to the existing file
    28  	Hardlink
    29  )
    30  
    31  func copyRegular(srcPath, dstPath string, fileinfo os.FileInfo, copyWithFileRange, copyWithFileClone *bool) error {
    32  	srcFile, err := os.Open(srcPath)
    33  	if err != nil {
    34  		return err
    35  	}
    36  	defer srcFile.Close()
    37  
    38  	// If the destination file already exists, we shouldn't blow it away
    39  	dstFile, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, fileinfo.Mode())
    40  	if err != nil {
    41  		return err
    42  	}
    43  	defer dstFile.Close()
    44  
    45  	if *copyWithFileClone {
    46  		err = unix.IoctlFileClone(int(dstFile.Fd()), int(srcFile.Fd()))
    47  		if err == nil {
    48  			return nil
    49  		}
    50  
    51  		*copyWithFileClone = false
    52  		if err == unix.EXDEV {
    53  			*copyWithFileRange = false
    54  		}
    55  	}
    56  	if *copyWithFileRange {
    57  		err = doCopyWithFileRange(srcFile, dstFile, fileinfo)
    58  		// Trying the file_clone may not have caught the exdev case
    59  		// as the ioctl may not have been available (therefore EINVAL)
    60  		if err == unix.EXDEV || err == unix.ENOSYS {
    61  			*copyWithFileRange = false
    62  		} else {
    63  			return err
    64  		}
    65  	}
    66  	return legacyCopy(srcFile, dstFile)
    67  }
    68  
    69  func doCopyWithFileRange(srcFile, dstFile *os.File, fileinfo os.FileInfo) error {
    70  	amountLeftToCopy := fileinfo.Size()
    71  
    72  	for amountLeftToCopy > 0 {
    73  		n, err := unix.CopyFileRange(int(srcFile.Fd()), nil, int(dstFile.Fd()), nil, int(amountLeftToCopy), 0)
    74  		if err != nil {
    75  			return err
    76  		}
    77  
    78  		amountLeftToCopy = amountLeftToCopy - int64(n)
    79  	}
    80  
    81  	return nil
    82  }
    83  
    84  func legacyCopy(srcFile io.Reader, dstFile io.Writer) error {
    85  	_, err := pools.Copy(dstFile, srcFile)
    86  
    87  	return err
    88  }
    89  
    90  func copyXattr(srcPath, dstPath, attr string) error {
    91  	data, err := system.Lgetxattr(srcPath, attr)
    92  	if err != nil {
    93  		if errors.Is(err, syscall.EOPNOTSUPP) {
    94  			// Task failed successfully: there is no xattr to copy
    95  			// if the source filesystem doesn't support xattrs.
    96  			return nil
    97  		}
    98  		return err
    99  	}
   100  	if data != nil {
   101  		if err := system.Lsetxattr(dstPath, attr, data, 0); err != nil {
   102  			return err
   103  		}
   104  	}
   105  	return nil
   106  }
   107  
   108  type fileID struct {
   109  	dev uint64
   110  	ino uint64
   111  }
   112  
   113  type dirMtimeInfo struct {
   114  	dstPath *string
   115  	stat    *syscall.Stat_t
   116  }
   117  
   118  // DirCopy copies or hardlinks the contents of one directory to another, properly
   119  // handling soft links, "security.capability" and (optionally) "trusted.overlay.opaque"
   120  // xattrs.
   121  //
   122  // The copyOpaqueXattrs controls if "trusted.overlay.opaque" xattrs are copied.
   123  // Passing false disables copying "trusted.overlay.opaque" xattrs.
   124  func DirCopy(srcDir, dstDir string, copyMode Mode, copyOpaqueXattrs bool) error {
   125  	copyWithFileRange := true
   126  	copyWithFileClone := true
   127  
   128  	// This is a map of source file inodes to dst file paths
   129  	copiedFiles := make(map[fileID]string)
   130  
   131  	dirsToSetMtimes := list.New()
   132  	err := filepath.Walk(srcDir, func(srcPath string, f os.FileInfo, err error) error {
   133  		if err != nil {
   134  			return err
   135  		}
   136  
   137  		// Rebase path
   138  		relPath, err := filepath.Rel(srcDir, srcPath)
   139  		if err != nil {
   140  			return err
   141  		}
   142  
   143  		dstPath := filepath.Join(dstDir, relPath)
   144  
   145  		stat, ok := f.Sys().(*syscall.Stat_t)
   146  		if !ok {
   147  			return fmt.Errorf("Unable to get raw syscall.Stat_t data for %s", srcPath)
   148  		}
   149  
   150  		isHardlink := false
   151  
   152  		switch mode := f.Mode(); {
   153  		case mode.IsRegular():
   154  			// the type is 32bit on mips
   155  			id := fileID{dev: uint64(stat.Dev), ino: stat.Ino} //nolint: unconvert
   156  			if copyMode == Hardlink {
   157  				isHardlink = true
   158  				if err2 := os.Link(srcPath, dstPath); err2 != nil {
   159  					return err2
   160  				}
   161  			} else if hardLinkDstPath, ok := copiedFiles[id]; ok {
   162  				isHardlink = true
   163  				if err2 := os.Link(hardLinkDstPath, dstPath); err2 != nil {
   164  					return err2
   165  				}
   166  			} else {
   167  				if err2 := copyRegular(srcPath, dstPath, f, &copyWithFileRange, &copyWithFileClone); err2 != nil {
   168  					return err2
   169  				}
   170  				copiedFiles[id] = dstPath
   171  			}
   172  
   173  		case mode.IsDir():
   174  			if err := os.Mkdir(dstPath, f.Mode()); err != nil && !os.IsExist(err) {
   175  				return err
   176  			}
   177  
   178  		case mode&os.ModeSymlink != 0:
   179  			link, err := os.Readlink(srcPath)
   180  			if err != nil {
   181  				return err
   182  			}
   183  
   184  			if err := os.Symlink(link, dstPath); err != nil {
   185  				return err
   186  			}
   187  
   188  		case mode&os.ModeNamedPipe != 0:
   189  			fallthrough
   190  		case mode&os.ModeSocket != 0:
   191  			if err := unix.Mkfifo(dstPath, stat.Mode); err != nil {
   192  				return err
   193  			}
   194  
   195  		case mode&os.ModeDevice != 0:
   196  			if userns.RunningInUserNS() {
   197  				// cannot create a device if running in user namespace
   198  				return nil
   199  			}
   200  			if err := unix.Mknod(dstPath, stat.Mode, int(stat.Rdev)); err != nil {
   201  				return err
   202  			}
   203  
   204  		default:
   205  			return fmt.Errorf("unknown file type (%d / %s) for %s", f.Mode(), f.Mode().String(), srcPath)
   206  		}
   207  
   208  		// Everything below is copying metadata from src to dst. All this metadata
   209  		// already shares an inode for hardlinks.
   210  		if isHardlink {
   211  			return nil
   212  		}
   213  
   214  		if err := os.Lchown(dstPath, int(stat.Uid), int(stat.Gid)); err != nil {
   215  			return err
   216  		}
   217  
   218  		if err := copyXattr(srcPath, dstPath, "security.capability"); err != nil {
   219  			return err
   220  		}
   221  
   222  		if copyOpaqueXattrs {
   223  			if err := doCopyXattrs(srcPath, dstPath); err != nil {
   224  				return err
   225  			}
   226  		}
   227  
   228  		isSymlink := f.Mode()&os.ModeSymlink != 0
   229  
   230  		// There is no LChmod, so ignore mode for symlink. Also, this
   231  		// must happen after chown, as that can modify the file mode
   232  		if !isSymlink {
   233  			if err := os.Chmod(dstPath, f.Mode()); err != nil {
   234  				return err
   235  			}
   236  		}
   237  
   238  		// system.Chtimes doesn't support a NOFOLLOW flag atm
   239  		//nolint: unconvert
   240  		if f.IsDir() {
   241  			dirsToSetMtimes.PushFront(&dirMtimeInfo{dstPath: &dstPath, stat: stat})
   242  		} else if !isSymlink {
   243  			aTime := time.Unix(stat.Atim.Unix())
   244  			mTime := time.Unix(stat.Mtim.Unix())
   245  			if err := system.Chtimes(dstPath, aTime, mTime); err != nil {
   246  				return err
   247  			}
   248  		} else {
   249  			ts := []syscall.Timespec{stat.Atim, stat.Mtim}
   250  			if err := system.LUtimesNano(dstPath, ts); err != nil {
   251  				return err
   252  			}
   253  		}
   254  		return nil
   255  	})
   256  	if err != nil {
   257  		return err
   258  	}
   259  	for e := dirsToSetMtimes.Front(); e != nil; e = e.Next() {
   260  		mtimeInfo := e.Value.(*dirMtimeInfo)
   261  		ts := []syscall.Timespec{mtimeInfo.stat.Atim, mtimeInfo.stat.Mtim}
   262  		if err := system.LUtimesNano(*mtimeInfo.dstPath, ts); err != nil {
   263  			return err
   264  		}
   265  	}
   266  
   267  	return nil
   268  }
   269  
   270  func doCopyXattrs(srcPath, dstPath string) error {
   271  	// We need to copy this attribute if it appears in an overlay upper layer, as
   272  	// this function is used to copy those. It is set by overlay if a directory
   273  	// is removed and then re-created and should not inherit anything from the
   274  	// same dir in the lower dir.
   275  	return copyXattr(srcPath, dstPath, "trusted.overlay.opaque")
   276  }