Motivation:
http-parser shipped a patche for node.js CVE-2019-15605, which allowed
HTTP request smuggling. This affected SwiftNIO as well, and so we need
to immediately ship an update to help protect affected users.
A CVE for SwiftNIO will follow, but as this patch is in the wild and
SwiftNIO is known to be affected we should not delay shipping this fix.
Modifications:
- Update http-parser.
- Add regression tests to validate this behaviour.
Result:
Close request smugging vector.
(cherry picked from commit f94b22b506)
Motivation:
Non-functional change: `bind0(_ makeSocketAddress: () throws -> SocketAddress)
-> EventLoopFuture<Channel>` calls `bind0` with a `register` closure that is
passed an event loop as first argument. However, the name of the first parameter
of the closure declaration is named "eventGroup" which is confusing. It should
therefore be renamed to "eventLoop" which is consistent with other closures
passed as `register` arguments at other callsites.
Modifications:
Rename (unused) closure parameter "eventGroup" to "eventLoop".
Result:
Improved code readability.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
Motivation:
The `ByteBuffer` API currently has `setString`/`writeString` support for the `String`
type but no support for the `Substring` type (see #1332).
Modifications:
Add `setSubstring`/`writeSubstring` functions to `ByteBuffer`. We do not change
the exisiting set-/writeString API to take a generic `StringProtocol` argument
as it would change the ABI and adds performance overhead. We also do not let
`setString` call into `setSubstring` for now, as Substring currently (as of
Swift 5.1.3) has no fast access to the backing storage and this therefore would
introduce a performance regression.
Result:
ByteBuffer API for writing Substrings.
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
improve flushNow re-entrancy protection
Motivation:
The fix in #1344 wasn't complete, there is another, quite complicated scenario where we would still forget to send flushed bytes until we see another `flush` call. The scenario is
1: writable()
2: --> flushNow (result: .writtenCompletely)
3: --> writabilityChanged callout
4: --> flushNow because user calls writeAndFlush (result: .couldNotWriteEverything)
5: --> registerForWritable (because line 4 could not write everything and flushNow returned .register)
6: --> unregisterForWritable (because line 2 wrote everything and flushNow returned .unregister)
Line 6 undoes the registeration in line 5.
Modification:
This fix makes sure that flushNow never re-enters and therefore the problem described above cannot happen anymore.
Result:
Hopefully actually fixes rdar://58571521
Motivation:
We add an empty `bindTimeout` function to `ServerBootstrap`. While
ServerBootstrap itself is based on a blocking socket bind operation, this
enables the possibility of having bind be asynchronous in other use cases and
it unifies the API with other Bootstrap classes, e.g. `NIOTSListenerBootstrap`.
See also #1135.
Modifications:
Add `bindTimeout` function to `ServerBootstrap`.
Add `Bootstrap.testServerBootstrapBindTimeout` test.
Result:
`ServerBootstrap` has a `bindTimeout` function/API compatibility with other
Bootstrap classes.
There is no `ChannelPipeline.addHTTPServerHandlers` but there is `ChannelPipeline.configureHTTPServerPipeline`.
Comment for `HTTPResponseDecoder` mentioning `ChannelPipeline.addHTTPClientHandlers` is correct.
On 32-bit systems we would try to read 4 byte, which is incorrect. From `man timerfd_read`:
> (...) then the buffer given to read(2) returns an unsigned 8-byte integer (uint64_t) containing the number of expirations that have occurred (...)
> A read(2) will fail with the error EINVAL if the size of the supplied buffer is less than 8 bytes.
Motivation:
The class name was a typo.
It is a client upgrader that upgrades WebSocket connections, so the updated name suits better.
Modifications:
Change class name of ‘NIOHTTPWebClientSocketUpgrader’ to ‘NIOHTTPWebSocketClientUpgrader’.
Update the WebSocket client example that uses this class.
Add a typealias to allow the old class name to be used.
Result:
Improved naming.
Motivation:
The byte to message decoder example on the ‘verifyDecoder’ method was not compiling.
Modifications:
Added the example output objects to an array so that they match the method signature.
Result:
The example is now compiling and can serve as the basis for creating an implementation from the example.
Motivation:
`subscript(name:)` and `first(name:)` incorrectly referred users to
`getCanonicalForm` for a maximally decomposed list of header fields.
This no longer exists.
Modifications:
Point users to `subscript(canonicalForm:)`.
Result:
More accurate documenation.
Motivation:
When initializing an `HTTPMethod` with a `String` we currently switch over all expected values to pick an explicit value, only to overwrite our found explicit value with a catchall `RAW(value: String)`. This doesn’t make a ton of sense. This went unnoticed because we use the conditional conformance on `RawRepresentable` to be `Equatable`. But `switch`es don’t use the `Equatable` protocol to match enums. The issue is visible there.
Modifications:
Added a testcase with a switch that fails, if the `.RAW(value: String)` value is used for `”GET”`. Removed the final overwrite in HTTPMethod(rawValue: String). Therefore the test passes.
Result:
We can initialize the HTTPMethod with a String and get an explicit value.
Motivation:
In performance tests was shown that the current base 64 encoding function doesn’t perform very well.
https://github.com/apple/swift-nio/issues/1322
Modifications:
This commit replaces the current Base64 implementation with a more performant one (by using UInt8 bytes instead of Unicode.Scalars).
Result:
The API will stay the same. Base64 encoding is just faster.
Motivation:
`ByteBuffer` should implement the `Hashable` protocol as stated by: https://github.com/apple/swift-nio/issues/1320
Modifications:
Implemented the `Hashable` protocol for `ByteBuffer` and added a test `testHasherUsesReadBuffersOnly`.
Result:
`ByteBuffer` implements the `Hashable` protocol. The test `testHasherUsesReadBuffersOnly` is failing for the moment though.
Motivation:
EmbeddedChannel advanced time to the distant future so that all
scheduled tasks would be run. However, if tasks were recursively
scheduled by executing the already scheduled tasks then the channel
would never finish.
Modifications:
When calling finish() on EmbeddedChannel, only run the tasks which have
been scheduled at that point in time.
Result:
Recursively scheduled tasks terminate when finish-ing the
EmbeddedChannel.
Motivation:
SelectableEventLoop's description was taking a lock and would also lock
every single scheduled task. That's overkill.
Modifications:
Make it only log the thread and selector (which don't require locks).
Result:
better description
Motivation:
Certain issues are easier debugged if we can print the thread names.
Modifications:
- add the thread name to SelectableEventLoop's description
- make EventLoop and NIOThread CustomStringConvertible
Result:
easier debugging.
Motivation:
We incorrectly asserted that HEAD and DELETE may not have request
bodies, but they can, it's just unlikely.
Modifications:
Change the categorisation of HEAD and DELETE.
Result:
Better behaviour in unusual cases.
Motivation:
There was always this one big embarrassment in the NIO codebase: We
violated the iron rule of 'no fd or scarce resource management in deinit'
in just one place: The most long-lived thing there is in NIO: The
Selector for the SelectableEventLoopGroup. Sure enough, even that tiny
violation lead to issues.
Modifications:
Close the fds in `close` rather than `deinit`.
Result:
- I'm feeling better
- makes @ktoso happy
- fixes#1302
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:
Due to rdar://53656794, we sometimes (especially on UNIX Domain Sockets)
see EVFILT_EXCEPT firing when data is available to read depite the fact
that we're setting the low watermark to CInt.max. This means that
EVFILT_EXCEPT becomes essentially unusable.
Modifications:
- Don't use EVFILT_EXCEPT on Darwin
- We lose early EOF delivery on Darwin
Result:
Fewer possibilities of a spin loop on Darwin.
Motivation:
Previously, we unconditionally woke up the selector for every task that
was added. But this is only necessary if we're not already on the
EventLoop. Because if we are, we'll have another look at the outstanding
tasks anyway.
Modifications:
Remove selector wakeups.
Result:
Faster executes.
Motivation:
In SelectableEventloop, Heap, PriorityQueue, etc there were quite a few
phantom publics left which cause issues with #1257 and are confusing.
Modifications:
- remove the phantom publics
- move SelectableEventLoop to its own file
Result:
- clearer what's going on (public means public)
This allows other EventLoopGroup implementations to swap in other
bootstrap implementations. By default, it is unimplemented and will
throw an error once `connect` is called on the returned Bootstrap.
Support is implemented for `MultiThreadedEventLoopGroup`,
`SelectableEventLoop` and `EmbeddedEventLoop`.
Motivation:
Some Swift nightly snapshots fail to compile NIO in release mode
(rdar://57793267), this change is to work around this issue by telling
them compiler the associatedtypes explicitly.
Modifications:
- add `Element` and `Indices` typealises to `CircularBuffer` explicitly.
Result:
Complies on all nightlies also in release mode.
Motivation:
Atomic references cannot easily be maintained correctly because the
`load` operation gets a pointer value that might (before the loader gets
a change to retain the returned reference) be destroyed by another
thread.
Modifications:
- Deprecate `AtomicBox`
- Implement `NIOCASLoopBox` with functionality similar to AtomicBox (but
implemented using a CAS loop :( ).
Result:
- fixes#1286
Motivation:
ClientBootstrap.connect was needlessly overallocaing (for a needless
promise and a needless cascade).
Modifications:
Remove the needless allocations.
Result:
Fewer allocations.
Motivation:
In some cases you only expect (or care about) a single value for a
header. However, getting this value without allocating an array or
traversing the whole array requres using first(where:) provided by
Sequence. This is not very ergonomic as it requires users to do the
case-insensitive comparison and then exctact the value from the
HTTPHeaders. Additionally, users cannot use NIO's case insensitive
ASCII comparison.
Modifications:
- Provide a first(name:) method on HTTPHeaders which returns the value
from the first header whose name is a case insentive match of the
subscript parameter.
Result:
It's easier to get the first value from HTTPHeaders matching a given
name.
Motivation:
The futures implementation used a particularly inefficient way to
accumulate all callbacks.
Modifications:
Improved this by allocating fewer arrays.
Result:
Fewer allocations.
Motivation:
AtomicBox doesn't properly work (#1286) and despite fixing it in #1287,
it's really not worth using AtomicBox (which as of #1287 instroduces a
CAS loop) anymore.
Modifications:
Remove the two uses of AtomicBox.
Result:
No usage of broken/slow data types.
Motivation:
ByteToMessageHandler was expecting to always be added to a
ChannelPipeline. That's mostly true but not always.
Modifications:
Make sure we don't crash if a ByteToMessageHandler was never added.
Result:
Fewer crashes.
Motivation:
Fixes the bug described in #1279
Modifications:
Moved state change in NIOHTTPClientUpgradeHandler.performUpgrade to after firing buffered messages.
Result:
- The upgradeState will now only change to upgradeComplete after buffered reads are handeld.
- Fixes#1279
* Add NIOSingleStepByteToMessageDecoder and NIOSingleStepByteToMessageProcessor
for processing byte streams outside of the channel pipeline.
Motivation:
ByteToMessageHandler works well when you can embed it in your pipeline, but if
you have a wrapped protocol (e.g. sending a protocol over HTTP), you can't use
it without losing the context of the outer protocol (e.g. HTTP headers/trailers).
Modifications:
Added NIOSingleStepByteToMessageDecoder and NIOSingleStepByteToMessageProcessor.
Result:
New functionality above.
Motivation:
So far we've been checking the heap property of our heaps _twice per
heap operation_. I think that's a bit much.
Modifications:
Remove the heap operation checks.
Result:
Runs much faster in debug mode.
Motivation:
The existing Atomic class holds an UnsafeEmbeddedAtomic which holds an OpaquePointer to raw memory for the C atomic. This results in multiple allocations on init. The new NIOAtomic class uses ManagedBufferPointer which tail allocates memory for the C atomic as part of the NIOAtomic class allocation.
Modifications:
Created NIOAtomic class that uses ManagedBufferPointer to allocate memory for the C atomic. Created version of catmc_atomic_* C functions that expect memory to be allocated/deallocated by caller. Created NIOAtomicPrimitive protocol for the new version of catmc_atomic_* functions.
Result:
Purely additive. NIOAtomic is available as a replacement for Atomic which results in fewer memory allocations.
Motivation:
In some cases it may be possible to write the (usually small) web socket
frame header to the buffer provided by the user. If we do this we can
avoid an extra pipeline traversal for the small write. This is only
going to be a performance win in cases where we can avoid a
copy-on-write operation on the buffer, but if we can then it's a useful
small win to achieve.
Modifications:
- Refactored the WebSocketFrameEncoder to potentially prepend the frame
header.
- Added a missing @inlinable attribute.
- Tests.
Result:
Potentially improved performance.
Motivation:
In Swift, writing
var something: T?
init() {
self.something = someValue
}
means that the compiler will first set `self.something` to `nil` and
then in the init override it with `self.someValue`
(https://bugs.swift.org/browse/SR-11777). Unfortunately, because of
https://bugs.swift.org/browse/SR-11768 , stored property initialisation
cannot be made `@inlinable` (short of using `@frozen` which isn't
available in Swift 5.0).
The combination of SR-11768 and SR-11777 leads to `var something: T?`
having much worse code than `var something: Optional<T>` iff the `init`
is `public` and `@inlinable`.
Modifications:
Change all `var something: T?` to `var something: Optional<T>`
Result:
Faster code, sad NIO developers.
Motivation:
We should join the threads that we spawned which has the extra benefit
of TSan being able to detect our thread leaks.
Modifications:
Join the SelectableEventLoop's thread after it's shut down.
Result:
We join all the threads.
Motivation:
ByteBufferView isn't a mutable collection, but it probably should be.
Modifications:
- Add `copyBytes(at:to:length)` to `ByteBuffer` to copy bytes from a
readable region of a buffer to another part of the buffer
- Conform `ByteBufferView` to `MutableCollection`, `RangeReplaceableCollection`
and `MutableDataProtocol`
- Add an allocation counting test
Result:
`ByteBufferView` is now mutable.
Motivation:
`public extension`s are very dangerous because the make it so easy to
slip in public API by accident.
Modifications:
Don't use `public extension`.
Result:
Fewer chances to accidentally make stuff public.
Motivation:
The ExpressibleBy*Literal conformances require `@usableFromInline` inits
which make it harder to make NIO compatible with library evolution
because we can no longer just remove all `@inlinable`s and call it a
day.
Modifications:
Remove the ExpressibleBy*Literal conformances for internal types.
Result:
NIO easy to convert into a library evolution mode.