using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
+#if SECURITY_DEP
+using Mono.Security.Protocol.Tls;
+#endif
namespace System.Net
{
None,
Status,
Headers,
- Content
+ Content,
+ Aborted
}
-
+
class WebConnection
{
ServicePoint sPoint;
byte [] buffer;
static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
EventHandler abortHandler;
- ReadState readState;
+ AbortHelper abortHelper;
internal WebConnectionData Data;
bool chunkedRead;
ChunkStream chunkStream;
Queue queue;
bool reused;
int position;
- bool busy;
- HttpWebRequest priority_request;
+ bool busy;
+ HttpWebRequest priority_request;
NetworkCredential ntlm_credentials;
bool ntlm_authenticated;
-#if NET_1_1
bool unsafe_sharing;
-#endif
+
+ enum NtlmAuthState
+ {
+ None,
+ Challenge,
+ Response
+ }
+ NtlmAuthState connect_ntlm_auth_state;
+ HttpWebRequest connect_request;
bool ssl;
bool certsAvailable;
static PropertyInfo piServer;
static PropertyInfo piTrustFailure;
+#if MONOTOUCH
+ static MethodInfo start_wwan;
+
+ static WebConnection ()
+ {
+ Type type = Type.GetType ("MonoTouch.ObjCRuntime.Runtime, monotouch");
+ if (type != null)
+ start_wwan = type.GetMethod ("StartWWAN", new Type [] { typeof (System.Uri) });
+ }
+#endif
+
public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
{
this.sPoint = sPoint;
buffer = new byte [4096];
- readState = ReadState.None;
Data = new WebConnectionData ();
- initConn = new WaitCallback (InitConnection);
- abortHandler = new EventHandler (Abort);
+ initConn = new WaitCallback (state => {
+ try {
+ InitConnection (state);
+ } catch {}
+ });
queue = group.Queue;
+ abortHelper = new AbortHelper ();
+ abortHelper.Connection = this;
+ abortHandler = new EventHandler (abortHelper.Abort);
+ }
+
+ class AbortHelper {
+ public WebConnection Connection;
+
+ public void Abort (object sender, EventArgs args)
+ {
+ WebConnection other = ((HttpWebRequest) sender).WebConnection;
+ if (other == null)
+ other = Connection;
+ other.Abort (sender, args);
+ }
}
bool CanReuse ()
return (socket.Poll (0, SelectMode.SelectRead) == false);
}
- void Connect ()
+ void Connect (HttpWebRequest request)
{
lock (socketLock) {
if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
IPHostEntry hostEntry = sPoint.HostEntry;
if (hostEntry == null) {
- status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
- WebExceptionStatus.NameResolutionFailure;
- return;
+#if MONOTOUCH
+ if (start_wwan != null) {
+ start_wwan.Invoke (null, new object [1] { sPoint.Address });
+ hostEntry = sPoint.HostEntry;
+ }
+ if (hostEntry == null) {
+#endif
+ status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
+ WebExceptionStatus.NameResolutionFailure;
+ return;
+#if MONOTOUCH
+ }
+#endif
}
+ //WebConnectionData data = Data;
foreach (IPAddress address in hostEntry.AddressList) {
- socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
-
+ try {
+ socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
+ } catch (Exception se) {
+ // The Socket ctor can throw if we run out of FD's
+ if (!request.Aborted)
+ status = WebExceptionStatus.ConnectFailure;
+ connect_exception = se;
+ return;
+ }
IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
+ socket.NoDelay = !sPoint.UseNagleAlgorithm;
+ try {
+ sPoint.KeepAliveSetup (socket);
+ } catch {
+ // Ignore. Not supported in all platforms.
+ }
-#if NET_2_0
- socket.NoDelay = true;
if (!sPoint.CallEndPointDelegate (socket, remote)) {
socket.Close ();
socket = null;
status = WebExceptionStatus.ConnectFailure;
} else {
-#endif
try {
+ if (request.Aborted)
+ return;
socket.Connect (remote);
status = WebExceptionStatus.Success;
break;
- } catch (SocketException exc) {
- // This might be null if the request is aborted
- if (socket != null) {
- socket.Close ();
- socket = null;
+ } catch (ThreadAbortException) {
+ // program exiting...
+ Socket s = socket;
+ socket = null;
+ if (s != null)
+ s.Close ();
+ return;
+ } catch (ObjectDisposedException) {
+ // socket closed from another thread
+ return;
+ } catch (Exception exc) {
+ Socket s = socket;
+ socket = null;
+ if (s != null)
+ s.Close ();
+ if (!request.Aborted)
status = WebExceptionStatus.ConnectFailure;
- connect_exception = exc;
- }
+ connect_exception = exc;
}
-#if NET_2_0
}
-#endif
}
}
}
if (sslStream != null)
return;
+#if NET_2_1 && SECURITY_DEP
+ sslStream = typeof (Mono.Security.Protocol.Tls.HttpsClientStream);
+#else
// HttpsClientStream is an internal glue class in Mono.Security.dll
sslStream = Type.GetType ("Mono.Security.Protocol.Tls.HttpsClientStream, " +
Consts.AssemblyMono_Security, false);
throw new NotSupportedException (msg);
}
+#endif
piClient = sslStream.GetProperty ("SelectedClientCertificate");
piServer = sslStream.GetProperty ("ServerCertificate");
piTrustFailure = sslStream.GetProperty ("TrustFailure");
}
}
- bool CreateTunnel (HttpWebRequest request, Stream stream, out byte [] buffer)
+ bool CreateTunnel (HttpWebRequest request, Uri connectUri,
+ Stream stream, out byte[] buffer)
{
StringBuilder sb = new StringBuilder ();
sb.Append ("CONNECT ");
sb.Append ("\r\nHost: ");
sb.Append (request.Address.Authority);
- string challenge = Data.Challenge;
+
+ bool ntlm = false;
+ var challenge = Data.Challenge;
Data.Challenge = null;
- bool have_auth = (request.Headers ["Proxy-Authorization"] != null);
+ var auth_header = request.Headers ["Proxy-Authorization"];
+ bool have_auth = auth_header != null;
if (have_auth) {
sb.Append ("\r\nProxy-Authorization: ");
- sb.Append (request.Headers ["Proxy-Authorization"]);
+ sb.Append (auth_header);
+ ntlm = auth_header.ToUpper ().Contains ("NTLM");
} else if (challenge != null && Data.StatusCode == 407) {
- have_auth = true;
ICredentials creds = request.Proxy.Credentials;
- Authorization auth = AuthenticationManager.Authenticate (challenge, request, creds);
- if (auth != null) {
+ have_auth = true;
+
+ if (connect_request == null) {
+ // create a CONNECT request to use with Authenticate
+ connect_request = (HttpWebRequest)WebRequest.Create (
+ connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
+ connect_request.Method = "CONNECT";
+ connect_request.Credentials = creds;
+ }
+
+ for (int i = 0; i < challenge.Length; i++) {
+ var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
+ if (auth == null)
+ continue;
+ ntlm = (auth.Module.AuthenticationType == "NTLM");
sb.Append ("\r\nProxy-Authorization: ");
sb.Append (auth.Message);
+ break;
}
}
+
+ if (ntlm) {
+ sb.Append ("\r\nProxy-Connection: keep-alive");
+ connect_ntlm_auth_state++;
+ }
+
sb.Append ("\r\n\r\n");
Data.StatusCode = 0;
stream.Write (connectBytes, 0, connectBytes.Length);
int status;
- WebHeaderCollection result = ReadHeaders (request, stream, out buffer, out status);
- if (!have_auth && result != null && status == 407) { // Needs proxy auth
+ WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
+ if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
+ result != null && status == 407) { // Needs proxy auth
+ var connectionHeader = result ["Connection"];
+ if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
+ connectionHeader.ToLower() == "close") {
+ // The server is requesting that this connection be closed
+ socket.Close();
+ socket = null;
+ }
+
Data.StatusCode = status;
- Data.Challenge = result ["Proxy-Authenticate"];
+ Data.Challenge = result.GetValues_internal ("Proxy-Authenticate", false);
return false;
} else if (status != 200) {
string msg = String.Format ("The remote server returned a {0} status code.", status);
return (result != null);
}
- WebHeaderCollection ReadHeaders (HttpWebRequest request, Stream stream, out byte [] retBuffer, out int status)
+ WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
{
retBuffer = null;
status = 200;
headers = new WebHeaderCollection ();
while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
if (str == null) {
- if (ms.Length - start > 0) {
- retBuffer = new byte [ms.Length - start];
- Buffer.BlockCopy (ms.GetBuffer (), start, retBuffer, 0, retBuffer.Length);
+ int contentLen = 0;
+ try {
+ contentLen = int.Parse(headers["Content-Length"]);
+ }
+ catch {
+ contentLen = 0;
+ }
+
+ if (ms.Length - start - contentLen > 0) {
+ // we've read more data than the response header and conents,
+ // give back extra data to the caller
+ retBuffer = new byte[ms.Length - start - contentLen];
+ Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
}
+ else {
+ // haven't read in some or all of the contents for the response, do so now
+ FlushContents(stream, contentLen - (int)(ms.Length - start));
+ }
+
return headers;
}
}
}
+ void FlushContents(Stream stream, int contentLength)
+ {
+ while (contentLength > 0) {
+ byte[] contentBuffer = new byte[contentLength];
+ int bytesRead = stream.Read(contentBuffer, 0, contentLength);
+ if (bytesRead > 0) {
+ contentLength -= bytesRead;
+ }
+ else {
+ break;
+ }
+ }
+ }
+
bool CreateStream (HttpWebRequest request)
{
try {
if (!reused || nstream == null || nstream.GetType () != sslStream) {
byte [] buffer = null;
if (sPoint.UseConnect) {
- bool ok = CreateTunnel (request, serverStream, out buffer);
+ bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
if (!ok)
return false;
}
request.ClientCertificates,
request, buffer};
nstream = (Stream) Activator.CreateInstance (sslStream, args);
+#if SECURITY_DEP
+ SslClientStream scs = (SslClientStream) nstream;
+ var helper = new ServicePointManager.ChainValidationHelper (request);
+ scs.ServerCertValidation2 += new CertificateValidationCallback2 (helper.ValidateChain);
+#endif
certsAvailable = false;
}
// we also need to set ServicePoint.Certificate
nstream = serverStream;
}
} catch (Exception) {
- status = WebExceptionStatus.ConnectFailure;
+ if (!request.Aborted)
+ status = WebExceptionStatus.ConnectFailure;
return false;
}
static void ReadDone (IAsyncResult result)
{
- WebConnection cnc = (WebConnection) result.AsyncState;
+ WebConnection cnc = (WebConnection)result.AsyncState;
WebConnectionData data = cnc.Data;
Stream ns = cnc.nstream;
if (ns == null) {
int nread = -1;
try {
nread = ns.EndRead (result);
+ } catch (ObjectDisposedException) {
+ return;
} catch (Exception e) {
+ if (e.InnerException is ObjectDisposedException)
+ return;
+
cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
return;
}
int pos = -1;
nread += cnc.position;
- if (cnc.readState == ReadState.None) {
+ if (data.ReadState == ReadState.None) {
Exception exc = null;
try {
- pos = cnc.GetResponse (cnc.buffer, nread);
+ pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
} catch (Exception e) {
exc = e;
}
- if (exc != null) {
+ if (exc != null || pos == -1) {
cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
return;
}
}
- if (cnc.readState != ReadState.Content) {
+ if (data.ReadState == ReadState.Aborted) {
+ cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
+ return;
+ }
+
+ if (data.ReadState != ReadState.Content) {
int est = nread * 2;
int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
byte [] newBuffer = new byte [max];
Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
cnc.buffer = newBuffer;
cnc.position = nread;
- cnc.readState = ReadState.None;
+ data.ReadState = ReadState.None;
InitRead (cnc);
return;
}
cnc.position = 0;
WebConnectionStream stream = new WebConnectionStream (cnc);
+ bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
+ string tencoding = null;
+ if (expect_content)
+ tencoding = data.Headers ["Transfer-Encoding"];
- string contentType = data.Headers ["Transfer-Encoding"];
- cnc.chunkedRead = (contentType != null && contentType.ToLower ().IndexOf ("chunked") != -1);
+ cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
if (!cnc.chunkedRead) {
stream.ReadBuffer = cnc.buffer;
stream.ReadBufferOffset = pos;
stream.ReadBufferSize = nread;
- stream.CheckResponseInBuffer ();
+ try {
+ stream.CheckResponseInBuffer ();
+ } catch (Exception e) {
+ cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
+ }
} else if (cnc.chunkStream == null) {
try {
cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
data.stream = stream;
- if (!ExpectContent (data.StatusCode))
+ if (!expect_content)
stream.ForceCompletion ();
data.request.SetResponseData (data);
}
- static bool ExpectContent (int statusCode)
+ static bool ExpectContent (int statusCode, string method)
{
+ if (method == "HEAD")
+ return false;
return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
}
}
}
- int GetResponse (byte [] buffer, int max)
+ static int GetResponse (WebConnectionData data, ServicePoint sPoint,
+ byte [] buffer, int max)
{
int pos = 0;
string line = null;
bool isContinue = false;
bool emptyFirstLine = false;
do {
- if (readState == ReadState.None) {
+ if (data.ReadState == ReadState.Aborted)
+ return -1;
+
+ if (data.ReadState == ReadState.None) {
lineok = ReadLine (buffer, ref pos, max, ref line);
if (!lineok)
- return -1;
+ return 0;
if (line == null) {
emptyFirstLine = true;
continue;
}
emptyFirstLine = false;
-
- readState = ReadState.Status;
+ data.ReadState = ReadState.Status;
string [] parts = line.Split (' ');
if (parts.Length < 2)
return -1;
if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
- Data.Version = HttpVersion.Version11;
+ data.Version = HttpVersion.Version11;
sPoint.SetVersion (HttpVersion.Version11);
} else {
- Data.Version = HttpVersion.Version10;
+ data.Version = HttpVersion.Version10;
sPoint.SetVersion (HttpVersion.Version10);
}
- Data.StatusCode = (int) UInt32.Parse (parts [1]);
+ data.StatusCode = (int) UInt32.Parse (parts [1]);
if (parts.Length >= 3)
- Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
+ data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
else
- Data.StatusDescription = "";
+ data.StatusDescription = "";
if (pos >= max)
return pos;
}
emptyFirstLine = false;
- if (readState == ReadState.Status) {
- readState = ReadState.Headers;
- Data.Headers = new WebHeaderCollection ();
+ if (data.ReadState == ReadState.Status) {
+ data.ReadState = ReadState.Headers;
+ data.Headers = new WebHeaderCollection ();
ArrayList headers = new ArrayList ();
bool finished = false;
while (!finished) {
}
if (!finished)
- return -1;
+ return 0;
foreach (string s in headers)
- Data.Headers.SetInternal (s);
+ data.Headers.SetInternal (s);
- if (Data.StatusCode == (int) HttpStatusCode.Continue) {
+ if (data.StatusCode == (int) HttpStatusCode.Continue) {
sPoint.SendContinue = true;
if (pos >= max)
return pos;
- if (Data.request.ExpectContinue) {
- Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
+ if (data.request.ExpectContinue) {
+ data.request.DoContinueDelegate (data.StatusCode, data.Headers);
// Prevent double calls when getting the
// headers in several packets.
- Data.request.ExpectContinue = false;
+ data.request.ExpectContinue = false;
}
- readState = ReadState.None;
+ data.ReadState = ReadState.None;
isContinue = true;
}
else {
- readState = ReadState.Content;
+ data.ReadState = ReadState.Content;
return pos;
}
}
void InitConnection (object state)
{
HttpWebRequest request = (HttpWebRequest) state;
+ request.WebConnection = this;
- if (status == WebExceptionStatus.RequestCanceled) {
- lock (this) {
- busy = false;
- Data = new WebConnectionData ();
- SendNext ();
- }
+ if (request.Aborted)
return;
- }
keepAlive = request.KeepAlive;
- Data = new WebConnectionData ();
- Data.request = request;
+ Data = new WebConnectionData (request);
retry:
- Connect ();
+ Connect (request);
+ if (request.Aborted)
+ return;
+
if (status != WebExceptionStatus.Success) {
- if (status != WebExceptionStatus.RequestCanceled) {
+ if (!request.Aborted) {
request.SetWriteStreamError (status, connect_exception);
Close (true);
}
}
if (!CreateStream (request)) {
+ if (request.Aborted)
+ return;
+
+ WebExceptionStatus st = status;
if (Data.Challenge != null)
goto retry;
Exception cnc_exc = connect_exception;
connect_exception = null;
- request.SetWriteStreamError (status, cnc_exc);
+ request.SetWriteStreamError (st, cnc_exc);
Close (true);
return;
}
- readState = ReadState.None;
request.SetWriteStream (new WebConnectionStream (this, request));
}
-
+
+#if MONOTOUCH
+ static bool warned_about_queue = false;
+#endif
+
internal EventHandler SendRequest (HttpWebRequest request)
{
+ if (request.Aborted)
+ return null;
+
lock (this) {
if (!busy) {
busy = true;
ThreadPool.QueueUserWorkItem (initConn, request);
} else {
lock (queue) {
+#if MONOTOUCH
+ if (!warned_about_queue) {
+ warned_about_queue = true;
+ Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
+ }
+#endif
queue.Enqueue (request);
}
}
internal void NextRead ()
{
lock (this) {
- Data.request.FinishedReading = true;
+ if (Data.request != null)
+ Data.request.FinishedReading = true;
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 (cncHeader != null) {
cncHeader = cncHeader.ToLower ();
- keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive") != -1);
+ keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
}
if ((socket != null && !socket.Connected) ||
- (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close") != -1))) {
+ (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
Close (false);
}
}
- internal IAsyncResult BeginRead (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
+ internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
{
- if (nstream == null)
- return null;
+ Stream s = null;
+ lock (this) {
+ if (Data.request != request)
+ throw new ObjectDisposedException (typeof (NetworkStream).FullName);
+ if (nstream == null)
+ return null;
+ s = nstream;
+ }
IAsyncResult result = null;
- if (!chunkedRead || chunkStream.WantMore) {
+ if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
try {
- result = nstream.BeginRead (buffer, offset, size, cb, state);
+ result = s.BeginRead (buffer, offset, size, cb, state);
cb = null;
} catch (Exception) {
HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
return result;
}
- internal int EndRead (IAsyncResult result)
+ internal int EndRead (HttpWebRequest request, IAsyncResult result)
{
- if (nstream == null)
- return 0;
+ Stream s = null;
+ lock (this) {
+ if (Data.request != request)
+ throw new ObjectDisposedException (typeof (NetworkStream).FullName);
+ if (nstream == null)
+ throw new ObjectDisposedException (typeof (NetworkStream).FullName);
+ s = nstream;
+ }
int nbytes = 0;
WebAsyncResult wr = null;
wr = (WebAsyncResult) nsAsync;
IAsyncResult inner = wr.InnerAsyncResult;
if (inner != null && !(inner is WebAsyncResult))
- nbytes = nstream.EndRead (inner);
+ nbytes = s.EndRead (inner);
} else if (!(nsAsync is WebAsyncResult)) {
- nbytes = nstream.EndRead (nsAsync);
+ nbytes = s.EndRead (nsAsync);
wr = (WebAsyncResult) result;
}
return true;
}
- internal IAsyncResult BeginWrite (byte [] buffer, int offset, int size, AsyncCallback cb, object state)
+
+ internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
{
- IAsyncResult result = null;
- if (nstream == null)
- return null;
+ Stream s = null;
+ lock (this) {
+ if (Data.request != request)
+ throw new ObjectDisposedException (typeof (NetworkStream).FullName);
+ if (nstream == null)
+ return null;
+ s = nstream;
+ }
+ IAsyncResult result = null;
try {
- result = nstream.BeginWrite (buffer, offset, size, cb, state);
+ result = s.BeginWrite (buffer, offset, size, cb, state);
} catch (Exception) {
status = WebExceptionStatus.SendFailure;
throw;
return result;
}
- internal bool EndWrite (IAsyncResult result)
+ internal void EndWrite2 (HttpWebRequest request, IAsyncResult result)
{
- if (nstream == null)
- return false;
+ if (request.FinishedReading)
+ return;
+
+ Stream s = null;
+ lock (this) {
+ if (Data.request != request)
+ throw new ObjectDisposedException (typeof (NetworkStream).FullName);
+ if (nstream == null)
+ throw new ObjectDisposedException (typeof (NetworkStream).FullName);
+ s = nstream;
+ }
+
+ try {
+ s.EndWrite (result);
+ } catch (Exception exc) {
+ status = WebExceptionStatus.SendFailure;
+ if (exc.InnerException != null)
+ throw exc.InnerException;
+ throw;
+ }
+ }
+
+ internal bool EndWrite (HttpWebRequest request, IAsyncResult result)
+ {
+ if (request.FinishedReading)
+ return true;
+
+ Stream s = null;
+ lock (this) {
+ if (Data.request != request)
+ throw new ObjectDisposedException (typeof (NetworkStream).FullName);
+ if (nstream == null)
+ throw new ObjectDisposedException (typeof (NetworkStream).FullName);
+ s = nstream;
+ }
try {
- nstream.EndWrite (result);
+ s.EndWrite (result);
return true;
} catch {
status = WebExceptionStatus.SendFailure;
}
}
- internal int Read (byte [] buffer, int offset, int size)
+ internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
{
- if (nstream == null)
- return 0;
+ Stream s = null;
+ lock (this) {
+ if (Data.request != request)
+ throw new ObjectDisposedException (typeof (NetworkStream).FullName);
+ if (nstream == null)
+ return 0;
+ s = nstream;
+ }
int result = 0;
try {
bool done = false;
if (!chunkedRead) {
- result = nstream.Read (buffer, offset, size);
+ result = s.Read (buffer, offset, size);
done = (result == 0);
}
return result;
}
- internal bool Write (byte [] buffer, int offset, int size)
+ internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
{
- if (nstream == null)
- return false;
+ err_msg = null;
+ Stream s = null;
+ lock (this) {
+ if (Data.request != request)
+ throw new ObjectDisposedException (typeof (NetworkStream).FullName);
+ if (nstream == null)
+ return false;
+ s = nstream;
+ }
try {
- nstream.Write (buffer, offset, size);
+ s.Write (buffer, offset, size);
// here SSL handshake should have been done
if (ssl && !certsAvailable)
GetCertificates ();
} catch (Exception e) {
+ err_msg = e.Message;
WebExceptionStatus wes = WebExceptionStatus.SendFailure;
- string msg = "Write";
+ string msg = "Write: " + err_msg;
if (e is WebException) {
HandleError (wes, e, msg);
return false;
socket = null;
}
+ if (ntlm_authenticated)
+ ResetNtlm ();
+ if (Data != null) {
+ lock (Data) {
+ Data.ReadState = ReadState.Aborted;
+ }
+ }
busy = false;
+ Data = new WebConnectionData ();
if (sendNext)
SendNext ();
+
+ connect_request = null;
+ connect_ntlm_auth_state = NtlmAuthState.None;
}
}
void Abort (object sender, EventArgs args)
{
lock (this) {
- if (Data.request == sender) {
- if (!Data.request.FinishedReading)
- HandleError (WebExceptionStatus.RequestCanceled, null, "Abort");
- return;
- }
-
lock (queue) {
- if (queue.Count > 0 && queue.Peek () == sender) {
- queue.Dequeue ();
+ HttpWebRequest req = (HttpWebRequest) sender;
+ if (Data.request == req || Data.request == null) {
+ if (!req.FinishedReading) {
+ status = WebExceptionStatus.RequestCanceled;
+ Close (false);
+ if (queue.Count > 0) {
+ Data.request = (HttpWebRequest) queue.Dequeue ();
+ SendRequest (Data.request);
+ }
+ }
return;
}
- object [] old = queue.ToArray ();
- queue.Clear ();
- for (int i = old.Length - 1; i >= 0; i--) {
- if (old [i] != sender)
- queue.Enqueue (old [i]);
+ req.FinishedReading = true;
+ req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
+ if (queue.Count > 0 && queue.Peek () == sender) {
+ queue.Dequeue ();
+ } else if (queue.Count > 0) {
+ object [] old = queue.ToArray ();
+ queue.Clear ();
+ for (int i = old.Length - 1; i >= 0; i--) {
+ if (old [i] != sender)
+ queue.Enqueue (old [i]);
+ }
}
}
}
set { ntlm_credentials = value; }
}
-#if NET_1_1
internal bool UnsafeAuthenticatedConnectionSharing {
get { return unsafe_sharing; }
set { unsafe_sharing = value; }
}
-#endif
// -
}
}