11 Commits
Author SHA1 Message Date
Mohammed HassanandCory Benfield 02d6d9ada2 Create temporary directories with owner-only permissions (#3771)
Create temporary directories with owner-only permissions.

### Motivation:

`FileSystem.createTemporaryDirectory(template:)` (and
`withTemporaryDirectory`, which uses it) creates the directory with
`FilePermissions.defaultsForDirectory`, i.e. 0755. When the template
points into a shared directory such as `/tmp`, other local users can
list the temporary directory and read anything written into it with the
default 0644 file permissions. `mkdtemp(3)`, Go's `os.MkdirTemp` and
Python's `tempfile.mkdtemp` all use 0700 for this reason.

Repro with a umask of 022:

```swift
let dir = try await FileSystem.shared.createTemporaryDirectory(template: "/tmp/nio-repro-XXXXXX")
try await FileSystem.shared.withFileHandle(forWritingAt: "\(dir)/secret", options: .newFile(replaceExisting: false)) { _ in }
// before: dir is drwxr-xr-x, secret is -rw-r--r--, readable by every local user
// after:  dir is drwx------
```

### Modifications:

- Pass `.ownerReadWriteExecute` when `_createTemporaryDirectory` creates
the directory, in both `NIOFS` and `_NIOFileSystem`. Intermediary
directories created from the template get the same permissions, since
they are created by the same `_createDirectory` call.
- Document the permissions on `createTemporaryDirectory(template:)`.
- Add `testCreateTemporaryDirectoryIsOnlyAccessibleByOwner`.

### Result:

Temporary directories are only accessible by their owner.

I verified the before/after modes for both modules with a small
executable against this branch on macOS (`swift build` is clean). I
couldn't run the XCTest target locally because this machine only has the
Command Line Tools.

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-11-03 17:44:08 +00:00
Jake PetroulesandGeorge Barnett b07752c676 [Windows] Skip unsupported/flaky tests and run the Windows unit tests in CI (#3680)
### Motivation:

All of the test targets now compile on Windows (#3663, #3665), but
`swift test` doesn't yet pass: a number of tests exercise functionality
that isn't supported or isn't yet functional on Windows, some crash or
hang, and a few are flaky on the WSAPoll-based selector. Before the
Windows unit tests can run in CI, those tests need to be skipped (with
reasons) so a full `swift test` exits cleanly.

### Modifications:

Skip the tests that don't pass on Windows, using `XCTSkip` / Swift
Testing's `.disabled` / a gated `setUp` where a fixture itself traps,
each with a reason. Broadly:

- **Unsupported transports/APIs:** Unix domain sockets, datagram/UDP
channels, pipe channels, raw sockets, vsock, pre-connected sockets, and
`FileRegion` sends.
- **Whole suites** for subsystems that aren't functional on Windows yet,
including the **NIOFileSystem family** (`NIOFSTests`,
`NIOFSIntegrationTests`, `NIOFSFoundationCompatTests`) whose Windows
syscall shims are still stubbed, plus `EchoServerClientTest`,
`ChannelTests`, `DatagramChannelTests`, `StreamChannelTest`,
`FileRegionTest`, `PipeChannelTest`, `RawSocketBootstrapTests`,
`ThreadTest`, and `SocketOptionProviderTest`.
- **Real crashes surfaced by a full run:** `System.enumerateDevices()`
(mis-sized `GetAdaptersAddresses` buffer), the WSAPoll selector trapping
on an invalid fd and on schedule-after-shutdown, and a connection-reset
promise leak.
- **Flaky, timing-sensitive tests:** the event-loop tick-count metrics
tests (the WSAPoll selector wakes far more often than epoll/kqueue).

Then enable the Windows 6.3 + nightly jobs in the reusable unit-tests
workflow (which runs `swift test`) in both the PR and push workflows,
and drop the separate build-only Windows job (which only ran `swift
build --build-tests`).

Windows uses the default `swift test` arguments rather than the Linux
`-Xswiftc -warnings-as-errors` override, because a `#warning` in the
(skipped) stream-channel tests would otherwise fail the build.

All skips are Windows-only; there is no behaviour change on other
platforms.

### Result:

`swift test` passes on Windows, and the Windows unit tests run in CI.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2026-07-29 09:41:53 +01:00
Gabriel Secula 3263350c88 Drop unused SystemPackage import from FileSystemTests (#3623)
Drop unused SystemPackage import from FileSystemTests

### Motivation:

swift-system 1.7.0 exposes a new type named `FileType`, which is
ambiguous with `NIOFS.FileType` when both modules are imported in the
same file. This causes a compile-time error when building
`FileSystemTests.swift` in the `NIOFSIntegrationTests` target.

Fixes #3622.

### Modifications:

Drop the unused `SystemPackage` import in `FileSystemTests.swift`.

### Result:

`NIOFSIntegrationTests` builds against swift-system 1.7.0 and later.
2026-06-13 02:25:51 +00:00
David SternandDavid Stern c077074e9f Allow concurrent createDirectory calls with shared ancestor paths (#3598)
Allow concurrent calls of `_createDirectory()` for file paths with
shared ancestors.

### Motivation:

The current implementation of
`_createDirectory(withIntermediateDirectories: true)` does not catch and
continue during execution when the intermediate directory path it is
trying to create already exists.

The current loop looks like this: 

```swift
 // Successfully made a directory, construct its children.
        while let subdirectory = droppedComponents.popLast() {
            path.append(subdirectory)
            switch Syscall.mkdir(at: path, permissions: permissions) {
            case .success:
                continue
            case let .failure(errno):
                return .failure(.mkdir(errno: errno, path: path, location: .here()))
            }
        }
```
If we are concurrently trying to create directories `/foo/bar/dir1` and
`foo/bar/dir2`, we can fail with an error like `directory /foo already
exists` because one of the two task's `mkdir` syscall on line 928
errored with a `fileExists` error.
 
### Modifications:

The code adds the same logic already present on lines 894-907 of
`FileSystem.swift` to the failure case while iterating over the
subdirectory paths:

If the syscall errors because the directory already exists, (but didn't
exist during the loop on lines 886-923), we can safely continue. Another
task must have beaten our task to creating the directory, but that is
ok.

### Result:

Without this change, it would be difficult to actually call the
`FileSystem.createDirectory(withIntermediateDirectories: true)` function
in concurrent tasks, because if you were creating directories with
common ancestors, at least one of the 2 tasks would error due to the
race condition on directory creation. With this change, the
`createDirectory()` function can now be called concurrently without this
race issue potentially causing an error. I added the change to both the
`NIOFS` and `_NIOFileSystem` directories since they seem to be copies of
each other.

Co-authored-by: David Stern <d_stern@apple.com>
2026-05-15 08:11:37 +00:00
Fabian Fett 08abc3a02c Fix flaky testCopyFileReplacingExistingFileSucceeds (#3554)
### Motivation
`testCopyFileReplacingExistingFileSucceeds` (and
`testCopySymlinkReplacingExistingSymlinkSucceeds`) verify that no .tmp-
prefixed files are left behind after a `copyItem(replaceExisting: true)`
call on Linux. However, both tests create their files in the shared
system temp directory (e.g. /tmp) and then scan that entire directory
for .tmp- files. When other tests run in parallel, their in-flight
`copyItem(replaceExisting: true)` operations leave transient .tmp- files
in the same directory, causing spurious failures.

### Changes

- Both tests now create a dedicated subdirectory for their files, so the
temp file scan only sees files belonging to that specific test.
- Cleanup is handled via `addTeardownBlock` to ensure the subdirectory
is removed even if the test fails early.

### Results

The temp file assertions are no longer affected by concurrent test
activity or other processes writing to the shared temp directory,
eliminating the flakiness.
2026-03-18 15:25:06 +00:00
Rick Newton-Rogers abe12cf13b Apple platforms CI issues (#3519)
Apple platform simulator CI failures

### Motivation

* Several tests failed when testing against simulators for Apple
platforms (iOS, tvOS, watchOS, visionOS)

### Modifications

* Added `@available(macOS 13, iOS 16, tvOS 16, watchOS 9, *)` to each
`@Test` method in `NIOThreadPoolTest`, `EventLoopFutureTest`, and
`NIOTransportAccessibleChannelCoreTests` to match the availability of
the APIs they use (`timeLimit` and `withUnsafeTransportIfAvailable`).
* Removed `.timeLimit(.minutes(1))` from the `@Suite` declarations on
`NIOThreadPoolTest` and `EventLoopFutureTest` - the `@Suite` macro
cannot be used with `@available`, so `timeLimit` cannot be used.
* Skip `testHomeDirectoryFromPasswd` on simulator targets via
`#if targetEnvironment(simulator)` / `XCTSkip`, since simulators retu>
success but nil information when invoking `getpwuid_r`.

### Result

* Apple simulator platform builds and test runs no longer fail due to
these issues. Some infrastructure issues remain to be resolved
separately.
2026-02-26 13:03:18 +00:00
Stepan UlyaninandGeorge Barnett be8fdc13c0 Allow to copy files and symlinks while overwriting the destination (#3508)
Adds capability to NIOFS to copy regular files and symlink, allowing to
overwrite the destination.

### Motivation:

Per https://github.com/apple/swift-nio/issues/3403 and
https://github.com/apple/swift-nio/pull/3470 we want to add
`replaceExisting: bool` to `FileSystem.copyItem`.

### Modifications:

1. Adds `replaceExisting: bool` parameter to
`FileSystemProtocol.copyItem`.
2. Adds `replaceExisting: bool` parameter to `FileSystem.copyItem` and
implementation for regular files and symbolic links.
3. Adds tests.

---------

Co-authored-by: George Barnett <gbarnett@apple.com>
2026-02-18 08:57:33 +00:00
Karan LokchandaniandCory Benfield 608e511d7a Add homeDirectory accessor to FileSystem (#3471)
Add homeDirectory accessor to FileSystem

### Motivation:
Addresses #3381 by adding a `homeDirectory` property to FileSystem,
equivalent to `FileManager.default.homeDirectoryForCurrentUser`.

### Modifications:
- Added `homeDirectory` property to `FileSystemProtocol` and implemented
in `FileSystem`
- Implementation checks `HOME` environment variable first, falls back to
`USERPROFILE` on Windows, or uses `getpwuid_r(3)` on POSIX systems
- Added system call wrappers (`system_getuid`, `libc_getpwuid_r`) with
proper platform guards
- Added `FileSystemError.getpwuid_r()` error helper

### Result:
Users can now access the home directory via `FileSystem.homeDirectory`,
returning a `FilePath` asynchronously. Follows the same pattern as
`currentWorkingDirectory` and `temporaryDirectory`.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2026-01-12 15:10:25 +00:00
George Barnett d963335ba0 Fail on early errors in parallel copy (#3435)
Motivation:

'copyItem' can be used to copy files/directories from a source to a
destination address and fails if the destination already exists. The
parallel version of it can wedge if a directory is being copied and the
directory can't be created at the destination path (for example, if a
file already exists at the destination).

The parallel copy works by feeding tasks (e.g. "copy this item from here
to there") into an async sequence and processing each task in a separate
child task within a task group. When copying directories a new directory
is created at the destination path and then each file within the source
directory is emitted as a separate item to process. Another item is sent
on the async sequence to indicate when the source directory is finished
with which may result in finishing the async sequence.

However, if creating the destination directory fails then that event
isn't sent. This results in the calling code never terminating the async
sequence and causes 'copyItem' to wedge.

Modifications:

- Use non-idempotent directory creation (copy item should fail if the
destination already exists, this was a regression introduced in
7124f096).
- Check whether to continue when a dir can't be created but always emit
the end of dir event
- If terminating when the task group hasn't reached its width limit then
check child tasks for errors

Result:

Parallel copy doesn't wedge
2025-11-05 08:47:05 +00:00
Hamza Hassanain 7124f0963a feat(NIOFileSystem): Add idempotent directory creation behavior (#3404) (#3410)
The createDirectory function will succeed without error if the target
directory already exists.

###  Motivation

This change addresses issue #3404. Currently,
`fileSystem.createDirectory` fails if the target directory already
exists, forcing users to write boilerplate try/catch blocks to handle
this common and expected case.

The goal is to make this function's behavior idempotent.

### Modifications

To achieve this, I've made the following changes:

**(Implementation)** A new private helper function,
`_handleCreateDirectoryFileExists`, was introduced. This function is
responsible for:

1. Performing a `stat` call on the path that failed.
2. Checking if the existing item is a directory (`S_IFDIR`).
3. Returning a success result if it's a directory, or re-throwing the
original `.fileExists` error if it's a file or another type of entity.

**(Logic)** The core `_createDirectory` function was updated to call
this new helper function whenever `Syscall.mkdir` fails with an `EEXIST`
(`.fileExists`) error. This check is applied in both internal loops to
correctly handle cases where either an intermediate directory or the
final target directory already exists.

### Result
With this change, users can now call the function
`fileSystem.createDirectory` and the operation will succeed even if the
directory is already present, leading to cleaner and more predictable
code.
2025-10-20 15:49:26 +01:00
George Barnett a18bddb0ac Add back NIOFileSystem (#3380)
Motivation:

We accidentally removed the 'NIOFileSystem' module from the
'_NIOFileSystem' product in the last release.

Modifications:

- Rename 'NIOFileSystem' and 'NIOFileSystemFoundationCompat' to 'NIOFS'
  and 'NIOFSFoundationCompat'
- Add back 'NIOFileSystem' which re-exports '_NIOFileSystem' (there was
  no publicly available 'NIOFileSystemFoundationCompat' module to
  remove, only '_NIOFileSystemFoundationCompat').

Result:

Fewer breaks
2025-09-23 17:29:01 +01:00