Motivation:
Instead of manual shifting / masking we can write the whole registration
ID code normally in Swift.
Modifications:
Refactored RegistrationID to use Swift instead of shifting / masking.
Result:
Nicer code.
Motivation:
Currently the selector implementation just discards all pending events from the kernel when a deregistration
has occurred during the event loop tick. This has been needed to not fail the test testWeDoNotDeliverEventsForPreviouslyClosedChannels.
A cleanup case has been around for a while at: https://github.com/apple/swift-nio/issues/381
And when discussing this in https://github.com/apple/swift-nio/pull/1788 (to solve https://github.com/apple/swift-nio/issues/1761)
we came to an agreement that the solution with tagging registrations on the backend would not suit only io_uring,
but also solve the issue robustly for kqueue and epoll.
Modification:
Added sequenceIdentifier to the Registration and add support for it throughout.
Mask in sequence identifier into user data in both kqueue and epoll.
In kqueue, we just store the sequence identifier in the udata field (to support 32-bit properly).
In epoll, where we know we have 64-bits, we mask it in together with fd.
Removed all references to the old workaround from #381.
Result:
- New solution that doesn't need to discard all events when deregistrations are done during the event loop tick.
- fixes#381
The `ignoreSIGPIPE` does nothing on Windows. However, add an overload
to differentiate between a socket and file descriptor as they may be
different. This is the case on Windows, where file descriptors are
32-bit but socket are 64-bit.
fixup! e51406c61972420c43734b1d089712bc408e097b
* NIO: implement `cleanupSocket(unixDomainSocketPath:)` for Windows
This adds an initial implementation for the UDS clean up path on
Windows. Unlike Unix, you cannot simply `stat` the destination to
determine if it is a UDS endpoint.
One must first create a file handle from the path. Assuming that we are
able to create that, we should verify that the file that we are dealing
with is a not a disk type as the subsequent checks will fail. Now, we
can use the file handle to query the information of the file. This will
allow us to determine if it is a reparse point. If not, it is
impossible for it to be a UDS as a UDS endpoint is a reparse point with
the tag IO_REPARSE_TAG_AF_UNIX. Once we know that we have a reparse
point, we must query the kernel for information about it via the
`DeviceIoControl` system call (perform an ioctl in Unix speak). The
returned buffer's tag will identify if we have a UDS.
For the next dance, we must now _close_ the handle as the handle being
left open will cause the subsequent `DeleteFileW` to fail due to there
being an open handle. Once we have cleaned up the file handle that we
created, we can safely attempt to remove the file via `DeleteFileW`.
This should hopefully be sufficiently robust from possible error
scenarios for the removal of a UDS endpoint.
* NIO: improve the UDS cleanup path on Windows
Instead of doing the complex close-handle dance, instead prefer
`SetFileInformationByHandle` which:
1. avoids a second UTF-8 -> UCS-2 conversion
2. avoids the need for the handle closing dance
3. avoids a third re-query of the handle
4. enables us to use "POSIX" deletion semantics (file is immediately
removed from the namespace but data streams are left intact)
This comes at the cost of being Windows 10 centric, which I find a
reasonable trade-off as Windows 7 has been EOL'ed by Microsoft, and more
importantly, Unix Domain Sockets are only available on Windows 10!
Thanks to @adierking for the reminder about SetFileInformationByHandle!
Motivation:
Cleanup some noise that came in with some previous Windows compat
patches.
Modifications:
- Move INVALID_SOCKET to NIOBSDSocket, and refer to it by a better name
there.
- Comment in an empty block to indicate that it's supposed to be empty.
Result:
Bit cleaner code.
* Cleanup unix socket pathname on server socket close or bind
* cleaner use of swift syntax
* using stat and unlink via syscal wrappers
* separate error type when UDS path is not a socket file
* track if socket needs cleanup to avoid extra syscall
* struct instead of enum for a single new error type
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Split out the internal implied BSD socket API code to allow alternative implementations of these interfaces on other platforms.
Modifications:
- Split the code apart.
- Provide POSIX and Windows implementations of the BSD socket API.
Result:
Should be easier to run NIO unmodified on Windows.
Motivation:
We know that on Darwin (eg. when the other end of a TCP connection reset
_really_ early on) F_SETNOSIGPIPE sometimes fails. We thought we could
handle it but we weren't able to handle everywhere.
Modifications:
- make us survive it everywhere
- tests
Result:
- Fewer crashes with ClientBootstrap.withConnectedSocket
Motivation:
The names of most of the BSD socket option values were brought over into
their NIO helper properties, with their namespace removed. This vastly
increases the risk of collision, particularly for things like TCP_INFO,
which just became .info.
Modifications:
- Added the prefixes back, e.g. `.info` is now `.tcp_info`.
- Renamed socket type `.dgram` to `.datagram`, as this is the nice clean
API and we should use nice clean names.
Result:
Better APIs
Motivation:
Newer Swift 5.3 snapshots have spotted more vars that could be lets.
Modifications:
Made two vars lets.
Result:
The word `let` appears more frequently; the word `var`, less so.
This finishes up the encapsulation that is required to ensure that we
are not leaking libc interfaces to clients but instead vend an
enumeration that they can use. The enumeration is open so although we
may not have the full interface enumerated, users will not be prevented
from using alternate values.
This adds a new enumeration which encapsulates the socket type values.
This enables ports to provide the same surface with a different name as
necessary.
* NIO: Add new `BSDSocket` namespace
This starts the split of the POSIX/Linux/Darwin/BSD interfaces and the
BSD Socket interfaces in order to support Windows. The constants on
Windows are not part of the C standard library and need to be explicitly
prefixed. Use the import by name to avoid the `#if` conditions on the
wrapped versions. This will allow us to cleanly cleave the dependency
on the underlying C library.
This change adds a `BSDSocket.OptionLevel` and `BSDSocket.Option` types
which allow us to get proper enumerations for these values and pipe them
throughout the NIO codebase.
* Apply suggestions from code review
Co-Authored-By: Cory Benfield <lukasa@apple.com>
A `FileDescriptor` is not necessarily selectable (e.g. Windows), and a
selectable is not necessarily a `FileDescriptor` (e.g. Windows).
This will allow a basic `Selector` on Windows which will use `WSASelect`
to select on sockets for some basic functionality even though
IOCompletionPorts are preferred.
The path was duplicated because the compiler was not previously able to
optimize with the constant value and would generate poor code. This has
now been addressed, so unify the blocking and non-blocking paths.
Co-authored-by: Cory Benfield <lukasa@apple.com>
This removes support for Unix Domain Sockets from NIO on Windows.
Although Windows 10.17063 introduced basic support for UDS, the support
is incomplete and has differences from the tradtional UDS sockets in
terms of behaviour. Excise the support initially to get NIO to build on
Windows.
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
Calling `function(otherFunction)` allocates, but
`function({ otherFunction($0) }` does not.
See: SR-12115 and SR-12116.
Modifications:
Avoid passing functions directly; pass them in new closures instead.
Result:
Fewer allocations.
## Motivation:
In SwiftNIO's codebase, most things were always testable just as well as user code is. With one big missing piece: We could never make the `Selector` do arbitrary things to the `Channel` implementations which lead to super expensive to (create, read, understand) integration tests like [`testWriteAndFlushFromReentrantFlushNowTriggeredOutOfWritabilityWhereOuterSaysAllWrittenAndInnerDoesNot `](https://github.com/apple/swift-nio/blob/5dc9083c6a78b10432b4b55b95704e61ca08f09d/Tests/NIOTests/StreamChannelsTest.swift#L468-L760).
## Modification
Add SAL, a 'syscall abstraction layer' which makes it possible to assert all syscalls that come through a `Socket` or the `Selector` by mocking them. It lets the NIO programmer play the kernel in these "SAL tests" which makes it possible to assert the exact syscalls (with their parameters) and decide the syscalls' returns.
## Result
Finally, we're able to write proper unit tests for scenarios where the `Channel` drove the `Selector` incorrectly.
Motivation:
There are use-cases for SwiftNIO where there are no actual sockets but
rather two pipe file descriptors - one for input, one for output.
There's no real reason why SwiftNIO shouldn't work for those.
Modifications:
Add a PipeChannel.
Result:
More use-cases for SwiftNIO.
Motivation:
Darwin does sometimes hand us back an (as of the docs) illegal error
code of EINVAL. So far, NIO has done the non-sensical thing of closing
the server socket as a result.
Modifications:
Just close the accepted socket, leave the server socket open, and fire
the error through the pipeline.
Result:
- fixes#1030
- better behaviour
Motivation:
Previously, we would just `F_SETFL, O_NONBLOCK` which would erase all
possibly pre-existing flags which isn't great.
Modifications:
First get the existing flags and then do `F_SETFL, existingFlags |
O_NONBLOCK`.
Result:
Possibly helps with #1030, definitely better style.
Motivation:
Swift naming guidelines mandate that factory methods start with `make`,
like `makeSomething`. We had a few that were `newSomething`.
Modifications:
make all factories start with make
Result:
more compliant to Swift naming rules
Motivation:
_ = expression() is ugly and in many cases unimportant. In fact we train
ourselves to overread it which makes special cases where you'd actually
expect a result to be used just look normal.
Modifications:
remove _ = from a lot of places. In many cases we already had a better
(and sometimes cheaper way) to not return a value but in some cases
(mostly `remove` functions) I added `@discardableResult`
Result:
NIO source code looks nicer
Motivation:
It's generally good style to explain why something needs to be force
unwrapped/tried if not obvious.
Modifications:
Add explanations to a bunch of places.
Result:
Code easier to understand.
Motivation:
WE should include the ipaddress in the description of SocketAddress if any way used as there may be no host at all.
Modifications:
- Always include ipaddress if possible.
- Add unit tests.
Result:
More useful description of the SocketAddress
Motivation:
Quite embarrasingly, we previously would only store one `ChannelOption`
per `ChannelOption` type. Most channel option types are distinct and
that's probably why it took so long to find this issue. Thanks
@pushkarnk for reporting. Unfortunately though, the most important
`ChannelOption` is `.socket` which crucially also holds a level and a
name. That means if you set two `ChannelOptions.socket` options with
distinct name/level, one would still override the other.
Example:
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEPORT), value: 1)
.serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)
would only actually set the latter.
Modifications:
- made all common `ChannelOption` types equatable (for 2.0 this will
be a protocol requirement)
- deprecated non-Equatable `ChannelOption` types
- zero out buffer before calling getsockopt as Linux doesn't do that
Result:
you can now set two distinct `ChannelOptions` for one type
Motivation:
Previously the code said that fcntl doesn't return anything but that's
just not true, it returns `CInt`.
Modifications:
Made `fcntl` return `CInt` and tested that.
Result:
more correct code and more tests
Motivation:
I came across a few typos and then went through the entire code base
fixing similar errors when I noticed a pattern.
Modifications:
No changes to the code, just to comments.
Result:
No changes.
Motivation:
@vlm hit an interesting situation which is very likely the sign of
another bug that we have yet to find:
During a close, @vlm hit an error in close which lead to a user callout
which then closed again.
The immediate fix is simple (this PR) is as always not to call out to
the user before reconciling our own state. But hitting this bug also
means that either a `socket.close` or a `selectableEventLoop.deregister`
failed as we only called out in those situations. That definitely hides
a condition that is hard to imagine without another bug that we still
need to find.
Modifications:
in `BaseSocketChannel.close0` follow rule 0 and don't call out before
reconciling state.
Result:
fewer crashes, less potential to hide other bugs.
Motivation:
We had a number of problems:
1. We wanted to lazily process input EOFs and connection resets only
when the user actually calls `read()`. On Linux however you cannot
unsubscribe from `EPOLLHUP` so that's not possible.
2. Lazily processing input EOFs/connection resets wastes kernel
resources and that could potentially lead to a DOS
3. The very low-level `Selector` interpreted the eventing mechanism's
events quite a lot so the `EventLoop`/`Channel` only ever saw
`readable` or `writable` without further information what exactly
happened.
4. We completely ignored `EPOLLHUP` until now which on Unix Domain
Socket close leads to a 100% CPU spin (issue #277)
Modifications:
- made the `Selector` interface richer, it now sends the following
events: `readable`, `writable`, `readEOF` (input EOF), `reset`
(connection reset or some error)
- process input EOFs and connection resets/errors eagerly
- change all tests which relied on using unconnected and unbound sockets
to user connected/bound ones as `epoll_wait` otherwise would keep
sending us a stream of `EPOLLHUP`s which would now lead to an eager
close
Result:
- most importantly: fix issue #277
- waste less kernel resources (by dealing with input EOFs/connection
resets eagerly)
- bring kqueue/epoll more in line
Motivation:
Reduce memory footprint of BaseSocket
Modifications:
- made isOpen a computed var from 'descriptor >= 0'
- BaseSocket init check precondition 'descriptor >= 0'
Result:
- isOpen no longer requires storage space
- close() sets descriptor to -1
- descriptor property changed from let to var
Motivation:
Reduce system calls on Linux required for configuring sockets as
nonblocking.
Modifications:
- expose accept4 as CNIOLinux_accept4
- add Linux internal enum for exposing Linux specific API
- wrap CNIOLinux_accept4 with Linux.accept4
- expose SOCK_NONBLOCK and SOCK_CLOEXEC on Linux
- add setNonBlocking parameter to BaseSocket.newSocket
- add setNonBlocking parameter to ServerSocket.accept
Result:
Servers and clients on Linux will use fewer system calls creating new sockets.
Motivation:
Reduce memory footprint of BaseSocket and FileHandle
Modifications:
- made isOpen a computed var from 'descriptor >= 0'
- add withSocketpair to TestUtils
- use real pipe and socketpair file descriptors for tests
- BaseSocket and FileHandle init check precondition 'descriptor >= 0'
Result:
- isOpen no longer requires storage space
- close() sets descriptor to -1
- descriptor property changed from let to var
- tests will need to use valid file descriptors
Motivation:
We can cleanup the code by removing return keywords in closures sometimes.
Modifications:
Remove return when possible.
Result:
Cleaner code.
Motivation:
Fix for issue #110, .description on IPv6 addresses
return a String with 0 codepoints in it, like so:
[IPv6]::1<NUL><NUL><NUL>....lots..
Modifications:
Use String(cString:) instead of decode, which doesn't
care about \0-cstr terminators.
Result:
Issue fixed, everything is awesome, everyone is happy.
Motivation:
When writing programs that use networks, particularly if you want to
perform multicast joins, it's extremely important to be able to query
network interfaces and get results.
Modifications:
Add support for querying interfaces using getifaddrs and wrap those query
results in a Swift class.
Result:
Users will be able to enumerate the interfaces on their machine.
Motivation:
FileHandle and BaseSocket should implement a common protocol as these are both "based" on file descriptors
Modifications:
- Add FileDescriptor protocol
- Implement it for FileHandler and BaseSocket
Result:
Better code structure
Motivation:
Channel.open was not really needed as for our use-case Selectable already provides everything we need. Also how we used Channel.open in some scenarios was not really correct.
Modifications:
- Remove extension method.
- Rename property
- Remove out-dated comment.
- Fix usage of open
Result:
More clear and correct API
Motivation:
Sometimes we deviated from the style the Swift stdlib sets out for no
reason.
Modifications:
Fixed some stylistic deviations.
Result:
Looks more Swift-like.
Motivation:
We missed to check if the file descriptor is still open in ServerSocket before we act on it. We can remove a lot of complexity by just providing a withUnsafeFileDescriptor which will do this for us and use it through out the code-base.
Modifications:
Introduce withUnsafeFileDescriptor and use it to ensure we always only act on open Selectables.
Result:
More correct code.
Motivation:
Leaking a fd is bad we should at least assert that we not do.
Modifications:
Add assert in deinit so we crash in debug mode if we leak a socket.
Result:
Code is more robust.