diff --git a/Sources/CNIOLinux/include/CNIOLinux.h b/Sources/CNIOLinux/include/CNIOLinux.h index a75e07f63..cde2942fd 100644 --- a/Sources/CNIOLinux/include/CNIOLinux.h +++ b/Sources/CNIOLinux/include/CNIOLinux.h @@ -133,5 +133,8 @@ extern const int CNIOLinux_AT_EMPTY_PATH; extern const unsigned int CNIOLinux_RENAME_NOREPLACE; extern const unsigned int CNIOLinux_RENAME_EXCHANGE; +extern const unsigned long CNIOLinux_UTIME_OMIT; +extern const unsigned long CNIOLinux_UTIME_NOW; + #endif #endif diff --git a/Sources/CNIOLinux/shim.c b/Sources/CNIOLinux/shim.c index dfe0076ab..832cef739 100644 --- a/Sources/CNIOLinux/shim.c +++ b/Sources/CNIOLinux/shim.c @@ -33,6 +33,7 @@ void CNIOLinux_i_do_nothing_just_working_around_a_darwin_toolchain_bug(void) {} #include #include #include +#include _Static_assert(sizeof(CNIOLinux_mmsghdr) == sizeof(struct mmsghdr), "sizes of CNIOLinux_mmsghdr and struct mmsghdr differ"); @@ -211,4 +212,7 @@ const unsigned int CNIOLinux_RENAME_NOREPLACE = RENAME_NOREPLACE; const unsigned int CNIOLinux_RENAME_EXCHANGE = RENAME_EXCHANGE; const int CNIOLinux_AT_EMPTY_PATH = AT_EMPTY_PATH; +const unsigned long CNIOLinux_UTIME_OMIT = UTIME_OMIT; +const unsigned long CNIOLinux_UTIME_NOW = UTIME_NOW; + #endif diff --git a/Sources/NIOFileSystem/FileHandle.swift b/Sources/NIOFileSystem/FileHandle.swift index a59436dc5..2f6f0ed47 100644 --- a/Sources/NIOFileSystem/FileHandle.swift +++ b/Sources/NIOFileSystem/FileHandle.swift @@ -83,6 +83,16 @@ extension _HasFileHandle { public func close() async throws { try await self.fileHandle.close() } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.fileHandle.setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } } /// Implements ``FileHandleProtocol`` by making system calls to interact with the local file system. @@ -148,6 +158,16 @@ public struct FileHandle: FileHandleProtocol { public func close() async throws { try await self.systemFileHandle.close() } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.systemFileHandle.setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } } /// Implements ``ReadableFileHandleProtocol`` by making system calls to interact with the local @@ -173,6 +193,16 @@ public struct ReadFileHandle: ReadableFileHandleProtocol, _HasFileHandle { public func readChunks(in range: Range, chunkLength: ByteCount) -> FileChunks { self.fileHandle.systemFileHandle.readChunks(in: range, chunkLength: chunkLength) } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.fileHandle.systemFileHandle.setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } } /// Implements ``WritableFileHandleProtocol`` by making system calls to interact with the local @@ -203,6 +233,16 @@ public struct WriteFileHandle: WritableFileHandleProtocol, _HasFileHandle { public func close(makeChangesVisible: Bool) async throws { try await self.fileHandle.systemFileHandle.close(makeChangesVisible: makeChangesVisible) } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.fileHandle.systemFileHandle.setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } } /// Implements ``ReadableAndWritableFileHandleProtocol`` by making system calls to interact with the @@ -247,6 +287,16 @@ public struct ReadWriteFileHandle: ReadableAndWritableFileHandleProtocol, _HasFi public func close(makeChangesVisible: Bool) async throws { try await self.fileHandle.systemFileHandle.close(makeChangesVisible: makeChangesVisible) } + + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.fileHandle.systemFileHandle.setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } } /// Implements ``DirectoryFileHandleProtocol`` by making system calls to interact with the local diff --git a/Sources/NIOFileSystem/FileHandleProtocol.swift b/Sources/NIOFileSystem/FileHandleProtocol.swift index 372bf0b01..e7607f782 100644 --- a/Sources/NIOFileSystem/FileHandleProtocol.swift +++ b/Sources/NIOFileSystem/FileHandleProtocol.swift @@ -143,6 +143,27 @@ public protocol FileHandleProtocol { /// /// After closing the handle calls to other functions will throw an appropriate error. func close() async throws + + /// Sets the file's last access and last data modification times to the given values. + /// + /// If **either** time is `nil`, the current value will not be changed. + /// If **both** times are `nil`, then both times will be set to the current time. + /// + /// > Important: Times are only considered valid if their nanoseconds components are one of the following: + /// > - `UTIME_NOW` (you can use ``FileInfo/Timespec/now`` to get a Timespec set to this value), + /// > - `UTIME_OMIT` (you can use ``FileInfo/Timespec/omit`` to get a Timespec set to this value), + /// > - Greater than zero and no larger than 1000 million: if outside of this range, the value will be clamped to the closest valid value. + /// > The seconds component must also be positive: if it's not, zero will be used as the value instead. + /// + /// - Parameters: + /// - lastAccessTime: The new value of the file's last access time, as time elapsed since the Epoch. + /// - lastDataModificationTime: The new value of the file's last data modification time, as time elapsed since the Epoch. + /// + /// - Throws: If there's an error updating the times. If this happens, the original values won't be modified. + func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws } // MARK: - Readable @@ -488,6 +509,36 @@ extension WritableFileHandleProtocol { } } +// MARK: - File times modifiers + +@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) +extension FileHandleProtocol { + /// Sets the file's last access time to the given time. + /// + /// - Parameter time: The time to which the file's last access time should be set. + /// + /// - Throws: If there's an error updating the time. If this happens, the original value won't be modified. + public func setLastAccessTime(to time: FileInfo.Timespec) async throws { + try await self.setTimes(lastAccess: time, lastDataModification: nil) + } + + /// Sets the file's last data modification time to the given time. + /// + /// - Parameter time: The time to which the file's last data modification time should be set. + /// + /// - Throws: If there's an error updating the time. If this happens, the original value won't be modified. + public func setLastDataModificationTime(to time: FileInfo.Timespec) async throws { + try await self.setTimes(lastAccess: nil, lastDataModification: time) + } + + /// Sets the file's last access and last data modification times to the current time. + /// + /// - Throws: If there's an error updating the times. If this happens, the original values won't be modified. + public func touch() async throws { + try await self.setTimes(lastAccess: nil, lastDataModification: nil) + } +} + /// A file handle which is suitable for reading and writing. @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) public typealias ReadableAndWritableFileHandleProtocol = ReadableFileHandleProtocol diff --git a/Sources/NIOFileSystem/FileInfo.swift b/Sources/NIOFileSystem/FileInfo.swift index 7f174bf6d..3df14db1c 100644 --- a/Sources/NIOFileSystem/FileInfo.swift +++ b/Sources/NIOFileSystem/FileInfo.swift @@ -19,8 +19,10 @@ import SystemPackage import Darwin #elseif canImport(Glibc) import Glibc +import CNIOLinux #elseif canImport(Musl) import Musl +import CNIOLinux #endif /// Information about a file system object. @@ -145,6 +147,29 @@ extension FileInfo { /// A time interval consisting of whole seconds and nanoseconds. public struct Timespec: Hashable, Sendable { + #if canImport(Darwin) + private static let utimeOmit = Int(UTIME_OMIT) + private static let utimeNow = Int(UTIME_NOW) + #elseif canImport(Glibc) || canImport(Musl) + private static let utimeOmit = Int(CNIOLinux_UTIME_OMIT) + private static let utimeNow = Int(CNIOLinux_UTIME_NOW) + #endif + + /// A timespec where the seconds are set to zero and the nanoseconds set to `UTIME_OMIT`. + /// In syscalls such as `futimens`, this means the time component set to this value will be ignored. + public static let omit = Self( + seconds: 0, + nanoseconds: Self.utimeOmit + ) + + /// A timespec where the seconds are set to zero and the nanoseconds set to `UTIME_NOW`. + /// In syscalls such as `futimens`, this means the time component set to this value will be + /// be set to the current time or the largest value supported by the platform, whichever is smaller. + public static let now = Self( + seconds: 0, + nanoseconds: Self.utimeNow + ) + /// The number of seconds. public var seconds: Int diff --git a/Sources/NIOFileSystem/FileSystemError+Syscall.swift b/Sources/NIOFileSystem/FileSystemError+Syscall.swift index 8f9808c00..a59185bb2 100644 --- a/Sources/NIOFileSystem/FileSystemError+Syscall.swift +++ b/Sources/NIOFileSystem/FileSystemError+Syscall.swift @@ -1066,6 +1066,44 @@ extension FileSystemError { location: location ) } + + @_spi(Testing) + public static func futimens( + errno: Errno, + path: FilePath, + lastAccessTime: FileInfo.Timespec?, + lastDataModificationTime: FileInfo.Timespec?, + location: SourceLocation + ) -> FileSystemError { + let code: FileSystemError.Code + let message: String + + switch errno { + case .permissionDenied, .notPermitted: + code = .permissionDenied + message = "Not permitted to change last access or last data modification times for \(path)." + + case .readOnlyFileSystem: + code = .unsupported + message = "Not permitted to change last access or last data modification times for \(path): this is a read-only file system." + + case .badFileDescriptor: + code = .closed + message = "Could not change last access or last data modification dates for \(path): file is closed." + + default: + code = .unknown + message = "Could not change last access or last data modification dates for \(path)." + } + + return FileSystemError( + code: code, + message: message, + systemCall: "futimens", + errno: errno, + location: location + ) + } } #endif diff --git a/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift b/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift index 06b268916..308c239c0 100644 --- a/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift +++ b/Sources/NIOFileSystem/Internal/System Calls/Syscall.swift @@ -266,6 +266,16 @@ public enum Syscall { } } #endif + + @_spi(Testing) + public static func futimens( + fileDescriptor fd: FileDescriptor, + times: UnsafePointer? + ) -> Result { + nothingOrErrno(retryOnInterrupt: false) { + system_futimens(fd.rawValue, times) + } + } } @_spi(Testing) diff --git a/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift b/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift index 120500c27..284d59d77 100644 --- a/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift +++ b/Sources/NIOFileSystem/Internal/System Calls/Syscalls.swift @@ -349,6 +349,18 @@ internal func system_sendfile( } #endif +internal func system_futimens( + _ fd: CInt, + _ times: UnsafePointer? +) -> CInt { + #if ENABLE_MOCKING + if mockingEnabled { + return mock(fd, times) + } + #endif + return futimens(fd, times) +} + // MARK: - libc /// fdopendir(3): Opens a directory stream for the file descriptor diff --git a/Sources/NIOFileSystem/Internal/SystemFileHandle.swift b/Sources/NIOFileSystem/Internal/SystemFileHandle.swift index 54496673d..34c8f6235 100644 --- a/Sources/NIOFileSystem/Internal/SystemFileHandle.swift +++ b/Sources/NIOFileSystem/Internal/SystemFileHandle.swift @@ -22,8 +22,10 @@ import NIOPosix import Darwin #elseif canImport(Glibc) import Glibc +import CNIOLinux #elseif canImport(Musl) import Musl +import CNIOLinux #endif /// An implementation of ``FileHandleProtocol`` which is backed by system calls and a file @@ -153,7 +155,7 @@ extension SystemFileHandle.SendableView { } } - /// Executes a closure with the file descriptor it it's available otherwise throws the result + /// Executes a closure with the file descriptor if it's available otherwise throws the result /// of `onUnavailable`. internal func _withUnsafeDescriptor( _ execute: (FileDescriptor) throws -> R, @@ -166,8 +168,8 @@ extension SystemFileHandle.SendableView { } } - /// Executes a closure with the file descriptor it it's available otherwise throws the result - /// of `onUnavailable`. + /// Executes a closure with the file descriptor if it's available otherwise returns the result + /// of `onUnavailable` as a `Result` Error. internal func _withUnsafeDescriptorResult( _ execute: (FileDescriptor) -> Result, onUnavailable: () -> FileSystemError @@ -355,6 +357,18 @@ extension SystemFileHandle: FileHandleProtocol { } } + public func setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) async throws { + try await self.threadPool.runIfActive { [sendableView] in + try sendableView._setTimes( + lastAccess: lastAccess, + lastDataModification: lastDataModification + ) + } + } + @_spi(Testing) public enum UpdatePermissionsOperation { case set, add, remove } } @@ -909,6 +923,84 @@ extension SystemFileHandle.SendableView { return result } + + func _setTimes( + lastAccess: FileInfo.Timespec?, + lastDataModification: FileInfo.Timespec? + ) throws { + try self._withUnsafeDescriptor { descriptor in + let syscallResult: Result + switch (lastAccess, lastDataModification) { + case (.none, .none): + // If the timespec array is nil, as per the `futimens` docs, + // both the last accessed and last modification times + // will be set to now. + syscallResult = Syscall.futimens( + fileDescriptor: descriptor, + times: nil + ) + + case (.some(let lastAccess), .none): + // Don't modify the last modification time. + syscallResult = Syscall.futimens( + fileDescriptor: descriptor, + times: [timespec(lastAccess), timespec(.omit)] + ) + + case (.none, .some(let lastDataModification)): + // Don't modify the last access time. + syscallResult = Syscall.futimens( + fileDescriptor: descriptor, + times: [timespec(.omit), timespec(lastDataModification)] + ) + + case (.some(let lastAccess), .some(let lastDataModification)): + syscallResult = Syscall.futimens( + fileDescriptor: descriptor, + times: [timespec(lastAccess), timespec(lastDataModification)] + ) + } + + try syscallResult.mapError { errno in + FileSystemError.futimens( + errno: errno, + path: self.path, + lastAccessTime: lastAccess, + lastDataModificationTime: lastDataModification, + location: .here() + ) + }.get() + } onUnavailable: { + FileSystemError( + code: .closed, + message: "Couldn't modify file dates, the file '\(self.path)' is closed.", + cause: nil, + location: .here() + ) + } + } +} + +extension timespec { + fileprivate init(_ fileinfoTimespec: FileInfo.Timespec) { + // Clamp seconds to be positive + let seconds = max(0, fileinfoTimespec.seconds) + + // If nanoseconds are not UTIME_NOW or UTIME_OMIT, clamp to be between + // 0 and 1,000 million. + let nanoseconds: Int + switch fileinfoTimespec { + case .now, .omit: + nanoseconds = fileinfoTimespec.nanoseconds + default: + nanoseconds = min(1_000_000_000, max(0, fileinfoTimespec.nanoseconds)) + } + + self.init( + tv_sec: seconds, + tv_nsec: nanoseconds + ) + } } // MARK: - Readable File Handle diff --git a/Tests/NIOFileSystemIntegrationTests/FileHandleTests.swift b/Tests/NIOFileSystemIntegrationTests/FileHandleTests.swift index 7356a9f12..ffcd85af1 100644 --- a/Tests/NIOFileSystemIntegrationTests/FileHandleTests.swift +++ b/Tests/NIOFileSystemIntegrationTests/FileHandleTests.swift @@ -1178,6 +1178,121 @@ final class FileHandleTests: XCTestCase { } } } + + func testSetLastAccesTime() async throws { + try await self.withTemporaryFile { handle in + let originalLastDataModificationTime = try await handle.info().lastDataModificationTime + let originalLastAccessTime = try await handle.info().lastAccessTime + + try await handle.setTimes( + lastAccess: FileInfo.Timespec(seconds: 10, nanoseconds: 5), + lastDataModification: nil + ) + + let actualLastAccessTime = try await handle.info().lastAccessTime + XCTAssertEqual(actualLastAccessTime, FileInfo.Timespec(seconds: 10, nanoseconds: 5)) + XCTAssertNotEqual(actualLastAccessTime, originalLastAccessTime) + + let actualLastDataModificationTime = try await handle.info().lastDataModificationTime + XCTAssertEqual(actualLastDataModificationTime, originalLastDataModificationTime) + } + } + + func testSetLastDataModificationTime() async throws { + try await self.withTemporaryFile { handle in + let originalLastDataModificationTime = try await handle.info().lastDataModificationTime + let originalLastAccessTime = try await handle.info().lastAccessTime + + try await handle.setTimes( + lastAccess: nil, + lastDataModification: FileInfo.Timespec(seconds: 10, nanoseconds: 5) + ) + + let actualLastDataModificationTime = try await handle.info().lastDataModificationTime + XCTAssertEqual(actualLastDataModificationTime, FileInfo.Timespec(seconds: 10, nanoseconds: 5)) + XCTAssertNotEqual(actualLastDataModificationTime, originalLastDataModificationTime) + + let actualLastAccessTime = try await handle.info().lastAccessTime + XCTAssertEqual(actualLastAccessTime, originalLastAccessTime) + } + } + + func testSetLastAccessAndLastDataModificationTimes() async throws { + try await self.withTemporaryFile { handle in + let originalLastDataModificationTime = try await handle.info().lastDataModificationTime + let originalLastAccessTime = try await handle.info().lastAccessTime + + try await handle.setTimes( + lastAccess: FileInfo.Timespec(seconds: 20, nanoseconds: 25), + lastDataModification: FileInfo.Timespec(seconds: 10, nanoseconds: 5) + ) + + let actualLastAccessTime = try await handle.info().lastAccessTime + XCTAssertEqual(actualLastAccessTime, FileInfo.Timespec(seconds: 20, nanoseconds: 25)) + XCTAssertNotEqual(actualLastAccessTime, originalLastAccessTime) + + let actualLastDataModificationTime = try await handle.info().lastDataModificationTime + XCTAssertEqual(actualLastDataModificationTime, FileInfo.Timespec(seconds: 10, nanoseconds: 5)) + XCTAssertNotEqual(actualLastDataModificationTime, originalLastDataModificationTime) + } + } + + func testSetLastAccessAndLastDataModificationTimesToNil() async throws { + try await self.withTemporaryFile { handle in + // Set some random value for both times, only to be overwritten by the current time + // right after. + try await handle.setTimes( + lastAccess: FileInfo.Timespec(seconds: 1, nanoseconds: 0), + lastDataModification: FileInfo.Timespec(seconds: 1, nanoseconds: 0) + ) + + var actualLastAccessTime = try await handle.info().lastAccessTime + XCTAssertEqual(actualLastAccessTime, FileInfo.Timespec(seconds: 1, nanoseconds: 0)) + + var actualLastDataModificationTime = try await handle.info().lastDataModificationTime + XCTAssertEqual(actualLastDataModificationTime, FileInfo.Timespec(seconds: 1, nanoseconds: 0)) + + try await handle.setTimes( + lastAccess: nil, + lastDataModification: nil + ) + let estimatedCurrentTime = Date.now.timeIntervalSince1970 + + // Assert that the times are equal to the current time, with up to a second difference (to avoid timing flakiness). + actualLastAccessTime = try await handle.info().lastAccessTime + XCTAssertEqual(Float(actualLastAccessTime.seconds), Float(estimatedCurrentTime), accuracy: 1) + + actualLastDataModificationTime = try await handle.info().lastDataModificationTime + XCTAssertEqual(Float(actualLastDataModificationTime.seconds), Float(estimatedCurrentTime), accuracy: 1) + } + } + + func testTouchFile() async throws { + try await self.withTemporaryFile { handle in + // Set some random value for both times, only to be overwritten by the current time + // right after. + try await handle.setTimes( + lastAccess: FileInfo.Timespec(seconds: 1, nanoseconds: 0), + lastDataModification: FileInfo.Timespec(seconds: 1, nanoseconds: 0) + ) + + var actualLastAccessTime = try await handle.info().lastAccessTime + XCTAssertEqual(actualLastAccessTime, FileInfo.Timespec(seconds: 1, nanoseconds: 0)) + + var actualLastDataModificationTime = try await handle.info().lastDataModificationTime + XCTAssertEqual(actualLastDataModificationTime, FileInfo.Timespec(seconds: 1, nanoseconds: 0)) + + try await handle.touch() + let estimatedCurrentTime = Date.now.timeIntervalSince1970 + + // Assert that the times are equal to the current time, with up to a second difference (to avoid timing flakiness). + actualLastAccessTime = try await handle.info().lastAccessTime + XCTAssertEqual(Float(actualLastAccessTime.seconds), Float(estimatedCurrentTime), accuracy: 1) + + actualLastDataModificationTime = try await handle.info().lastDataModificationTime + XCTAssertEqual(Float(actualLastDataModificationTime.seconds), Float(estimatedCurrentTime), accuracy: 1) + } + } } @available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) diff --git a/Tests/NIOFileSystemTests/FileSystemErrorTests.swift b/Tests/NIOFileSystemTests/FileSystemErrorTests.swift index 308b21da8..f32165f62 100644 --- a/Tests/NIOFileSystemTests/FileSystemErrorTests.swift +++ b/Tests/NIOFileSystemTests/FileSystemErrorTests.swift @@ -558,6 +558,19 @@ final class FileSystemErrorTests: XCTestCase { } } + func testErrnoMapping_futimens() { + self.testErrnoToErrorCode( + expected: [ + .permissionDenied: .permissionDenied, + .notPermitted: .permissionDenied, + .readOnlyFileSystem: .unsupported, + .badFileDescriptor: .closed, + ] + ) { errno in + .futimens(errno: errno, path: "", lastAccessTime: nil, lastDataModificationTime: nil, location: .fixed) + } + } + private func testErrnoToErrorCode( expected mapping: [Errno: FileSystemError.Code], _ makeError: (Errno) -> FileSystemError diff --git a/Tests/NIOFileSystemTests/Internal/SyscallTests.swift b/Tests/NIOFileSystemTests/Internal/SyscallTests.swift index 2c22d87a1..abd7209c9 100644 --- a/Tests/NIOFileSystemTests/Internal/SyscallTests.swift +++ b/Tests/NIOFileSystemTests/Internal/SyscallTests.swift @@ -398,6 +398,22 @@ final class SyscallTests: XCTestCase { testCases.run() } + func test_futimens() throws { + let fd = FileDescriptor(rawValue: 42) + let times = timespec(tv_sec: 1, tv_nsec: 1) + withUnsafePointer(to: times) { unsafeTimesPointer in + let testCases = [ + MockTestCase(name: "futimens", .noInterrupt, 42, unsafeTimesPointer) { _ in + try Syscall.futimens( + fileDescriptor: fd, + times: unsafeTimesPointer + ).get() + } + ] + testCases.run() + } + } + func testValueOrErrno() throws { let r1: Result = valueOrErrno(retryOnInterrupt: false) { Errno._current = .addressInUse