We were using -Wall but now use -Weverything and opt out of only
a handful of issues such as C++-98 compat, which we don't need.
The most notable impact is that the compiler now catches
narrowing implicit conversions, which was also the primary
motivation for doing this now as there was known debt in our
unsupervised usage of 64-bit types for sizes.
We now assert on bad buffer sizes *and* retain full checks in
release builds to be completely defensive against overflow.
We now use int32_t for scratch buffer sizes. int64_t remains for
file offsets and uint64_t remains for memory mapped files, but
int32_t for scratch eliminates a bunch of managed casts and
therefore makes it easier to reason about overflow prevention.
INT32_MAX is also the most portable limit on these buffer sizes
because the behavior of functions like read is only implementation
defined when the input size is greater than SSIZE_MAX and ssize_t
is int32_t on the lowest common denominator of modern platforms.
Enums corresponding to platform values are now enum X : T instead
of enum class X : T. The PAL_* names are descriptive enough without
scoping and the implicit conversion to raw integer is actually helpful
to avoid a bunch of casts, which are otherwise needed to interop with
the corresponding native API.
Commit migrated from https://github.com/dotnet/corefx/commit/648c01d69fba8d23750122d9823f53257785c8ca
This fix realigns CurlHandler with WinHttpHandler w.r.t Redirect handling.
When redirect is detected, we clear the credentials if the credentials were originally provided as NetworkCredentials Otherwise we use the
forwarding URI to get the new set of credentials.
Like wise, in case of redirects, we get the cookies again from the cookieContainer
In addition, this commit also collects the cookies from the response header
Commit migrated from https://github.com/dotnet/corefx/commit/5d6c82b64c317a6e7e724778affb0f571acdcb2e
The corefx build used an older beta5 version of DNX which hardcoded the path to bash in dnu, breaking the build on FreeBSD.
Updating DNX to the latest "stable" beta7 release fixes this.
After updating I noticed a few test projects didn't build anymore as they were missing some dependencies in project.json, added those.
Fixesdotnet/corefx#3173
Commit migrated from https://github.com/dotnet/corefx/commit/6df77fdbb6cf8e0d35a3074bb325f7810085daa3
PR dotnet/corefx#3105 addressed the issue we were facing with libcurl and the write callback used when libcurl has response body data available. We were blocking libcurl's callback until a reader was available to consume the data, resulting in both significant scalability issues as well as the potential for easy deadlock. This was fixed by making the whole operation async via libcurl's ability to pause connections.
The same issue exists for libcurl's read callback, used by libcurl to read data from the request stream to send as part of the request. The issue here isn't as impactful as on the write side, because a) a common case has no request stream or has a MemoryStream that serves up its data immediately, and b) other streams (e.g. FileStream) typically serve their data quickly even if blocking is involved and don't interact with the HttpClient in a way that could lead to deadlock. However, it's still an issue, and it's still possible to construct cases where deadlock is possible, e.g. if the output stream of one request is used as the input stream of another request associated with the same libcurl multi handle.
This commit addresses the read callback case by relying on the same pause mechanism used for the write callback. When libcurl requests data, if the source is a memory stream, we just do the read and hand back the data. Otherwise, we issue a ReadAsync on the stream. If the operation completes immediately, we synchronously hand the data back to libcurl, storing any extra beyond what libcurl asked for. If the operation didn't complete immediately, we store it for later, and pause the connection, requesting an unpause when the read operation completes. Subsequent read requests from libcurl first try to be satisfied from any previous ReadAsync with
data remaining.
As part of this, I also removed the pause state tracking I'd previously added. In my previous PR as part of adding support for pausing, I added a field to EasyRequest to attempt to mirror the current paused state as known by libcurl. This was done to try to avoid requesting unpausing in cases where we'd like to be unpaused but have already requested it. However, this appears to have been premature optimization, as the case is relatively rare, the overheads relatively low for processing the extra request, and it causes additional headaches once we're able to pause sending/receiving individually.
Commit migrated from https://github.com/dotnet/corefx/commit/fbb6664ab924d82b536389822be1fe4c974f9f3c
- Changed properties on EasyRequest to be fields
- Changed CurlResponseStream to wrap an EasyRequest rather than a CurlResponseMessage
- Removed _position field that was only used for verbose tracing
- Added a few more VerboseTrace calls
- Changed _pendingReadRequest = null to ClearPendingReadRequest (not necessary, but good for consistency)
- Added another couple Debug.Asserts
Commit migrated from https://github.com/dotnet/corefx/commit/7ee7c7100ab70776546e78b2c84ef14519c4ffc5
When receiving the body of an HTTP response, libcurl provides the data
received via a callback that's invoked synchronously from the thread
pumping libcurl's processing. This callback can't return until it's
handed off all of the available data, and thus the current implementation
of CurlHandler blocks that thread until a reader has consumed the data.
This is both expensive and dangerous. It's expensive because we end up
blocking a thread until some reader comes along, and it's dangerous
because this can easily lead to deadlock. A libcurl multi handle may be
used by only one thread at a time, which means that if the handle is being
used by a thread while blocked on the write callback, no other thread can
access the multi handle, which means no other callbacks for other
concurrent requests can be invoked. If multiple operations were queued,
and then the data for them arrived in an order that didn't exactly match
the order of readers consuming the data, deadlock would ensue.
This change makes it so that we no longer block the callback, taking
advantage of a pausing mechanism libcurl provides that allows one to pause
a connection until it's needed.
I rewrote the CurlResponseStream to manage this. Now when the callback
has data to write, it attempts to transfer it to the stream. If there's a
reader already waiting for the data (represented by a task stored on the
stream), the callback simply transfers its data to the reader. If the
callback has too much data than would fit in the reader, the remaining
data is buffered on the stream. If instead the callback finds that either
there isn't a waiting task or that there's already some remaining data
buffered from a previous callback, it instead pauses the connection, such
that no more callbacks will be invoked until we unpause. From the reader
side, a reader who tries to read data from the stream can pull data from
the remaining buffer if there is any, or can register a task with the
stream that will be filled with data at some point when callback has data
available.
As part of debugging some issues with this change, I added a verbose
tracing mechanism that's enabled by compiling the library with the
CURLHANDLER_VERBOSE constant (the same that we use for enabling libcurl's
verbose diagnostic output). I left the tracing in as I found it valuable
in diagnosing issues with the library, but we can remove it later if
desired.
I also added a test that deadlocks before the change and that completes
successfully after.
Commit migrated from https://github.com/dotnet/corefx/commit/308efaba2833e5e146319f74a2281e12ef3e5519
This commit fixesdotnet/corefx#3045.
WebExecption class currently looks at the value of underlying HResult to
set the value of the Status.
We need to set the value of HttpRequestMessage.HResult to appropriate
CURLcode in case of errors. WebException maps this to the relevant
WebExceptionStatus
Commit migrated from https://github.com/dotnet/corefx/commit/7938b0df7624d35c0cff566e8c5a5f2475cefbe8
There are two HttpClientHandler.Unix.cs files checked in:
- One in System.Net.Http\src\System\Net\Http
- One in System.Net.Http\src\System\Net\Http\Unix
The former is the original stubbed out version, throws from every
property, and isn't referenced by the .csproj, whereas the latter is where
all of the recent development related to CurlHandler has happened.
This commit simply deletes the former from the repo.
Commit migrated from https://github.com/dotnet/corefx/commit/94ea117c8c558dfeae3327f089f820c0c0d4a487
In the previous commit, we only polled the user-provided CancellationToken prior to waiting on the synchronization primitive, but the sync primitive wait was only cancelable by shutting down the stream. This commit updates that logic to support also canceling the asynchronous wait via the user-provided CancellationToken.
Commit migrated from https://github.com/dotnet/corefx/commit/80d2b157525211b655c3f81dde0ace6be9617720
Today, CurlHandler provides a response content stream that doesn't override ReadAsync. As such, any consumers reading data using ReadAsync will actually end up blocking a thread pool thread doing a synchronous Read.
This commit fixes that by implementing ReadAsync to be truly asynchronous. If data is already available, a task is returned immediately. Otherwise, the reader asynchronously waits for the writer to publish data and then consumes that data.
The overall design of the response stream remains the same as it was. However, there are some notable changes:
- A SemaphoreSlim is now used instead of a ManualResetEventSlim for the _writerPublishedDataEvent. This was done because SemaphoreSlim supports both synchronous and asynchronous waiting.
- The _readerRequestingDataEvent was removed, as it was no longer necessary.
- We no longer allocate an UnmanagedMemoryStream per write operation, instead simply storing the IntPtr buffer and long length on the response stream.
- Additional reorganization was done, primarily to share logic between Read and ReadAsync.
Commit migrated from https://github.com/dotnet/corefx/commit/c2af3efe7356efa34887c144940c2c1e6f60271a
This change overhauls how CurlHandler manages its threading and resources.
CurlHandler is now split into three types:
- CurlHandler, which represents the shell of the handler, contains some helper functions, and contains a "MultiAgent". It submits "EasyRequest"s to the "MultiAgent".
- CurlHandler.EasyRequest, which represents all of the state associated with a SendAsync request on the HttpClient.
- CurlHandler.MultiAgent, which represents the owner of a libcurl multi handle and all of the processing associated with it. The MultiAgent is responsible for actually processing EasyRequests, which CurlHandler queues to it.
MultiAgent is designed to not require any cleanup. When the first EasyRequest arrives, it spins up a worker that creates a multi handle to process the request. Any additional requests to arrive while that worker is active will be processed by that worker and multi handle. When no work remains, the multi handle and the worker goes away. If/when another request arrives, a new multi handle / worker are spun up. Etc.
Almost all of the locking previously there was removed, as the worker thread is now solely responsible for doing all work on the multi handle. The only locking now is when the CurlHandler hands off an EasyRequest to the MultiAgent, it needs to lock to store the request into the agent's queue, and the MultiAgent needs to lock to access it.
This design avoids threading issues we faced with regards to accessing state managed by the multi handle without holding the lock (e.g. polling file descriptors) and avoids having multiple threads blocked waiting on the lock to do processing associated with the multi handle. It also makes resource cleanup easy: all state associated with the easy handle is cleaned up when that thread is done processing the easy handle, and all state associated with the multi handle is cleaned up when the worker thread shuts down.
The change also ensures that we always complete the response message, and that any exceptions that occur are propagated as needed to Read on the response stream.
And the design will make it trivial in the future to change the relationship between a CurlHandler and a MultiAgent:
- If we want one MultiAgent shared across all CurlHandlers, we just change the _agent field to be static instead of instance.
- If we want a pool of MultiAgents, we can simply create a collection of them and round-robin between them from one or more CurlHandlers.
- Etc.
All of the configuration code remains, e.g. what options are set on the easy and multi handles, but the code has been refactored. I also include CURLOPT_NOSIGNAL to avoid multithreading problems per the docs.
Along the way, I cleaned up some stale interop that's gotten left behind through various iterations, and I fixed a few small issues related to behavioral differences from Windows, e.g. CookieContainer never returning null, UseCookies defaulting to true, etc.
Commit migrated from https://github.com/dotnet/corefx/commit/b7e7847677236ca0afd0b400bd1fcc138d960902
HttpContent.ReadAsStringAsync() has a bunch of calls to
Encoding.GetPreamble() as part of its encoding detection.
GetPreamble() creates a new byte[] each time it is called.
These byte[] allocations can be avoided. Also, as part of this,
cleaned up and improved the performance of the encoding detection.
Commit migrated from https://github.com/dotnet/corefx/commit/de05c8642746842f61cb063c3d43976f7ee00540
- If a timeout happens, the socket fd is not removed from _fdSet. When
SafeCurlMultiHandle is finalized, it checks if _fdSet is empty and
this assertion was failing. So ensuring that all codepaths of
EndRequest result in cleanup from _fdSet
Commit migrated from https://github.com/dotnet/corefx/commit/bf40c3f442a59616f03871057633344d9230d4b6
- On OSX, the read end of the pipe sometimes wakes up the poll
with a POLLOUT. Since we are interested in only reading on it,
scoping down to POLLIN prevents this from happening. Else we
attempt a read on it which fails
- CheckForCompletedTransfers was being unnecessarily called from the
socket callback. We are only interested in MSG_DONE after the socket
callback indicates removal. This will anyway wake up PollFunction which
calls CheckForCompletedTransfers. This race is also causing a seg fault
sometimes because curl_multi_socket_action has been called on an fd
that was getting cleaned up via curl_easy_cleanup (call sequence is
CurlSocketCallback --> CheckForCompletedTransfers --> EndRequest)
- Also removed some unnecessary CharSet attributes
cc: @stephentoub @davidsh @CIPop @SidharthNabar @pgavlin
Commit migrated from https://github.com/dotnet/corefx/commit/58178ce07fdf0e478467a77698c58fb6d1b4e866