We have an unexpected rooted cycle that's unexpectedly keeping an HttpConnectionPoolManager and all of its state alive indefinitely if the HttpClient/SocketsHttpHandler isn't Disposed.
HttpConnectionPoolManager creates a "cleaning timer" that runs every now and then in order to remove stale connection pools that are no longer needed. In order to do that, the Timer is passed the HttpConnectionManagerPool as state. That normally wouldn't be a problem, except that the HttpConnectionManagerPool then stores a strong reference to the Timer, creating a cycle: Timer -> TimerHolder -> TimerQueueTimer -> HttpConnectionPoolManager -> Timer. The TimerQueueTimer is rooted by the underlying timer implementation, with it stored in a static array. And TimerHolder has a finalizer that disposes of the Timer, but it's being kept alive as part of the cycle.
To break the cycle, we give the Timer a weak reference (rather than strong reference) to the HttpConnectionPoolManager.
Commit migrated from https://github.com/dotnet/corefx/commit/449190d7c873b56337ba6a7f2d9b53f5232ad16d
SocketAsyncEventArgs has a few issues with ExecutionContext, presumably stemming from the fact that capturing ExecutionContext in .NET Framework is not a cheap operation. As a result, when this code was written, it was optimized for avoiding calls to ExecutionContext.Capture. The SAEA tries to hold onto a captured ExecutionContext for as long as possible, only re-capturing when either the SAEA is used with a different socket instance or when an event handler is changed. That has several problems, though. First, it largely violates the purpose of ExecutionContext, which is to flow information from the point where the async operation begins to the continuation/callback, but if the context is only being captured when the Socket or handler is changed, then the context isn't actually tied to the location where the async operation begins, and that means that data like that in an AsyncLocal doesn't properly flow across the async point. Second, it means that the SocketAsyncEventArgs (the whole purpose of which is to cache it) can end up keeping state in an ExecutionContext alive well beyond when it should be kept alive, because the SocketAsyncEventArgs is holding onto the ExecutionContext instance until either the Socket or handler is changed.
This commit fixes this behavior. Since ExecutionContext.Capture in .NET Core is relatively cheap (no allocation, primarily just a ThreadStatic access), we now just always capture the context when starting an operation, and then clear it out when completing the operation.
Commit migrated from https://github.com/dotnet/corefx/commit/851a53bee21639cd65e109b72fd5f9ef90cc0f39
SocketsHttpHandler wasn't even trying to send Negotiate/NTLM auth tokens to a proxy. This was due
to some invalid logic regarding the "usingProxy" field in HttpConnection. Reworked this logic to
be clearer about the various kinds of proxy scenarios.
I refactored the loopback proxy server and made it much more robust. It can now handle multiple
requests and multiple connections which helps test against the other handlers whose behavior is
different in this area. I plan to do further work in consolidating the LoopbackServer and
LoopbackProxyServer classes in future PRs.
I created a separate HttpClientHandlerTest.Proxy.cs file and moved many existing proxy tests and
added new tests. The current HttpClientHandlerTest.cs file is still over 3000 lines and needs more
refactoring to make it easier to maintain and track test scenario coverage.
Fixesdotnet/corefx#30330
Commit migrated from https://github.com/dotnet/corefx/commit/ec1671fd7feffe1070a94d9d86379e0dd95ddcdf
To behave similarly to netfx and WinHTTP, which ensure some known methods are sent uppercased. They differ on exactly which, so I've standardized on doing the ones for which HttpMethod has static properties. Since we're paying for this normalization, I've then taken advantage of it to use reference comparisons on the HttpMethod instances where we're later checking for known methods, and I also removed an allocation from HttpMethod's GetHashCode, since we're now storing these in a dictionary which uses GetHashCode.
Commit migrated from https://github.com/dotnet/corefx/commit/02b11fae98fd2d6662e1c490cae8462b0ce1ecdf
Similar to PR dotnet/corefx#29988, testing implementation details of SocketsHttpHandler behaviors
doesn't make sense against the other handlers.
Running HTTP tests generally across all the handlers is useful when we're trying to
validate HTTP protocol and API behaviors to be consistent everywhere.
However, testing SocketsHttpHandler implementation details, such as connection-pooling
algorithms, with other handlers leads to brittle tests with random test failures. The
internal code of each handler and native code (i.e. WinHTTP) use different rules
(timeouts, lifetime, etc.) for such low-level connection details.
So it makes sense to only run tests such as this against the code that was written to
match the tests, i.e. SocketsHttpHandler.
Closesdotnet/corefx#27272
Commit migrated from https://github.com/dotnet/corefx/commit/31f7b653fe62317c7edd5c3fc59430462197934d
Fixed a few bugs in both WinHttpHandler and SocketsHttpHandler regarding the behavior of
'Accept-Encoding' request headers and automatic decompression of response body content.
On Windows 7, native WinHTTP doesn't support automatic decompression. That also means it doesn't automatically append 'Accept-Encoding' request headers. WinHttpHandler was relying on WinHTTP to add those headers. But it wasn't happening on Windows 7. So, now WinHttpHandler will make sure those headers are added if not already present. WinHttpHandler was also always decompressing content even when the encodings in the .AutomaticDecompression property didn't match.
SocketsHttpHandler had a different bug. It would make sure that the 'Accept-Encoding' headers were
present when .AutomaticDecompression was being used. But it wouldn't check for existing headers and duplicate encodings would be present in the outbound 'Accept-Encoding' request header. I.e., it would end up with "Accept-Encoding: gzip, gzip".
In addition to fixing these bugs, I added more tests to both Http Functional and WinHttpHandler Unit
tests (which can simulate running on Windows 7 using the existing mocks).
Fixesdotnet/corefx#29747Fixesdotnet/corefx#26991
Commit migrated from https://github.com/dotnet/corefx/commit/40ce4cb20270f731d7d826291e1edce8d1ce2c37
* Fix SocketsHttpHandler handling of pooling timeouts with max connections
Fixes two cases:
1. When a pooling timeout (lifetime or idle) is set to 0, we fail to enforce the MaxConnectionsPerServer limit.
2. When MaxConnectionsPerServer is set and the limit is reached, when a request completes and we transfer the connection from the completing request to a waiting request, we fail to check / enforce the connection lifetime limit.
* Address PR feedback
Commit migrated from https://github.com/dotnet/corefx/commit/50e30118b37db1c3a48a0920e670b9ca5f9631d4
* Add two missing ConfigureAwait(false) calls in SocketsHttpHandler
ChunkedTransferEncodingReadStream's ReadAsync had one await missing a ConfigureAwait(false). If there's a synchronization context set on the calling thread, this results in a continuation being created that posts back to that context, which can cause problems (e.g. deadlocks) if that context is blocked, e.g. if the synchronous Read method is being used to block waiting for ReadAsync to complete. The fix is simply to add `.ConfigureAwait(false)`.
As long as I was fixing that, I also reviewed all `await`s in SocketsHttpHandler and found one more that was missing `.ConfigureAwait(false)`, in HttpConnectionPool's EstablishProxyTunnel, and so fixed that, too.
And added some tests.
* Refactor ContentMode support in tests
Commit migrated from https://github.com/dotnet/corefx/commit/9e8c200f0888a1db590da8ffa026aa7384771611
- Add “Connection: close\r\n” response header in more cases where the loopback server explicitly closes a connection, and in particular where the client makes multiple connections.
- Change several Task.WaitAlls on paired tasks to instead use our WhenAllOrAnyFailed helper.
Commit migrated from https://github.com/dotnet/corefx/commit/cebcf436358600a4808656b142a74f57d1e8f6f0
Now that the authentication test failures have been diagnosed, re-enable most of the Digest authentication test cases on CurlHandler. Four additional cases had to be moved to the SocketsHttpHandler only tests, since they fail on CurlHandler and do not have fixes yet.
The digest test cases have to use credentials without a domain when run against CurlHandler. This is because Curl does not allow us to set the realm parameter used to send the domain along with a digest authorization header.
Commit migrated from https://github.com/dotnet/corefx/commit/0257e6cc85c3a0421cb99a473fa187a43eb46b6a
Adds a small test to visit a list of sites using SocketsHttpHandler and allow easy debugging and comparison with platform handlers in case one needs to investigate. The tests are disabled by default and are controlled by Xunit traits.
Commit migrated from https://github.com/dotnet/corefx/commit/8e18a0e0453654ed88c3729ffad580dff984601a
When SocketsHttpHandler puts a connection back into the pool, it issues a pre-emptive asynchronous read on the transport stream. This enables us to check whether any unexpected data has arrived on the connection, whether the connection has been closed, etc., and without polling (which could be done with a NetworkStream but not well with an SslStream). However, when we dispose of a connection from the pool, this task will potentially end up getting faulted, and while it won't crash the application by default, it will end up invoking the TaskScheduler.UnobservedException event.
This commit address this by ensuring that we always observe any exceptions that come from the read ahead task when the connection is disposed of (in the rare case where an HttpConnection is instead left for finalization, the event may still be raised, which is arguably a good thing, as the developer should be disposing responses.)
(The alternative would be to stop using the read ahead, and instead poll every time we wanted to know if the connection was still valid. That would mean storing the socket in addition to the stream on the connection, and would mean we might miss some errant data that was already pulled from the socket into an SslStream. It would also mean at least one more syscall for each request, as we'd check whether a connection from the pool was valid. For now I'm sticking with the read ahead.)
Commit migrated from https://github.com/dotnet/corefx/commit/850c1d76e7c5371c5a6e015afa7f25da32f9cdaa
* Add response drain max time to SocketsHttpHandler
Adds support for a max time limit on how long we'll try to drain a connection before returning it to the pool, and adds a (currently non-public) knob for controlling that limit.
This also fixes a race condition with regards to cancellation and chunked responses. If cancellation was requested after returning the connection to the pool but before we disposed of the cancellation registration, someone else could get the pooled connection and then cancellation of one request could end up canceling the other request.
* Address PR feedback
Commit migrated from https://github.com/dotnet/corefx/commit/4ca662cf7ed1bff8e423839936083838d705008d
* Add MaxResponseDrainSize, and fix a few draining bugs
I've added MaxResponseDrainSize to make the setting configurable rather than a const; I left it internal until the API is approved.
In adding tests for it, I found a few existing bugs in draining that I fixed:
- HttpConnectionResponseContent nulls out its Stream when the Stream is consumed. Then when the response content is disposed, the Stream is null, so it's not disposed, so it's not drained.
- HttpContentReadStream's Dispose wasn't checking whether it was already called, and would kick off a new draining operation if the connection was still associated. So if the stream was disposed multiple times, which happens if the response content and stream are both disposed (since the content disposes of the stream), we end up corrupting the response due to multiple threads concurrently accessing and draining it.
* Address PR feedback
Commit migrated from https://github.com/dotnet/corefx/commit/eb80d133d066e72626643dddb3171bf9bb6a7c42
* Disable SocketsHttpHandler's concurrent content sends
SocketsHttpHandler currently has some support for allowing request content sending to run concurrently with response content receiving. However, we don't actually have a need for this, and there are a lot of subtleties that would need to be made robust, e.g. how to handle exceptions that occur concurrently in the sending and receiving. For now, we're removing it. Unless ExpectContinue is set to true, we just send the content before receiving the response, and if it is set, we start the send and then wait for it once we've received the final status code from the server.
* Address PR feedback
Commit migrated from https://github.com/dotnet/corefx/commit/fecb772f0607dc85afdb782eda1b42ddffcba61b
With the expectation that we'll want to expose this in 2.1, implement Expect100ContinueTimeout and ConnectTimeout. The members are currently internal but can be flipped public easily once the APIs are approved. This also fixes an issue with cancellation around the connect phase, where a cancellation request that came in during the SSL auth phase would not be respected.
Commit migrated from https://github.com/dotnet/corefx/commit/01fa16ffd618846a913cad719269c8bb441ceb28
* Improve test coverage of SocketsHttpHandler
Used code coverage information to write targeted tests to cover various uncovered paths in SocketsHttpHandler. Along the way fixed a variety of issues relating to throwing the wrong exception type, a stack overflow due to an unexpected recursive call, etc.
* Address PR feedback
* Re-disable a test
Commit migrated from https://github.com/dotnet/corefx/commit/39677219aaeab8c6591b625ab2874acb17eaf4ef