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.Reflection;
35 using System.Security.Cryptography.X509Certificates;
37 using System.Threading;
38 using System.Diagnostics;
39 using Mono.Net.Security;
56 internal Socket socket;
57 object socketLock = new object ();
58 IWebConnectionState state;
59 WebExceptionStatus status;
60 WaitCallback initConn;
63 static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
64 EventHandler abortHandler;
65 AbortHelper abortHelper;
66 internal WebConnectionData Data;
68 ChunkStream chunkStream;
72 HttpWebRequest priority_request;
73 NetworkCredential ntlm_credentials;
74 bool ntlm_authenticated;
83 NtlmAuthState connect_ntlm_auth_state;
84 HttpWebRequest connect_request;
87 Exception connect_exception;
88 static object classLock = new object ();
89 IMonoTlsProvider tlsProvider;
90 MonoTlsStream tlsStream;
93 [System.Runtime.InteropServices.DllImport ("__Internal")]
94 static extern void xamarin_start_wwan (string uri);
97 internal ChunkStream ChunkStream {
98 get { return chunkStream; }
101 public WebConnection (IWebConnectionState wcs, ServicePoint sPoint)
104 this.sPoint = sPoint;
105 buffer = new byte [4096];
106 Data = new WebConnectionData ();
107 initConn = new WaitCallback (state => {
109 InitConnection (state);
112 queue = wcs.Group.Queue;
113 abortHelper = new AbortHelper ();
114 abortHelper.Connection = this;
115 abortHandler = new EventHandler (abortHelper.Abort);
119 public WebConnection Connection;
121 public void Abort (object sender, EventArgs args)
123 WebConnection other = ((HttpWebRequest) sender).WebConnection;
126 other.Abort (sender, args);
132 // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
133 // but if there's data pending to read (!) we won't reuse the socket.
134 return (socket.Poll (0, SelectMode.SelectRead) == false);
137 void Connect (HttpWebRequest request)
140 if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
141 // Take the chunked stream to the expected state (State.None)
142 if (CanReuse () && CompleteChunkedRead ()) {
149 if (socket != null) {
155 IPHostEntry hostEntry = sPoint.HostEntry;
157 if (hostEntry == null) {
159 xamarin_start_wwan (sPoint.Address.ToString ());
160 hostEntry = sPoint.HostEntry;
161 if (hostEntry == null) {
163 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
164 WebExceptionStatus.NameResolutionFailure;
171 //WebConnectionData data = Data;
172 foreach (IPAddress address in hostEntry.AddressList) {
174 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
175 } catch (Exception se) {
176 // The Socket ctor can throw if we run out of FD's
177 if (!request.Aborted)
178 status = WebExceptionStatus.ConnectFailure;
179 connect_exception = se;
182 IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
183 socket.NoDelay = !sPoint.UseNagleAlgorithm;
185 sPoint.KeepAliveSetup (socket);
187 // Ignore. Not supported in all platforms.
190 if (!sPoint.CallEndPointDelegate (socket, remote)) {
193 status = WebExceptionStatus.ConnectFailure;
198 socket.Connect (remote);
199 status = WebExceptionStatus.Success;
201 } catch (ThreadAbortException) {
202 // program exiting...
208 } catch (ObjectDisposedException) {
209 // socket closed from another thread
211 } catch (Exception exc) {
216 if (!request.Aborted)
217 status = WebExceptionStatus.ConnectFailure;
218 connect_exception = exc;
225 void EnsureSSLStreamAvailable (HttpWebRequest request)
227 tlsProvider = request.TlsProvider;
228 if (tlsProvider != null)
231 tlsProvider = MonoTlsProviderFactory.GetProviderInternal ();
234 bool CreateTunnel (HttpWebRequest request, Uri connectUri,
235 Stream stream, out byte[] buffer)
237 StringBuilder sb = new StringBuilder ();
238 sb.Append ("CONNECT ");
239 sb.Append (request.Address.Host);
241 sb.Append (request.Address.Port);
242 sb.Append (" HTTP/");
243 if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
248 sb.Append ("\r\nHost: ");
249 sb.Append (request.Address.Authority);
252 var challenge = Data.Challenge;
253 Data.Challenge = null;
254 var auth_header = request.Headers ["Proxy-Authorization"];
255 bool have_auth = auth_header != null;
257 sb.Append ("\r\nProxy-Authorization: ");
258 sb.Append (auth_header);
259 ntlm = auth_header.ToUpper ().Contains ("NTLM");
260 } else if (challenge != null && Data.StatusCode == 407) {
261 ICredentials creds = request.Proxy.Credentials;
264 if (connect_request == null) {
265 // create a CONNECT request to use with Authenticate
266 connect_request = (HttpWebRequest)WebRequest.Create (
267 connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
268 connect_request.Method = "CONNECT";
269 connect_request.Credentials = creds;
272 for (int i = 0; i < challenge.Length; i++) {
273 var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
276 ntlm = (auth.Module.AuthenticationType == "NTLM");
277 sb.Append ("\r\nProxy-Authorization: ");
278 sb.Append (auth.Message);
284 sb.Append ("\r\nProxy-Connection: keep-alive");
285 connect_ntlm_auth_state++;
288 sb.Append ("\r\n\r\n");
291 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
292 stream.Write (connectBytes, 0, connectBytes.Length);
295 WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
296 if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
297 result != null && status == 407) { // Needs proxy auth
298 var connectionHeader = result ["Connection"];
299 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
300 connectionHeader.ToLower() == "close") {
301 // The server is requesting that this connection be closed
306 Data.StatusCode = status;
307 Data.Challenge = result.GetValues_internal ("Proxy-Authenticate", false);
309 } else if (status != 200) {
310 string msg = String.Format ("The remote server returned a {0} status code.", status);
311 HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
315 return (result != null);
318 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
323 byte [] buffer = new byte [1024];
324 MemoryStream ms = new MemoryStream ();
327 int n = stream.Read (buffer, 0, 1024);
329 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
333 ms.Write (buffer, 0, n);
336 bool gotStatus = false;
337 WebHeaderCollection headers = new WebHeaderCollection ();
338 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
342 contentLen = int.Parse(headers["Content-Length"]);
348 if (ms.Length - start - contentLen > 0) {
349 // we've read more data than the response header and conents,
350 // give back extra data to the caller
351 retBuffer = new byte[ms.Length - start - contentLen];
352 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
355 // haven't read in some or all of the contents for the response, do so now
356 FlushContents(stream, contentLen - (int)(ms.Length - start));
367 string[] parts = str.Split (' ');
368 if (parts.Length < 2) {
369 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
373 if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
374 Data.ProxyVersion = HttpVersion.Version11;
375 else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
376 Data.ProxyVersion = HttpVersion.Version10;
378 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
382 status = (int)UInt32.Parse (parts [1]);
388 void FlushContents(Stream stream, int contentLength)
390 while (contentLength > 0) {
391 byte[] contentBuffer = new byte[contentLength];
392 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
394 contentLength -= bytesRead;
402 bool CreateStream (HttpWebRequest request)
405 NetworkStream serverStream = new NetworkStream (socket, false);
407 if (request.Address.Scheme == Uri.UriSchemeHttps) {
410 EnsureSSLStreamAvailable (request);
411 if (!reused || nstream == null || tlsStream == null) {
412 byte [] buffer = null;
413 if (sPoint.UseConnect) {
414 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
418 tlsStream = new MonoTlsStream (request, serverStream);
419 nstream = tlsStream.CreateStream (buffer);
421 // we also need to set ServicePoint.Certificate
422 // and ServicePoint.ClientCertificate but this can
423 // only be done later (after handshake - which is
424 // done only after a read operation).
426 throw new NotSupportedException ();
430 nstream = serverStream;
432 } catch (Exception ex) {
433 if (tlsStream != null)
434 status = tlsStream.ExceptionStatus;
435 else if (!request.Aborted)
436 status = WebExceptionStatus.ConnectFailure;
443 void HandleError (WebExceptionStatus st, Exception e, string where)
447 if (st == WebExceptionStatus.RequestCanceled)
448 Data = new WebConnectionData ();
451 if (e == null) { // At least we now where it comes from
453 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
454 } catch (Exception e2) {
459 HttpWebRequest req = null;
460 if (Data != null && Data.request != null)
465 req.FinishedReading = true;
466 req.SetResponseError (st, e, where);
470 static void ReadDone (IAsyncResult result)
472 WebConnection cnc = (WebConnection)result.AsyncState;
473 WebConnectionData data = cnc.Data;
474 Stream ns = cnc.nstream;
482 nread = ns.EndRead (result);
483 } catch (ObjectDisposedException) {
485 } catch (Exception e) {
486 if (e.InnerException is ObjectDisposedException)
489 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
494 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
499 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
504 nread += cnc.position;
505 if (data.ReadState == ReadState.None) {
506 Exception exc = null;
508 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
509 } catch (Exception e) {
513 if (exc != null || pos == -1) {
514 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
519 if (data.ReadState == ReadState.Aborted) {
520 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
524 if (data.ReadState != ReadState.Content) {
526 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
527 byte [] newBuffer = new byte [max];
528 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
529 cnc.buffer = newBuffer;
530 cnc.position = nread;
531 data.ReadState = ReadState.None;
538 WebConnectionStream stream = new WebConnectionStream (cnc, data);
539 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
540 string tencoding = null;
542 tencoding = data.Headers ["Transfer-Encoding"];
544 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
545 if (!cnc.chunkedRead) {
546 stream.ReadBuffer = cnc.buffer;
547 stream.ReadBufferOffset = pos;
548 stream.ReadBufferSize = nread;
550 stream.CheckResponseInBuffer ();
551 } catch (Exception e) {
552 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
554 } else if (cnc.chunkStream == null) {
556 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
557 } catch (Exception e) {
558 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
562 cnc.chunkStream.ResetBuffer ();
564 cnc.chunkStream.Write (cnc.buffer, pos, nread);
565 } catch (Exception e) {
566 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
571 data.stream = stream;
574 stream.ForceCompletion ();
576 data.request.SetResponseData (data);
579 static bool ExpectContent (int statusCode, string method)
581 if (method == "HEAD")
583 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
586 internal static void InitRead (object state)
588 WebConnection cnc = (WebConnection) state;
589 Stream ns = cnc.nstream;
592 int size = cnc.buffer.Length - cnc.position;
593 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
594 } catch (Exception e) {
595 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
599 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
600 byte [] buffer, int max)
605 bool isContinue = false;
606 bool emptyFirstLine = false;
608 if (data.ReadState == ReadState.Aborted)
611 if (data.ReadState == ReadState.None) {
612 lineok = ReadLine (buffer, ref pos, max, ref line);
617 emptyFirstLine = true;
620 emptyFirstLine = false;
621 data.ReadState = ReadState.Status;
623 string [] parts = line.Split (' ');
624 if (parts.Length < 2)
627 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
628 data.Version = HttpVersion.Version11;
629 sPoint.SetVersion (HttpVersion.Version11);
631 data.Version = HttpVersion.Version10;
632 sPoint.SetVersion (HttpVersion.Version10);
635 data.StatusCode = (int) UInt32.Parse (parts [1]);
636 if (parts.Length >= 3)
637 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
639 data.StatusDescription = "";
645 emptyFirstLine = false;
646 if (data.ReadState == ReadState.Status) {
647 data.ReadState = ReadState.Headers;
648 data.Headers = new WebHeaderCollection ();
649 ArrayList headers = new ArrayList ();
650 bool finished = false;
652 if (ReadLine (buffer, ref pos, max, ref line) == false)
656 // Empty line: end of headers
661 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
662 int count = headers.Count - 1;
666 string prev = (string) headers [count] + line;
667 headers [count] = prev;
676 foreach (string s in headers)
677 data.Headers.SetInternal (s);
679 if (data.StatusCode == (int) HttpStatusCode.Continue) {
680 sPoint.SendContinue = true;
684 if (data.request.ExpectContinue) {
685 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
686 // Prevent double calls when getting the
687 // headers in several packets.
688 data.request.ExpectContinue = false;
691 data.ReadState = ReadState.None;
695 data.ReadState = ReadState.Content;
699 } while (emptyFirstLine || isContinue);
704 void InitConnection (object state)
706 HttpWebRequest request = (HttpWebRequest) state;
707 request.WebConnection = this;
708 if (request.ReuseConnection)
709 request.StoredConnection = this;
714 keepAlive = request.KeepAlive;
715 Data = new WebConnectionData (request);
721 if (status != WebExceptionStatus.Success) {
722 if (!request.Aborted) {
723 request.SetWriteStreamError (status, connect_exception);
729 if (!CreateStream (request)) {
733 WebExceptionStatus st = status;
734 if (Data.Challenge != null)
737 Exception cnc_exc = connect_exception;
738 connect_exception = null;
739 request.SetWriteStreamError (st, cnc_exc);
744 request.SetWriteStream (new WebConnectionStream (this, request));
748 static bool warned_about_queue = false;
751 internal EventHandler SendRequest (HttpWebRequest request)
757 if (state.TrySetBusy ()) {
758 status = WebExceptionStatus.Success;
759 ThreadPool.QueueUserWorkItem (initConn, request);
763 if (!warned_about_queue) {
764 warned_about_queue = true;
765 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
768 queue.Enqueue (request);
779 if (queue.Count > 0) {
780 SendRequest ((HttpWebRequest) queue.Dequeue ());
785 internal void NextRead ()
788 if (Data.request != null)
789 Data.request.FinishedReading = true;
790 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
791 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
792 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
793 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
795 if (cncHeader != null) {
796 cncHeader = cncHeader.ToLower ();
797 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
800 if ((socket != null && !socket.Connected) ||
801 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
806 if (priority_request != null) {
807 SendRequest (priority_request);
808 priority_request = null;
815 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
817 bool foundCR = false;
818 StringBuilder text = new StringBuilder ();
821 while (start < max) {
822 c = (int) buffer [start++];
824 if (c == '\n') { // newline
825 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
830 } else if (foundCR) {
839 text.Append ((char) c);
842 if (c != '\n' && c != '\r')
845 if (text.Length == 0) {
847 return (c == '\n' || c == '\r');
853 output = text.ToString ();
858 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
862 if (Data.request != request)
863 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
869 IAsyncResult result = null;
870 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
872 result = s.BeginRead (buffer, offset, size, cb, state);
874 } catch (Exception) {
875 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
881 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
882 wr.InnerAsyncResult = result;
883 if (result == null) {
884 // Will be completed from the data in ChunkStream
885 wr.SetCompleted (true, (Exception) null);
894 internal int EndRead (HttpWebRequest request, IAsyncResult result)
898 if (Data.request != request)
899 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
901 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
907 WebAsyncResult wr = null;
908 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
909 if (chunkedRead && (nsAsync is WebAsyncResult)) {
910 wr = (WebAsyncResult) nsAsync;
911 IAsyncResult inner = wr.InnerAsyncResult;
912 if (inner != null && !(inner is WebAsyncResult)) {
913 nbytes = s.EndRead (inner);
916 } else if (!(nsAsync is WebAsyncResult)) {
917 nbytes = s.EndRead (nsAsync);
918 wr = (WebAsyncResult) result;
924 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
925 if (!done && nbytes == 0 && chunkStream.WantMore)
926 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
927 } catch (Exception e) {
928 if (e is WebException)
931 throw new WebException ("Invalid chunked data.", e,
932 WebExceptionStatus.ServerProtocolViolation, null);
935 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
936 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
937 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
941 return (nbytes != 0) ? nbytes : -1;
944 // To be called on chunkedRead when we can read no data from the ChunkStream yet
945 int EnsureRead (byte [] buffer, int offset, int size)
947 byte [] morebytes = null;
949 while (nbytes == 0 && chunkStream.WantMore) {
950 int localsize = chunkStream.ChunkLeft;
951 if (localsize <= 0) // not read chunk size yet
953 else if (localsize > 16384)
956 if (morebytes == null || morebytes.Length < localsize)
957 morebytes = new byte [localsize];
959 int nread = nstream.Read (morebytes, 0, localsize);
963 chunkStream.Write (morebytes, 0, nread);
964 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
970 bool CompleteChunkedRead()
972 if (!chunkedRead || chunkStream == null)
975 while (chunkStream.WantMore) {
976 int nbytes = nstream.Read (buffer, 0, buffer.Length);
978 return false; // Socket was disconnected
980 chunkStream.Write (buffer, 0, nbytes);
986 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
990 if (Data.request != request)
991 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
997 IAsyncResult result = null;
999 result = s.BeginWrite (buffer, offset, size, cb, state);
1000 } catch (Exception) {
1001 status = WebExceptionStatus.SendFailure;
1008 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1010 if (request.FinishedReading)
1015 if (status == WebExceptionStatus.RequestCanceled)
1017 if (Data.request != request)
1018 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1019 if (nstream == null)
1020 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1025 s.EndWrite (result);
1027 } catch (Exception exc) {
1028 status = WebExceptionStatus.SendFailure;
1029 if (throwOnError && exc.InnerException != null)
1030 throw exc.InnerException;
1035 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1039 if (Data.request != request)
1040 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1041 if (nstream == null)
1050 result = s.Read (buffer, offset, size);
1051 done = (result == 0);
1056 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1057 if (!done && result == 0 && chunkStream.WantMore)
1058 result = EnsureRead (buffer, offset, size);
1059 } catch (Exception e) {
1060 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1064 if ((done || result == 0) && chunkStream.WantMore) {
1065 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1066 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1069 } catch (Exception e) {
1070 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1076 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1081 if (Data.request != request)
1082 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1089 s.Write (buffer, offset, size);
1090 } catch (Exception e) {
1091 err_msg = e.Message;
1092 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1093 string msg = "Write: " + err_msg;
1094 if (e is WebException) {
1095 HandleError (wes, e, msg);
1099 HandleError (wes, e, msg);
1105 internal void Close (bool sendNext)
1108 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1109 Data.request.ReuseConnection = false;
1113 if (nstream != null) {
1120 if (socket != null) {
1127 if (ntlm_authenticated)
1131 Data.ReadState = ReadState.Aborted;
1135 Data = new WebConnectionData ();
1139 connect_request = null;
1140 connect_ntlm_auth_state = NtlmAuthState.None;
1144 void Abort (object sender, EventArgs args)
1148 HttpWebRequest req = (HttpWebRequest) sender;
1149 if (Data.request == req || Data.request == null) {
1150 if (!req.FinishedReading) {
1151 status = WebExceptionStatus.RequestCanceled;
1153 if (queue.Count > 0) {
1154 Data.request = (HttpWebRequest) queue.Dequeue ();
1155 SendRequest (Data.request);
1161 req.FinishedReading = true;
1162 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1163 if (queue.Count > 0 && queue.Peek () == sender) {
1165 } else if (queue.Count > 0) {
1166 object [] old = queue.ToArray ();
1168 for (int i = old.Length - 1; i >= 0; i--) {
1169 if (old [i] != sender)
1170 queue.Enqueue (old [i]);
1177 internal void ResetNtlm ()
1179 ntlm_authenticated = false;
1180 ntlm_credentials = null;
1181 unsafe_sharing = false;
1184 internal bool Connected {
1187 return (socket != null && socket.Connected);
1192 // -Used for NTLM authentication
1193 internal HttpWebRequest PriorityRequest {
1194 set { priority_request = value; }
1197 internal bool NtlmAuthenticated {
1198 get { return ntlm_authenticated; }
1199 set { ntlm_authenticated = value; }
1202 internal NetworkCredential NtlmCredential {
1203 get { return ntlm_credentials; }
1204 set { ntlm_credentials = value; }
1207 internal bool UnsafeAuthenticatedConnectionSharing {
1208 get { return unsafe_sharing; }
1209 set { unsafe_sharing = value; }