Compare commits

...
Author SHA1 Message Date
Martin Baulig b314414144 [Http]: Fix a potential race condition in the WebConnectionGroup's connection list.
Remove the "ConnectionState" from the connection list before closing the connection,
this should avoid ServicePoint.SendRequest() ever crashing with a NullReferenceException
due to getting a null return value from WebConnectionGroup.GetConnection().
2014-06-11 18:54:46 +02:00
Martin Baulig c02a31ca53 [Http]: Cosmetic, remove some dead code to fix warnings.
The is no reason to ever invoke the callback on the ThreadPool,
it would in fact only cause trouble.
2014-06-10 23:05:35 +02:00
Martin Baulig 87057e4155 [System.Net.Http]: Always add "Content-Length" in HttpClientHandler.SendAsync().
This has been reported on the forums:
http://forums.xamarin.com/discussion/17770/length-required-error-in-http-post-since-latest-release
2014-06-10 16:10:12 -04:00
Martin Baulig 1bd68c2096 [Http]: Only recycle ServicePoints from the idle timer (fixes #19823).
Thanks a lot for Martin Potter to find and report the race condition
which was causing the problem.

ServicePointManager.RecycleServicePoints() was a left-over from the
old times when we didn't have an idle-timer based approach.
2014-06-10 16:04:02 -04:00
Martin Baulig d973f792b6 [Http]: Read version from "HTTP CONNECT" response.
When using "HTTP CONNECT" to create a tunnel to a proxy server,
check the proxy server's response for the HTTP Version and close
the connection if it's HTTP/1.0.
2014-06-10 16:03:55 -04:00
Martin Baulig da91ea9bd2 [Http]: Fix the loop in WebConnection.ReadHeaders().
We need to reset `gotStatus' each time we enter the outer loop or we
would attempt to interpret the status line as a header.
2014-06-10 16:03:47 -04:00
Martin Baulig 170f9bfa3c Small fix. 2014-06-10 16:03:39 -04:00
Martin Baulig 717d7b27f5 [Http]: Cleanup and simplify the ServicePoint's connection group list. 2014-06-10 16:03:27 -04:00
Martin Baulig 521d18af45 [Http]: Cleanup chained async operations; bug #19161.
Conflicts:
	mcs/class/System/System.Net/WebConnectionStream.cs
2014-06-10 16:03:15 -04:00
Miguel de Icaza 9de8c08d26 Force use of 4.0.0.0 version for System.Net.Http 2014-05-13 12:09:44 -04:00
Martin Baulig bc488bd546 [Http]: Correctly handle request bodies when resending with authentication.
My previous changes modified the way how we're handing the request body when
resending a request due to a 30x redirection.

Authentication is a "special" form of redirection because we sometimes need
to resend a request with additional authentication headers.  Unfortunately,
I forgot this, causing a regression which is now fixed.

This has been reported as bugs #19119 and #19068.
2014-04-17 22:46:42 +02:00
Martin Baulig 8593ebe2b3 [Http]: Disable redirect with body and no buffering. 2014-04-17 22:45:00 +02:00
Martin Baulig 15f8e79bb9 [Http]: Clear the 'SendChunked' flag when redirecting. 2014-04-17 22:44:52 +02:00
Martin Baulig b266dd15a3 [Http]: Remove chunked/etc headers when redirecting a request as GET. 2014-04-17 22:44:26 +02:00
Rodrigo Kumpera fcf29c0e2f [corlib] Fix the mobile profile. 2014-04-08 11:01:39 -04:00
Jonathan Pryor b4c684a209 [android-hack] Fix SleepEx() compilation under the Android NDK
Apparently the Android NDK on Wrench doesn't declare
clock_nanosleep()/etc., so 0947ffd8 resulted in the same error.

The correct fix would be to update the NDK on Wrench, which has a
proper solution which isn't yet ready, so in the meantime/for
expediency, declare the required functions so that we can get on with
our lives.

DO NOT CHERRY-PICK.
2014-04-08 09:50:58 -04:00
Jonathan Pryor 0947ffd89c [runtime] Fix SleepEx() compilation under the Android NDK.
SleepEx() requires clock_nanosleep(), which Android provides, but
declares in <time.h>, not <sys/time.h>

Add #include<time.h> so that SleepEx() compiles.
2014-04-07 23:12:33 -04:00
Miguel de Icaza bca9714576 WebResponse.cs: Implement SupportsHeaders property 2014-04-07 14:35:07 -04:00
Miguel de Icaza 242ea36e35 System/PCL: Implement HttpWebRequest.SupportsCookieContainer, WebRequest.CreateHttp; Fixes #18378 2014-04-07 14:35:00 -04:00
18 changed files with 569 additions and 463 deletions

No files matched your search

@@ -44,10 +44,10 @@ using System.Runtime.InteropServices;
[assembly: AssemblyCompany (Consts.MonoCompany)]
[assembly: AssemblyProduct (Consts.MonoProduct)]
[assembly: AssemblyCopyright (Consts.MonoCopyright)]
[assembly: AssemblyVersion (Consts.FxVersion)]
[assembly: SatelliteContractVersion (Consts.FxVersion)]
[assembly: AssemblyInformationalVersion (Consts.FxFileVersion)]
[assembly: AssemblyFileVersion (Consts.FxFileVersion)]
[assembly: AssemblyVersion ("4.0.0.0")]
[assembly: SatelliteContractVersion ("4.0.0.0")]
[assembly: AssemblyInformationalVersion ("4.0.50524.0")]
[assembly: AssemblyFileVersion ("4.0.50524.0")]
[assembly: NeutralResourcesLanguage ("en-US")]
[assembly: CLSCompliant (true)]
@@ -311,6 +311,11 @@ namespace System.Net.Http
var stream = await wrequest.GetRequestStreamAsync ().ConfigureAwait (false);
await request.Content.CopyToAsync (stream).ConfigureAwait (false);
} else if (HttpMethod.Post.Equals (request.Method) || HttpMethod.Put.Equals (request.Method) || HttpMethod.Delete.Equals (request.Method)) {
// Explicitly set this to make sure we're sending a "Content-Length: 0" header.
// This fixes the issue that's been reported on the forums:
// http://forums.xamarin.com/discussion/17770/length-required-error-in-http-post-since-latest-release
wrequest.ContentLength = 0;
}
HttpWebResponse wresponse = null;
@@ -533,6 +533,38 @@ namespace MonoTests.System.Net.Http
}
}
[Test]
public void Send_Complete_NoContent ()
{
foreach (var method in new HttpMethod[] { HttpMethod.Post, HttpMethod.Put, HttpMethod.Delete }) {
bool? failed = null;
var listener = CreateListener (l => {
try {
var request = l.Request;
Assert.AreEqual (2, request.Headers.Count, "#1");
Assert.AreEqual ("0", request.Headers ["Content-Length"], "#1b");
Assert.AreEqual (method.Method, request.HttpMethod, "#2");
failed = false;
} catch {
failed = true;
}
});
try {
var client = new HttpClient ();
var request = new HttpRequestMessage (method, LocalServer);
var response = client.SendAsync (request, HttpCompletionOption.ResponseHeadersRead).Result;
Assert.AreEqual ("", response.Content.ReadAsStringAsync ().Result, "#100");
Assert.AreEqual (HttpStatusCode.OK, response.StatusCode, "#101");
Assert.AreEqual (false, failed, "#102");
} finally {
listener.Close ();
}
}
}
[Test]
public void Send_Complete_Error ()
{
+112 -126
View File
@@ -56,6 +56,7 @@ namespace System.Net
bool allowBuffering = true;
X509CertificateCollection certificates;
string connectionGroup;
bool haveContentLength;
long contentLength = -1;
HttpContinueDelegate continueDelegate;
CookieContainer cookieContainer;
@@ -277,6 +278,7 @@ namespace System.Net
throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
contentLength = value;
haveContentLength = true;
}
}
@@ -593,10 +595,11 @@ namespace System.Net
get { return servicePoint; }
}
#if NET_4_0
[MonoTODO ("for portable library support")]
public virtual bool SupportsCookieContainer {
get {
throw new NotImplementedException ();
// The managed implementation supports the cookie container
// it is only Silverlight that returns false here
return true;
}
}
#endif
@@ -862,29 +865,29 @@ namespace System.Net
return EndGetRequestStream (asyncResult);
}
WebAsyncResult CheckIfForceWrite (AsyncCallback callback, object state)
bool CheckIfForceWrite (SimpleAsyncResult result)
{
if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
return null;
#if NET_4_0
return false;
#if NET_4_0
if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
return null;
return false;
if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
InternalContentLength = writeStream.WriteBufferLength;
#else
#else
if (contentLength < 0 && writeStream.CanWrite == true)
return null;
#endif
return false;
#endif
// This will write the POST/PUT if the write stream already has the expected
// amount of bytes in it (ContentLength) (bug #77753) or if the write stream
// contains data and it has been closed already (xamarin bug #1512).
if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
return writeStream.WriteRequestAsync (callback, state);
return writeStream.WriteRequestAsync (result);
return null;
return false;
}
public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
@@ -911,59 +914,41 @@ namespace System.Net
WebAsyncResult aread = asyncRead;
initialMethod = method;
aread.InnerAsyncResult = CheckIfForceWrite (GetResponseAsyncCB, aread);
if (aread.InnerAsyncResult == null)
GetResponseAsyncCB2 (aread);
else
Monitor.Exit (locker);
return aread;
}
SimpleAsyncResult.RunWithLock (locker, CheckIfForceWrite, inner => {
var synch = inner.CompletedSynchronously;
void GetResponseAsyncCB (IAsyncResult ar)
{
var result = (WebAsyncResult)ar;
var innerResult = (WebAsyncResult)result.InnerAsyncResult;
result.InnerAsyncResult = null;
if (innerResult != null && innerResult.GotException) {
asyncRead.SetCompleted (true, innerResult.Exception);
asyncRead.DoCallback ();
return;
}
Monitor.Enter (locker);
GetResponseAsyncCB2 ((WebAsyncResult)ar);
}
void GetResponseAsyncCB2 (WebAsyncResult aread)
{
if (haveResponse) {
Exception saved = saved_exc;
if (webResponse != null) {
Monitor.Exit (locker);
if (saved == null) {
aread.SetCompleted (true, webResponse);
} else {
aread.SetCompleted (true, saved);
}
aread.DoCallback ();
return;
} else if (saved != null) {
Monitor.Exit (locker);
aread.SetCompleted (true, saved);
if (inner.GotException) {
aread.SetCompleted (synch, inner.Exception);
aread.DoCallback ();
return;
}
}
if (!requestSent) {
requestSent = true;
redirects = 0;
servicePoint = GetServicePoint ();
abortHandler = servicePoint.SendRequest (this, connectionGroup);
}
if (haveResponse) {
Exception saved = saved_exc;
if (webResponse != null) {
if (saved == null) {
aread.SetCompleted (synch, webResponse);
} else {
aread.SetCompleted (synch, saved);
}
aread.DoCallback ();
return;
} else if (saved != null) {
aread.SetCompleted (synch, saved);
aread.DoCallback ();
return;
}
}
Monitor.Exit (locker);
if (!requestSent) {
requestSent = true;
redirects = 0;
servicePoint = GetServicePoint ();
abortHandler = servicePoint.SendRequest (this, connectionGroup);
}
});
return aread;
}
public override WebResponse EndGetResponse (IAsyncResult asyncResult)
@@ -1108,8 +1093,15 @@ namespace System.Net
if (continueDelegate != null)
continueDelegate (statusCode, headers);
}
void RewriteRedirectToGet ()
{
method = "GET";
webHeaders.RemoveInternal ("Transfer-Encoding");
sendChunked = false;
}
bool Redirect (WebAsyncResult result, HttpStatusCode code)
bool Redirect (WebAsyncResult result, HttpStatusCode code, WebResponse response)
{
redirects++;
Exception e = null;
@@ -1121,12 +1113,12 @@ namespace System.Net
case HttpStatusCode.MovedPermanently: // 301
case HttpStatusCode.Redirect: // 302
if (method == "POST")
method = "GET";
RewriteRedirectToGet ();
break;
case HttpStatusCode.TemporaryRedirect: // 307
break;
case HttpStatusCode.SeeOther: //303
method = "GET";
RewriteRedirectToGet ();
break;
case HttpStatusCode.NotModified: // 304
return false;
@@ -1139,12 +1131,13 @@ namespace System.Net
break;
}
if (method != "GET" && !InternalAllowBuffering)
e = new WebException ("The request requires buffering data to succeed.", null, WebExceptionStatus.ProtocolError, webResponse);
if (e != null)
throw e;
contentLength = -1;
//bodyBufferLength = 0;
//bodyBuffer = null;
uriString = webResponse.Headers ["Location"];
if (uriString == null)
@@ -1174,12 +1167,15 @@ namespace System.Net
} else if (contentLength != -1) {
if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
// We don't send any body with the NTLM Challenge request.
webHeaders.SetInternal ("Content-Length", "0");
if (haveContentLength || gotRequestStream || contentLength > 0)
webHeaders.SetInternal ("Content-Length", "0");
else
webHeaders.RemoveInternal ("Content-Length");
} else {
if (contentLength > 0)
continue100 = true;
if (gotRequestStream || contentLength > 0)
if (haveContentLength || gotRequestStream || contentLength > 0)
webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
}
webHeaders.RemoveInternal ("Transfer-Encoding");
@@ -1309,16 +1305,52 @@ namespace System.Net
writeStream.SendChunked = false;
}
try {
var result = writeStream.SetHeadersAsync (false, SetWriteStreamCB, null);
if (result == null)
SetWriteStreamCB (null);
} catch (Exception exc) {
SetWriteStreamErrorCB (exc);
}
writeStream.SetHeadersAsync (false, result => {
if (result.GotException) {
SetWriteStreamError (result.Exception);
return;
}
haveRequest = true;
SetWriteStreamInner (inner => {
if (inner.GotException) {
SetWriteStreamError (inner.Exception);
return;
}
if (asyncWrite != null) {
asyncWrite.SetCompleted (inner.CompletedSynchronously, writeStream);
asyncWrite.DoCallback ();
asyncWrite = null;
}
});
});
}
void SetWriteStreamErrorCB (Exception exc)
SimpleAsyncResult SetWriteStreamInner (SimpleAsyncCallback callback)
{
return SimpleAsyncResult.Run (result => {
if (bodyBuffer != null) {
// The body has been written and buffered. The request "user"
// won't write it again, so we must do it.
if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
// FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
writeStream.Write (bodyBuffer, 0, bodyBufferLength);
bodyBuffer = null;
writeStream.Close ();
}
} else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
method != "TRACE") {
if (getResponseCalled && !writeStream.RequestWritten)
return writeStream.WriteRequestAsync (result);
}
return false;
}, callback);
}
void SetWriteStreamError (Exception exc)
{
WebException wexc = exc as WebException;
if (wexc != null)
@@ -1327,53 +1359,6 @@ namespace System.Net
SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
}
void SetWriteStreamCB (IAsyncResult ar)
{
WebAsyncResult result = ar as WebAsyncResult;
if (result != null && result.Exception != null) {
SetWriteStreamErrorCB (result.Exception);
return;
}
haveRequest = true;
WebAsyncResult writeRequestResult = null;
if (bodyBuffer != null) {
// The body has been written and buffered. The request "user"
// won't write it again, so we must do it.
if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
// FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
writeStream.Write (bodyBuffer, 0, bodyBufferLength);
bodyBuffer = null;
writeStream.Close ();
}
} else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
method != "TRACE") {
if (getResponseCalled && !writeStream.RequestWritten)
writeRequestResult = writeStream.WriteRequestAsync (SetWriteStreamCB2, null);
}
if (writeRequestResult == null)
SetWriteStreamCB2 (null);
}
void SetWriteStreamCB2 (IAsyncResult ar)
{
var result = (WebAsyncResult)ar;
if (result != null && result.GotException) {
SetWriteStreamErrorCB (result.Exception);
return;
}
if (asyncWrite != null) {
asyncWrite.SetCompleted (false, writeStream);
asyncWrite.DoCallback ();
asyncWrite = null;
}
}
internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
{
if (Aborted)
@@ -1517,6 +1502,11 @@ namespace System.Net
r.SetCompleted (false, webResponse);
r.DoCallback ();
} else {
if (sendChunked) {
sendChunked = false;
webHeaders.RemoveInternal ("Transfer-Encoding");
}
if (webResponse != null) {
if (HandleNtlmAuth (r))
return;
@@ -1651,11 +1641,7 @@ namespace System.Net
if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
// Keep the written body, so it can be rewritten in the retry
if (InternalAllowBuffering) {
// NTLM: This is to avoid sending data in the 'challenge' request
// We save it in the first request (first 401), don't send anything
// in the challenge request and send it in the response request along
// with the buffers kept form the first request.
if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
if (writeStream.WriteBufferLength > 0) {
bodyBuffer = writeStream.WriteBuffer;
bodyBufferLength = writeStream.WriteBufferLength;
}
@@ -1702,7 +1688,7 @@ namespace System.Net
bool b = false;
int c = (int) code;
if (allowAutoRedirect && c >= 300) {
b = Redirect (result, code);
b = Redirect (result, code, webResponse);
if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
bodyBuffer = writeStream.WriteBuffer;
bodyBufferLength = writeStream.WriteBufferLength;
+19 -49
View File
@@ -52,7 +52,6 @@ namespace System.Net
X509Certificate clientCertificate;
IPHostEntry host;
bool usesProxy;
WebConnectionGroup firstGroup;
Dictionary<string,WebConnectionGroup> groups;
bool sendContinue = true;
bool useConnect;
@@ -255,45 +254,25 @@ namespace System.Net
*/
WebConnectionGroup group;
if (firstGroup != null && name == firstGroup.Name)
return firstGroup;
if (groups != null && groups.TryGetValue (name, out group))
return group;
group = new WebConnectionGroup (this, name);
group.ConnectionClosed += (s, e) => currentConnections--;
if (firstGroup == null)
firstGroup = group;
else {
if (groups == null)
groups = new Dictionary<string, WebConnectionGroup> ();
groups.Add (name, group);
}
if (groups == null)
groups = new Dictionary<string, WebConnectionGroup> ();
groups.Add (name, group);
return group;
}
void RemoveConnectionGroup (WebConnectionGroup group)
{
if (groups == null || groups.Count == 0) {
// No more connection groups left.
if (group != firstGroup)
throw new InvalidOperationException ();
else
firstGroup = null;
return;
}
if (groups == null || groups.Count == 0)
throw new InvalidOperationException ();
if (group == firstGroup) {
// Steal one entry from the dictionary.
var en = groups.GetEnumerator ();
en.MoveNext ();
firstGroup = en.Current.Value;
groups.Remove (en.Current.Key);
} else {
groups.Remove (group.Name);
}
groups.Remove (group.Name);
}
internal bool CheckAvailableForRecycling (out DateTime outIdleSince)
@@ -301,10 +280,9 @@ namespace System.Net
outIdleSince = DateTime.MinValue;
TimeSpan idleTimeSpan;
WebConnectionGroup singleGroup, singleRemove = null;
List<WebConnectionGroup> groupList = null, removeList = null;
lock (this) {
if (firstGroup == null) {
if (groups == null || groups.Count == 0) {
idleSince = DateTime.MinValue;
return true;
}
@@ -320,30 +298,20 @@ namespace System.Net
*
*/
singleGroup = firstGroup;
if (groups != null)
groupList = new List<WebConnectionGroup> (groups.Values);
groupList = new List<WebConnectionGroup> (groups.Values);
}
if (singleGroup.TryRecycle (idleTimeSpan, ref outIdleSince))
singleRemove = singleGroup;
if (groupList != null) {
foreach (var group in groupList) {
if (!group.TryRecycle (idleTimeSpan, ref outIdleSince))
continue;
if (removeList == null)
removeList = new List<WebConnectionGroup> ();
removeList.Add (group);
}
foreach (var group in groupList) {
if (!group.TryRecycle (idleTimeSpan, ref outIdleSince))
continue;
if (removeList == null)
removeList = new List<WebConnectionGroup> ();
removeList.Add (group);
}
lock (this) {
idleSince = outIdleSince;
if (singleRemove != null)
RemoveConnectionGroup (singleRemove);
if (removeList != null) {
foreach (var group in removeList)
RemoveConnectionGroup (group);
@@ -352,9 +320,11 @@ namespace System.Net
if (groups != null && groups.Count == 0)
groups = null;
if (firstGroup == null) {
idleTimer.Dispose ();
idleTimer = null;
if (groups == null) {
if (idleTimer != null) {
idleTimer.Dispose ();
idleTimer = null;
}
return true;
}
@@ -264,7 +264,6 @@ namespace System.Net
throw new ArgumentException ("value");
maxServicePoints = value;
RecycleServicePoints ();
}
}
@@ -329,9 +328,6 @@ namespace System.Net
if (address == null)
throw new ArgumentNullException ("address");
if ((servicePoints.Count % 4) == 0)
RecycleServicePoints ();
var origAddress = new Uri (address.Scheme + "://" + address.Authority);
bool usesProxy = false;
@@ -378,41 +374,6 @@ namespace System.Net
return sp;
}
// Internal Methods
static void RecycleServicePoints ()
{
lock (servicePoints) {
var toRemove = new ArrayList ();
var idleList = new SortedDictionary<DateTime, ServicePoint> ();
IDictionaryEnumerator e = servicePoints.GetEnumerator ();
while (e.MoveNext ()) {
ServicePoint sp = (ServicePoint) e.Value;
DateTime idleSince;
if (sp.CheckAvailableForRecycling (out idleSince)) {
toRemove.Add (e.Key);
continue;
}
while (idleList.ContainsKey (idleSince))
idleSince = idleSince.AddMilliseconds (1);
idleList.Add (idleSince, sp);
}
for (int i = 0; i < toRemove.Count; i++)
servicePoints.Remove (toRemove [i]);
if (maxServicePoints == 0 || servicePoints.Count <= maxServicePoints)
return;
// get rid of the ones with the longest idle time
foreach (var sp in idleList.Values) {
if (servicePoints.Count <= maxServicePoints)
break;
servicePoints.Remove (sp);
}
}
}
#if SECURITY_DEP
internal class ChainValidationHelper {
object sender;
@@ -0,0 +1,220 @@
//
// System.Net.WebAsyncResult
//
// Authors:
// Gonzalo Paniagua Javier ([email protected])
// Martin Baulig ([email protected])
//
// (C) 2003 Ximian, Inc (http://www.ximian.com)
// Copyright (c) 2014 Xamarin Inc. (http://www.xamarin.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.IO;
using System.Threading;
namespace System.Net
{
delegate void SimpleAsyncCallback (SimpleAsyncResult result);
delegate bool SimpleAsyncFunc (SimpleAsyncResult result);
class SimpleAsyncResult : IAsyncResult
{
ManualResetEvent handle;
bool synch;
bool isCompleted;
SimpleAsyncCallback cb;
object state;
bool callbackDone;
Exception exc;
object locker = new object ();
SimpleAsyncResult (SimpleAsyncCallback cb)
{
this.cb = cb;
}
protected SimpleAsyncResult (AsyncCallback cb, object state)
{
this.state = state;
this.cb = result => {
if (cb != null)
cb (this);
};
}
public static SimpleAsyncResult Run (SimpleAsyncFunc func, SimpleAsyncCallback callback)
{
var result = new SimpleAsyncResult (callback);
try {
if (!func (result))
result.SetCompleted (true);
} catch (Exception ex) {
result.SetCompleted (true, ex);
}
return result;
}
public static SimpleAsyncResult RunWithLock (object locker, SimpleAsyncFunc func, SimpleAsyncCallback callback)
{
return Run (inner => {
bool running = func (inner);
if (running)
Monitor.Exit (locker);
return running;
}, inner => {
if (inner.GotException) {
if (inner.CompletedSynchronously)
Monitor.Exit (locker);
callback (inner);
return;
}
try {
if (!inner.CompletedSynchronously)
Monitor.Enter (locker);
callback (inner);
} finally {
Monitor.Exit (locker);
}
});
}
protected void Reset_internal ()
{
callbackDone = false;
exc = null;
exc = null;
lock (locker) {
isCompleted = false;
if (handle != null)
handle.Reset ();
}
}
internal void SetCompleted (bool synch, Exception e)
{
SetCompleted_internal (synch, e);
DoCallback_private ();
}
internal void SetCompleted (bool synch)
{
SetCompleted_internal (synch);
DoCallback_private ();
}
protected void SetCompleted_internal (bool synch, Exception e)
{
this.synch = synch;
exc = e;
lock (locker) {
isCompleted = true;
if (handle != null)
handle.Set ();
}
}
protected void SetCompleted_internal (bool synch)
{
this.synch = synch;
exc = null;
lock (locker) {
isCompleted = true;
if (handle != null)
handle.Set ();
}
}
void DoCallback_private ()
{
if (callbackDone)
return;
callbackDone = true;
if (cb == null)
return;
cb (this);
}
protected void DoCallback_internal ()
{
if (!callbackDone && cb != null) {
callbackDone = true;
cb (this);
}
}
internal void WaitUntilComplete ()
{
if (IsCompleted)
return;
AsyncWaitHandle.WaitOne ();
}
internal bool WaitUntilComplete (int timeout, bool exitContext)
{
if (IsCompleted)
return true;
return AsyncWaitHandle.WaitOne (timeout, exitContext);
}
public object AsyncState {
get { return state; }
}
public WaitHandle AsyncWaitHandle {
get {
lock (locker) {
if (handle == null)
handle = new ManualResetEvent (isCompleted);
}
return handle;
}
}
public bool CompletedSynchronously {
get { return synch; }
}
public bool IsCompleted {
get {
lock (locker) {
return isCompleted;
}
}
}
internal bool GotException {
get { return (exc != null); }
}
internal Exception Exception {
get { return exc; }
}
}
}
+15 -121
View File
@@ -33,173 +33,67 @@ using System.Threading;
namespace System.Net
{
class WebAsyncResult : IAsyncResult
class WebAsyncResult : SimpleAsyncResult
{
ManualResetEvent handle;
bool synch;
bool isCompleted;
AsyncCallback cb;
object state;
int nbytes;
IAsyncResult innerAsyncResult;
bool callbackDone;
Exception exc;
HttpWebResponse response;
Stream writeStream;
byte [] buffer;
int offset;
int size;
object locker = new object ();
public bool EndCalled;
public bool AsyncWriteAll;
public WebAsyncResult (AsyncCallback cb, object state)
: base (cb, state)
{
this.cb = cb;
this.state = state;
}
public WebAsyncResult (HttpWebRequest request, AsyncCallback cb, object state)
: base (cb, state)
{
this.cb = cb;
this.state = state;
}
public WebAsyncResult (AsyncCallback cb, object state, byte [] buffer, int offset, int size)
: base (cb, state)
{
this.cb = cb;
this.state = state;
this.buffer = buffer;
this.offset = offset;
this.size = size;
}
internal void SetCompleted (bool synch, Exception e)
{
this.synch = synch;
exc = e;
lock (locker) {
isCompleted = true;
if (handle != null)
handle.Set ();
}
}
internal void Reset ()
{
callbackDone = false;
exc = null;
response = null;
writeStream = null;
exc = null;
lock (locker) {
isCompleted = false;
if (handle != null)
handle.Reset ();
}
this.nbytes = 0;
this.response = null;
this.buffer = null;
this.offset = 0;
this.size = 0;
Reset_internal ();
}
internal void SetCompleted (bool synch, int nbytes)
{
this.synch = synch;
this.nbytes = nbytes;
exc = null;
lock (locker) {
isCompleted = true;
if (handle != null)
handle.Set ();
}
SetCompleted_internal (synch);
}
internal void SetCompleted (bool synch, Stream writeStream)
{
this.synch = synch;
this.writeStream = writeStream;
exc = null;
lock (locker) {
isCompleted = true;
if (handle != null)
handle.Set ();
}
SetCompleted_internal (synch);
}
internal void SetCompleted (bool synch, HttpWebResponse response)
{
this.synch = synch;
this.response = response;
exc = null;
lock (locker) {
isCompleted = true;
if (handle != null)
handle.Set ();
}
SetCompleted_internal (synch);
}
internal void DoCallback ()
{
if (!callbackDone && cb != null) {
callbackDone = true;
if (synch)
cb (this);
else
ThreadPool.QueueUserWorkItem (CB, null);
}
}
void CB (object unused)
{
cb (this);
}
internal void WaitUntilComplete ()
{
if (IsCompleted)
return;
AsyncWaitHandle.WaitOne ();
}
internal bool WaitUntilComplete (int timeout, bool exitContext)
{
if (IsCompleted)
return true;
return AsyncWaitHandle.WaitOne (timeout, exitContext);
}
public object AsyncState {
get { return state; }
}
public WaitHandle AsyncWaitHandle {
get {
lock (locker) {
if (handle == null)
handle = new ManualResetEvent (isCompleted);
}
return handle;
}
}
public bool CompletedSynchronously {
get { return synch; }
}
public bool IsCompleted {
get {
lock (locker) {
return isCompleted;
}
}
}
internal bool GotException {
get { return (exc != null); }
}
internal Exception Exception {
get { return exc; }
DoCallback_internal ();
}
internal int NBytes {
+16 -6
View File
@@ -356,8 +356,6 @@ namespace System.Net
byte [] buffer = new byte [1024];
MemoryStream ms = new MemoryStream ();
bool gotStatus = false;
WebHeaderCollection headers = null;
while (true) {
int n = stream.Read (buffer, 0, 1024);
@@ -369,7 +367,8 @@ namespace System.Net
ms.Write (buffer, 0, n);
int start = 0;
string str = null;
headers = new WebHeaderCollection ();
bool gotStatus = false;
WebHeaderCollection headers = new WebHeaderCollection ();
while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
if (str == null) {
int contentLen = 0;
@@ -399,13 +398,22 @@ namespace System.Net
continue;
}
int spaceidx = str.IndexOf (' ');
if (spaceidx == -1) {
string[] parts = str.Split (' ');
if (parts.Length < 2) {
HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
return null;
}
status = (int) UInt32.Parse (str.Substring (spaceidx + 1, 3));
if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
Data.ProxyVersion = HttpVersion.Version11;
else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
Data.ProxyVersion = HttpVersion.Version10;
else {
HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
return null;
}
status = (int)UInt32.Parse (parts [1]);
gotStatus = true;
}
}
@@ -841,6 +849,8 @@ namespace System.Net
string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
keepAlive = false;
if (cncHeader != null) {
cncHeader = cncHeader.ToLower ();
keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
@@ -39,6 +39,7 @@ namespace System.Net
public string StatusDescription;
public WebHeaderCollection Headers;
public Version Version;
public Version ProxyVersion;
public Stream stream;
public string[] Challenge;
ReadState _readState;
@@ -70,14 +70,16 @@ namespace System.Net
//TODO: abort requests or wait for them to finish
lock (sPoint) {
closing = true;
foreach (var cnc in connections) {
if (cnc.Connection == null)
continue;
cnc.Connection.Close (false);
cnc.Connection = null;
var iter = connections.First;
while (iter != null) {
var cnc = iter.Value.Connection;
var node = iter;
iter = iter.Next;
connections.Remove (node);
cnc.Close (false);
OnConnectionClosed ();
}
connections.Clear ();
}
}
@@ -120,7 +122,7 @@ namespace System.Net
ConnectionState FindIdleConnection ()
{
foreach (var cnc in connections) {
if (cnc.Busy || cnc.Connection == null)
if (cnc.Busy)
continue;
connections.Remove (cnc);
@@ -140,7 +142,7 @@ namespace System.Net
return cnc.Connection;
}
if (sPoint.ConnectionLimit > connections.Count) {
if (sPoint.ConnectionLimit > connections.Count || connections.Count == 0) {
created = true;
cnc = new ConnectionState (this);
connections.AddFirst (cnc);
@@ -177,14 +179,11 @@ namespace System.Net
}
int count = 0;
for (var node = connections.First; node != null; node = node.Next) {
var cnc = node.Value;
if (cnc.Connection == null) {
connections.Remove (node);
OnConnectionClosed ();
continue;
}
var iter = connections.First;
while (iter != null) {
var cnc = iter.Value;
var node = iter;
iter = iter.Next;
++count;
if (cnc.Busy)
@@ -205,7 +204,7 @@ namespace System.Net
if (connectionsToClose == null)
connectionsToClose = new List<WebConnection> ();
connectionsToClose.Add (cnc.Connection);
cnc.Connection = null;
connections.Remove (node);
}
recycled = connections.Count == 0;
@@ -224,7 +223,10 @@ namespace System.Net
}
class ConnectionState : IWebConnectionState {
public WebConnection Connection;
public WebConnection Connection {
get;
private set;
}
public WebConnectionGroup Group {
get;
@@ -514,6 +514,13 @@ namespace System.Net
Buffer.BlockCopy (buffer, offset, newBuffer, head.Length, size);
Buffer.BlockCopy (crlf, 0, newBuffer, head.Length + size, crlf.Length);
if (allowBuffering) {
if (writeBuffer == null)
writeBuffer = new MemoryStream ();
writeBuffer.Write (buffer, offset, size);
totalWritten += size;
}
buffer = newBuffer;
offset = 0;
size = chunkSize;
@@ -626,10 +633,15 @@ namespace System.Net
{
}
internal WebAsyncResult SetHeadersAsync (bool setInternalLength, AsyncCallback callback, object state)
internal SimpleAsyncResult SetHeadersAsync (bool setInternalLength, SimpleAsyncCallback callback)
{
return SimpleAsyncResult.Run (r => SetHeadersAsync (r, setInternalLength), callback);
}
bool SetHeadersAsync (SimpleAsyncResult result, bool setInternalLength)
{
if (headersSent)
return null;
return false;
string method = request.Method;
bool no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" ||
@@ -641,59 +653,61 @@ namespace System.Net
if (setInternalLength && !no_writestream && writeBuffer != null)
request.InternalContentLength = writeBuffer.Length;
if (sendChunked || request.ContentLength > -1 || no_writestream || webdav) {
headersSent = true;
headers = request.GetRequestHeaders ();
if (!(sendChunked || request.ContentLength > -1 || no_writestream || webdav))
return false;
var result = new WebAsyncResult (callback, state);
result.InnerAsyncResult = cnc.BeginWrite (request, headers, 0, headers.Length, new AsyncCallback (SetHeadersCB), result);
if (result.InnerAsyncResult != null)
return result;
}
headersSent = true;
headers = request.GetRequestHeaders ();
return null;
}
void SetHeadersCB (IAsyncResult r)
{
WebAsyncResult result = (WebAsyncResult) r.AsyncState;
result.InnerAsyncResult = null;
try {
cnc.EndWrite (request, true, r);
result.SetCompleted (false, 0);
if (!initRead) {
initRead = true;
WebConnection.InitRead (cnc);
var innerResult = cnc.BeginWrite (request, headers, 0, headers.Length, r => {
try {
cnc.EndWrite (request, true, r);
if (!initRead) {
initRead = true;
WebConnection.InitRead (cnc);
}
var cl = request.ContentLength;
if (!sendChunked && cl == 0)
requestWritten = true;
result.SetCompleted (false);
} catch (WebException e) {
result.SetCompleted (false, e);
} catch (Exception e) {
result.SetCompleted (false, new WebException ("Error writing headers", e, WebExceptionStatus.SendFailure));
}
long cl = request.ContentLength;
if (!sendChunked && cl == 0)
requestWritten = true;
} catch (WebException e) {
result.SetCompleted (false, e);
} catch (Exception e) {
result.SetCompleted (false, new WebException ("Error writing headers", e, WebExceptionStatus.SendFailure));
}
result.DoCallback ();
}, null);
return innerResult != null;
}
internal bool RequestWritten {
get { return requestWritten; }
}
internal WebAsyncResult WriteRequestAsync (AsyncCallback callback, object state)
internal SimpleAsyncResult WriteRequestAsync (SimpleAsyncCallback callback)
{
var result = WriteRequestAsync (callback);
try {
if (!WriteRequestAsync (result))
result.SetCompleted (true);
} catch (Exception ex) {
result.SetCompleted (true, ex);
}
return result;
}
internal bool WriteRequestAsync (SimpleAsyncResult result)
{
if (requestWritten)
return null;
return false;
requestWritten = true;
if (sendChunked)
return null;
if (sendChunked || !allowBuffering || writeBuffer == null)
return false;
if (!allowBuffering || writeBuffer == null)
return null;
byte[] bytes = writeBuffer.GetBuffer ();
int length = (int)writeBuffer.Length;
// Keep the call for a potential side-effect of GetBuffer
var bytes = writeBuffer.GetBuffer ();
var length = (int)writeBuffer.Length;
if (request.ContentLength != -1 && request.ContentLength < length) {
nextReadCalled = true;
cnc.Close (true);
@@ -701,63 +715,39 @@ namespace System.Net
WebExceptionStatus.ServerProtocolViolation, null);
}
var result = new WebAsyncResult (callback, state);
result.InnerAsyncResult = SetHeadersAsync (true, WriteRequestAsyncCB, result);
if (result.InnerAsyncResult == null)
WriteRequestAsyncCB (result);
return result;
}
var ret = SetHeadersAsync (true, inner => {
if (inner.GotException) {
result.SetCompleted (inner.CompletedSynchronously, inner.Exception);
return;
}
void WriteRequestAsyncCB (IAsyncResult ar)
{
var result = (WebAsyncResult)ar;
var innerResult = (WebAsyncResult)result.InnerAsyncResult;
result.InnerAsyncResult = null;
if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100) {
result.SetCompleted (inner.CompletedSynchronously);
return;
}
if (innerResult != null && innerResult.GotException) {
result.SetCompleted (false, innerResult.Exception);
result.DoCallback ();
return;
}
if (!initRead) {
initRead = true;
WebConnection.InitRead (cnc);
}
if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100) {
result.SetCompleted (false, 0);
result.DoCallback ();
return;
}
if (length == 0) {
complete_request_written = true;
result.SetCompleted (inner.CompletedSynchronously);
return;
}
byte[] bytes = writeBuffer.GetBuffer ();
int length = (int)writeBuffer.Length;
cnc.BeginWrite (request, bytes, 0, length, r => {
try {
complete_request_written = cnc.EndWrite (request, false, r);
result.SetCompleted (false);
} catch (Exception exc) {
result.SetCompleted (false, exc);
}
}, null);
});
if (length > 0)
result.InnerAsyncResult = cnc.BeginWrite (request, bytes, 0, length, WriteRequestAsyncCB2, result);
if (!initRead) {
initRead = true;
WebConnection.InitRead (cnc);
}
if (length == 0) {
result.SetCompleted (false, 0);
result.DoCallback ();
complete_request_written = true;
}
}
void WriteRequestAsyncCB2 (IAsyncResult ar)
{
var result = (WebAsyncResult)ar.AsyncState;
var innerResult = result.InnerAsyncResult;
result.InnerAsyncResult = null;
try {
complete_request_written = cnc.EndWrite (request, false, innerResult);
result.SetCompleted (false, 0);
} catch (Exception exc) {
result.SetCompleted (false, exc);
} finally {
result.DoCallback ();
}
return true;
}
internal void InternalClose ()
+14 -4
View File
@@ -287,16 +287,26 @@ namespace System.Net
return GetCreator (requestUri.Scheme).Create (requestUri);
}
#if NET_4_0
[MonoTODO ("for portable library support")]
static HttpWebRequest SharedCreateHttp (Uri uri)
{
if (uri.Scheme != "http" && uri.Scheme != "https")
throw new NotSupportedException ("The uri should start with http or https");
return new HttpWebRequest (uri);
}
public static HttpWebRequest CreateHttp (string requestUriString)
{
throw new NotImplementedException ();
if (requestUriString == null)
throw new ArgumentNullException ("requestUriString");
return SharedCreateHttp (new Uri (requestUriString));
}
[MonoTODO ("for portable library support")]
public static HttpWebRequest CreateHttp (Uri requestUri)
{
throw new NotImplementedException ();
if (requestUri == null)
throw new ArgumentNullException ("requestUri");
return SharedCreateHttp (requestUri);
}
#endif
public virtual Stream EndGetRequestStream (IAsyncResult asyncResult)
+6 -2
View File
@@ -86,9 +86,13 @@ namespace System.Net
get { throw new NotSupportedException (); }
}
#if NET_4_0
[MonoTODO ("for portable library support")]
public virtual bool SupportsHeaders {
get { throw new NotImplementedException (); }
get {
// The managed stack always returns this as true, it is only
// the Silverlight stack that does not support this.
return true;
}
}
#endif
// Methods
+1
View File
@@ -834,6 +834,7 @@ System.Net.Security/SslPolicyErrors.cs
System.Net/ServicePoint.cs
System.Net/ServicePointManager.cs
System.Net/ServicePointManager.extra.cs
System.Net/SimpleAsyncResult.cs
System.Net/SocketAddress.cs
System.Net/SocketPermissionAttribute.cs
System.Net/SocketPermission.cs
@@ -526,6 +526,7 @@ System.Net/SecurityProtocolType.cs
System.Net/ServicePoint.cs
System.Net/ServicePointManager.cs
System.Net/ServicePointManager.extra.cs
System.Net/SimpleAsyncResult.cs
System.Net/SocketAddress.cs
System.Net/TransportContext.cs
System.Net/TransportType.cs
@@ -85,7 +85,11 @@ namespace System.Threading {
if (ec.FlowSuppressed)
return null;
if (nullOnEmpty && ec._sc == null && (ec._lcc == null || !ec._lcc.HasInfo))
if (nullOnEmpty
#if !MOBILE
&& ec._sc == null
#endif
&& (ec._lcc == null || !ec._lcc.HasInfo))
return null;
ExecutionContext capture = new ExecutionContext (ec);
+15
View File
@@ -17,6 +17,7 @@
#include <signal.h>
#include <sched.h>
#include <sys/time.h>
#include <time.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
@@ -36,6 +37,20 @@
#include <valgrind/memcheck.h>
#endif
#ifdef PLATFORM_ANDROID
/*
* HACK
* Android supports clock_*(), but didn't declare them consistently until
* recently, e.g. on NDK r8e API-3, API-4, and API-5 declare them in <time.h>,
* but higher API levels do not. This isn't corrected until r9c, which
* Wrench isn't currently using.
*
* Manually declare them so that we don't get implicit declaration errors.
*/
extern int clock_gettime(clockid_t, struct timespec *);
extern int clock_nanosleep(clockid_t, int, const struct timespec *, struct timespec *);
#endif /* PLATFORM_ANDROID */
#if 0
#define DEBUG(...) g_message(__VA_ARGS__)
#else