// CopyFile is a utility for copying a file - used for the LCOW scratch cache.
// Uses CopyFileW win32 API for performance.
18024
func CopyFile(srcFile, destFile string, overwrite bool) error {
	var bFailIfExists uint32 = 1
	if overwrite {
		bFailIfExists = 0
	}

	lpExistingFileName, err := syscall.UTF16PtrFromString(srcFile)
	if err != nil {
		return err
	}
	lpNewFileName, err := syscall.UTF16PtrFromString(destFile)
	if err != nil {
		return err
	}
	r1, _, err := syscall.Syscall(
		procCopyFileW.Addr(),
		3,
		uintptr(unsafe.Pointer(lpExistingFileName)),
		uintptr(unsafe.Pointer(lpNewFileName)),
		uintptr(bFailIfExists))
	if r1 == 0 {
		return fmt.Errorf("failed CopyFileW Win32 call from '%s' to '%s': %s", srcFile, destFile, err)
	}
	return nil
}
1325840
func CopyFile(target, source string) error {
	src, err := os.Open(source)
	if err != nil {
		return errors.Wrapf(err, "failed to open source %s", source)
	}
	defer src.Close()
	tgt, err := os.Create(target)
	if err != nil {
		return errors.Wrapf(err, "failed to open target %s", target)
	}
	defer tgt.Close()

	return copyFileContent(tgt, src)
}
889651
func CopyFile(source string, dest string) error {
	si, err := os.Lstat(source)
	if err != nil {
		return err
	}

	st, ok := si.Sys().(*syscall.Stat_t)
	if !ok {
		return fmt.Errorf("could not convert to syscall.Stat_t")
	}

	uid := int(st.Uid)
	gid := int(st.Gid)

	// Handle symlinks
	if si.Mode()&os.ModeSymlink != 0 {
		target, err := os.Readlink(source)
		if err != nil {
			return err
		}
		if err := os.Symlink(target, dest); err != nil {
			return err
		}
	}

	// Handle device files
	if st.Mode&syscall.S_IFMT == syscall.S_IFBLK || st.Mode&syscall.S_IFMT == syscall.S_IFCHR {
		devMajor := int64(major(uint64(st.Rdev)))
		devMinor := int64(minor(uint64(st.Rdev)))
		mode := uint32(si.Mode() & 07777)
		if st.Mode&syscall.S_IFMT == syscall.S_IFBLK {
			mode |= syscall.S_IFBLK
		}
		if st.Mode&syscall.S_IFMT == syscall.S_IFCHR {
			mode |= syscall.S_IFCHR
		}
		if err := syscall.Mknod(dest, mode, int(mkdev(devMajor, devMinor))); err != nil {
			return err
		}
	}

	// Handle regular files
	if si.Mode().IsRegular() {
		sf, err := os.Open(source)
		if err != nil {
			return err
		}
		defer sf.Close()

		df, err := os.Create(dest)
		if err != nil {
			return err
		}
		defer df.Close()

		_, err = io.Copy(df, sf)
		if err != nil {
			return err
		}
	}

	// Chown the file
	if err := os.Lchown(dest, uid, gid); err != nil {
		return err
	}

	// Chmod the file
	if !(si.Mode()&os.ModeSymlink == os.ModeSymlink) {
		if err := os.Chmod(dest, si.Mode()); err != nil {
			return err
		}
	}

	return nil
}
234533
func Copy(l Logger) Logger {
	if l, ok := l.(LoggerCopier); ok {
		return l.Copy()
	}
	return NopLogger
}
383090
func (fs *Filespace) Copy(src, dest string) error {
	srcNode, err := fs.root.GetByPath(src)
	if err != nil {
		return err
	}
	if srcNode.IsDir() {
		return fs.CopyDirectory(src, dest)
	}
	return fs.CopyFile(src, dest)
}
478865
func (p *PNSExecutor) CopyFile(containerID string, sourcePath string, destPath string) (err error) {
	destFile, err := os.Create(destPath)
	if err != nil {
		return err
	}
	defer func() {
		// exit chroot and close the file. preserve the original error
		deferErr := p.exitChroot()
		if err == nil && deferErr != nil {
			err = errors.InternalWrapError(deferErr)
		}
		deferErr = destFile.Close()
		if err == nil && deferErr != nil {
			err = errors.InternalWrapError(deferErr)
		}
	}()
	w := bufio.NewWriter(destFile)
	err = p.enterChroot()
	if err != nil {
		return err
	}

	err = archive.TarGzToWriter(sourcePath, w)
	if err != nil {
		return err
	}

	return nil
}
1178901
func copyFileWithMetadata(srcRoot, destRoot *os.File, subPath string, isDir bool) (fileInfo *winio.FileBasicInfo, err error) {
	src, err := safefile.OpenRelative(
		subPath,
		srcRoot,
		syscall.GENERIC_READ|winio.ACCESS_SYSTEM_SECURITY,
		syscall.FILE_SHARE_READ,
		safefile.FILE_OPEN,
		safefile.FILE_OPEN_REPARSE_POINT)
	if err != nil {
		return nil, err
	}
	defer src.Close()
	srcr := winio.NewBackupFileReader(src, true)
	defer srcr.Close()

	fileInfo, err = winio.GetFileBasicInfo(src)
	if err != nil {
		return nil, err
	}

	extraFlags := uint32(0)
	if isDir {
		extraFlags |= safefile.FILE_DIRECTORY_FILE
	}
	dest, err := safefile.OpenRelative(
		subPath,
		destRoot,
		syscall.GENERIC_READ|syscall.GENERIC_WRITE|winio.WRITE_DAC|winio.WRITE_OWNER|winio.ACCESS_SYSTEM_SECURITY,
		syscall.FILE_SHARE_READ,
		safefile.FILE_CREATE,
		extraFlags)
	if err != nil {
		return nil, err
	}
	defer dest.Close()

	err = winio.SetFileBasicInfo(dest, fileInfo)
	if err != nil {
		return nil, err
	}

	destw := winio.NewBackupFileWriter(dest, true)
	defer func() {
		cerr := destw.Close()
		if err == nil {
			err = cerr
		}
	}()

	_, err = io.Copy(destw, srcr)
	if err != nil {
		return nil, err
	}

	return fileInfo, nil
}
255635
func (client *Client) CopyImage(args *CopyImageArgs) (string, error) {
	response := &CopyImageResponse{}
	err := client.Invoke("CopyImage", args, &response)
	if err != nil {
		return "", err
	}
	return response.ImageId, nil
}
291849
func Copy(src, dest string) error {
	if IsDir(src) {
		return CopyDirectory(src, dest)
	}
	return CopyFile(src, dest)
}
648289
func (mock *Mock) WriteFile(file string, data []byte) error {
	items := mock.getReturnValues("WriteFile")
	return items[0].(error)
}
1342322
func (e *fileExtractor) copyFile(ctx context.Context, containerID, path string) ([]byte, error) {
	var buf bytes.Buffer
	if err := e.client.CopyFromContainer(ctx, docker.CopyFromContainerOptions{
		Container:    containerID,
		Resource:     path,
		OutputStream: &buf,
	}); err != nil {
		return nil, err
	}

	// Open the tar archive for reading.
	r := bytes.NewReader(buf.Bytes())

	return firstFile(tar.NewReader(r))
}
792470
func CopyDir(srcPath, destPath string, filters ...func(filePath string) bool) error {
	// Check if target directory exists.
	if IsExist(destPath) {
		return errors.New("file or directory alreay exists: " + destPath)
	}

	err := os.MkdirAll(destPath, os.ModePerm)
	if err != nil {
		return err
	}

	// Gather directory info.
	infos, err := StatDir(srcPath, true)
	if err != nil {
		return err
	}

	var filter func(filePath string) bool
	if len(filters) > 0 {
		filter = filters[0]
	}

	for _, info := range infos {
		if filter != nil && filter(info) {
			continue
		}

		curPath := path.Join(destPath, info)
		if strings.HasSuffix(info, "/") {
			err = os.MkdirAll(curPath, os.ModePerm)
		} else {
			err = Copy(path.Join(srcPath, info), curPath)
		}
		if err != nil {
			return err
		}
	}
	return nil
}
776298
func (_m *ContainerRuntimeExecutor) CopyFile(containerID string, sourcePath string, destPath string) error {
	ret := _m.Called(containerID, sourcePath, destPath)

	var r0 error
	if rf, ok := ret.Get(0).(func(string, string, string) error); ok {
		r0 = rf(containerID, sourcePath, destPath)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
1323623
func (b *UpdateService) ScriptFile(scriptFile string) *UpdateService {
	b.scriptFile = scriptFile
	return b
}
1105364
func (f *FS) MoveFile(ctx context.Context, src dokan.File, sourceFI *dokan.FileInfo, targetPath string, replaceExisting bool) (err error) {
	// User checking was handled by original file open, this is no longer true.
	// However we only allow fake files with names that are not potential rename
	// paths. Filter those out here.

	f.vlog.CLogf(
		ctx, libkb.VLog1, "MoveFile %T %q -> %q", src,
		sourceFI.Path(), targetPath)
	// isPotentialRenamePath filters out some special paths
	// for rename. Especially those provided by fakeroot.go.
	if !isPotentialRenamePath(sourceFI.Path()) {
		f.log.CErrorf(ctx, "Refusing MoveFile access: not potential rename path")
		return dokan.ErrAccessDenied
	}
	switch src.(type) {
	case *FolderList, *File, *Dir, *TLF, *EmptyFolder:
	default:
		f.log.CErrorf(ctx, "Refusing MoveFile access: wrong type source argument")
		return dokan.ErrAccessDenied
	}

	f.logEnter(ctx, "FS MoveFile")
	// No racing deletions or renames.
	// Note that this calls Cleanup multiple times, however with nil
	// FileInfo which means that Cleanup will not try to lock renameAndDeletionLock.
	// renameAndDeletionLock should be the first lock to be grabbed in libdokan.
	f.renameAndDeletionLock.Lock()
	defer func() {
		f.renameAndDeletionLock.Unlock()
		f.reportErr(ctx, libkbfs.WriteMode, err)
	}()

	oc := newSyntheticOpenContext()

	// Source directory
	srcDirPath, err := windowsPathSplit(sourceFI.Path())
	if err != nil {
		return err
	}
	if len(srcDirPath) < 1 {
		return errors.New("Invalid source for move")
	}
	srcName := srcDirPath[len(srcDirPath)-1]
	srcDirPath = srcDirPath[0 : len(srcDirPath)-1]
	srcDir, _, err := f.open(ctx, oc, srcDirPath)
	if err != nil {
		return err
	}
	defer srcDir.Cleanup(ctx, nil)

	// Destination directory, not the destination file
	dstPath, err := windowsPathSplit(targetPath)
	if err != nil {
		return err
	}
	if len(dstPath) < 1 {
		return errors.New("Invalid destination for move")
	}
	dstDirPath := dstPath[0 : len(dstPath)-1]

	dstDir, dstCst, err := f.open(ctx, oc, dstDirPath)
	f.vlog.CLogf(
		ctx, libkb.VLog1, "FS MoveFile dstDir open %v -> %v,%v,%v dstType %T",
		dstDirPath, dstDir, dstCst, err, dstDir)
	if err != nil {
		return err
	}
	defer dstDir.Cleanup(ctx, nil)
	if !dstCst.IsDir() {
		return errors.New("Tried to move to a non-directory path")
	}

	fl1, ok := srcDir.(*FolderList)
	fl2, ok2 := dstDir.(*FolderList)
	if ok && ok2 && fl1 == fl2 {
		return f.folderListRename(ctx, fl1, oc, src, srcName, dstPath, replaceExisting)
	}

	srcDirD := asDir(ctx, srcDir)
	if srcDirD == nil {
		return errors.New("Parent of src not a Dir")
	}
	srcFolder := srcDirD.folder
	srcParent := srcDirD.node

	ddst := asDir(ctx, dstDir)
	if ddst == nil {
		return errors.New("Destination directory is not of type Dir")
	}

	switch src.(type) {
	case *Dir:
	case *File:
	case *TLF:
	default:
		return dokan.ErrAccessDenied
	}

	// here we race...
	if !replaceExisting {
		x, _, err := f.open(ctx, oc, dstPath)
		if err == nil {
			defer x.Cleanup(ctx, nil)
		}
		if !isNoSuchNameError(err) {
			f.vlog.CLogf(
				ctx, libkb.VLog1,
				"FS MoveFile required non-existent destination, got: %T %v",
				err, err)
			return dokan.ErrObjectNameCollision
		}

	}

	if srcFolder != ddst.folder {
		return dokan.ErrNotSameDevice
	}

	// overwritten node, if any, will be removed from Folder.nodes, if
	// it is there in the first place, by its Forget

	dstName := dstPath[len(dstPath)-1]
	f.vlog.CLogf(
		ctx, libkb.VLog1, "FS MoveFile KBFSOps().Rename(ctx,%v,%v,%v,%v)",
		srcParent, srcName, ddst.node, dstName)
	if err := srcFolder.fs.config.KBFSOps().Rename(
		ctx, srcParent, srcName, ddst.node, dstName); err != nil {
		f.log.CDebugf(ctx, "FS MoveFile KBFSOps().Rename FAILED %v", err)
		return err
	}

	switch x := src.(type) {
	case *Dir:
		x.parent = ddst.node
		x.name = dstName
	case *File:
		x.parent = ddst.node
		x.name = dstName
	}

	f.vlog.CLogf(ctx, libkb.VLog1, "FS MoveFile SUCCESS")
	return nil
}
513491
func Copy(source, destination string) error {
	src := cleanPath(source)
	dst := cleanPath(destination)
	s, err := os.Open(src)
	if err != nil {
		return err
	}
	// no need to check errors on read only file, we already got everything
	// we need from the filesystem, so nothing can go wrong now.
	defer s.Close()

	if IsDir(src) {
		return fmt.Errorf("source path is a directory")
	}
	if IsDir(dst) {
		basename := filepath.Base(src)
		dst = path.Join(dst, basename)
	}

	d, err := os.Create(dst)
	if err != nil {
		return err
	}
	if _, err := io.Copy(d, s); err != nil {
		d.Close()
		return err
	}
	return d.Close()
}
242065
func copyFile(sourceDir, sourceFile, destDir string, libRootURLs []string) error {
	var source io.Reader

	if strings.HasPrefix(sourceFile, "http://") || strings.HasPrefix(sourceFile, "https://") {
		resp, err := http.Get(sourceFile)
		if err != nil {
			return err
		}
		defer resp.Body.Close()
		source = resp.Body
	} else {
		sourceFile, err := os.Open(filepath.Join(sourceDir, sourceFile))
		if err != nil {
			return err
		}
		source = sourceFile
	}

	dest := filepath.Join(destDir, libraries.StripLibRootURL(sourceFile, libRootURLs))

	// create target dir if needed
	if err := os.MkdirAll(filepath.Dir(dest), 0777); err != nil {
		return err
	}

	// creaate dest file
	destFile, err := os.OpenFile(dest, os.O_CREATE|os.O_RDWR, 0666)
	if err != nil {
		return err
	}

	_, err = io.Copy(destFile, source)
	return err
}