[Http]: Cleanup chained async operations; bug #19161.

This commit is contained in:
Martin Baulig committed 2014-05-21 02:26:48 +02:00
1 parent 00ecc7392d
commit e49d56e8d1
6 files changed
+402 -325

No files matched your search

+82 -111
View File
@@ -865,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)
@@ -914,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)
@@ -1323,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)
@@ -1341,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)
@@ -0,0 +1,228 @@
//
// 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)
throw new InvalidOperationException ();
callbackDone = true;
if (cb == null)
return;
cb (this);
}
protected void DoCallback_internal ()
{
if (!callbackDone && cb != null) {
callbackDone = true;
if (true || 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; }
}
}
}
+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 {
@@ -633,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" ||
@@ -648,60 +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 (!allowBuffering || writeBuffer == null)
return null;
if (sendChunked || !allowBuffering || writeBuffer == null)
return false;
// Keep the call for a potential side-effect of GetBuffer
writeBuffer.GetBuffer ();
int length = (int)writeBuffer.Length;
var bytes = writeBuffer.GetBuffer ();
var length = (int)writeBuffer.Length;
if (request.ContentLength != -1 && request.ContentLength < length) {
nextReadCalled = true;
cnc.Close (true);
@@ -709,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 ()
+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