875 Commits
Author SHA1 Message Date
Cory Benfield 8da5c5a4e6 Update http-parser for CVE. (#1388)
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)
2020-02-10 15:31:16 +00:00
Romain Pouclet 381fd99df2 Actually remove promise logging info. (#752) (#987)
Motivation:

While it's really a good idea to keep track of where promises get
allocated, once the promise has been fulfilled we probably don't
need to keep track of it any more.

Happily this leak only affects debug mode.

Modifications:

- Actually removed the element from the promise log when we
  said we would.

Result:

Memory usage doesn't get totally out of hand in debug mode.
2019-04-30 21:21:18 +01:00
Daniel Alm ba7970fe39 Make EventLoopFuture.hopTo(eventLoop:) public again. (#963) 2019-04-11 09:14:56 +01:00
Johannes Weiss 02c11d9007 Simplify Heap implementation. (#961)
Motivation:

Our original Heap implementation used a bunch of static functions
in order to make it clear how it related to textbook heap
implementations. This was primarily done to ensure that it was easier
to see the correctness of the code.

However, we've long been satisfied with the correctness of the code,
and the Heap is one of the best tested parts of NIO. For this reason,
we should be free to refactor it.

Given https://bugs.swift.org/browse/SR-10346, we've been given an
incentive to do that refactor right now. This is because the Heap
is causing repeated CoW operations each time we enqueue new work
onto the event loop. That's a substantial performance cost: well
worth fixing with a small rewrite.

Modifications:

- Removed all static funcs from Heap
- Rewrote some into instance funcs
- Merged the implementation of insert into append.
- Added an allocation test to avoid regressing this change.

Result:

Faster Heap, happier users, sadder textbook authors.

(cherry picked from commit f79c7aea2e)
2019-04-10 14:53:35 +01:00
Daniel Alm 6b914e891f Backport whenAll[Succeed] to NIO 1 (#947)
* Cherry-pick "Significantly improve the performance of `EventLoopFuture.{and,when}AllSucceed`. (#943)"

* NIO 1 fixes.
2019-04-08 22:56:28 +01:00
Johannes Weiss 29a9f2aca7 Selector: make sure timerfd is level triggered (#881)
Motivation:

In the Selector (because of the deregistrationsHappened workaround) we
expect all events to be level triggered. If there are deregistrations,
we just expect epoll/kqueue to deliver the event again. But timerfd was
configured as `EPOLLET`. That means is a timer fires after some
deregistrations, we lose it.

Modifications:

make timerfd level triggered

Result:

- no more timer stalls
- fixes #872

(cherry picked from commit c8ac593b39)
2019-03-08 18:24:06 +00:00
Daniel Alm 3bd0fc5128 Make NIOAny log the contents of its storage when encountering fatal unwrapping errors. (#879)
Motivation:
This should make debugging crashes easier, as knowing the contents of the badly-unwrapped `NIOAny` should make it more clear where exactly it could have been written. Personally I'd prefer this to never cause a fatal error, but I assume that would need more discussion.
2019-03-07 11:08:26 +00:00
Johannes Weiss 87dbd0216c fix new Swift 5 warnings for NIO 1 (#850)
Motivation:

Swift 5 brought a bunch of new warnings for NIO 1.

Modifications:

fix the warnings

Result:

happier compiles
2019-02-28 11:55:37 +00:00
Jari (LotU) 98434c1f1d Allow to set RemoveAfterUpgradeStrategy on HTTPResponseDecoder (#744)
* Allow to set RemoveAfterUpgradeStrategy on HTTPResponseDecoder
2019-01-23 08:58:52 +00:00
Johannes Weiss 03c541a24d speed up getBytes (#762)
Motivation:

Due to https://bugs.swift.org/browse/SR-9604, ByteBuffer.getBytes
seriously regressed (factor 10x) since NIO 1.11 . This works around it
until the issue is fixed.

Modifications:

bind the memory to UInt8s to get an UnsafeBufferPointer<UInt8> rather
than an UnsafeRawBufferPointer.

Result:

- getBytes 10x faster
- make @John-Connolly happy, thanks for reporting!

(cherry picked from commit 264fbe0f315bd50e4a5b81b92ffc5cc93dc558f3)
2019-01-22 08:49:12 +00:00
Johannes Weiss 37457897d9 remove bogus 'is active' assertion in channelRead0 (#740)
(cherry picked from commit 722ceb869d)

Motivation:

BaseSocketChannel used to assert that `channelRead0` is only called when
the channel is active. That's bogus and it's trivial to hit this issue
when calling `fireChannelRead` in the last `ChannelHandler` when the
channel has gone inactive.

Modifications:

remove assertion, add comment

Result:

fewer crashes
2019-01-07 13:49:51 +00:00
Ilya Puchka 37237d880c override content encoding header value in compressor
Resolves #717

Motivation:

Content encoding header may contain invalid value if handlers before compressor have already set it.

Modifications:

Instead of headers.add which appends header value use headers.replaceOrAdd which replaces existing value

Result:

If Content-Encoding header was set to some value, compressor will reset it to the value of compression algorithm it have picked.
2019-01-04 14:05:53 +00:00
Florent Pillet 8df414b716 Fix: BlockingIOThreadPool not releasing the latest WorkItem (#716)
BUGFIX: BlockingIOThreadPool not releasing the latest WorkItem

Fix is to clear the latest work item just before waiting for
the next one to be submitted.

Added two tests to validate the fix: submitting only one work item
to an IO thread pool, and submitting two consecutive work items.

Thanks to Gwynne Raskind for help troubleshooting & fix
2019-01-02 23:02:49 +00:00
Johannes Weiss a20e129c22 change newPromise(for: T.Type) to newPromise(of: T.Type) (#672)
Motivation:

making a promise of a type is more grammatical than making a promise for
a type.

Modifications:

s/newPromise(for/newPromise(of/g

Result:

more grammar
2018-11-28 17:32:07 +00:00
Johannes Weiss c1a84a0085 optional type parameter for newPromise() (#671)
Motivation:

When creating new promises I always find it very frustrating to type the
`: EventLoopPromise<Type>` type annotation but it's necessary for the
compiler to know type the promise will be fulfilled with.

Modifications:

allow an optional `for: SomeType.self` parameter for `newPromise` as

    let p = eventLoop.newPromise(for: Int.self)

is much easier to type than

    let p: EventLoopPromise<Int> = eventLoop.newPromise()

Result:

easier to write code
2018-11-28 12:18:03 +00:00
Bouke Haarsma 29398d5f26 Assign channel variable in docs (#662) 2018-11-27 08:09:06 +00:00
Kyle Jessup ac9e5d02ac Added public init for HTTPServerProtocolErrorHandler (#660) 2018-11-23 15:29:09 +00:00
Johannes Weiss c66386eb3a don't capture in the callout closures in BaseSocketChannel (#658)
Motivation:

We were complaining that we can't use `@convention(thin)` in a place
where we really need to make sure we don't get allocations for returning
a closure (that doesn't capture any context), so it should just be a
function pointer.

In reality however, we were actually capturing context...

Modifications:

Don't capture context anymore.

Result:

Closures should not actually not enclose anything.
2018-11-21 09:48:06 +00:00
Johannes Weiss cf958fb5a5 ignore pthread_setname_np result (#656)
Motivation:

We have seen pthread_setname_np fail with EPERM in containers, it's
non-critical so best to ignore.

Modifications:

ignore pthread_setname_np's return code.

Result:

works in containers.
2018-11-16 20:01:11 +00:00
Jim Dovey bf0cd5295e Make the member variables of HTTPHeader and HTTPHeaderIndex visible to swift-nio-http2. (#654) 2018-11-15 10:46:27 +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
Cory Benfield a0b3b19cf4 Provide ChannelPipeline.remove methods with promises. (#651)
Motivation:

ChannelPipeline.remove0 contains a comment that indicates that users
were expected to be able to use the ChannelHandlerContext when both
handlerRemoved and the promise for channel removal call out.

This works when invoking remove() from outside the event loop, but if
a handler invokes remove on itself then it will only be able to attach
a callback to the future *after* the callout occurs. This means that a
ChannelHandler removing itself from the pipeline cannot rely on there
being a moment when it can still invoke the ChannelHandlerContext, but
when it is no longer a formal part of the pipeline.

This kind of behaviour is useful in some unusual cases, and it would
be nice to support it.

Modifications:

- Added remove() methods that accept promises as input.
- Rewrote the current remove() methods in terms of the new ones.
- Added tests.

Result:

ChannelHandlers can perform cleanup with a valid ChannelHandlerContext
but outside the Channel.
2018-11-07 11:50:51 +00:00
Johannes Weiss 035962e6b6 EventLoop.assertInEventLoop and preconditionInEventLoop (#644)
Motivation:

Dispatch can only precondition that code is run from a certain queue, it
can't return if code is running on a certain queue.
To support that this introduces new EventLoop.assertInEventLoop and
EventLoop.preconditionInEventLoop methods instead of
assert(eventLoop.inEventLoop).

Modifications:

add EventLoop.assertInEventLoop and EventLoop.preconditionInEventLoop

Result:

better support for Network.framework in NIOTS
2018-11-05 09:50:33 +00:00
Johannes Weiss 26bee21674 fix Swift 5 warnings (mostly redundant modifiers (#642)
Motivation:

Swift 5 complains on redundant modifiers. For example declaring a
`public func` inside of a `public extension` is now a warning. I don't
agree with this but I dislike warnings even more, so...

Modifications:

remove all redundant modifiers that the compiler now warns about such as

    swift-nio/Sources/NIOPriorityQueue/PriorityQueue.swift:90:5: warning: 'public' modifier is redundant for property declared in a public extension

Result:

no warnings in Swift 5
2018-11-01 09:50:55 +00:00
Johannes Weiss 054f65e473 add String blitting benchmarks (#641)
Motivation:

Writing Strings to ByteBuffers is important, let's have some more
benchmarks.

Modifications:

add String to ByteBuffer benchmarks

Result:

more benchmarks
2018-10-30 23:41:20 -07:00
Johannes Weiss ab69133269 ByteBuffer: small & medium sized string copies over 10% faster (#640)
Motivation:

urbp[start ..< end] is quite a bit faster than when done in two
operations urbp.dropFirst(start).prefix(length). This improves small (4
bytes) & medium sized (24 bytes) String copies by over 10%. Good for
HTTP headers etc.

Modifications:

replace urbp.dropFirst(start).prefix(length) by urbp[start ..< start +
length]

Result:

small & medium sized String copies faster
2018-10-30 21:01:19 +00:00
Johannes Weiss ee9a229a33 String decoding: go through URBP directly instead of Slice (#639)
Motivation:

String decoding can work faster when going through URBP directly instead
of a Slice of a URBP. The reason is that if the String has the utf8
represenation stored directly it'll just be a memcpy (+ validation).

Modifications:

go through URBP when decoding a String using String(decoding:as:)

Result:

faster if the String utf8 representation happens to be available
2018-10-30 08:20:21 +00:00
Norio Nomura 287d50c373 CONNECT method should not have request body (#637)
* CONNECT method has no request body

### Motivation:

[rfc7231](https://tools.ietf.org/html/rfc7231#section-4.3.6) said:
> A payload within a `CONNECT` request message has no defined semantics;
   sending a payload body on a `CONNECT` request might cause some existing
   implementations to reject the request.

### Modifications:

Change `HTTPMethod.CONNECT.hasRequestBody` to returns `.no`.

### Result:

`HTTPRequestEncoder` does not generate chunked body for `CONNECT` method.

* Change `HTTPMethod.CONNECT.hasRequestBody` to returns `.unlikely`
2018-10-29 22:54:52 -07:00
Johannes Weiss 6e6c68c1b2 verify that IOThreadPools get shut down (#635)
Motivation:

Not shutting down IOThreadPools leads to thread leaks so we should
verify they're actually shut down.

Modifications:

add a check that we're shutting down

Result:

fewer thread leaks
2018-10-29 09:51:31 -07:00
Johannes Weiss 176dd6e856 fix potential deadlock in BlockingIOThreadPool (#634)
Motivation:

BlockingIOThreadPool used to call out with a lock held and on top of
that on the wrong thread...

Modifications:

Make BlockingIOThreadPool call out on the supplied `queue`

Result:

fewer deadlock and surprises
2018-10-19 16:52:51 +01:00
Johannes Weiss 9bae007a15 use umbrella headers for C modules (#636)
Motivation:

SwiftPM only generates fully usable clang modules for C modules if they
have umbrella headers. Therefore, adding a generated NIO.xcodeproj to
another Xcode project as a sub-project never worked.
To make a header an umbrella header you need to name them _exactly_ like
the module.

Modifications:

give each C module an umbrella header

Result:

generated NIO Xcode projects can be used as sub-projects.
2018-10-19 14:49:43 +01:00
Johannes Weiss ed28803a78 update http_parser.c (#627)
Motivation:

There was an outstanding change in http_parser.c that we did not yet
have in our copy.

Modifications:

run the update http parser script and add changes as well as a test case
designed to hit the change.

Result:

ship the latest and greatest
2018-10-16 10:27:44 +01:00
Gopal Sharma 8d7d4cb9ca Fix minor typo (#626) 2018-09-30 08:19:08 +01: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 be4ea8ac74 Add SocketOptionChannel for wider socket options. (#589)
Motivation:

A small number of socket options have values that do not fit into a C
int type. Our current ChannelOption based approach for setting these
simply does not work, and cannot be extended to support the truly arbitrary
types that the setsockopt/getsockopt functions allow here.

This makes it impossible to use some socket options, which is hardly a
good place to be.

There were a number of ways we could have addressed this: we could have
special-cased all socket options with non-integer types in ChannelOption,
but I believe that would be too manual, and risk limiting users that need
to set other socket options. We could also have added a ChannelOption
that simply allows users to pass a buffer to write into or read from,
but that is a very un-Swift-like API that feels pretty gross to hold.

Ultimately, the nicest seemed to be a new protocol users could check
for, and that would provide APIs that let users hold the correct concrete
type. As with setsockopt/getsockopt, while this API is typed it is
not type-safe: ultimately, the struct we have here is treated just as a
buffer by setsockopt/getsockopt. We do not attempt to prevent users from
shooting themselves in the foot here.

This PR does not include an example use case in any server, as I will
provide such an example in a subsequent multicast PR.

Modifications:

- Added a SocketOptionChannel protocol.
- Conformed BaseSocketChannel to SocketOptionChannel.
- Wrote some tests for this.

Result:

Users can set and get sockopts with data that is larger than a C int.
2018-09-18 13:40:38 +02:00
Norman Maurer a0c6cffc88 Correct propagate channelActive events to the next handler when using… (#615)
* Correct propagate channelActive events to the next handler when using IdleStateHandler.

Motivation:

We missed to propagate the channelActive event to the next handler in IdleStateHandler, which means handlers placed after it in the pipeline will never receive such an event.

Modifications:

- Correctly call ctx.fireChannelActive()
- Add unit test to assert we forward all inbound events.

Result:

Fixes https://github.com/apple/swift-nio/issues/614.
2018-09-13 09:09:15 +02:00
Johannes Weiss 463f8d95d2 EventLoopPromise didn't point out it has reference semantics (#612)
Motivation:

Sometimes people assume that all `struct`s have value semantics but
that's not true. We should still point that out.

Modifications:

point out that EventLoopPromise has reference semantics

Result:

clearer docs
2018-09-11 15:16:06 +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
Norman Maurer bf8c642896 Include ipaddress in SocketAddress.description. (#601)
Motivation:

WE should include the ipaddress in the description of SocketAddress if any way used as there may be no host at all.

Modifications:

- Always include ipaddress if possible.
- Add unit tests.

Result:

More useful description of the SocketAddress
2018-08-30 20:46:08 +02:00
Johannes Weiss 501af860f5 allow two distinct ChannelOptions of one type (#597)
Motivation:

Quite embarrasingly, we previously would only store one `ChannelOption`
per `ChannelOption` type. Most channel option types are distinct and
that's probably why it took so long to find this issue. Thanks
@pushkarnk for reporting. Unfortunately though, the most important
`ChannelOption` is `.socket` which crucially also holds a level and a
name. That means if you set two `ChannelOptions.socket` options with
distinct name/level, one would still override the other.

Example:

    .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEPORT), value: 1)
    .serverChannelOption(ChannelOptions.socket(SocketOptionLevel(SOL_SOCKET), SO_REUSEADDR), value: 1)

would only actually set the latter.

Modifications:

- made all common `ChannelOption` types equatable (for 2.0 this will
  be a protocol requirement)
- deprecated non-Equatable `ChannelOption` types
- zero out buffer before calling getsockopt as Linux doesn't do that

Result:

you can now set two distinct `ChannelOptions` for one type
2018-08-29 15:24:58 +01:00
Johannes Weiss df764fedf0 don't crash when Channel goes inactive in read triggered by write error (#594)
Motivation:

Previously we asserted that a Channel cannot go inactive after calling
out for a read that was triggered by (draining the receive buffer after)
a write error.

This assertion was put in place to guard against `readComplete` events
sent on inactive channels. It did that job just fine but crashes aren't
great so we now conditionally fire the `readComplete` event if the
Channel stays active.

Modifications:

make the readComplete event firing conditional

Result:

fewer crashes, more happy faces
2018-08-27 11:49:58 +01:00
Johannes Weiss ce0c6d92e9 pipeline handler: fix error state tracking (#595)
Motivation:

@pushkarnk hit an interesting edge case that we previously mishandled
and crashed. All these conditions need to be true

1. Whilst have an ongoing request (ie. outstanding response), ...
2. ... a `HTTPParserError` arrives (which we correctly queue)
3. Later the outstanding response is completed and then ...
4. ... the `HTTPServerProtocolErrorHandler` sends a .badRequest response

We previously crashed. The reason we crashed is that the
`HTTPServerPipelineHandler` obviously tracks state and then asserts that
no response is sent for a wrong request. It does have an affordance to
allow a .badRequest response for a request it couldn't parse. However
this state tracking wasn't done if the error itself was enqueued for
later delivery.

Thanks very much @pushkarnk for the report!

Modifications:

instead of delivering the error directly use the `deliverOneError`
function which transitions the state correctly.

Result:

fewer crashes & hopefully happy Pushkar
2018-08-27 11:09:51 +01:00
Johannes Weiss 8ecced9e24 warn that ChannelHandlers should be instantiated within initializer closures (#590)
Motivation:

For (stateful) ChannelHandlers it's very important that the
ChannelHandlers get instantiated _within_ the bootstrap's initializer
closures (and not before that).

Modifications:

Add warnings about the fact that they should be instantiated within the
closures.

Result:

- better docs
- more correct user code
2018-08-24 09:04:44 +02:00
Johannes Weiss 927034f7de mark more Collections as ContiguousCollections (#586)
Motivation:

All the mutable variants and also some slices of clearly contiguous
collections weren't marked as ContiguousCollections but they should be.

Modifications:

- made UnsafeMutable[Raw]BufferPointer a ContiguousCollection
- made Slice<UnsafeRawBufferPointer> a ContiguousCollection

Result:

faster code
2018-08-23 17:18:51 +01:00
Johannes Weiss aaf434022f fix limits on 32-bit systems to values that work (#580)
Motivation:

We should have different constants for 32-bit systems where necessary
for example all the maximums should be Int32.max and not UInt32.max
because UInt32.max doesn't fit into an Int on 32-bit platforms. But
where unnecessary 32-bit and 64-bit should share maximum values.

Modifications:

- removed some constraints that should be unnecessary
- skip tests that can't work on 32-bit systems

Result:

better and more consistent 32-bit runs
2018-08-23 10:38:47 +01:00
Johannes Weiss 7de224eaf3 better documentation for MultiThreadedEventLoopGroup (#582)
Motivation:

MultiThreadedEventLoopGroup's docs didn't make it clear that you leak
threads if not shut down.

Modifications:

Add clarification that you should shut down
MultiThreadedEventLoopGroups.

Result:

hopefully clearer documentation.
2018-08-21 11:43:42 +01:00
Matt Eaton 7895bc88fd Enhanced the output of the NIOEchoClient Example (#585)
Motivation:

I was testing the NIOEchoClient example on Linux and noticed that I received no character output.
I thought this would be handy and added this code to do so.

Modifications:

Small modification to the channelRead method in NIOEchoClient to read the bytes and transform to a string.

Result:

The display of the characters on your echo client before the channel closes.
2018-08-20 11:45:16 +01:00
Cotton Hou ee52d7694a Typo in EchoServer example (#583) 2018-08-18 18:44:32 +01:00