Commit Graph
68 Commits
Author SHA1 Message Date
Johannes Weiss e2990d9672 refactor registration IDs (#1801)
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.
2021-04-23 12:43:30 +01:00
Joakim Hassila f0b825f9b7 Add sequenceIdentifier to Registrations to handle outdated events robustly. (#1799)
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
2021-04-13 10:35:41 +01:00
Saleem Abdulrasool 70ca7aad2b NIO: silence error on Windows (#1668)
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
2020-10-14 08:25:28 +01:00
Saleem Abdulrasool 5d57ca0f3a NIO: implement cleanupSocket(unixDomainSocketPath:) for Windows (#1654)
* 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!
2020-10-05 12:49:28 +01:00
Cory Benfield c3e2359c55 Minor cleanups of Windows compatability code. (#1663)
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.
2020-09-30 19:55:21 +01:00
Saleem AbdulrasoolandCory Benfield 0ae9524ca8 NIO: invalid sockets are not -1 but INVALID_SOCKET (#1660)
Adjust the sentinel indicating an invalid socket.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-09-30 10:32:52 +01:00
Saleem AbdulrasoolandCory Benfield bc328cd3a8 NIO: ignore SIGPIPE on Windows (#1653)
Windows does not support Unix-style signals.  Simply exclude the SIGPIPE
path on Windows.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-09-30 10:13:10 +01:00
AndriusandCory Benfield b2f3de8ed5 Cleanup unix socket pathname on server socket close or bind (#1637)
* 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>
2020-09-22 15:30:49 +01:00
Saleem Abdulrasool 5de1e41310 NIO: Implement BSD sockets APIs for Windows (#1471)
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.
2020-07-03 10:14:36 +01:00
Johannes Weiss 120acb15c3 ClientBootstrap: allow binding sockets (#1490) 2020-06-08 10:46:20 +01:00
Johannes Weiss 1df9ad3402 survive having disableSIGPIPE fail (#1515)
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
2020-05-13 13:07:35 +01:00
Cory Benfield 30265d69a8 Adjust names of BSDSocket option values. (#1510)
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
2020-05-11 15:13:58 +01:00
Cory Benfield d536e6619c Make some vars lets. (#1493)
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.
2020-04-30 15:24:47 +01:00
Saleem Abdulrasool c7ab09013d Add BSDSocket.AddressFamily (#1469)
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.
2020-04-07 22:17:30 +01:00
Saleem Abdulrasool 2e2dcc25ca Add BSDSocket.ProtocolFamily (#1468)
This encapsulates the enumeration of protocol families rather than
relying on the underlying C library to provide the value.
2020-04-07 11:45:20 +01:00
Saleem Abdulrasool 37b48094ba Add BSDSocket.SocketType to represent the socket type (#1467)
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.
2020-04-03 17:16:48 +01:00
Saleem AbdulrasoolandCory Benfield bcc180dab6 Add new BSDSocket namespace (#1461)
* 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>
2020-04-02 19:06:48 +01:00
Saleem Abdulrasool 834a5f2185 NIO: split out FileDescriptor and Selectable (#1444)
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.
2020-03-18 15:48:40 +00:00
Saleem AbdulrasoolandCory Benfield 648a6712ff NIO: unify the syscall wrapper (#1423)
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>
2020-03-12 15:11:12 +00:00
Saleem Abdulrasool f44d524d56 NIO: use Posix "namespace" more aggressively (#1439)
Convert many more cases of the raw address family constant to the
definition in the System version.
2020-03-11 17:31:53 +00:00
Saleem Abdulrasool 7103febd74 NIO: undo exclusion of UDS on Windows (#1437)
This is in-scope for Windows now.
2020-03-09 17:38:10 +00:00
Saleem AbdulrasoolandCory Benfield ca9f613bbc NIO: excise UDS support for Windows (#1404)
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>
2020-02-18 09:36:18 +00:00
George Barnett b4483e5c49 Avoid curried thunks (workaround SR-12115) (#1374)
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.
2020-01-31 17:57:30 +00:00
Johannes Weiss 52a4cae14d add SAL (Syscall Abstraction Layer) and new SALChannelTests
## 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.
2020-01-28 12:36:36 +00:00
Johannes Weiss e102aa9ae9 add PipeChannel (#1138)
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.
2019-10-16 22:06:55 -07:00
Johannes Weiss bc816050cc don't close server socket if fcntl(O_NONBLOCK) throws EINVAL (#1041)
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
2019-06-19 15:42:18 +01:00
Johannes Weiss 3e7198f52c when making a socket non-blocking, get & OR flags (#1040)
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.
2019-06-18 15:37:38 +01:00
Johannes Weiss 305ee9818b make factory method names start with make (#692)
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
2018-12-10 17:59:24 +00:00
Johannes Weiss 08ab8b51cd remove ugly and unnecessary ignore result (_ = ...) (#652)
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
2018-11-13 14:49:08 +00:00
Johannes Weiss 2e96e47016 explain some force tries/unwraps (#619)
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.
2018-09-19 15:51:03 +01:00
Norman Maurer bf8c642896 Include ipaddress in SocketAddress.description. (#601)
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
2018-08-30 20:46:08 +02:00
Johannes Weiss 501af860f5 allow two distinct ChannelOptions of one type (#597)
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
2018-08-29 15:24:58 +01:00
Johannes Weiss b6473b3539 fix Posix.fcntl return type (#575)
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
2018-08-14 15:01:34 +01:00
Ole Begemann c6acf77fc9 Fix some typos in comments (#543)
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.
2018-08-01 15:57:27 +01:00
Johannes Weiß 5bebbf5565 don't crash if close is called when close fails (#387)
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.
2018-05-03 17:35:49 +02:00
Johannes Weiß b109389c54 eagerly process input EOF/connection resets (fixes #277) (#286)
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
2018-04-16 19:36:47 +02:00
Jason Toffaletti 5a4f630c5b make isOpen a computed property (#136)
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
2018-03-12 22:04:47 +01:00
Jason Toffaletti 49e159c51d use accept4 and SOCK_NONBLOCK on Linux (#124)
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.
2018-03-12 20:12:20 +01:00
Cory Benfield fee84ed63a Revert "make isOpen a computed property (#123)" (#129)
This reverts commit 4deeaf6365.
2018-03-12 13:27:42 +01:00
Jason Toffaletti 4deeaf6365 make isOpen a computed property (#123)
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
2018-03-12 19:07:30 +09:00
Norman Maurer 95a6e44e93 Remove return when possible. (#122)
Motivation:

We can cleanup the code by removing return keywords in closures sometimes.

Modifications:

Remove return when possible.

Result:

Cleaner code.
2018-03-11 22:47:29 +09:00
Helge Heß ad8afee8aa Fix issue #110, IPv6 address desc contains 0 bytes (#111)
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.
2018-03-08 20:22:42 +09:00
Cory Benfield f3f37af4ae Support enumerating network interfaces. (#47)
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.
2018-03-03 09:04:57 +09:00
adamnemecek 0bbed6d72f * removed trailing whitespace (#52) 2018-03-02 15:40:52 +09:00
Norman Maurer ee6cfcf9cf Add FileDescriptor protocol and implement it for FileHandle / BaseSocket (#38)
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
2018-02-28 09:46:29 +00:00
Norman Maurer d74dda7439 Remove Channel.open and rename Selectable.open to isOpen (#19)
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
2018-02-27 09:34:26 +09:00
Johannes Weiß 73a805c7f6 minor stylistic improvements (#36)
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.
2018-02-26 15:52:49 +00:00
Norman Maurer 580924909d Add Selectable.withUnsafeFileDescriptor and use it through the code. (#28)
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.
2018-02-26 11:30:37 +00:00
Norman Maurer d41c528b68 Add docs for BaseSocket, Socket and ServerSocket. (#27)
Motivation:

Our *Socket classes did not have any docs.

Modification:

Add docs.

Result:

More documentation.
2018-02-23 17:04:53 +00:00
Norman Maurer c7eab7f0b9 We should assert that the BaseSocket was closed when deinit() is called. (#26)
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.
2018-02-23 12:15:35 +00:00