From 5ae5d5a3afd5428511f906fcb8bf341803befc9a Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Mon, 25 Mar 2024 18:28:18 +0000 Subject: [PATCH] Refactor FilePathTemp, add tests for permission code. Broke `FilePathTemp.swift` into separate files for POSIX and Windows. Added tests for permissions code on Windows. Added leading underscores to some function names. Made some other functions `fileprivate`. rdar://125087707 --- Sources/System/ErrnoWindows.swift | 2 +- Sources/System/FileOperations.swift | 46 ++- Sources/System/FilePath/FilePathTemp.swift | 263 +++--------------- .../System/FilePath/FilePathTempPosix.swift | 153 ++++++++++ .../System/FilePath/FilePathTempWindows.swift | 114 ++++++++ Sources/System/Internals/Syscalls.swift | 12 + .../Internals/WindowsSyscallAdapters.swift | 72 +++-- Tests/SystemTests/FileOperationsTest.swift | 4 +- .../FileOperationsTestWindows.swift | 241 ++++++++++++++++ .../FilePathTests/FilePathTempTest.swift | 8 +- 10 files changed, 657 insertions(+), 258 deletions(-) create mode 100644 Sources/System/FilePath/FilePathTempPosix.swift create mode 100644 Sources/System/FilePath/FilePathTempWindows.swift create mode 100644 Tests/SystemTests/FileOperationsTestWindows.swift diff --git a/Sources/System/ErrnoWindows.swift b/Sources/System/ErrnoWindows.swift index 98fda43..b94b577 100644 --- a/Sources/System/ErrnoWindows.swift +++ b/Sources/System/ErrnoWindows.swift @@ -13,7 +13,7 @@ import WinSDK extension Errno { public init(windowsError: DWORD) { - self.init(rawValue: mapWindowsErrorToErrno(windowsError)) + self.init(rawValue: _mapWindowsErrorToErrno(windowsError)) } } diff --git a/Sources/System/FileOperations.swift b/Sources/System/FileOperations.swift index d2e8d65..ba70e87 100644 --- a/Sources/System/FileOperations.swift +++ b/Sources/System/FileOperations.swift @@ -135,8 +135,6 @@ extension FileDescriptor { if let permissions = permissions { return system_open(path, oFlag, permissions.rawValue) } - precondition(!options.contains(.create), - "Create must be given permissions") return system_open(path, oFlag) } return descOrError.map { FileDescriptor(rawValue: $0) } @@ -510,3 +508,47 @@ extension FileDescriptor { } } } + +extension FilePermissions { + /// The file creation permission mask (aka "umask"). + /// + /// Permissions set in this mask will be cleared by functions that create + /// files or directories. Note that this mask is process-wide, and that + /// *getting* it is not thread safe. + @_alwaysEmitIntoClient + public static var creationMask: FilePermissions { + get { + let oldMask = _umask(0o22) + _ = _umask(oldMask) + return FilePermissions(rawValue: oldMask) + } + set { + _ = _umask(newValue.rawValue) + } + } + + /// Change the file creation permission mask, run some code, then + /// restore it to its original value. + /// + /// - Parameters: + /// - permissions: The new permission mask. + /// + /// This is more efficient than reading `creationMask` and restoring it + /// afterwards, because of the way reading the creation mask works. + @_alwaysEmitIntoClient + public static func withCreationMask( + _ permissions: FilePermissions, + body: () throws -> R + ) rethrows -> R { + let oldMask = _umask(permissions.rawValue) + defer { + _ = _umask(oldMask) + } + return try body() + } + + @usableFromInline + internal static func _umask(_ mode: CModeT) -> CModeT { + return system_umask(mode) + } +} diff --git a/Sources/System/FilePath/FilePathTemp.swift b/Sources/System/FilePath/FilePathTemp.swift index ea67428..7b41d0b 100644 --- a/Sources/System/FilePath/FilePathTemp.swift +++ b/Sources/System/FilePath/FilePathTemp.swift @@ -9,13 +9,22 @@ // MARK: - API -public func withTemporaryPath( +/// Create a temporary path for the duration of the closure. +/// +/// - Parameters: +/// - basename: The base name for the temporary path. +/// - body: The closure to execute. +/// +/// Creates a temporary directory with a name based on the given `basename`, +/// executes `body`, passing in the path of the created directory, then +/// deletes the directory and all of its contents before returning. +public func withTemporaryFilePath( basename: FilePath.Component, _ body: (FilePath) throws -> R ) throws -> R { let temporaryDir = try createUniqueTemporaryDirectory(basename: basename) defer { - try? recursiveRemove(at: temporaryDir) + try? _recursiveRemove(at: temporaryDir) } return try body(temporaryDir) @@ -23,230 +32,20 @@ public func withTemporaryPath( // MARK: - Internals -#if os(Windows) -import WinSDK - -fileprivate func getTemporaryDirectory() throws -> FilePath { - return try withUnsafeTemporaryAllocation(of: CInterop.PlatformChar.self, - capacity: Int(MAX_PATH) + 1) { - buffer in - - guard GetTempPath2W(DWORD(buffer.count), buffer.baseAddress) != 0 else { - throw Errno(windowsError: GetLastError()) - } - - return FilePath(SystemString(platformString: buffer.baseAddress!)) - } -} - -fileprivate func forEachFile( - at path: FilePath, - _ body: (WIN32_FIND_DATAW) throws -> () -) rethrows { - let searchPath = path.appending("\\*") - - try searchPath.withPlatformString { szPath in - var findData = WIN32_FIND_DATAW() - let hFind = FindFirstFileW(szPath, &findData) - if hFind == INVALID_HANDLE_VALUE { - throw Errno(windowsError: GetLastError()) - } - defer { - FindClose(hFind) - } - - repeat { - // Skip . and .. - if findData.cFileName.0 == 46 - && (findData.cFileName.1 == 0 - || (findData.cFileName.1 == 46 - && findData.cFileName.2 == 0)) { - continue - } - - try body(findData) - } while FindNextFileW(hFind, &findData) - } -} - -fileprivate func recursiveRemove(at path: FilePath) throws { - // First, deal with subdirectories - try forEachFile(at: path) { findData in - if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 { - let name = withUnsafeBytes(of: findData.cFileName) { - return SystemString(platformString: $0.assumingMemoryBound( - to: CInterop.PlatformChar.self).baseAddress!) - } - let component = FilePath.Component(name)! - let subpath = path.appending(component) - - try recursiveRemove(at: subpath) - } - } - - // Now delete everything else - try forEachFile(at: path) { findData in - let name = withUnsafeBytes(of: findData.cFileName) { - return SystemString(platformString: $0.assumingMemoryBound( - to: CInterop.PlatformChar.self).baseAddress!) - } - let component = FilePath.Component(name)! - let subpath = path.appending(component) - - if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 { - try subpath.withPlatformString { - if !DeleteFileW($0) { - throw Errno(windowsError: GetLastError()) - } - } - } - } - - // Finally, delete the parent - try path.withPlatformString { - if !RemoveDirectoryW($0) { - throw Errno(windowsError: GetLastError()) - } - } -} - -#else -fileprivate func getTemporaryDirectory() throws -> FilePath { - #if SYSTEM_PACKAGE_DARWIN - var capacity = 1024 - while true { - let path: FilePath? = withUnsafeTemporaryAllocation( - of: CInterop.PlatformChar.self, - capacity: capacity - ) { buffer in - let len = system_confstr(SYSTEM_CS_DARWIN_USER_TEMP_DIR, - buffer.baseAddress!, - buffer.count) - if len == 0 { - // Fall back to "/tmp" if we can't read the temp directory - return "/tmp" - } - // If it was truncated, increase capaciy and try again - if len > buffer.count { - capacity = len - return nil - } - return FilePath(SystemString(platformString: buffer.baseAddress!)) - } - if let path = path { - return path - } - } - #else - return "/tmp" - #endif -} - -fileprivate func recursiveRemove(at path: FilePath) throws { - let dirfd = try FileDescriptor.open(path, .readOnly, options: .directory) - defer { - try? dirfd.close() - } - - let dot: (CInterop.PlatformChar, CInterop.PlatformChar) = (46, 0) - try withUnsafeBytes(of: dot) { - try recursiveRemove( - in: dirfd.rawValue, - path: $0.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress! - ) - } - - try path.withPlatformString { - if system_rmdir($0) != 0 { - throw Errno.current - } - } -} - -fileprivate func impl_opendirat( - _ dirfd: CInt, - _ path: UnsafePointer -) -> UnsafeMutablePointer? { - let fd = system_openat(dirfd, path, - FileDescriptor.AccessMode.readOnly.rawValue - | FileDescriptor.OpenOptions.directory.rawValue) - if fd < 0 { - return nil - } - return system_fdopendir(fd) -} - -fileprivate func forEachFile( - in dirfd: CInt, path: UnsafePointer, - _ body: (system_dirent) throws -> () -) throws { - guard let dir = impl_opendirat(dirfd, path) else { - throw Errno.current - } - defer { - _ = system_closedir(dir) - } - - while let dirent = system_readdir(dir) { - // Skip . and .. - if dirent.pointee.d_name.0 == 46 - && (dirent.pointee.d_name.1 == 0 - || (dirent.pointee.d_name.1 == 46 - && dirent.pointee.d_name.2 == 0)) { - continue - } - - try body(dirent.pointee) - } -} - -internal func recursiveRemove( - in dirfd: CInt, - path: UnsafePointer -) throws { - // First, deal with subdirectories - try forEachFile(in: dirfd, path: path) { dirent in - if dirent.d_type == SYSTEM_DT_DIR { - try withUnsafeBytes(of: dirent.d_name) { - try recursiveRemove( - in: dirfd, - path: $0.assumingMemoryBound(to: CInterop.PlatformChar.self) - .baseAddress! - ) - } - } - } - - // Now delete the contents of this directory - try forEachFile(in: dirfd, path: path) { dirent in - let flag: CInt - - if dirent.d_type == SYSTEM_DT_DIR { - flag = SYSTEM_AT_REMOVE_DIR - } else { - flag = 0 - } - - let result = withUnsafeBytes(of: dirent.d_name) { - system_unlinkat(dirfd, - $0.assumingMemoryBound(to: CInterop.PlatformChar.self) - .baseAddress!, - flag) - } - - if result != 0 { - throw Errno.current - } - } -} -#endif - fileprivate let base64 = Array( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".utf8 ) -fileprivate func makeTempDirectory(at: FilePath) throws -> Bool { - return try at.withPlatformString { +/// Create a directory that is only accessible to the current user. +/// +/// - Parameters: +/// - path: The path of the directory to create. +/// - Returns: `true` if a new directory was created. +/// +/// This function will throw if there is an error, except if the error +/// is that the directory exists, in which case it returns `false`. +fileprivate func makeLockedDownDirectory(at path: FilePath) throws -> Bool { + return try path.withPlatformString { if system_mkdir($0, 0o700) == 0 { return true } @@ -259,6 +58,11 @@ fileprivate func makeTempDirectory(at: FilePath) throws -> Bool { } } +/// Generate a random string of base64 filename safe characters. +/// +/// - Parameters: +/// - length: The number of characters in the returned string. +/// - Returns: A random string of length `length`. fileprivate func createRandomString(length: Int) -> String { return String( decoding: (0.. String { ) } -internal func createUniqueTemporaryDirectory( +/// Given a base name, create a uniquely named temporary directory. +/// +/// - Parameters: +/// - basename: The base name for the new directory. +/// - Returns: The path to the new directory. +/// +/// Creates a directory in the system temporary directory whose name +/// starts with `basename`, followed by a `.` and then a random +/// string of characters. +fileprivate func createUniqueTemporaryDirectory( basename: FilePath.Component ) throws -> FilePath { - var tempDir = try getTemporaryDirectory() + var tempDir = try _getTemporaryDirectory() tempDir.append(basename) while true { tempDir.extension = createRandomString(length: 16) - if try makeTempDirectory(at: tempDir) { + if try makeLockedDownDirectory(at: tempDir) { return tempDir } } diff --git a/Sources/System/FilePath/FilePathTempPosix.swift b/Sources/System/FilePath/FilePathTempPosix.swift new file mode 100644 index 0000000..623ccae --- /dev/null +++ b/Sources/System/FilePath/FilePathTempPosix.swift @@ -0,0 +1,153 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information + */ + +#if !os(Windows) + +/// Get the path to the system temporary directory. +internal func _getTemporaryDirectory() throws -> FilePath { + guard let tmp = system_getenv("TMPDIR") else { + return "/tmp" + } + + return FilePath(SystemString(platformString: tmp)) +} + +/// Delete the entire contents of a directory, including its subdirectories. +/// +/// - Parameters: +/// - path: The directory to be deleted. +/// +/// Removes a directory completely, including all of its contents. +internal func _recursiveRemove( + at path: FilePath +) throws { + let dirfd = try FileDescriptor.open(path, .readOnly, options: .directory) + defer { + try? dirfd.close() + } + + let dot: (CInterop.PlatformChar, CInterop.PlatformChar) = (46, 0) + try withUnsafeBytes(of: dot) { + try recursiveRemove( + in: dirfd.rawValue, + name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self).baseAddress! + ) + } + + try path.withPlatformString { + if system_rmdir($0) != 0 { + throw Errno.current + } + } +} + +/// Open a directory by reference to its parent and name. +/// +/// - Parameters: +/// - dirfd: An open file descriptor for the parent directory. +/// - name: The name of the directory to open. +/// - Returns: A pointer to a `DIR` structure. +/// +/// This is like `opendir()`, but instead of taking a path, it uses a +/// file descriptor pointing at the parent, thus avoiding path length +/// limits. +fileprivate func impl_opendirat( + _ dirfd: CInt, + _ name: UnsafePointer +) -> UnsafeMutablePointer? { + let fd = system_openat(dirfd, name, + FileDescriptor.AccessMode.readOnly.rawValue + | FileDescriptor.OpenOptions.directory.rawValue) + if fd < 0 { + return nil + } + return system_fdopendir(fd) +} + +/// Invoke a closure for each file within a particular directory. +/// +/// - Parameters: +/// - dirfd: The parent of the directory to be enumerated. +/// - subdir: The subdirectory to be enumerated. +/// - body: The closure that will be invoked. +/// +/// We skip the `.` and `..` pseudo-entries. +fileprivate func forEachFile( + in dirfd: CInt, + subdir: UnsafePointer, + _ body: (system_dirent) throws -> () +) throws { + guard let dir = impl_opendirat(dirfd, subdir) else { + throw Errno.current + } + defer { + _ = system_closedir(dir) + } + + while let dirent = system_readdir(dir) { + // Skip . and .. + if dirent.pointee.d_name.0 == 46 + && (dirent.pointee.d_name.1 == 0 + || (dirent.pointee.d_name.1 == 46 + && dirent.pointee.d_name.2 == 0)) { + continue + } + + try body(dirent.pointee) + } +} + +/// Delete the entire contents of a directory, including its subdirectories. +/// +/// - Parameters: +/// - dirfd: The parent of the directory to be removed. +/// - name: The name of the directory to be removed. +/// +/// Removes a directory completely, including all of its contents. +fileprivate func recursiveRemove( + in dirfd: CInt, + name: UnsafePointer +) throws { + // First, deal with subdirectories + try forEachFile(in: dirfd, subdir: name) { dirent in + if dirent.d_type == SYSTEM_DT_DIR { + try withUnsafeBytes(of: dirent.d_name) { + try recursiveRemove( + in: dirfd, + name: $0.assumingMemoryBound(to: CInterop.PlatformChar.self) + .baseAddress! + ) + } + } + } + + // Now delete the contents of this directory + try forEachFile(in: dirfd, subdir: name) { dirent in + let flag: CInt + + if dirent.d_type == SYSTEM_DT_DIR { + flag = SYSTEM_AT_REMOVE_DIR + } else { + flag = 0 + } + + let result = withUnsafeBytes(of: dirent.d_name) { + system_unlinkat(dirfd, + $0.assumingMemoryBound(to: CInterop.PlatformChar.self) + .baseAddress!, + flag) + } + + if result != 0 { + throw Errno.current + } + } +} + +#endif // !os(Windows) diff --git a/Sources/System/FilePath/FilePathTempWindows.swift b/Sources/System/FilePath/FilePathTempWindows.swift new file mode 100644 index 0000000..0d97edc --- /dev/null +++ b/Sources/System/FilePath/FilePathTempWindows.swift @@ -0,0 +1,114 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +#if os(Windows) + +import WinSDK + +/// Get the path to the system temporary directory. +internal func _getTemporaryDirectory() throws -> FilePath { + return try withUnsafeTemporaryAllocation(of: CInterop.PlatformChar.self, + capacity: Int(MAX_PATH) + 1) { + buffer in + + guard GetTempPath2W(DWORD(buffer.count), buffer.baseAddress) != 0 else { + throw Errno(windowsError: GetLastError()) + } + + return FilePath(SystemString(platformString: buffer.baseAddress!)) + } +} + +/// Invoke a closure for each file within a particular directory. +/// +/// - Parameters: +/// - path: The path at which we should enumerate items. +/// - body: The closure that will be invoked. +/// +/// We skip the `.` and `..` pseudo-entries. +fileprivate func forEachFile( + at path: FilePath, + _ body: (WIN32_FIND_DATAW) throws -> () +) rethrows { + let searchPath = path.appending("\\*") + + try searchPath.withPlatformString { szPath in + var findData = WIN32_FIND_DATAW() + let hFind = FindFirstFileW(szPath, &findData) + if hFind == INVALID_HANDLE_VALUE { + throw Errno(windowsError: GetLastError()) + } + defer { + FindClose(hFind) + } + + repeat { + // Skip . and .. + if findData.cFileName.0 == 46 + && (findData.cFileName.1 == 0 + || (findData.cFileName.1 == 46 + && findData.cFileName.2 == 0)) { + continue + } + + try body(findData) + } while FindNextFileW(hFind, &findData) + } +} + +/// Delete the entire contents of a directory, including its subdirectories. +/// +/// - Parameters: +/// - path: The directory to be deleted. +/// +/// Removes a directory completely, including all of its contents. +internal func _recursiveRemove( + at path: FilePath +) throws { + // First, deal with subdirectories + try forEachFile(at: path) { findData in + if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) != 0 { + let name = withUnsafeBytes(of: findData.cFileName) { + return SystemString(platformString: $0.assumingMemoryBound( + to: CInterop.PlatformChar.self).baseAddress!) + } + let component = FilePath.Component(name)! + let subpath = path.appending(component) + + try _recursiveRemove(at: subpath) + } + } + + // Now delete everything else + try forEachFile(at: path) { findData in + let name = withUnsafeBytes(of: findData.cFileName) { + return SystemString(platformString: $0.assumingMemoryBound( + to: CInterop.PlatformChar.self).baseAddress!) + } + let component = FilePath.Component(name)! + let subpath = path.appending(component) + + if (findData.dwFileAttributes & DWORD(FILE_ATTRIBUTE_DIRECTORY)) == 0 { + try subpath.withPlatformString { + if !DeleteFileW($0) { + throw Errno(windowsError: GetLastError()) + } + } + } + } + + // Finally, delete the parent + try path.withPlatformString { + if !RemoveDirectoryW($0) { + throw Errno(windowsError: GetLastError()) + } + } +} + +#endif // os(Windows) diff --git a/Sources/System/Internals/Syscalls.swift b/Sources/System/Internals/Syscalls.swift index cec8413..1c6ed72 100644 --- a/Sources/System/Internals/Syscalls.swift +++ b/Sources/System/Internals/Syscalls.swift @@ -239,3 +239,15 @@ internal func system_openat( return openat(fd, path, oflag) } #endif + +internal func system_umask( + _ mode: CInterop.Mode +) -> CInterop.Mode { + return umask(mode) +} + +internal func system_getenv( + _ name: UnsafePointer +) -> UnsafeMutablePointer? { + return getenv(name) +} diff --git a/Sources/System/Internals/WindowsSyscallAdapters.swift b/Sources/System/Internals/WindowsSyscallAdapters.swift index fa88cbe..3e3f9c6 100644 --- a/Sources/System/Internals/WindowsSyscallAdapters.swift +++ b/Sources/System/Internals/WindowsSyscallAdapters.swift @@ -12,15 +12,21 @@ import ucrt import WinSDK +fileprivate var _umask: CInterop.Mode = 0o22 + +@inline(__always) +func umask( + _ mode: CInterop.Mode +) -> CInterop.Mode { + let oldMask = _umask + _umask = mode + return oldMask +} + @inline(__always) internal func open( _ path: UnsafePointer, _ oflag: Int32 ) -> CInt { - if (oflag & _O_CREAT) != 0 { - ucrt._set_errno(EINVAL) - return -1 - } - let decodedFlags = DecodedOpenFlags(oflag) var saAttrs = SECURITY_ATTRIBUTES( @@ -40,7 +46,7 @@ internal func open( nil) if hFile == INVALID_HANDLE_VALUE { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -52,8 +58,10 @@ internal func open( _ path: UnsafePointer, _ oflag: Int32, _ mode: CInterop.Mode ) -> CInt { - guard let pSD = createSecurityDescriptor(from: mode) else { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + let actualMode = mode & ~_umask + + guard let pSD = _createSecurityDescriptor(from: actualMode, for: .file) else { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -80,7 +88,7 @@ internal func open( nil) if hFile == INVALID_HANDLE_VALUE { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -146,7 +154,7 @@ internal func pread( var nNumberOfBytesRead: DWORD = 0 if !ReadFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesRead, &ovlOverlapped) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return Int(-1) } return Int(nNumberOfBytesRead) @@ -169,7 +177,7 @@ internal func pwrite( var nNumberOfBytesWritten: DWORD = 0 if !WriteFile(hFile, buf, DWORD(nbyte), &nNumberOfBytesWritten, &ovlOverlapped) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return Int(-1) } return Int(nNumberOfBytesWritten) @@ -193,7 +201,7 @@ internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 { // Save the current position and restore it when we're done if !SetFilePointerEx(hFile, liCurrentOffset, &liCurrentOffset, DWORD(FILE_CURRENT)) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } defer { @@ -203,7 +211,7 @@ internal func ftruncate(_ fd: Int32, _ length: off_t) -> Int32 { // Truncate (or extend) the file if !SetFilePointerEx(hFile, liDesiredLength, nil, DWORD(FILE_BEGIN)) || !SetEndOfFile(hFile) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -215,8 +223,11 @@ internal func mkdir( _ path: UnsafePointer, _ mode: CInterop.Mode ) -> CInt { - guard let pSD = createSecurityDescriptor(from: mode) else { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + let actualMode = mode & ~_umask + + guard let pSD = _createSecurityDescriptor(from: actualMode, + for: .directory) else { + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } defer { @@ -230,7 +241,7 @@ internal func mkdir( ) if !CreateDirectoryW(path, &saAttrs) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -242,7 +253,7 @@ internal func rmdir( _ path: UnsafePointer ) -> CInt { if !RemoveDirectoryW(path) { - ucrt._set_errno(mapWindowsErrorToErrno(GetLastError())) + ucrt._set_errno(_mapWindowsErrorToErrno(GetLastError())) return -1 } @@ -250,7 +261,7 @@ internal func rmdir( } @usableFromInline -internal func mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt { +internal func _mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt { switch Int32(errorCode) { case ERROR_SUCCESS: return 0 @@ -323,7 +334,9 @@ internal func mapWindowsErrorToErrno(_ errorCode: DWORD) -> CInt { } fileprivate func rightsFromModeBits( - _ bits: Int, sticky: Bool = false + _ bits: Int, + sticky: Bool = false, + for fileOrDirectory: _FileOrDirectory ) -> DWORD { var rights: DWORD = 0 @@ -341,7 +354,7 @@ fileprivate func rightsFromModeBits( | FILE_WRITE_EA | STANDARD_RIGHTS_WRITE | SYNCHRONIZE) - if !sticky { + if fileOrDirectory == .directory && !sticky { rights |= DWORD(FILE_DELETE_CHILD) } } @@ -384,19 +397,30 @@ fileprivate func getTokenInformation( return nil } +@usableFromInline +internal enum _FileOrDirectory { + case file + case directory +} + /// Build a SECURITY_DESCRIPTOR from UNIX-style "mode" bits. This only /// takes account of the rwx and sticky bits; there's really nothing that /// we can do about setuid/setgid. @usableFromInline -internal func createSecurityDescriptor(from mode: CInterop.Mode) +internal func _createSecurityDescriptor(from mode: CInterop.Mode, + for fileOrDirectory: _FileOrDirectory) -> PSECURITY_DESCRIPTOR? { let ownerPerm = (Int(mode) >> 6) & 0o7 let groupPerm = (Int(mode) >> 3) & 0o7 let otherPerm = Int(mode) & 0o7 - let ownerRights = rightsFromModeBits(ownerPerm) - let groupRights = rightsFromModeBits(groupPerm, sticky: (mode & 0o1000) != 0) - let otherRights = rightsFromModeBits(otherPerm, sticky: (mode & 0o1000) != 0) + let ownerRights = rightsFromModeBits(ownerPerm, for: fileOrDirectory) + let groupRights = rightsFromModeBits(groupPerm, + sticky: (mode & 0o1000) != 0, + for: fileOrDirectory) + let otherRights = rightsFromModeBits(otherPerm, + sticky: (mode & 0o1000) != 0, + for: fileOrDirectory) // If group or other permissions are *more* permissive, then we need // some DENY ACEs as well to implement the expected semantics diff --git a/Tests/SystemTests/FileOperationsTest.swift b/Tests/SystemTests/FileOperationsTest.swift index ee82128..be5a67d 100644 --- a/Tests/SystemTests/FileOperationsTest.swift +++ b/Tests/SystemTests/FileOperationsTest.swift @@ -137,7 +137,7 @@ final class FileOperationsTest: XCTestCase { // Ad-hoc test touching a file system. do { // TODO: Test this against a virtual in-memory file system - try withTemporaryPath(basename: "testAdhocOpen") { path in + try withTemporaryFilePath(basename: "testAdhocOpen") { path in let fd = try FileDescriptor.open(path.appending("b.txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite) try fd.closeAfter { try fd.writeAll("abc".utf8) @@ -186,7 +186,7 @@ final class FileOperationsTest: XCTestCase { } func testResizeFile() throws { - try withTemporaryPath(basename: "testResizeFile") { path in + try withTemporaryFilePath(basename: "testResizeFile") { path in let fd = try FileDescriptor.open(path.appending("\(UUID().uuidString).txt"), .readWrite, options: [.create, .truncate], permissions: .ownerReadWrite) try fd.closeAfter { // File should be empty initially. diff --git a/Tests/SystemTests/FileOperationsTestWindows.swift b/Tests/SystemTests/FileOperationsTestWindows.swift new file mode 100644 index 0000000..35df731 --- /dev/null +++ b/Tests/SystemTests/FileOperationsTestWindows.swift @@ -0,0 +1,241 @@ +/* + This source file is part of the Swift System open source project + + Copyright (c) 2024 Apple Inc. and the Swift System project authors + Licensed under Apache License v2.0 with Runtime Library Exception + + See https://swift.org/LICENSE.txt for license information +*/ + +import XCTest + +#if os(Windows) + +#if SYSTEM_PACKAGE +import SystemPackage +#else +import System +#endif + +import WinSDK + +@available(iOS 8, *) +final class FileOperationsTestWindows: XCTestCase { + private let r = ACCESS_MASK( + FILE_READ_ATTRIBUTES + | FILE_READ_DATA + | FILE_READ_EA + | STANDARD_RIGHTS_READ + | SYNCHRONIZE + ) + private let w = ACCESS_MASK( + FILE_APPEND_DATA + | FILE_WRITE_ATTRIBUTES + | FILE_WRITE_DATA + | FILE_WRITE_EA + | STANDARD_RIGHTS_WRITE + | SYNCHRONIZE + ) + private let x = ACCESS_MASK( + FILE_EXECUTE + | FILE_READ_ATTRIBUTES + | STANDARD_RIGHTS_EXECUTE + | SYNCHRONIZE + ) + + private struct Test { + var permissions: CModeT + var ownerAccess: ACCESS_MASK + var groupAccess: ACCESS_MASK + var otherAccess: ACCESS_MASK + + init(_ permissions: CModeT, + _ ownerAccess: ACCESS_MASK, + _ groupAccess: ACCESS_MASK, + _ otherAccess: ACCESS_MASK) { + self.permissions = permissions + self.ownerAccess = ownerAccess + self.groupAccess = groupAccess + self.otherAccess = otherAccess + } + } + + /// Retrieve the owner, group and other access masks for a given file. + /// + /// - Parameters: + /// - path: The path to the file to inspect + /// - Returns: A tuple of ACCESS_MASK values. + func getAccessMasks( + path: FilePath + ) -> (ACCESS_MASK, ACCESS_MASK, ACCESS_MASK) { + var SIDAuthWorld = SID_IDENTIFIER_AUTHORITY(Value: (0, 0, 0, 0, 0, 1)) + var psidEveryone: PSID? = nil + + XCTAssert(AllocateAndInitializeSid(&SIDAuthWorld, 1, + DWORD(SECURITY_WORLD_RID), + 0, 0, 0, 0, 0, 0, 0, + &psidEveryone)) + defer { + FreeSid(psidEveryone) + } + + var everyone = TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_GROUP, + ptstrName: + psidEveryone!.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + + return path.withPlatformString { objectName in + var psidOwner: PSID? = nil + var psidGroup: PSID? = nil + var pDacl: PACL? = nil + var pSD: PSECURITY_DESCRIPTOR? = nil + + XCTAssertEqual(GetNamedSecurityInfoW( + objectName, + SE_FILE_OBJECT, + SECURITY_INFORMATION( + DACL_SECURITY_INFORMATION + | GROUP_SECURITY_INFORMATION + | OWNER_SECURITY_INFORMATION + ), + &psidOwner, + &psidGroup, + &pDacl, + nil, + &pSD), DWORD(ERROR_SUCCESS)) + defer { + LocalFree(pSD) + } + + var owner = TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_USER, + ptstrName: + psidOwner!.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + var group = TRUSTEE_W( + pMultipleTrustee: nil, + MultipleTrusteeOperation: NO_MULTIPLE_TRUSTEE, + TrusteeForm: TRUSTEE_IS_SID, + TrusteeType: TRUSTEE_IS_GROUP, + ptstrName: + psidGroup!.assumingMemoryBound(to: CInterop.PlatformChar.self) + ) + + var ownerAccess = ACCESS_MASK(0) + var groupAccess = ACCESS_MASK(0) + var otherAccess = ACCESS_MASK(0) + + XCTAssertEqual(GetEffectiveRightsFromAclW( + pDacl, + &owner, + &ownerAccess), DWORD(ERROR_SUCCESS)) + XCTAssertEqual(GetEffectiveRightsFromAclW( + pDacl, + &group, + &groupAccess), DWORD(ERROR_SUCCESS)) + XCTAssertEqual(GetEffectiveRightsFromAclW( + pDacl, + &everyone, + &otherAccess), DWORD(ERROR_SUCCESS)) + + return (ownerAccess, groupAccess, otherAccess) + } + } + + private func runTests(_ tests: [Test], at path: FilePath) throws { + for test in tests { + let octal = String(test.permissions, radix: 8) + let testPath = path.appending("test-\(octal).txt") + let fd = try FileDescriptor.open( + testPath, + .readWrite, + options: [.create, .truncate], + permissions: FilePermissions(rawValue: test.permissions) + ) + _ = try fd.closeAfter { + try fd.writeAll("Hello World".utf8) + } + + let (ownerAccess, groupAccess, otherAccess) + = getAccessMasks(path: testPath) + + XCTAssertEqual(ownerAccess, test.ownerAccess) + XCTAssertEqual(groupAccess, test.groupAccess) + XCTAssertEqual(otherAccess, test.otherAccess) + } + } + + /// Test that the umask works properly + func testUmask() throws { + // Default mask should be 0o022 + XCTAssertEqual(FilePermissions.creationMask, [.groupWrite, .otherWrite]) + + try withTemporaryFilePath(basename: "testUmask") { path in + let tests = [ + Test(0o000, 0, 0, 0), + Test(0o700, r|w|x, 0, 0), + Test(0o770, r|w|x, r|x, 0), + Test(0o777, r|w|x, r|x, r|x) + ] + + try runTests(tests, at: path) + } + + try FilePermissions.withCreationMask([.groupWrite, .groupExecute, + .otherWrite, .otherExecute]) { + try withTemporaryFilePath(basename: "testUmask") { path in + let tests = [ + Test(0o000, 0, 0, 0), + Test(0o700, r|w|x, 0, 0), + Test(0o770, r|w|x, r, 0), + Test(0o777, r|w|x, r, r) + ] + + try runTests(tests, at: path) + } + } + } + + /// Test that setting permissions on a file works as expected + func testPermissions() throws { + try FilePermissions.withCreationMask([]) { + try withTemporaryFilePath(basename: "testPermissions") { path in + let tests = [ + Test(0o000, 0, 0, 0), + + Test(0o400, r, 0, 0), + Test(0o200, w, 0, 0), + Test(0o100, x, 0, 0), + Test(0o040, 0, r, 0), + Test(0o020, 0, w, 0), + Test(0o010, 0, x, 0), + Test(0o004, 0, 0, r), + Test(0o002, 0, 0, w), + Test(0o001, 0, 0, x), + + Test(0o700, r|w|x, 0, 0), + Test(0o770, r|w|x, r|w|x, 0), + Test(0o777, r|w|x, r|w|x, r|w|x), + + Test(0o755, r|w|x, r|x, r|x), + Test(0o644, r|w, r, r), + + Test(0o007, 0, 0, r|w|x), + Test(0o070, 0, r|w|x, 0), + Test(0o077, 0, r|w|x, r|w|x), + ] + + try runTests(tests, at: path) + } + } + } +} + +#endif // os(Windows) diff --git a/Tests/SystemTests/FilePathTests/FilePathTempTest.swift b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift index b2b1fa2..dc8597b 100644 --- a/Tests/SystemTests/FilePathTests/FilePathTempTest.swift +++ b/Tests/SystemTests/FilePathTests/FilePathTempTest.swift @@ -18,7 +18,7 @@ import System final class TemporaryPathTest: XCTestCase { #if SYSTEM_PACKAGE_DARWIN func testNotInSlashTmp() throws { - try withTemporaryPath(basename: "NotInSlashTmp") { path in + try withTemporaryFilePath(basename: "NotInSlashTmp") { path in // We shouldn't be using "/tmp" on Darwin XCTAssertNotEqual(path.components.first!, "tmp") } @@ -26,10 +26,10 @@ final class TemporaryPathTest: XCTestCase { #endif func testUnique() throws { - try withTemporaryPath(basename: "test") { path in + try withTemporaryFilePath(basename: "test") { path in let strPath = String(decoding: path) XCTAssert(strPath.contains("test")) - try withTemporaryPath(basename: "test") { path2 in + try withTemporaryFilePath(basename: "test") { path2 in let strPath2 = String(decoding: path2) XCTAssertNotEqual(strPath, strPath2) } @@ -39,7 +39,7 @@ final class TemporaryPathTest: XCTestCase { func testCleanup() throws { var thePath: FilePath? = nil - try withTemporaryPath(basename: "test") { path in + try withTemporaryFilePath(basename: "test") { path in thePath = path.appending("foo.txt") let fd = try FileDescriptor.open(thePath!, .readWrite, options: [.create, .truncate],