* 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.
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.
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.
Motivation:
We can cleanup the code by removing return keywords in closures sometimes.
Modifications:
Remove return when possible.
Result:
Cleaner code.
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:
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:
There were a couple of places in the Channel implementations that just
weren't thread-safe at all, namely:
- localAddress
- remoetAddress
- parent
those are now fixed. I also re-ordered the code so it should be easier
to maintain in the future (the `// MARK` markers were totally
incorrect).
Modifications:
- made Channel.{local,remote}Address return a future
- made Channel.parent a `let`
- unified more of `SocketChannel` and `DatagramSocketChannel`
- fixed the `// MARK`s by reordering code
- annotated methods/properties that are in the Channel API and need to
be thread-safe
Result:
slightly more thread-safety :)
Motivation:
Previously `FileRegion` was a special snow flake, a bit like
`ByteBuffer` but also totally different. That caused surprise and made
`PendingWritesManager` even harder. It was also used to manage the
lifetime of a file descriptor but only sort of.
Modifications:
We now have a `FileHandle` which is a one-to-one mapping with a file
descriptor and its lifetime must be managed appropriately.
Result:
hopefully less bugs and fd leaks.
* Use aliases to reduce duplication and make it easier to maintain.
Motivation:
We used many #if #else blocks which made the code very clumby.
Modifications:
Use aliases and define these in one place.
Result:
Easier to maintain code.
* Comments
* Comments
Motivation:
To ensure we not leave any unread data on the socket we should try to read one last time (if autoread is enabled).
Modifications:
- Depending on if autoread is enabled or not we will try to read one more time
- Guard against re-entry of flushNow0()
- Correctly handle SIGPIPE in all cases
- Add testcase
Result:
Drain data from socket on write error if needed.
Motivation:
Explain here the context, and why you're making that change.
What is the problem you're trying to solve.
Modifications:
Describe the modifications you've done.
Result:
After your change, what will change.
Motivation:
Creating an IOError is not "cheap" as we use String formatting to do so. In cases of EWOULDBLOCK we will never use the IOError at the end so we should not even create one.
Modifications:
Handle EWOUDLBOCK without creating and IOError
Result:
Less overhead when a syscall will fail because it would block