diff --git a/Sources/_NIOFileSystem/Docs.docc/Extensions/FileSystemProtocol.md b/Sources/_NIOFileSystem/Docs.docc/Extensions/FileSystemProtocol.md index c7f2d4b07..fcc7ba8e2 100644 --- a/Sources/_NIOFileSystem/Docs.docc/Extensions/FileSystemProtocol.md +++ b/Sources/_NIOFileSystem/Docs.docc/Extensions/FileSystemProtocol.md @@ -34,6 +34,7 @@ closing it to avoid leaking resources. ### Managing files - ``copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` +- ``copyItem(at:to:strategy:replaceExisting:shouldProceedAfterError:shouldCopyItem:)`` - ``removeItem(at:)`` - ``moveItem(at:to:)`` - ``replaceItem(at:withItemAt:)`` diff --git a/Sources/_NIOFileSystem/FileSystem.swift b/Sources/_NIOFileSystem/FileSystem.swift index ad589c89d..0c0786d91 100644 --- a/Sources/_NIOFileSystem/FileSystem.swift +++ b/Sources/_NIOFileSystem/FileSystem.swift @@ -306,7 +306,7 @@ public struct FileSystem: Sendable, FileSystemProtocol { // MARK: - File copying, removal, and moving - /// See ``FileSystemProtocol/copyItem(at:to:shouldProceedAfterError:shouldCopyFile:)`` + /// See ``FileSystemProtocol/copyItem(at:to:strategy:replaceExisting:shouldProceedAfterError:shouldCopyItem:)`` /// /// The item to be copied must be a: /// - regular file, @@ -325,10 +325,19 @@ public struct FileSystem: Sendable, FileSystemProtocol { /// /// This function is platform dependent. On Darwin the `copyfile(2)` system call is used and /// items are cloned where possible. On Linux the `sendfile(2)` system call is used. + /// + /// When `replaceExisting` is `true`, regular files are atomically replaced using `COPYFILE_UNLINK` + /// on Darwin or a temporary file followed by `renameat2(2)` on Linux. Symbolic links are + /// atomically replaced using a temporary symlink followed by `renamex_np(2)` on Darwin or + /// `renameat2(2)` on Linux. + /// + /// Note that `replaceExisting` is ignored for directories and implemented only for regular + /// files and symbolic links. public func copyItem( at sourcePath: FilePath, to destinationPath: FilePath, strategy copyStrategy: CopyStrategy, + replaceExisting: Bool, shouldProceedAfterError: @escaping @Sendable ( _ source: DirectoryEntry, @@ -355,10 +364,10 @@ public struct FileSystem: Sendable, FileSystemProtocol { if await shouldCopyItem(.init(path: sourcePath, type: info.type)!, destinationPath) { switch info.type { case .regular: - try await self.copyRegularFile(from: sourcePath, to: destinationPath) + try await self.copyRegularFile(from: sourcePath, to: destinationPath, replaceExisting: replaceExisting) case .symlink: - try await self.copySymbolicLink(from: sourcePath, to: destinationPath) + try await self.copySymbolicLink(from: sourcePath, to: destinationPath, replaceExisting: replaceExisting) case .directory: try await self.copyDirectory( @@ -1104,7 +1113,8 @@ extension FileSystem { do { try await self.copyRegularFile( from: source.path, - to: destination + to: destination, + replaceExisting: false ) } catch { try await shouldProceedAfterError(source, error) @@ -1114,7 +1124,8 @@ extension FileSystem { do { try await self.copySymbolicLink( from: source.path, - to: destination + to: destination, + replaceExisting: false ) } catch { try await shouldProceedAfterError(source, error) @@ -1212,7 +1223,8 @@ extension FileSystem { do { try await self.copyRegularFile( from: from.path, - to: to + to: to, + replaceExisting: false ) } catch { try await shouldProceedAfterError(from, error) @@ -1222,7 +1234,8 @@ extension FileSystem { do { try await self.copySymbolicLink( from: from.path, - to: to + to: to, + replaceExisting: false ) } catch { try await shouldProceedAfterError(from, error) @@ -1260,34 +1273,27 @@ extension FileSystem { private func copyRegularFile( from sourcePath: FilePath, - to destinationPath: FilePath + to destinationPath: FilePath, + replaceExisting: Bool ) async throws { try await self.threadPool.runIfActive { - try self._copyRegularFile(from: sourcePath, to: destinationPath).get() + try self._copyRegularFile(from: sourcePath, to: destinationPath, replaceExisting: replaceExisting).get() } } private func _copyRegularFile( from sourcePath: FilePath, - to destinationPath: FilePath + to destinationPath: FilePath, + replaceExisting: Bool = false ) -> Result { - func makeOnUnavailableError( - path: FilePath, - location: FileSystemError.SourceLocation - ) -> FileSystemError { - FileSystemError( - code: .closed, - message: "Can't copy '\(sourcePath)' to '\(destinationPath)', '\(path)' is closed.", - cause: nil, - location: location - ) - } - #if canImport(Darwin) // COPYFILE_CLONE clones the file if possible and will fallback to doing a copy. // COPYFILE_ALL is shorthand for: // COPYFILE_STAT | COPYFILE_ACL | COPYFILE_XATTR | COPYFILE_DATA - let flags = copyfile_flags_t(COPYFILE_CLONE) | copyfile_flags_t(COPYFILE_ALL) + var flags = copyfile_flags_t(COPYFILE_CLONE) | copyfile_flags_t(COPYFILE_ALL) + if replaceExisting { + flags |= copyfile_flags_t(COPYFILE_UNLINK) + } return Libc.copyfile( from: sourcePath, to: destinationPath, @@ -1303,6 +1309,165 @@ extension FileSystem { } #elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic) + if replaceExisting { + return self._copyRegularFileReplacing(from: sourcePath, to: destinationPath) + } else { + return self._copyFileContents( + from: sourcePath, + to: destinationPath + ) { destinationPath, writeOptions in + self._openFile( + forWritingAt: destinationPath, + options: writeOptions + ).mapError { + FileSystemError( + message: "Can't copy '\(sourcePath)' as '\(destinationPath)' couldn't be opened.", + wrapping: $0 + ) + } + } + } + #endif + } + + #if canImport(Glibc) || canImport(Musl) || canImport(Bionic) + private func _copyRegularFileReplacing( + from sourcePath: FilePath, + to destinationPath: FilePath + ) -> Result { + // on Linux platforms we implement replaceExisting by copying the source file into + // a temporary destination and then atomically renaming it, using the renameat2(2) system call. + let parentDirectory = destinationPath.removingLastComponent() + let destinationDirectoryHandle: DirectoryFileHandle + switch self._openDirectory( + at: parentDirectory.isEmpty ? FilePath(".") : parentDirectory, + // not following symlinks here to prevent TOCTOU attacks where the parent directory + // is replaced with a symlink pointing to an attacker-controlled location + options: OpenOptions.Directory(followSymbolicLinks: false) + ) { + case let .success(handle): + destinationDirectoryHandle = handle + case let .failure(error): + return .failure( + FileSystemError( + message: "Can't copy '\(sourcePath)' to '\(destinationPath)', directory couldn't be opened.", + wrapping: error + ) + ) + } + defer { + _ = destinationDirectoryHandle + .fileHandle + .systemFileHandle + .sendableView + ._close(materialize: true) + } + + guard + let destinationDirectoryFD = destinationDirectoryHandle + .fileHandle + .systemFileHandle + .sendableView + .descriptorIfAvailable() + else { + let error = FileSystemError( + code: .closed, + message: + "Can't copy '\(sourcePath)' to '\(destinationPath)', directory descriptor unavailable.", + cause: nil, + location: .here() + ) + return .failure(error) + } + + let temporaryFilepath = FilePath(".tmp-" + String(randomAlphaNumericOfLength: 6)) + let copyResult = self._copyFileContents( + from: sourcePath, + to: temporaryFilepath + ) { destinationPath, writeOptions in + destinationDirectoryFD.open( + atPath: destinationPath, + mode: .writeOnly, + options: writeOptions.descriptorOptions, + permissions: writeOptions.permissionsForRegularFile + ) + .mapError { errno in + let openError = FileSystemError.open( + "openat", + error: errno, + path: destinationPath, + location: .here() + ) + return FileSystemError( + message: "Can't copy '\(sourcePath)' as '\(destinationPath)' couldn't be opened.", + wrapping: openError + ) + } + .map { fd in + let handle = SystemFileHandle( + takingOwnershipOf: fd, + path: destinationPath, + threadPool: self.threadPool + ) + return WriteFileHandle(wrapping: handle) + } + } + guard case .success = copyResult else { + _ = Syscall.unlinkat(path: temporaryFilepath, relativeTo: destinationDirectoryFD) + return copyResult + } + + guard let destinationFilename = destinationPath.lastComponent else { + return .failure( + FileSystemError( + code: .invalidArgument, + message: "Can't copy to '\(destinationPath)', path has no filename component.", + cause: nil, + location: .here() + ) + ) + } + let destinationFilepath = FilePath(root: nil, components: destinationFilename) + + switch Syscall.rename( + from: temporaryFilepath, + relativeTo: destinationDirectoryFD, + to: destinationFilepath, + relativeTo: destinationDirectoryFD, + flags: [] + ) { + case .failure(let errno): + _ = Syscall.unlinkat(path: temporaryFilepath, relativeTo: destinationDirectoryFD) + return .failure( + FileSystemError.rename( + "renameat2", + errno: errno, + oldName: temporaryFilepath, + newName: destinationFilepath, + location: .here() + ) + ) + case .success: + return .success(()) + } + } + + private func _copyFileContents( + from sourcePath: FilePath, + to destinationPath: FilePath, + openDestination: (FilePath, OpenOptions.Write) -> Result + ) -> Result { + func makeOnUnavailableError( + path: FilePath, + location: FileSystemError.SourceLocation + ) -> FileSystemError { + FileSystemError( + code: .closed, + message: "Can't copy '\(sourcePath)' to '\(destinationPath)', '\(path)' is closed.", + cause: nil, + location: location + ) + } let openSourceResult = self._openFile( forReadingAt: sourcePath, @@ -1342,18 +1507,8 @@ extension FileSystem { ) ) - let openDestinationResult = self._openFile( - forWritingAt: destinationPath, - options: options - ).mapError { - FileSystemError( - message: "Can't copy '\(sourcePath)' as '\(destinationPath)' couldn't be opened.", - wrapping: $0 - ) - } - let destination: WriteFileHandle - switch openDestinationResult { + switch openDestination(destinationPath, options) { case let .success(handle): destination = handle case let .failure(error): @@ -1399,25 +1554,163 @@ extension FileSystem { let closeResult = destination.fileHandle.systemFileHandle.sendableView._close(materialize: true) return copyResult.flatMap { closeResult } - #endif } + #endif private func copySymbolicLink( from sourcePath: FilePath, - to destinationPath: FilePath + to destinationPath: FilePath, + replaceExisting: Bool ) async throws { try await self.threadPool.runIfActive { - try self._copySymbolicLink(from: sourcePath, to: destinationPath).get() + try self._copySymbolicLink(from: sourcePath, to: destinationPath, replaceExisting: replaceExisting).get() } } private func _copySymbolicLink( + from sourcePath: FilePath, + to destinationPath: FilePath, + replaceExisting: Bool + ) -> Result { + if replaceExisting { + return self._copySymbolicLinkReplacing(from: sourcePath, to: destinationPath) + } else { + return self._destinationOfSymbolicLink(at: sourcePath).flatMap { linkDestination in + self._createSymbolicLink(at: destinationPath, withDestination: linkDestination) + } + } + } + + private func _copySymbolicLinkReplacing( from sourcePath: FilePath, to destinationPath: FilePath ) -> Result { - self._destinationOfSymbolicLink(at: sourcePath).flatMap { linkDestination in - self._createSymbolicLink(at: destinationPath, withDestination: linkDestination) + // There is no atomic symlink replace copy on either Darwin or Linux platforms + // so we copy the source symlink into a temporary symlink using `symlinkat` system call and then + // rename it into the destination symlink using the `renameatx_np(2)` on Darwin and + // `renameat2(2)` on Linux. + let parentDirectory = destinationPath.removingLastComponent() + let destinationDirectoryHandle: DirectoryFileHandle + switch self._openDirectory( + at: parentDirectory.isEmpty ? FilePath(".") : parentDirectory, + // not following symlinks here to prevent TOCTOU attacks where the parent directory + // is replaced with a symlink pointing to an attacker-controlled location + options: OpenOptions.Directory(followSymbolicLinks: false) + ) { + case let .success(handle): + destinationDirectoryHandle = handle + case let .failure(error): + return .failure( + FileSystemError( + message: "Can't copy '\(sourcePath)' to '\(destinationPath)', directory couldn't be opened.", + wrapping: error + ) + ) } + defer { + _ = destinationDirectoryHandle + .fileHandle + .systemFileHandle + .sendableView + ._close(materialize: true) + } + + guard + let destinationDirectoryFD = destinationDirectoryHandle + .fileHandle + .systemFileHandle + .sendableView + .descriptorIfAvailable() + else { + let error = FileSystemError( + code: .closed, + message: + "Can't copy '\(sourcePath)' to '\(destinationPath)', directory descriptor unavailable.", + cause: nil, + location: .here() + ) + return .failure(error) + } + + let sourceSymlinkTarget: FilePath + switch self._destinationOfSymbolicLink(at: sourcePath) { + case let .success(target): + sourceSymlinkTarget = target + case let .failure(error): + return .failure(error) + } + + let temporarySymlinkPath = FilePath(".tmp-link-" + String(randomAlphaNumericOfLength: 6)) + if case let .failure(errno) = Syscall.symlinkat( + to: sourceSymlinkTarget, + in: destinationDirectoryFD, + from: temporarySymlinkPath + ) { + let error = FileSystemError.symlink( + "symlinkat", + errno: errno, + link: temporarySymlinkPath, + target: sourceSymlinkTarget, + location: .here() + ) + return .failure(error) + } + + guard let destinationFilename = destinationPath.lastComponent else { + return .failure( + FileSystemError( + code: .invalidArgument, + message: "Can't copy to '\(destinationPath)', path has no filename component.", + cause: nil, + location: .here() + ) + ) + } + + let destinationFilePath = FilePath(root: nil, components: destinationFilename) + #if canImport(Darwin) + switch Syscall.rename( + from: temporarySymlinkPath, + relativeTo: destinationDirectoryFD, + to: destinationFilePath, + relativeTo: destinationDirectoryFD, + options: [] + ) { + case .success: + return .success(()) + case .failure(let errno): + _ = Syscall.unlinkat(path: temporarySymlinkPath, relativeTo: destinationDirectoryFD) + let error = FileSystemError.rename( + "renameatx_np", + errno: errno, + oldName: temporarySymlinkPath, + newName: destinationFilePath, + location: .here() + ) + return .failure(error) + } + #elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic) + switch Syscall.rename( + from: temporarySymlinkPath, + relativeTo: destinationDirectoryFD, + to: destinationFilePath, + relativeTo: destinationDirectoryFD, + flags: [] + ) { + case .success: + return .success(()) + case .failure(let errno): + _ = Syscall.unlinkat(path: temporarySymlinkPath, relativeTo: destinationDirectoryFD) + let error = FileSystemError.rename( + "renameat2", + errno: errno, + oldName: temporarySymlinkPath, + newName: destinationFilePath, + location: .here() + ) + return .failure(error) + } + #endif } @_spi(Testing) diff --git a/Sources/_NIOFileSystem/FileSystemProtocol.swift b/Sources/_NIOFileSystem/FileSystemProtocol.swift index eeceb6a30..4fd4ed2cb 100644 --- a/Sources/_NIOFileSystem/FileSystemProtocol.swift +++ b/Sources/_NIOFileSystem/FileSystemProtocol.swift @@ -175,7 +175,7 @@ public protocol FileSystemProtocol: Sendable { /// The following error codes may be thrown: /// - ``FileSystemError/Code-swift.struct/notFound`` if the item at `sourcePath` does not exist, /// - ``FileSystemError/Code-swift.struct/invalidArgument`` if an item at `destinationPath` - /// exists prior to the copy or its parent directory does not exist. + /// exists prior to the copy (when `replaceExisting` is `false`) or its parent directory does not exist. /// /// Note that other errors may also be thrown. /// @@ -186,6 +186,7 @@ public protocol FileSystemProtocol: Sendable { /// - sourcePath: The path to the item to copy. /// - destinationPath: The path at which to place the copy. /// - copyStrategy: How to deal with concurrent aspects of the copy, only relevant to directories. + /// - replaceExisting: If `true`, atomically replace any existing file at `destinationPath`. /// - shouldProceedAfterError: A closure which is executed to determine whether to continue /// copying files if an error is encountered during the operation. See Errors section for full details. /// - shouldCopyItem: A closure which is executed before each copy to determine whether each @@ -195,7 +196,7 @@ public protocol FileSystemProtocol: Sendable { /// /// No errors should be throw by implementors without first calling `shouldProceedAfterError`, /// if that returns without throwing this is taken as permission to continue and the error is swallowed. - /// If instead the closure throws then ``copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` + /// If instead the closure throws then ``copyItem(at:to:strategy:replaceExisting:shouldProceedAfterError:shouldCopyItem:)`` /// will throw and copying will stop, though the precise semantics of this can depend on the `strategy`. /// /// if using ``CopyStrategy/parallel(maxDescriptors:)`` @@ -236,6 +237,7 @@ public protocol FileSystemProtocol: Sendable { at sourcePath: FilePath, to destinationPath: FilePath, strategy copyStrategy: CopyStrategy, + replaceExisting: Bool, shouldProceedAfterError: @escaping @Sendable ( _ source: DirectoryEntry, @@ -466,6 +468,36 @@ extension FileSystemProtocol { try await self.info(forFileAt: path, infoAboutSymbolicLink: false) } + /// Copies the item at the specified path to a new location. + /// + /// Calls through to + /// ``copyItem(at:to:strategy:replaceExisting:shouldProceedAfterError:shouldCopyItem:)`` + /// with `replaceExisting` set to `false`. + public func copyItem( + at sourcePath: FilePath, + to destinationPath: FilePath, + strategy copyStrategy: CopyStrategy, + shouldProceedAfterError: + @escaping @Sendable ( + _ source: DirectoryEntry, + _ error: Error + ) async throws -> Void, + shouldCopyItem: + @escaping @Sendable ( + _ source: DirectoryEntry, + _ destination: FilePath + ) async -> Bool + ) async throws { + try await self.copyItem( + at: sourcePath, + to: destinationPath, + strategy: copyStrategy, + replaceExisting: false, + shouldProceedAfterError: shouldProceedAfterError, + shouldCopyItem: shouldCopyItem + ) + } + /// Copies the item at the specified path to a new location. /// /// The following error codes may be thrown: @@ -475,7 +507,7 @@ extension FileSystemProtocol { /// /// Note that other errors may also be thrown. If any error is encountered during the copy /// then the copy is aborted. You can modify the behaviour with the `shouldProceedAfterError` - /// parameter of ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)``. + /// parameter of ``FileSystemProtocol/copyItem(at:to:strategy:replaceExisting:shouldProceedAfterError:shouldCopyItem:)``. /// /// If the file at `sourcePath` is a symbolic link then only the link is copied to the new path. /// @@ -488,11 +520,18 @@ extension FileSystemProtocol { to destinationPath: FilePath, strategy copyStrategy: CopyStrategy = .platformDefault ) async throws { - try await self.copyItem(at: sourcePath, to: destinationPath, strategy: copyStrategy) { path, error in - throw error - } shouldCopyItem: { source, destination in - true - } + try await self.copyItem( + at: sourcePath, + to: destinationPath, + strategy: copyStrategy, + replaceExisting: false, + shouldProceedAfterError: { _, error in + throw error + }, + shouldCopyItem: { _, _ in + true + } + ) } /// Copies the item at the specified path to a new location. @@ -513,7 +552,7 @@ extension FileSystemProtocol { /// /// #### Backward Compatibility details /// - /// This is implemented in terms of ``copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` + /// This is implemented in terms of ``copyItem(at:to:strategy:replaceExisting:shouldProceedAfterError:shouldCopyItem:)`` /// using ``CopyStrategy/sequential`` to avoid changing the concurrency semantics of the should callbacks /// /// - Parameters: @@ -543,6 +582,7 @@ extension FileSystemProtocol { at: sourcePath, to: destinationPath, strategy: .sequential, + replaceExisting: false, shouldProceedAfterError: shouldProceedAfterError, shouldCopyItem: { (source, destination) in await shouldCopyFile(source.path, destination) @@ -574,7 +614,7 @@ extension FileSystemProtocol { /// /// This overload uses ``CopyStrategy/platformDefault`` which is likely to result in multiple concurrency domains being used /// in the event of copying a directory. - /// See the detailed description on ``copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` + /// See the detailed description on ``copyItem(at:to:strategy:replaceExisting:shouldProceedAfterError:shouldCopyItem:)`` /// for the implications of this with respect to the `shouldProceedAfterError` and `shouldCopyItem` callbacks public func copyItem( at sourcePath: FilePath, @@ -594,6 +634,7 @@ extension FileSystemProtocol { at: sourcePath, to: destinationPath, strategy: .platformDefault, + replaceExisting: false, shouldProceedAfterError: shouldProceedAfterError, shouldCopyItem: shouldCopyItem ) diff --git a/Sources/_NIOFileSystem/IOStrategy.swift b/Sources/_NIOFileSystem/IOStrategy.swift index 4c88476aa..8c1d10e6e 100644 --- a/Sources/_NIOFileSystem/IOStrategy.swift +++ b/Sources/_NIOFileSystem/IOStrategy.swift @@ -56,7 +56,7 @@ enum IOStrategy: Hashable, Sendable { } /// How to perform copies. Currently only relevant to directory level copies when using -/// ``FileSystemProtocol/copyItem(at:to:strategy:shouldProceedAfterError:shouldCopyItem:)`` or other +/// ``FileSystemProtocol/copyItem(at:to:strategy:replaceExisting:shouldProceedAfterError:shouldCopyItem:)`` or other /// overloads that use the default behaviour. public struct CopyStrategy: Hashable, Sendable { internal let wrapped: IOStrategy