1218 Commits
Author SHA1 Message Date
Johannes Weiss a27a07719c testSafeToExecute*: fix threading issues (#1455)
Motivation:

testSafeToExecuteTrue/False accessed an internal property of the event
loop without synchronisation.

Modifications:

Fix the threading issue.

Result:

Tests with TSan happy.
2020-03-18 22:36:08 +00:00
Johannes Weiss bd4df32a26 downgrade 'schedule after shutdown' to printing error (#1454)
Motivation:

Since #1395, we crash when something is scheduled to an already shutdown
EventLoop. That's a good intent (#1383) but we feel it's a little too
risky right now.

Modifications:

Print an ERROR instead of just crashing.

Result:

Fewer crashes.
2020-03-18 18:20:35 +00:00
Johannes WeissandCory Benfield 2ad77f9a9b WIP: universal bootstrap (#1323)
Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-03-18 16:20:19 +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 Abdulrasool 2673be6ae3 NIO: move comment to right location (NFC) (#1452)
Move the block comment to the right location before the function it
describes.
2020-03-17 09:31:00 +00:00
d3d7589a29 NIO: implement core counting on Windows (#1448)
* NIO: implement core counting on Windows

Implement the core counting logic for Windows, which does not support
`sysconf`.  It uses the Windows SDK to get the processor topology and
computes the core count from the topology.

Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-03-16 18:41:58 +00:00
Ludovic DewaillyandLudovic Dewailly fefd0c854f Provides a means to control the underlying header storage capacity. (#1451)
Motivation:

It's not always possible to initialize `HTTPHeaders` with all the headers one needs to set. In such case, the underlying array will be expanded as and when needed upon headers being appended. `Array` provides the means to reserve capacity to optimize such use case. This PR exposes this functionality in `HTTPHeaders`.

Modifications:

Expose method `reserveCapacity(_ minimumCapacity: Int)` and computed variable `capacity: Int` in `HTTPHeaders` and added some tests.

Result:

Developers will be able to control the capacity of the underlying headers array as such:

```
var headers = HTTPHeaders()
headers.reserveCapacity(5)
```

Co-authored-by: Ludovic Dewailly <ldewailly@apple.com>
2020-03-16 17:47:34 +00:00
Saleem Abdulrasool e5298263ec SelectableEventLoop: make Darwin the special case (#1449)
Treat the `autoreleasepool` case for Darwin as the special case rather
than Linux as the special case.  This is following the case throughout
the rest of the code base.  This is also needed for the Windows port.
2020-03-16 09:14:21 +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 790698cd54 NIO: swap selector implementations (NFC) (#1443)
In most of the code, Linux is treated as the fallback case.  This
adjusts the selector implementation to follow the same pattern, checking
if on Darwin and using kqueue (which would also be available on F/BSD)
and otherwise falling back to `epoll` (assuming Linux).  This
homogeneous behaviour makes it easier to reason about when trying to add
support for additional platforms.
2020-03-12 07:43:33 +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
Kaitlin Mahar a8e08d9757 BlockingIOThreadPool -> NIOThreadPool (#1438)
Update NonBlockingFileIO.init documentation to match the new type name.
2020-03-11 08:35:39 +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
35078406c7 CNIOSHA1: make the code more portable (#1399)
Replace the non-portable `u_*_t` types with the C standard `u*_t` types
instead.  Remove the Unix headers as the only headers really needed are
the C standard headers.  Provide shims for deprecated `strings.h`
functions in terms of "modern" (C89+) functions from `string.h`.  Move
an android only include into the implementation from the interface.

This enables building this library on Windows.

Co-Authored-By: George Barnett <gbrntt@gmail.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-03-09 16:15:38 +00:00
Johannes Weiss ffb196f544 Thread: repair build on Windows after #1433 (#1434)
This repairs the build on Windows after the thread implementation was
split out.
2020-03-05 08:32:51 +00:00
Doug FriedmanandJohannes Weiss 51238f4df8 Prevent execution of tasks on an already shutdown EL (#1395)
* prevent execution of tasks on an already shutdown EL

* fixup! prevent execution of tasks on an already shutdown EL

* fixup! prevent execution of tasks on an already shutdown EL

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-03-04 17:20:13 +00:00
Shekhar RajakandJohannes Weiss 95f014c9ba use Posix.read instead of Glibc.read for timerfd (#1432)
Motivation:

To read the bytes from timerfd, we use Glibc.read directly but we should use try! Posix.read

Modifications:

Using Posix instead of Glibc for read operation with try! to check for any error.

Result:

Fixes #1341

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-03-04 16:51:30 +00:00
Shekhar Rajak 2900f03352 ByteToMessageDecoder: Default implementation for decodeLast should be provided (#1426)
* removed decodeLast function from NIOChatServer

* updated decodeLast function from WebSocketFrameDecoder

* default implementation of decodeLast function

* removed implementation of decodeLast in WebSocketFrameDecoder
2020-03-04 16:22:06 +00:00
Johannes Weiss a5e35655e6 fix macOS build & cleanup Thread (#1433)
Motivation:

The macOS build was broken by #1424, also the Thread.swift file became
a bit of a mess with `#if os(...)/#else` everywhere.

Modifications:

- fix macOS build
- cleanup Thread by splitting it into ThreadPosix & ThreadWindows

Result:

- build working again
- cleaner code
2020-03-04 15:12:10 +00:00
Saleem AbdulrasoolandJohannes Weiss 546a84c4e1 Thread: port to Windows (#1424)
This restructures `Thread` to have a more generic representation of a
thread handle.  Using that it is possible to have an implementation of
the threading APIs for Windows.

Similarly, introduce an abstraction over the Thread Specific Key.  This
allows us to abstract away the key type and the usage.

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-03-03 20:21:45 +00:00
Saleem AbdulrasoolandJohannes Weiss 5e728b5786 NIOConcurrencyHelpers: port to Windows (#1403)
Add support for Windows to the `NIOConcurrencyHelpers`, replacing the
`pthreads` usage for Windows threading primitives.

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-03-03 19:18:59 +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
Kyle Browning 06cdd7f619 Allow discardable results on NIOAtomic for mutating functions (#1417)
* Allow discardable results on NIOAtomic for mutating functions

* Address nits.

* add a tests.

* Removes discards.
2020-02-26 21:43:35 +00:00
Saleem AbdulrasoolandJohannes Weiss 1595c42b9a CNIOAtomics: define types for uintptr_t and intptr_t (#1401)
On LLP64 hosts, `Int` is mapped to `intptr_t` and `UInt` to `uintptr_t`.
As a result, we need to ensure that we map the atomic extensions to
those types for type conversions.

Add the types for `uintptr_t` and `intptr_t` so that they can be used to
implement `CNIOConcurrencyHelpers` on Windows.

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-02-26 17:07:39 +00:00
trungducc 8ad2549a49 Stop copying Strings into Arrays for SHA1 (#1413)
Motivation:

Resolve #1409

Modifications:

Using withContiguousStorageIfAvailable if string.utf8 supports an internal representation in a form. Otherwise, fall back to use withUnsafeBufferPointer.

Result:

Save an allocation for each hash function update
2020-02-25 08:52:36 +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
Shekhar Rajak 58a80c300e Use UInt instead of ObjectIdentifier in promiseCreationStore (#1411)
* Use UInt instead of ObjectIdentifier in promiseCreationStore

* defined obfuscatePointerValue method
2020-02-24 17:01:16 +00:00
2c555d144a NIOConcurrencyHelpers: make LLP64 friendly (#1402)
On LLP64 platforms, `Int` is mapped to `intptr_t` and `UInt` is mapped
to `uintptr_t`.  Use the newly minted `CNIOAtomics` operations to
support these semantics.

Co-authored-by: Cory Benfield <lukasa@apple.com>
Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-02-19 19:05:58 +00:00
PeterAdams76andJohannes Weiss 0db1cd5318 Add custom index methods to ByteBufferView (#1394)
Motivation:

The performance of firstIndex and lastIndex is
dramatically improved by addding custom
indexing methods as detailed in issue 1385.

Modifications:

Added methods to ByteBufferView:
_customIndexOfEquatableElement
for firstIndex
_customLastIndexOfEquatableElement
for lastIndex

Added a unit test for firstIndex and lastIndex
to ensure functional behaviour is unchanged.

Result:

firstIndex and lastIndex behave as before.

Performance is improved by approximately 20% for
the shortest searches.
When tested searching over 1024 byte buffer
with either no match or a match at the end
I observed approximately 15 times performance

Co-authored-by: Johannes Weiss <johannesweiss@apple.com>
2020-02-19 18:12:38 +00:00
Saleem AbdulrasoolandCory Benfield 1832cff669 CNIOAtomics: declare atomic operations using a macro (#1400)
Use a macro to define the interface for the typed atomics.  This reduces
the boiler plate that is expanded by hand.  More importantly, it makes
it easier to add new types in the future.

Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-02-18 10:24:20 +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
Johannes Weiss 16ab4d657e add AcceptHandler after serverChannelInitializer runs (#1393)
Motivation:

For compatibility with 2.13.1 and earlier, we're adding the
AcceptHandler after the serverChannelInitializer runs. If that's the
best solution is discussed in #1392.

Modifications:

- add AcceptHandler after the serverChannelInitializer
- give the AcceptHandler the name AcceptHandler

Result:

- better compatibility
2020-02-13 12:55:52 +00:00
Cory Benfield bfde40cac8 Update http-parser for CVE. (#1387)
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.
2020-02-10 16:44:44 +00:00
Johannes Weiss c6e5fe88e1 ByteBuffer: make getInteger for UInt8 faster (#1380)
Motivation:

getInteger used the normal, generic implementation for UInt8s, however
they can be made considerably faster by using a specialised method.
ByteBufferIterator was also affected by this.

Modifications:

Use a specialised version for UInt8s for getInteger.

Result:

- ByteBufferView can be iterated about 20% faster.
2020-02-06 11:59:10 +00:00
Johannes Weiss d1ef9be53c update vendored code & attribute it correctly (#1382)
Motivation:

This updates all vendored code and also lets github know what's vendored
code through `.gitattributes`.

Modifications:

- http_parser update
- attribution

Result:

- better github stats
- up to date software
2020-02-05 15:04:35 +00:00
George Barnett a678727747 Provide descriptions for EventLoopError (#1381)
Motivation:

EventLoopError does not conform to CustomStringConvertible. When these
errors appear in programs depending on NIO the source of the error is
non-obvious to the user.

EventLoopError.shutdown, for example, would appear in logs as
"shutdown" with no indication that it was the event loop being referred
to.

Modifications:

- Conform EventLoopError to CustomStringConvertible

Result:

- More helpful error descriptions for EventLoopError
2020-02-05 11:26:41 +00:00
George Barnett c92a9c638c Reserve capacity in terms of writable bytes (#1378)
Motivation:

Often we know ahead of time that we will need to write a certain number
of bytes into a buffer. It is useful to ensure the buffer has enough
capacity to store these bytes without causing unnecessary allocations.
However, `reserveCapacity()` is defined in terms of the capacity of the
buffer and it's can be easy to forget that this does not take into
account the writer index.

Modifications:

- Add a method which reserves enough capacity to write at least the
  specified number of bytes.
- Update `writeWithUnsafeMutableBytes(minimumWritableBytes:body:)` to use the
  new method.

Result:

It's easier for users to reserve enough writable capacity ahead of time.
2020-02-04 14:38:11 +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
ba37512da9 apply ChannelOptions before channel initializer runs (#1372)
Motivation:

The channel initializers should see the the Channel after the options
have been applied so they can potentially override the options.

Modifications:

Set the options before the channel initialiser rather than after.

Result:

- More sense, more compatibility with Netty
- fixes #1114

Co-authored-by: George Barnett <gbrntt@gmail.com>
Co-authored-by: Cory Benfield <lukasa@apple.com>
2020-02-01 10:21:54 +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
Fabian Fett 5dc9083c6a Recursive file reading not building up EventLoopFuture chain (#1353)
* Recursive file reading not building up EventLoopFuture chain

# Motivation:

After a long discussion with @adam-fowler today in aws-sdk-swift about how to recursively build a streaming interface (see https://github.com/swift-aws/aws-sdk-swift-core/pull/181), we came to the conclusion that it’s probably for the best not to build up an EventLoopFuture chain, since all EventLoopFutures are kept in memory while iterating. It would be better to create a promise that is captured by the recursive function, because in this case the internal EventLoopFutures can be released.

The memory footprint should be O(1) instead O(n) with a EventLoopFuture chain.

Later today, @adam-fowler made me aware of this code in NIO and that it uses a chain.

# Modifications:

```swift
_read(remainingReads: Int, bytesReadSoFar: Int64)
```

The internal read function no longer returns an EventLoopFuture. All Futures end with an `whenSuccess` or `whenFailure` case.

# Result:

From my understanding the memory footprint should be reduced when reading large files. The interface stays completely the same.
2020-01-27 13:33:50 +00:00
Christian PriebeandJohannes Weiss 4409b57d4c Rename misnamed closure parameter argument in ServerBootstrap.bind0 (#1347)
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>
2020-01-22 15:13:34 +00:00
Christian PriebeandJohannes Weiss 03d90a6f2d Add setSubstring/writeSubstring to ByteBuffer. (#1346)
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>
2020-01-22 14:45:40 +00:00
Johannes Weiss 45bca5672c improve flushNow re-entrancy protection (#1348)
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
2020-01-22 12:08:15 +00:00
Christian Priebe 84a33c5cdd Add bindTimeout function to ServerBootstrap (#1349)
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.
2020-01-22 11:26:51 +00:00
Johannes Weiss 99ca704088 improve flushNow behaviour tests & description (#1345) 2020-01-20 15:55:47 +00:00
Johannes Weiss 6633f54708 support pread (#1324) 2020-01-20 09:56:54 +00:00
Johannes Weiss ca0ed86766 flushes from channelWritabilityChanged callbacks get lost (#1344) 2020-01-18 09:05:37 +00:00
Volodymyr Sapsai eb2dfd8d1b Fix documentation for HTTPRequestDecoder. (#1342)
There is no `ChannelPipeline.addHTTPServerHandlers` but there is `ChannelPipeline.configureHTTPServerPipeline`.

Comment for `HTTPResponseDecoder` mentioning `ChannelPipeline.addHTTPClientHandlers` is correct.
2020-01-16 09:51:53 +00:00