* Break out control message parsing by IP version
* Add shims for Darwin packet info
* Add shims for Linux packet info
* Add channel option for receiving datagram packet info
* Add NIOPacketInfo to AddressedEnvelope.Metadata
* Pipe up packet info channel option to receive path
* Add NIOPacketInfo info and fix backwards compatability
* Document packet info socket options
* Cleanup packet info control message parsing
* Add packet info and ECN combined tests
* Find real interface index during NIOPacketInfo tests
* Add PacketInfo tests to Linux tests
Motivation:
On some Linux platforms the definition of SO_TIMESTAMP is too complex
for the clang importer to handle. Delegate to C to find out what it
should be. The same problem applies to SO_RCVTIMEO.
Modifications:
- Define SO_TIMESTAMP in CNIOLinux instead.
- Define SO_RCVTIMEO in CNIOLinux instead.
Result:
Should build on the awkward Linux platforms.
Motivation:
I noticed in a recent PR that a bunch of `internal` types have functions
with public access modifiers. This is redundant and a little confusing
in PRs (as you have to know the type is internal).
Modifications:
- Make a bunch of `public` functions on `internal` types `internal`
Result:
Less confusing API.
This reverts commit 4853e910e8.
While we have been able to observe the effect that this change was
trying to workaround, the change seems to interact poorly with a
different issue in Big Sur that can cause EPROTOTYPE to be consistently
emitted during socket writes on otherwise connected sockets. This would
change a connection-terminating error into a 100% CPU spin that rendered
the event loop entirely useless: a substantial regression.
For this reason, we should back this out until the issue is better
characterised.
Motivation:
When writing to a network socket on Apple platforms it is possible to
see EPROTOTYPE returned as an error. This is an undocumented and
special-case error code that appears to be associated with socket
shutdown, and so can fire when writing to a socket that is being shut
down by the other side. This should not be fired into the pipeline but
instead should be retried.
Modifications:
- Retry EPROTOTYPE errors on socket write methods.
- Add an (unfortunately) probabilistic test bed.
Result:
Should avoid weird error cases.
Motivation:
Be able to run and test swift-nio on Android.
Modifications:
- Remove the custom ifaddrs and use the one from the Android NDK instead.
- Enable a bunch of conditionally-compiled code for Android.
- Add a handful of constants and other Android declarations.
- Cast some types because of mismatches specific to Android.
Result:
Most tests pass on Android AArch64 and ARMv7.
Co-authored-by: Cory Benfield <lukasa@apple.com>
These are part of the BSD sockets APIs, but not directly related to the
socket interfaces. Create an extension point to permit the different
platforms to shuffle their implementation into place. This provides a
nicer spelling for the functions and enables the codepaths on Windows as
well.
`System` interfaces should be considered deprecated and not be used.
This removes more of the interfaces from Windows as the socket
interfaces are now part of BSDSocketAPI.
Co-authored-by: Cory Benfield <lukasa@apple.com>
This shaves off parts of System to reduce the noise when building to get
the Windows build more manageable.
Co-authored-by: Cory Benfield <lukasa@apple.com>
* 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>
* Recover from EINVAL even if the error is untyped
* Handle fcntl EINVAL error
* Fix EINVAL test
* Rename and deprecate errors
Co-authored-by: Cory Benfield <lukasa@apple.com>
Motivation:
We included netinet/ip.h in CNIODarwin, which unfortunately is not
modularised. This causes issues when using SwiftPM to create xcodeproj
files. There's no real reason to do it this way, when we can just as
easily abstract the issue.
Modifications:
- Moved netinet/ip.h to the .c file instead of the .h.
- Defined some exported namespaced integers to correspond to the macros.
- Performed platform abstraction in Posix instead of everywhere.
Result:
- Creating xcodeproj files should be fine.
Motivation:
cmsghdrs can be used to send an receive extra data on UDP packets.
For example ECN data.
Modifications:
Map in Linux and Darwin versions of cmsghdr macros as functions.
Create strctures for holding a received collection; parsing ecn
data from a received collection and building a collection suitable
for sending.
Result:
Functions to manipulate cmsghdr and data exist.
Motivation:
sendmsg is more powerful - this is paving the way for
Explicit Congestion Notifications to be sent.
Modifications:
Replace the sendto system call with sendmsg up to DatagramChannel.
Result:
Sendmsg will be used to send UDP data.
Motivation:
When attempting to obtain metadata about a read, we need to use recvmsg
in order to obtain that data. While we're using recvmmsg for vector
reads right now, our scalar reads use recvfrom, which does not provide
us with that metadata.
While we're not extracting metadata right now, we may well do so in
future, so we can apply it now.
Modifications:
- Move recvfrom usage to recvmsg.
Result:
We'll be able to extend recvmsg to extract metadata.
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:
It's 2020, we shouldn't use unnecessary offensive, insulting, or
outdated language.
Modifications:
Fix a few examples.
Result:
More inclusive.
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>
There are three different error domains that we deal with in NIO, which
need to be differentiated. Store the error with the domain to ensure
that we can identify the error domain.
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>
* Add offset writes and file size support to NonBlockingFileIO
Motivation:
NonBlockingFileIO currently only supports writes from 0 or appending,
if opened with O_APPEND. To facilitate random read/write file access
the API needs to evolve.
Modifications:
- Add toOffset function parameter to write for offset file write access
- Add changeFileSize function for growing or shrinking the file
- Add readFileSize function for asynchronously reading the file size
Result:
- Improve API for random access scenarios
- Provide method for reading and writing file size
* Conform to code review
* Formatting
* Update Sources/NIO/NonBlockingFileIO.swift
Co-Authored-By: Johannes Weiss <johannesweiss@apple.com>
* Update Sources/NIO/NonBlockingFileIO.swift
Co-Authored-By: Johannes Weiss <johannesweiss@apple.com>
* Modify offset handling to support partial writes.
Clean up stray comment.
* Fix precondition check within offset pwrite handling
* Improve guard for readability
* White space cleanup
* Single spacing issue
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
resolves#1355 shaving off some bytes from IOError struct
Motivation:
It's important for frequently used errors to fit in existential containers because otherwise throwing them leads to allocations.
Modifications:
- Don't store `StaticString`s anymore which are 2 words + 1 bytes wide
Result:
Fewer allocations when IOErrors are thrown.
Motivation:
We never look at the socket address that accept(4) returns so we
shouldn't ask for it. Additionally, it wasn't always the right size (in
IPv6 case) and also the pointer operations were dodgy.
Modifications:
Remove the whole socket address pointer stuff for accept.
Result:
Cleaner code.
Motivation:
Certain POSIX error numbers mean the NIO program is broken beyond repair and should crash. One such value is EBADF, which indicates that the file descriptor that NIO passed to the kernel is invalid for some reason. SR-11557 was discovered in part because debug builds of NIO crash for this.
I have promoted these checks from an assertion to a precondition adding a function preconditionIsNotBlacklistedErrno. Issue was raised in issue #1156
Modifications:
- Add function preconditionIsNotBlacklistedErrno to enable option to stop program execution in both debug mode and release mode if the errno is blacklisted.
- Update assertIsNotBlacklistedErrno to all preconditionIsNotBlacklistedErrno when the program is in debug mode
- Update wrapSyscallMayBlock, wrapSyscall, wrapErrorIsNullReturnCall, and close to call preconditionIsNotBlacklistedErrno in stead of assertIsNotBlacklistedErrno
Result:
Functions wrapSyscallMayBlock, wrapSyscall, wrapErrorIsNullReturnCall, and close will stop the execution in both debug mode and release mode if the errno is blacklisted.
Motivation:
For some reason, we never added `socketpair` to the POSIX wrappers but
it should be there.
Modifications:
Add socketpair to the POSIX wrappers and make use of it.
Result:
Nicer code base.
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:
A race condition occurs when a socket is closed from the remote end after `accept()` returns it, but before `fcntl(F_SETFL, F_SETNOSIGPIPE)` is invoked. This causes the `fcntl()` call to fail with `EINVAL` ("The socket has been shut down."). This currently triggers an assertion failure. As the race depends on the remote and can be easily demonstrated (using `nmap` is a good way to set it off), the assertion is semantically invalid (`EINVAL` is not programmer error). Additionally, errors reported by `fcntl()` in general are being ignored when not asserted.
Modifications:
The race is avoided by treating `EINVAL` as a normal error while retaining the existing behavior for all other error cases. Both uses of `fcntl()` to disable `SIGPIPE` now properly report errors.
Result:
`Posix.accept()` and `Posix.socket()` may now potentially throw additional errors. It is no longer possible to crash a debug server by running `nmap` against it.
Motivation:
testCloseInReadTriggeredByDrainingTheReceiveBufferBecauseOfWriteError
expected (without knowing it) that networking on localhost is
synchronous enough that a succeeded write means that it has
simultaneously arrived in the reader's read buffer.
On macOS that's not necessarily true, so this test failed very seldom
seemingly more often if you had more physical cores.
Modifications:
Introduce a nasty blocking `poll` call in the test that waits until we
have bytes in the read buffer.
Result:
- fixes#657
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:
make swift-nio compatible with Android, and pass all test in Android.
### Modifications:
* add missed `ifaddrs` implementation
* add missed thread related functions - `CNIOLinux_pthread_getname_np`, `CNIOLinux_pthread_setaffinity_np` and `CNIOLinux_pthread_getaffinity_np`
* fix types incositency between Linux and Android, e.g. `Epoll.swift` class
* make bytes counter explicitely 64bits to avoid overflow on 32bit, in `PendingWritesManager.swift` and `PendingDatagramWritesState.swift`
* fix issue with Unix domain socket, first byte need to be zero in Android
* several incosistency fixes between Linux and Android api.
### Result:
now swift-nio works on Android. All tests passed!
Motivation:
A large number of very useful protocols are implemented using multicast
with UDP. As a result, it would be helpful to add support for joining and
leaving IP multicast groups using SwiftNIO.
Modifications:
- Defines a MulticastChannel protocol for channels that support joining and
leaving multicast groups.
- Adds an implementation of MulticastChannel to DatagramChannel.
- Adds a interfaceIndex property to NIONetworkInterface.
- Adds if_nametoindex to the Posix enum.
- Adds a isMulticast computed property to SocketAddress
- Adds a demo multicast chat application.
- Add a number of multicast-related socket options to SocketOptionProvider.
Result:
NIO users will be able to write channels that handle multicast UDP.
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:
It's not all that useful to print the value of the pointer from sterror.
Instead we should aim to print the string. While we're here, let's avoid
repeating too much code.
Modifications:
- Centralised the handling of blacklisted errnos.
- Correctly printed the error string when a blacklisted errno is hit.
- Updated the output of the assertion to include the function failing.
Result:
Better diagnostics when blacklisted errnos are hit.
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:
The bytes that a Unsafe(Mutable)RawBufferPointers points to can be
accessed directly as `UInt8`s. We didn't know that so we bind
`ByteBuffer`s memory to `UInt8` so that we can access it as
`UnsafePointer<UInt8>` using `assumingMemoryBound(to: UInt8.self)` in
many places. Most of the time that is unnecessarily awkward and
unnecessary.
Modifications:
- remove some easy instances where we access an
`UnsafeMutableBufferPointer` as `UnsafeBufferPointer<UInt8>` just to
read some `UInt8`s.
Result:
less awkward looking code
Motivation:
Given that wrapErrorIsNullReturnCall exists purely to wrap syscalls that
return NULL pointers on errors, there is no point allowing the return
value to be nil. Additionally, it's currently weirdly specific about the
return pointer type, so we can make the function generic.
Modifications:
- Make the return value of wrapErrorIsNullReturnCall generic.
- Make the return value of wrapErrorIsNullReturnCall non-optional.
Result:
Easier to use wrapErrorIsNullReturnCall and any matching function
Explicitly define constants through Posix and import errno.h
Motivation:
We implicitly depend on errno's ENOENT in Linux.swift, but don't explicitly import errno.h.
Similarly, in some cases the compiler can be confused as to where SHUT_* come from, so make them an exported value from Posix instead.
Result:
Compiles successfully on Linux and Darwin.
Motivation:
We only use our GetaddrinfoResolver for SocketChannels (TCP stream channels), so we should set some hints for getaddrinfo.
Modifications:
Set proto and socktype hints.
Result:
More correct usage of getaddrinfo. Fixes https://github.com/apple/swift-nio/issues/201.
Motivation:
Resolves#228
Modifications:
Remove type information in empty closure fixed build warning with compiler suggestion
Result:
No API changes, no issues building on 4.1!
Motivation:
Usually we retry the syscall when EINTR is reported. This is not safe in the case of close(...) as the file descriptor may already be closed. The problem arise if this was the case and we retry it and the file descriptor is already reused again. In this case we would close a wrong file descriptor.
See:
- https://bugs.chromium.org/p/chromium/issues/detail?id=269623
- https://lwn.net/Articles/576478/
Modifications:
Ignore EINTR on close(...) and just assume the FD was closed.
Result:
Not possible to close the wrong file descriptor when close(...) reports EINTR.
Motivation:
There are quite a few `switch`es that cover just two cases. Explicitly state this via an `if case` + `else` structure.
Modifications:
Changes something like:
switch a {
case .b:
return c
default:
return d
}
to
if case .b = a {
return c
} else {
return d
}
Result:
This should prevent misinterpretation and thus potential bugs in the future.
Motivation:
This changes two things:
- it removes the negation of non-used associated types (the removal of `(_)`).
- it prefers exhausting `switch`es over `default`ing.
This change does not impact bahavior; it is pure refactoring.
Modifications:
Omitting needless `(_)`'s and explicitly exhausting switches.
Result:
This change is pure refactoring.