2 // System.Net.WebConnection
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.Net.Sockets;
34 using System.Security.Cryptography.X509Certificates;
36 using System.Threading;
37 using System.Diagnostics;
38 using Mono.Net.Security;
55 internal Socket socket;
56 object socketLock = new object ();
57 IWebConnectionState state;
58 WebExceptionStatus status;
59 WaitCallback initConn;
62 static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
63 EventHandler abortHandler;
64 AbortHelper abortHelper;
65 internal WebConnectionData Data;
67 ChunkStream chunkStream;
71 HttpWebRequest priority_request;
72 NetworkCredential ntlm_credentials;
73 bool ntlm_authenticated;
82 NtlmAuthState connect_ntlm_auth_state;
83 HttpWebRequest connect_request;
85 Exception connect_exception;
86 static object classLock = new object ();
87 MonoTlsStream tlsStream;
89 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
90 [System.Runtime.InteropServices.DllImport ("__Internal")]
91 static extern void xamarin_start_wwan (string uri);
94 internal ChunkStream ChunkStream {
95 get { return chunkStream; }
98 public WebConnection (IWebConnectionState wcs, ServicePoint sPoint)
101 this.sPoint = sPoint;
102 buffer = new byte [4096];
103 Data = new WebConnectionData ();
104 initConn = new WaitCallback (state => {
106 InitConnection (state);
109 queue = wcs.Group.Queue;
110 abortHelper = new AbortHelper ();
111 abortHelper.Connection = this;
112 abortHandler = new EventHandler (abortHelper.Abort);
116 public WebConnection Connection;
118 public void Abort (object sender, EventArgs args)
120 WebConnection other = ((HttpWebRequest) sender).WebConnection;
123 other.Abort (sender, args);
129 // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
130 // but if there's data pending to read (!) we won't reuse the socket.
131 return (socket.Poll (0, SelectMode.SelectRead) == false);
134 void Connect (HttpWebRequest request)
137 if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
138 // Take the chunked stream to the expected state (State.None)
139 if (CanReuse () && CompleteChunkedRead ()) {
146 if (socket != null) {
152 IPHostEntry hostEntry = sPoint.HostEntry;
154 if (hostEntry == null) {
155 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
156 xamarin_start_wwan (sPoint.Address.ToString ());
157 hostEntry = sPoint.HostEntry;
158 if (hostEntry == null) {
160 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
161 WebExceptionStatus.NameResolutionFailure;
163 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
168 //WebConnectionData data = Data;
169 foreach (IPAddress address in hostEntry.AddressList) {
171 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
172 } catch (Exception se) {
173 // The Socket ctor can throw if we run out of FD's
174 if (!request.Aborted)
175 status = WebExceptionStatus.ConnectFailure;
176 connect_exception = se;
179 IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
180 socket.NoDelay = !sPoint.UseNagleAlgorithm;
182 sPoint.KeepAliveSetup (socket);
184 // Ignore. Not supported in all platforms.
187 if (!sPoint.CallEndPointDelegate (socket, remote)) {
190 status = WebExceptionStatus.ConnectFailure;
195 socket.Connect (remote);
196 status = WebExceptionStatus.Success;
198 } catch (ThreadAbortException) {
199 // program exiting...
205 } catch (ObjectDisposedException) {
206 // socket closed from another thread
208 } catch (Exception exc) {
213 if (!request.Aborted)
214 status = WebExceptionStatus.ConnectFailure;
215 connect_exception = exc;
222 bool CreateTunnel (HttpWebRequest request, Uri connectUri,
223 Stream stream, out byte[] buffer)
225 StringBuilder sb = new StringBuilder ();
226 sb.Append ("CONNECT ");
227 sb.Append (request.Address.Host);
229 sb.Append (request.Address.Port);
230 sb.Append (" HTTP/");
231 if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
236 sb.Append ("\r\nHost: ");
237 sb.Append (request.Address.Authority);
240 var challenge = Data.Challenge;
241 Data.Challenge = null;
242 var auth_header = request.Headers ["Proxy-Authorization"];
243 bool have_auth = auth_header != null;
245 sb.Append ("\r\nProxy-Authorization: ");
246 sb.Append (auth_header);
247 ntlm = auth_header.ToUpper ().Contains ("NTLM");
248 } else if (challenge != null && Data.StatusCode == 407) {
249 ICredentials creds = request.Proxy.Credentials;
252 if (connect_request == null) {
253 // create a CONNECT request to use with Authenticate
254 connect_request = (HttpWebRequest)WebRequest.Create (
255 connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
256 connect_request.Method = "CONNECT";
257 connect_request.Credentials = creds;
260 for (int i = 0; i < challenge.Length; i++) {
261 var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
264 ntlm = (auth.ModuleAuthenticationType == "NTLM");
265 sb.Append ("\r\nProxy-Authorization: ");
266 sb.Append (auth.Message);
272 sb.Append ("\r\nProxy-Connection: keep-alive");
273 connect_ntlm_auth_state++;
276 sb.Append ("\r\n\r\n");
279 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
280 stream.Write (connectBytes, 0, connectBytes.Length);
283 WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
284 if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
285 result != null && status == 407) { // Needs proxy auth
286 var connectionHeader = result ["Connection"];
287 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
288 connectionHeader.ToLower() == "close") {
289 // The server is requesting that this connection be closed
294 Data.StatusCode = status;
295 Data.Challenge = result.GetValues ("Proxy-Authentic");
296 Data.Headers = result;
298 } else if (status != 200) {
299 string msg = String.Format ("The remote server returned a {0} status code.", status);
300 HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
304 return (result != null);
307 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
312 byte [] buffer = new byte [1024];
313 MemoryStream ms = new MemoryStream ();
316 int n = stream.Read (buffer, 0, 1024);
318 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
322 ms.Write (buffer, 0, n);
325 bool gotStatus = false;
326 WebHeaderCollection headers = new WebHeaderCollection ();
327 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
331 contentLen = int.Parse(headers["Content-Length"]);
337 if (ms.Length - start - contentLen > 0) {
338 // we've read more data than the response header and conents,
339 // give back extra data to the caller
340 retBuffer = new byte[ms.Length - start - contentLen];
341 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
344 // haven't read in some or all of the contents for the response, do so now
345 FlushContents(stream, contentLen - (int)(ms.Length - start));
356 string[] parts = str.Split (' ');
357 if (parts.Length < 2) {
358 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
362 if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
363 Data.ProxyVersion = HttpVersion.Version11;
364 else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
365 Data.ProxyVersion = HttpVersion.Version10;
367 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
371 status = (int)UInt32.Parse (parts [1]);
372 if (parts.Length >= 3)
373 Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
380 void FlushContents(Stream stream, int contentLength)
382 while (contentLength > 0) {
383 byte[] contentBuffer = new byte[contentLength];
384 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
386 contentLength -= bytesRead;
394 bool CreateStream (HttpWebRequest request)
397 NetworkStream serverStream = new NetworkStream (socket, false);
399 if (request.Address.Scheme == Uri.UriSchemeHttps) {
401 if (!reused || nstream == null || tlsStream == null) {
402 byte [] buffer = null;
403 if (sPoint.UseConnect) {
404 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
408 tlsStream = new MonoTlsStream (request, serverStream);
409 nstream = tlsStream.CreateStream (buffer);
411 // we also need to set ServicePoint.Certificate
412 // and ServicePoint.ClientCertificate but this can
413 // only be done later (after handshake - which is
414 // done only after a read operation).
416 throw new NotSupportedException ();
419 nstream = serverStream;
421 } catch (Exception ex) {
422 if (tlsStream != null)
423 status = tlsStream.ExceptionStatus;
424 else if (!request.Aborted)
425 status = WebExceptionStatus.ConnectFailure;
426 connect_exception = ex;
433 void HandleError (WebExceptionStatus st, Exception e, string where)
437 if (st == WebExceptionStatus.RequestCanceled)
438 Data = new WebConnectionData ();
441 if (e == null) { // At least we now where it comes from
443 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
444 } catch (Exception e2) {
449 HttpWebRequest req = null;
450 if (Data != null && Data.request != null)
455 req.FinishedReading = true;
456 req.SetResponseError (st, e, where);
460 static void ReadDone (IAsyncResult result)
462 WebConnection cnc = (WebConnection)result.AsyncState;
463 WebConnectionData data = cnc.Data;
464 Stream ns = cnc.nstream;
472 nread = ns.EndRead (result);
473 } catch (ObjectDisposedException) {
475 } catch (Exception e) {
476 if (e.InnerException is ObjectDisposedException)
479 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
484 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
489 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
494 nread += cnc.position;
495 if (data.ReadState == ReadState.None) {
496 Exception exc = null;
498 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
499 } catch (Exception e) {
503 if (exc != null || pos == -1) {
504 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
509 if (data.ReadState == ReadState.Aborted) {
510 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
514 if (data.ReadState != ReadState.Content) {
516 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
517 byte [] newBuffer = new byte [max];
518 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
519 cnc.buffer = newBuffer;
520 cnc.position = nread;
521 data.ReadState = ReadState.None;
528 WebConnectionStream stream = new WebConnectionStream (cnc, data);
529 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
530 string tencoding = null;
532 tencoding = data.Headers ["Transfer-Encoding"];
534 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
535 if (!cnc.chunkedRead) {
536 stream.ReadBuffer = cnc.buffer;
537 stream.ReadBufferOffset = pos;
538 stream.ReadBufferSize = nread;
540 stream.CheckResponseInBuffer ();
541 } catch (Exception e) {
542 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
544 } else if (cnc.chunkStream == null) {
546 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
547 } catch (Exception e) {
548 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
552 cnc.chunkStream.ResetBuffer ();
554 cnc.chunkStream.Write (cnc.buffer, pos, nread);
555 } catch (Exception e) {
556 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
561 data.stream = stream;
564 stream.ForceCompletion ();
566 data.request.SetResponseData (data);
569 static bool ExpectContent (int statusCode, string method)
571 if (method == "HEAD")
573 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
576 internal static void InitRead (object state)
578 WebConnection cnc = (WebConnection) state;
579 Stream ns = cnc.nstream;
582 int size = cnc.buffer.Length - cnc.position;
583 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
584 } catch (Exception e) {
585 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
589 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
590 byte [] buffer, int max)
595 bool isContinue = false;
596 bool emptyFirstLine = false;
598 if (data.ReadState == ReadState.Aborted)
601 if (data.ReadState == ReadState.None) {
602 lineok = ReadLine (buffer, ref pos, max, ref line);
607 emptyFirstLine = true;
610 emptyFirstLine = false;
611 data.ReadState = ReadState.Status;
613 string [] parts = line.Split (' ');
614 if (parts.Length < 2)
617 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
618 data.Version = HttpVersion.Version11;
619 sPoint.SetVersion (HttpVersion.Version11);
621 data.Version = HttpVersion.Version10;
622 sPoint.SetVersion (HttpVersion.Version10);
625 data.StatusCode = (int) UInt32.Parse (parts [1]);
626 if (parts.Length >= 3)
627 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
629 data.StatusDescription = "";
635 emptyFirstLine = false;
636 if (data.ReadState == ReadState.Status) {
637 data.ReadState = ReadState.Headers;
638 data.Headers = new WebHeaderCollection ();
639 ArrayList headers = new ArrayList ();
640 bool finished = false;
642 if (ReadLine (buffer, ref pos, max, ref line) == false)
646 // Empty line: end of headers
651 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
652 int count = headers.Count - 1;
656 string prev = (string) headers [count] + line;
657 headers [count] = prev;
666 // .NET uses ParseHeaders or ParseHeadersStrict which is much better
667 foreach (string s in headers) {
669 int pos_s = s.IndexOf (':');
671 throw new ArgumentException ("no colon found", "header");
673 var header = s.Substring (0, pos_s);
674 var value = s.Substring (pos_s + 1).Trim ();
676 var h = data.Headers;
677 if (WebHeaderCollection.AllowMultiValues (header)) {
678 h.AddInternal (header, value);
680 h.SetInternal (header, value);
684 if (data.StatusCode == (int) HttpStatusCode.Continue) {
685 sPoint.SendContinue = true;
689 if (data.request.ExpectContinue) {
690 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
691 // Prevent double calls when getting the
692 // headers in several packets.
693 data.request.ExpectContinue = false;
696 data.ReadState = ReadState.None;
700 data.ReadState = ReadState.Content;
704 } while (emptyFirstLine || isContinue);
709 void InitConnection (object state)
711 HttpWebRequest request = (HttpWebRequest) state;
712 request.WebConnection = this;
713 if (request.ReuseConnection)
714 request.StoredConnection = this;
719 keepAlive = request.KeepAlive;
720 Data = new WebConnectionData (request);
726 if (status != WebExceptionStatus.Success) {
727 if (!request.Aborted) {
728 request.SetWriteStreamError (status, connect_exception);
734 if (!CreateStream (request)) {
738 WebExceptionStatus st = status;
739 if (Data.Challenge != null)
742 Exception cnc_exc = connect_exception;
743 if (cnc_exc == null && (Data.StatusCode == 401 || Data.StatusCode == 407)) {
744 st = WebExceptionStatus.ProtocolError;
745 if (Data.Headers == null)
746 Data.Headers = new WebHeaderCollection ();
748 var webResponse = new HttpWebResponse (sPoint.Address, "CONNECT", Data, null);
749 cnc_exc = new WebException (Data.StatusCode == 407 ? "(407) Proxy Authentication Required" : "(401) Unauthorized", null, st, webResponse);
752 connect_exception = null;
753 request.SetWriteStreamError (st, cnc_exc);
758 request.SetWriteStream (new WebConnectionStream (this, request));
762 static bool warned_about_queue = false;
765 internal EventHandler SendRequest (HttpWebRequest request)
771 if (state.TrySetBusy ()) {
772 status = WebExceptionStatus.Success;
773 ThreadPool.QueueUserWorkItem (initConn, request);
777 if (!warned_about_queue) {
778 warned_about_queue = true;
779 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
782 queue.Enqueue (request);
793 if (queue.Count > 0) {
794 SendRequest ((HttpWebRequest) queue.Dequeue ());
799 internal void NextRead ()
802 if (Data.request != null)
803 Data.request.FinishedReading = true;
804 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
805 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
806 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
807 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
809 if (cncHeader != null) {
810 cncHeader = cncHeader.ToLower ();
811 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
814 if ((socket != null && !socket.Connected) ||
815 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
820 if (priority_request != null) {
821 SendRequest (priority_request);
822 priority_request = null;
829 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
831 bool foundCR = false;
832 StringBuilder text = new StringBuilder ();
835 while (start < max) {
836 c = (int) buffer [start++];
838 if (c == '\n') { // newline
839 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
844 } else if (foundCR) {
853 text.Append ((char) c);
856 if (c != '\n' && c != '\r')
859 if (text.Length == 0) {
861 return (c == '\n' || c == '\r');
867 output = text.ToString ();
872 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
876 if (Data.request != request)
877 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
883 IAsyncResult result = null;
884 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
886 result = s.BeginRead (buffer, offset, size, cb, state);
888 } catch (Exception) {
889 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
895 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
896 wr.InnerAsyncResult = result;
897 if (result == null) {
898 // Will be completed from the data in ChunkStream
899 wr.SetCompleted (true, (Exception) null);
908 internal int EndRead (HttpWebRequest request, IAsyncResult result)
913 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
914 if (Data.request != request)
915 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
917 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
923 WebAsyncResult wr = null;
924 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
925 if (chunkedRead && (nsAsync is WebAsyncResult)) {
926 wr = (WebAsyncResult) nsAsync;
927 IAsyncResult inner = wr.InnerAsyncResult;
928 if (inner != null && !(inner is WebAsyncResult)) {
929 nbytes = s.EndRead (inner);
932 } else if (!(nsAsync is WebAsyncResult)) {
933 nbytes = s.EndRead (nsAsync);
934 wr = (WebAsyncResult) result;
940 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
941 if (!done && nbytes == 0 && chunkStream.WantMore)
942 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
943 } catch (Exception e) {
944 if (e is WebException)
947 throw new WebException ("Invalid chunked data.", e,
948 WebExceptionStatus.ServerProtocolViolation, null);
951 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
952 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
953 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
957 return (nbytes != 0) ? nbytes : -1;
960 // To be called on chunkedRead when we can read no data from the ChunkStream yet
961 int EnsureRead (byte [] buffer, int offset, int size)
963 byte [] morebytes = null;
965 while (nbytes == 0 && chunkStream.WantMore) {
966 int localsize = chunkStream.ChunkLeft;
967 if (localsize <= 0) // not read chunk size yet
969 else if (localsize > 16384)
972 if (morebytes == null || morebytes.Length < localsize)
973 morebytes = new byte [localsize];
975 int nread = nstream.Read (morebytes, 0, localsize);
979 chunkStream.Write (morebytes, 0, nread);
980 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
986 bool CompleteChunkedRead()
988 if (!chunkedRead || chunkStream == null)
991 while (chunkStream.WantMore) {
992 int nbytes = nstream.Read (buffer, 0, buffer.Length);
994 return false; // Socket was disconnected
996 chunkStream.Write (buffer, 0, nbytes);
1002 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
1006 if (Data.request != request)
1007 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1008 if (nstream == null)
1013 IAsyncResult result = null;
1015 result = s.BeginWrite (buffer, offset, size, cb, state);
1016 } catch (Exception) {
1017 status = WebExceptionStatus.SendFailure;
1024 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1028 if (status == WebExceptionStatus.RequestCanceled)
1030 if (Data.request != request)
1031 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1032 if (nstream == null)
1033 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1038 s.EndWrite (result);
1040 } catch (Exception exc) {
1041 status = WebExceptionStatus.SendFailure;
1042 if (throwOnError && exc.InnerException != null)
1043 throw exc.InnerException;
1048 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1052 if (Data.request != request)
1053 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1054 if (nstream == null)
1063 result = s.Read (buffer, offset, size);
1064 done = (result == 0);
1069 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1070 if (!done && result == 0 && chunkStream.WantMore)
1071 result = EnsureRead (buffer, offset, size);
1072 } catch (Exception e) {
1073 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1077 if ((done || result == 0) && chunkStream.WantMore) {
1078 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1079 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1082 } catch (Exception e) {
1083 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1089 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1094 if (Data.request != request)
1095 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1102 s.Write (buffer, offset, size);
1103 } catch (Exception e) {
1104 err_msg = e.Message;
1105 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1106 string msg = "Write: " + err_msg;
1107 if (e is WebException) {
1108 HandleError (wes, e, msg);
1112 HandleError (wes, e, msg);
1118 internal void Close (bool sendNext)
1121 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1122 Data.request.ReuseConnection = false;
1126 if (nstream != null) {
1133 if (socket != null) {
1140 if (ntlm_authenticated)
1144 Data.ReadState = ReadState.Aborted;
1148 Data = new WebConnectionData ();
1152 connect_request = null;
1153 connect_ntlm_auth_state = NtlmAuthState.None;
1157 void Abort (object sender, EventArgs args)
1161 HttpWebRequest req = (HttpWebRequest) sender;
1162 if (Data.request == req || Data.request == null) {
1163 if (!req.FinishedReading) {
1164 status = WebExceptionStatus.RequestCanceled;
1166 if (queue.Count > 0) {
1167 Data.request = (HttpWebRequest) queue.Dequeue ();
1168 SendRequest (Data.request);
1174 req.FinishedReading = true;
1175 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1176 if (queue.Count > 0 && queue.Peek () == sender) {
1178 } else if (queue.Count > 0) {
1179 object [] old = queue.ToArray ();
1181 for (int i = old.Length - 1; i >= 0; i--) {
1182 if (old [i] != sender)
1183 queue.Enqueue (old [i]);
1190 internal void ResetNtlm ()
1192 ntlm_authenticated = false;
1193 ntlm_credentials = null;
1194 unsafe_sharing = false;
1197 internal bool Connected {
1200 return (socket != null && socket.Connected);
1205 // -Used for NTLM authentication
1206 internal HttpWebRequest PriorityRequest {
1207 set { priority_request = value; }
1210 internal bool NtlmAuthenticated {
1211 get { return ntlm_authenticated; }
1212 set { ntlm_authenticated = value; }
1215 internal NetworkCredential NtlmCredential {
1216 get { return ntlm_credentials; }
1217 set { ntlm_credentials = value; }
1220 internal bool UnsafeAuthenticatedConnectionSharing {
1221 get { return unsafe_sharing; }
1222 set { unsafe_sharing = value; }