Commit Graph
75 Commits
Author SHA1 Message Date
Cory Benfield 1a2996bfc5 Revert "Retry on EPROTOTYPE on socket writes. (#1706)" (#1707)
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.
2020-12-18 15:32:53 +00:00
Cory Benfield 4853e910e8 Retry on EPROTOTYPE on socket writes. (#1706)
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.
2020-12-17 17:45:23 +00:00
buttafaceandCory Benfield 44d67ba4e0 Update and finish Android port. (#1695)
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>
2020-11-27 11:16:11 +00:00
Saleem Abdulrasool 20e63d07dc NIO: extract control message handling into a separate protocol (#1678)
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.
2020-10-19 16:18:57 +01:00
Saleem AbdulrasoolandCory Benfield 8e59cd159e NIO: carve away more of System.swift on Windows (#1669)
`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>
2020-10-13 10:17:24 +01:00
Saleem AbdulrasoolandCory Benfield 8454066e8d NIO: shave off parts of System (#1658)
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>
2020-09-30 11:35:07 +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
Timothée PeignierandCory Benfield 0570d9a1cb Recover from EINVAL even if the error is untyped (#1598)
* 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>
2020-08-12 15:05:42 +01:00
Cory Benfield acf5465b5e Avoid including non-modular headers. (#1605)
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.
2020-07-31 09:57:25 +01:00
Peter Adams f12803dbf1 Add methods to create and parse cmsghdr structured data. (#1590)
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.
2020-07-14 12:29:31 +01:00
Peter Adams ee8acd9b3d Use sendmsg rather than sendto to send UDP data. (#1587)
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.
2020-07-10 13:41:13 +01:00
Cory Benfield e3508b0d04 Move DatagramChannel over to using recvmsg. (#1473)
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.
2020-07-08 09:10:32 +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 5268726898 fix inappropriate lanugage in NIO (#1554)
Motivation:

It's 2020, we shouldn't use unnecessary offensive, insulting, or
outdated language.

Modifications:

Fix a few examples.

Result:

More inclusive.
2020-06-12 19:34:05 +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 5270fa81df IO: extend IOError for Windows (#1460)
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.
2020-03-23 16:29:14 +00: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
Marcus LiottaandJohannes Weiss 5755c21a61 Add offset writes and file size support to NonBlockingFileIO (#1408)
* 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>
2020-03-02 11:02:05 +00:00
Shekhar RajakandJohannes Weiss dfd56c8b56 undo @convention(c) hacks in System.swift (#1412)
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-02-25 07:51:07 +00:00
Doug Friedman a4fe7d4840 get IOError down to git in an existential container (#1355) (#1376)
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.
2020-02-03 12:30:37 +00:00
Johannes Weiss 6633f54708 support pread (#1324) 2020-01-20 09:56:54 +00:00
Johannes Weiss 9f94448bc6 accept: don't do unnecessary dodgy pointer things (#1306)
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.
2019-12-17 11:57:38 +00:00
Heidi Puk Hermann bad79c584e Add function preconditionIsNotBlacklistedErrno (#1201)
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.
2019-10-31 13:10:00 +01:00
Johannes Weiss 22073b97be add socketpair to the POSIX wrappers (#1198)
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.
2019-10-30 08:01:42 +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
Gwynne Raskind 642076e9f8 Fix a race condition when remote closes connection after accept() but before fcntl() on macOS. (#807)
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.
2019-02-06 17:08:00 +00:00
Johannes Weiss 89a4eaa807 fix #657 (#795)
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
2019-01-31 16:41:55 +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
Albert Aleksieiev a59293cbcd add Android support (#609)
### 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!
2018-09-27 11:32:43 +01:00
Cory Benfield c73eb57694 Support UDP multicast. (#618)
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.
2018-09-24 10:24:09 +01: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
Cory Benfield 19444825fa Actually report errors when hitting blacklisted errnos. (#610)
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.
2018-09-10 10:58:50 +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 Weiss 8c5eee85fc remove unnecessary UInt8 pointer binds (#524)
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
2018-07-23 19:11:19 +01:00
Cory Benfield 799060071a Cleanup wrapErrorIsNullReturnCall. (#511)
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
2018-07-12 12:21:19 +01:00
Alex Blewitt 1fa9f15aca Explicitly define constants through Posix and import errno.h (#400)
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.
2018-05-10 20:12:33 +02:00
Norman Maurer b1f948a115 Set hints for getaddrinfo to restrict results (#221)
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.
2018-03-28 10:49:05 +02:00
Tim a0b7f646fb Fixes build issue on 4.1 (#229)
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!
2018-03-23 16:28:43 +00:00
Gopal Sharma 61f03a7a53 Annotate global constants that refer to C functions with @convention(c) (#223)
Motivation:

This fixes https://github.com/apple/swift-nio/issues/206.

Also see: https://bugs.swift.org/browse/SR-7242.

Modifications:

Annotated global constants that refer to C functions with @convention(c), and added explcit types.

Results:

https://bugs.swift.org/browse/SR-7242 is worked around.
2018-03-23 09:37:51 +00:00
Norman Maurer 91d7058a36 Not retry calling close(...) when EINTR is reported. (#217)
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.
2018-03-22 18:16:00 +01:00
Bas Broek a095decbc2 Prefer if case over switch
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.
2018-03-19 14:45:32 +01:00
Bas Broek b180113d81 Improve switch readability
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.
2018-03-19 14:43:38 +01:00
Helge Heß b06b712085 No need to wrap fatalError within code
Motivation:

No need for the "self-invoking function" here.

Modifications:

Call fatalError directly.

Result:

18 bytes are saved in the source code. No functional
difference.
2018-03-19 09:52:44 +01:00
Helge Heß 94718bcaa8 Wrap sendfile() in #if's that match the import
Motivation:

NIO doesn't compile on iOS. Which I'd like to do.

Modifications:

The #if's used to protect the syscall do not match
the #if's used to import.
Specifically the Darwin branch only applied to
macOS, not watchOS or homePodOS.

Result:

Hopefully will compile on iOS.
2018-03-19 09:52:44 +01: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