Commit Graph
17 Commits
Author SHA1 Message Date
scottmarchant 5bf0267df4 build: Elide NIOPosix for WASI platforms only (#3485)
### Motivation:

Packages that consume NIOPosix should be able to compile to WASI
platforms without special configurations. This change elides the
NIOPosix source from WASI platforms to simplify configuration.

Without this change:

```swift
dependencies: [
    // Without this PR, downstream packages must maintain exhaustive platform list to exclude `.wasi`:
    .product(
        name: "NIOPosix",
        package: "swift-nio",
        condition: .when(platforms: [
            .macOS,
            .macCatalyst,
            .iOS,
            .tvOS,
            .watchOS,
            .visionOS,
            .driverKit,
            .linux,
            .windows,
            .android,
            .openbsd,
            // .wasi // <-- Need to exclude this, because there is no exclusion list api for SPM conditionals
        ])
    ),
]
```

With this change:

```swift
dependencies: [
    // Without this PR, downstream packages can consume NIOPosix simply:
    .product(name: "NIOPosix", package: "swift-nio"),
]
```

### Modifications:

- Add compiler directives (`#if !os(WASI)`) to all source files in
NIOPosix

### Result:

Downstream packages can compile to wasm without manually excluding the
NIOPosix dependency.

### Testing performed

- Verified `swift build --swift-sdk wasm32-unknown-wasip1 --target
NIOPosix` compiles, which demonstrates proper elision of source files in
NIOPosix that aren't wasm-ready.
- Confirmed GitHub [checks
pass](https://github.com/PassiveLogic/swift-nio/actions/runs/21151341738).
2026-01-23 16:39:32 +00:00
3405691582andRick Newton-Rogers 2bc71a6aff Partial OpenBSD support. (#3394)
### Motivation:

Additional partial platform support.

### Modifications: 

* Create a new CNIOBSD module for OpenBSD, for general cleanliness, and
make use of it throughout. Some of the changes are borrowed directly
from CNIOLinux; some may technically be unnecessary; I am erring
somewhat on expediency to functionality.

* Since `malloc_size` is unavailable on OpenBSD, and some of the helpers
make use of ManagedBufferPointer which makes use of it, mark some of
this as unavailable as well.

* Usual pthread optional typing changes, since pthread types are
pointers on this platform.

* Add conditionals to exclude other functionality not available here,
like IP_RECVPKTINFO or IP_PKTINFO.

* d_ino is a backwards-compatibility macro valued token for dirent, so
instead, just expand with a conditional.

* Use kqueue on OpenBSD. This necessitates adding some conditionals for
type and feature compatibility.

* The vsock API is unavailable on OpenBSD.

### Result:

Tested the NIOTCPEchoClient and NIOTCPEchoServer appears to work and
that swift-nio-ssh (hopefully wlog) builds with a local repository with
these changes.

Because NIOFS/_NIOFileSystem depend on some non-portable components,
such as extended attributes, sendfile, non-portable linkat flags, and
renameat2, this is only just partial OpenBSD support, which means that
`swift build` on the full swift-nio project won't build cleanly, but at
least the portable parts can be used to build servers and clients. This
commit will mark the linked bug as fixed; I will open a new bug for file
system support.

Fixes #3383.

---------

Co-authored-by: Rick Newton-Rogers <rnro@apple.com>
2025-11-26 09:07:02 +00:00
Rick Newton-Rogers 60089114f8 Enable MemberImportVisibility check - attempt 2 (#3029)
Enable MemberImportVisibility check on all targets. Use a standard
string header and footer to bracket the new block for ease of updating
in the future with scripts.

See https://github.com/apple/swift-nio/pull/3021
2024-12-17 11:21:02 +00:00
Johannes Weiss 70dfce82b0 give common blocking functions a clear name (#2984)
### Motivation:

In many situations, for example continuous profiling with sampling
profilers, it's important to distinguish between on- and off-CPU work.
That's most easily done if there are clear function names/prefixes to
grep for that are common places to just wait (off-CPU) and do no real
work. In SwiftNIO those are chiefly three places:
1. The `EventLoops` waiting for work
2. `The NIOThreadPool` threads waiting for work
3. `EventLoopFuture.wait()`

This patch makes sure that each of those will have a function with
prefix `_blockingWaitFor` in the function name which is easily
greppable.

### Modifications:

- Create some non-inlinable functions with `_blockingWaitFor...` that
just wait for `...`.

### Result:

SwiftNIO makes operational excellence easier and your SRE team more
happy.
2024-11-23 22:47:34 +00:00
Rick Newton-Rogers adfd61adc5 Use Swift 6.0 docs pipeline (#2966)
### Motivation:

Documentation checking catches more issues in Swift 6.0.

### Modifications:

Adopt the Swift 6.0 image and fix the errors.

### Result:

More accurate docs.
2024-11-07 13:03:47 +00:00
Franz Busch c9756e1083 Adopt swift-format (#2794)
* Apply formatting

* Apply no block comments rule

* Apply OmitExplicitReturns

* Apple OnlyOneTrailingClosureArgument

* Apply NoAssignmentInExpressions

* Fix up DontRepeatTypeInStaticProperties lint errors

* Apply `OrderedImports`

* Apply `ReplaceForEachWithForLoop`

* format file

* Enable the formatting pipeline

* Adopt `AmbiguousTrailingClosureOverload`

* Fix license header

* Fix format check

* Fix `EndOfLineComment`

* Fix CI

* Adapt CI script to check if changes when running formatting

* Separate lint and format into to steps

* Fix format

* Adopt `UseEarlyExits`

* Revert "Adopt `UseEarlyExits`"

This reverts commit d1ac5bbe12.
2024-07-19 11:48:17 +02:00
Cory BenfieldandFranz Busch 30595ad289 Don't lose or delay writes before channelActive (#2486)
* Don't lose or delay writes before channelActive

Motivation:

In rare circumstances, some users have reported hangs, delays, or
lost writes when writing network proxies. These proxies have
typically been derived from our TLSify example:
https://github.com/apple/swift-nio-examples/tree/main/TLSify

This proxy makes its outbound connections in handlerAdded.
Generally this works without issue, as the connection takes
long enough to set up that channelActive fires before the
outbound connection has been made.

However, in some rare circumstances it is possible to both make an
outbound connection, have it succeed, _and_ read from the network
on that connection before NIO activates the inbound channel. This
would cause users to lose writes.

This violates a cardinal NIO rule: writes should never be lost.
If it is practical for us to delay them and apply them later, we
should. This patch addresses several holes in this area to correctly
handle these outbound writes.

The first hole is that we would fail writes if the Channel wasn't
yet active. This constraint was unnecessary: it was added in a
refactor to use an internal state machine, and while we had a test
that this happened, it didn't protect us from anything. We can
safely buffer a write at this point: and indeed, we _do_ buffer
flushes at this point. So the check was unneeded.

The second hole was that, even if we buffered the writes, we
frequently wouldn't unbuffer them again until a flush happened
after channelActive. This didn't happen on _every_ path: in the
rare case that connect() succeeded immediately, we would flush
the writes. But in all other cases, including listening
connections, we needed _another_ flush to happen to get the
writes out.

This fix patches up both issues and reconciles the flows. Now
we _always_ try to push out flushed writes when we activate the
Channel, just as we always try to read.

Modifications:

- Remove a check that failed writes if we weren't active.
- Remove a test that validated that we did that.
- Attempt to emit flushed writes on channelActive.
- Make sure we mark ourselves writable if we couldn't write
  it all.
- Make `BaseSocket.getOption` non-final so we can hook it
  in the SAL.
- Make `AcceptHandler` non-private so we can use it in tests.
- Extend the SAL to support `getOption`
- Write several SAL tests to ensure we manage our writes.

Result:

No lost writes.

* Code review feedback

---------

Co-authored-by: Franz Busch <f.busch@apple.com>
2023-07-31 04:13:33 -07:00
Si Beaumont 1de708f023 Skip TCP_NODELAY on sockets that NIO doesn't explicitly support (#2476)
* Skip TCP_NODELAY on sockets that NIO doesn't explicitly support

Signed-off-by: Si Beaumont <beaumont@apple.com>

* fixup: Skip IPv6 test if host does not have IPv6

Signed-off-by: Si Beaumont <beaumont@apple.com>

* fixup: Rename test helper function

Signed-off-by: Si Beaumont <beaumont@apple.com>

* fixup: Remove test for unix domain socket

Signed-off-by: Si Beaumont <beaumont@apple.com>

---------

Signed-off-by: Si Beaumont <beaumont@apple.com>
2023-07-21 10:25:05 +01:00
Si Beaumont 83f49cb335 Throw SocketAddressError (cf. fatalError) in SocketAddress.convert for unknown address family (#2477)
* Throw SocketAddressError (cf. fatalError) in SocketAddress.convert for unknown address family

Signed-off-by: Si Beaumont <beaumont@apple.com>

* fixup: Use AF_UNSPEC, not AF_SYSTEM, in tests

Signed-off-by: Si Beaumont <beaumont@apple.com>

* fixup: Use try! instead of catch and fatalError

Signed-off-by: Si Beaumont <beaumont@apple.com>

* fixup: Move address conversion before side effects

Signed-off-by: Si Beaumont <beaumont@apple.com>

* fixup: Propagate error from SocketAddress.convert in DGVRM

Signed-off-by: Si Beaumont <beaumont@apple.com>

* fixup: Add __test_only shim for Swift 5.6

Signed-off-by: Si Beaumont <beaumont@apple.com>

---------

Signed-off-by: Si Beaumont <beaumont@apple.com>
2023-07-20 12:13:07 +01:00
Andrew TrickandCory Benfield e63326aa50 Fix an upcoming compiler warning on implicit raw pointer casts. (#2377)
setOption forms a raw pointer to a generic argument. The compiler will
warn on this as of:

[proposal] Constrain implicit raw pointer conversion... #1963
https://github.com/apple/swift-evolution/pull/1963

/Sources/NIOPosix/BaseSocket.swift:286:31: warning: forming
'UnsafeRawPointer' to a variable of type 'T'; this is likely incorrect
because 'T' may contain an object reference.

                option_value: &val,
                              ^

Ideally, this would be fixed by adding a BitwiseCopyable constraint to
the 'value' parameter of 'BaseSocker.setOption'. That would not only
eliminate the warning, but would make the API safer. But
BitwiseCopyable isn't quite ready for public use. In the meantime,
this is a reasonable workaround.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2023-02-28 00:23:36 -08:00
David Nadoba 0b4edd8329 Add NIOBSDSocket.ProtocolSubtype (#2317)
* RawSocket prototype

* Conform `ProtocolSubtype` to `Hashable`

* Add public `NIOIPProtocol` type

Make `ProtocolSubtype` internal

* Subset of IANA protocols with an RFC

* Add `CustomStringConvertible` to `NIOIPProtocol`

* Add `init(_ rawValue: Int)`

* Rename `NIOBSDSocket.ProtocolSubtype.ip` to `.default`

* Add `NIOBSDSocket.ProtocolSubtype.mptcp`

and remove `NIOBSDSocket.mptcpProtocolSubtype`
2022-11-22 06:01:52 -08:00
Cory Benfield 558e4f2fb8 MPTCP support on Linux (#2308)
Motivation

MPTCP provides multipath capability for TCP connections. This
allows TCP connections to consume multiple independent network
paths, providing devices with a number of capabilities to
improve throughput, latency, or reliability.

MPTCP is not totally transparent, and requires servers to support
the functionality as well as clients. To that end, we should expose
some MPTCP capability.

Importantly, MPTCP uses a number of new socket flags and options.
To enable us to support this when it is available but gracefully fail
when it is not, we've hardcoded a number of Linux kernel constants
instead of relying on libc to expose them. This is safe to do on Linux
because its syscall layer is ABI stable.

Modifications

- Add ClientBootstrap and ServerBootstrap flags for MPTCP
- Plumb MPTCP through the stack
- Add new socket options for MPTCP

Result

MPTCP is supported on Linux
2022-11-09 11:02:45 +00:00
Saleem Abdulrasool 65c3f576b1 NIOPosix: reduce imports for Windows (#2170)
Reduce unnecessary noise in the files after previous refactoring
shuffled the use of the imported interfaces.  We can centralise most of
the imports and internal typealiases which avoids cluttering the shared
interfaces with compatibility handling for Windows.
2022-06-07 09:37:11 -07:00
Si Beaumont 124119f0bb BaseSocket: Remove dead code in BaseSocket.bind(to:) (#2086)
Signed-off-by: Si Beaumont <beaumont@apple.com>
2022-04-22 09:42:09 -07:00
Cory BenfieldandGuillaume Lessard b2195f7973 Rebind less load more (#2055)
* rebind less, load more.

* Rebind even less, load even more

* Remove the mutatings

Co-authored-by: Guillaume Lessard <guillaume.lessard@apple.com>
2022-03-07 03:20:16 -08:00
Cory Benfield 19403414ba Get unit tests running again on nightly builds. (#1961)
Motivation:

In February, @weissi noticed that the nightly builds of Swift could no
longer compile the unit tests. We disabled them at that time and
reported an upstream bug, https://bugs.swift.org/browse/SR-14268. This
is not an ideal situation, but the Swift core team has provided a
workaround we can use to re-enable the tests.

Modifications:

Provide free functions that wrap some specific extension methods that
are called in unit tests, and amend the call sites to use them.

Result:

We can re-enable the nightly tests.
2021-09-17 20:50:29 +01:00
Cory Benfield b05c6f2206 Move NIO to NIOPosix, make NIO a shell. (#1936)
Motivation:

The remaining NIO code really conceptually belongs in a module called
NIOPosix, and NIOCore should really be called NIO. We can't really do
that last step, but we can prepare by pushing the bulk of the remaining
code into a module called NIOPosix.

Modifications:

- Move NIO to NIOPosix
- Make NIO an umbrella module.

Result:

NIOPosix exists.
2021-08-16 16:50:40 +01:00