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;
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) {
156 xamarin_start_wwan (sPoint.Address.ToString ());
157 hostEntry = sPoint.HostEntry;
158 if (hostEntry == null) {
160 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
161 WebExceptionStatus.NameResolutionFailure;
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.Module.AuthenticationType == "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_internal ("Proxy-Authenticate", false);
297 } else if (status != 200) {
298 string msg = String.Format ("The remote server returned a {0} status code.", status);
299 HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
303 return (result != null);
306 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
311 byte [] buffer = new byte [1024];
312 MemoryStream ms = new MemoryStream ();
315 int n = stream.Read (buffer, 0, 1024);
317 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
321 ms.Write (buffer, 0, n);
324 bool gotStatus = false;
325 WebHeaderCollection headers = new WebHeaderCollection ();
326 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
330 contentLen = int.Parse(headers["Content-Length"]);
336 if (ms.Length - start - contentLen > 0) {
337 // we've read more data than the response header and conents,
338 // give back extra data to the caller
339 retBuffer = new byte[ms.Length - start - contentLen];
340 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
343 // haven't read in some or all of the contents for the response, do so now
344 FlushContents(stream, contentLen - (int)(ms.Length - start));
355 string[] parts = str.Split (' ');
356 if (parts.Length < 2) {
357 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
361 if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
362 Data.ProxyVersion = HttpVersion.Version11;
363 else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
364 Data.ProxyVersion = HttpVersion.Version10;
366 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
370 status = (int)UInt32.Parse (parts [1]);
376 void FlushContents(Stream stream, int contentLength)
378 while (contentLength > 0) {
379 byte[] contentBuffer = new byte[contentLength];
380 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
382 contentLength -= bytesRead;
390 bool CreateStream (HttpWebRequest request)
393 NetworkStream serverStream = new NetworkStream (socket, false);
395 if (request.Address.Scheme == Uri.UriSchemeHttps) {
397 if (!reused || nstream == null || tlsStream == null) {
398 byte [] buffer = null;
399 if (sPoint.UseConnect) {
400 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
404 tlsStream = new MonoTlsStream (request, serverStream);
405 nstream = tlsStream.CreateStream (buffer);
407 // we also need to set ServicePoint.Certificate
408 // and ServicePoint.ClientCertificate but this can
409 // only be done later (after handshake - which is
410 // done only after a read operation).
412 throw new NotSupportedException ();
415 nstream = serverStream;
417 } catch (Exception ex) {
418 if (tlsStream != null)
419 status = tlsStream.ExceptionStatus;
420 else if (!request.Aborted)
421 status = WebExceptionStatus.ConnectFailure;
428 void HandleError (WebExceptionStatus st, Exception e, string where)
432 if (st == WebExceptionStatus.RequestCanceled)
433 Data = new WebConnectionData ();
436 if (e == null) { // At least we now where it comes from
438 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
439 } catch (Exception e2) {
444 HttpWebRequest req = null;
445 if (Data != null && Data.request != null)
450 req.FinishedReading = true;
451 req.SetResponseError (st, e, where);
455 static void ReadDone (IAsyncResult result)
457 WebConnection cnc = (WebConnection)result.AsyncState;
458 WebConnectionData data = cnc.Data;
459 Stream ns = cnc.nstream;
467 nread = ns.EndRead (result);
468 } catch (ObjectDisposedException) {
470 } catch (Exception e) {
471 if (e.InnerException is ObjectDisposedException)
474 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
479 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
484 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
489 nread += cnc.position;
490 if (data.ReadState == ReadState.None) {
491 Exception exc = null;
493 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
494 } catch (Exception e) {
498 if (exc != null || pos == -1) {
499 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
504 if (data.ReadState == ReadState.Aborted) {
505 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
509 if (data.ReadState != ReadState.Content) {
511 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
512 byte [] newBuffer = new byte [max];
513 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
514 cnc.buffer = newBuffer;
515 cnc.position = nread;
516 data.ReadState = ReadState.None;
523 WebConnectionStream stream = new WebConnectionStream (cnc, data);
524 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
525 string tencoding = null;
527 tencoding = data.Headers ["Transfer-Encoding"];
529 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
530 if (!cnc.chunkedRead) {
531 stream.ReadBuffer = cnc.buffer;
532 stream.ReadBufferOffset = pos;
533 stream.ReadBufferSize = nread;
535 stream.CheckResponseInBuffer ();
536 } catch (Exception e) {
537 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
539 } else if (cnc.chunkStream == null) {
541 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
542 } catch (Exception e) {
543 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
547 cnc.chunkStream.ResetBuffer ();
549 cnc.chunkStream.Write (cnc.buffer, pos, nread);
550 } catch (Exception e) {
551 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
556 data.stream = stream;
559 stream.ForceCompletion ();
561 data.request.SetResponseData (data);
564 static bool ExpectContent (int statusCode, string method)
566 if (method == "HEAD")
568 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
571 internal static void InitRead (object state)
573 WebConnection cnc = (WebConnection) state;
574 Stream ns = cnc.nstream;
577 int size = cnc.buffer.Length - cnc.position;
578 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
579 } catch (Exception e) {
580 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
584 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
585 byte [] buffer, int max)
590 bool isContinue = false;
591 bool emptyFirstLine = false;
593 if (data.ReadState == ReadState.Aborted)
596 if (data.ReadState == ReadState.None) {
597 lineok = ReadLine (buffer, ref pos, max, ref line);
602 emptyFirstLine = true;
605 emptyFirstLine = false;
606 data.ReadState = ReadState.Status;
608 string [] parts = line.Split (' ');
609 if (parts.Length < 2)
612 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
613 data.Version = HttpVersion.Version11;
614 sPoint.SetVersion (HttpVersion.Version11);
616 data.Version = HttpVersion.Version10;
617 sPoint.SetVersion (HttpVersion.Version10);
620 data.StatusCode = (int) UInt32.Parse (parts [1]);
621 if (parts.Length >= 3)
622 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
624 data.StatusDescription = "";
630 emptyFirstLine = false;
631 if (data.ReadState == ReadState.Status) {
632 data.ReadState = ReadState.Headers;
633 data.Headers = new WebHeaderCollection ();
634 ArrayList headers = new ArrayList ();
635 bool finished = false;
637 if (ReadLine (buffer, ref pos, max, ref line) == false)
641 // Empty line: end of headers
646 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
647 int count = headers.Count - 1;
651 string prev = (string) headers [count] + line;
652 headers [count] = prev;
661 foreach (string s in headers)
662 data.Headers.SetInternal (s);
664 if (data.StatusCode == (int) HttpStatusCode.Continue) {
665 sPoint.SendContinue = true;
669 if (data.request.ExpectContinue) {
670 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
671 // Prevent double calls when getting the
672 // headers in several packets.
673 data.request.ExpectContinue = false;
676 data.ReadState = ReadState.None;
680 data.ReadState = ReadState.Content;
684 } while (emptyFirstLine || isContinue);
689 void InitConnection (object state)
691 HttpWebRequest request = (HttpWebRequest) state;
692 request.WebConnection = this;
693 if (request.ReuseConnection)
694 request.StoredConnection = this;
699 keepAlive = request.KeepAlive;
700 Data = new WebConnectionData (request);
706 if (status != WebExceptionStatus.Success) {
707 if (!request.Aborted) {
708 request.SetWriteStreamError (status, connect_exception);
714 if (!CreateStream (request)) {
718 WebExceptionStatus st = status;
719 if (Data.Challenge != null)
722 Exception cnc_exc = connect_exception;
723 connect_exception = null;
724 request.SetWriteStreamError (st, cnc_exc);
729 request.SetWriteStream (new WebConnectionStream (this, request));
733 static bool warned_about_queue = false;
736 internal EventHandler SendRequest (HttpWebRequest request)
742 if (state.TrySetBusy ()) {
743 status = WebExceptionStatus.Success;
744 ThreadPool.QueueUserWorkItem (initConn, request);
748 if (!warned_about_queue) {
749 warned_about_queue = true;
750 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
753 queue.Enqueue (request);
764 if (queue.Count > 0) {
765 SendRequest ((HttpWebRequest) queue.Dequeue ());
770 internal void NextRead ()
773 if (Data.request != null)
774 Data.request.FinishedReading = true;
775 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
776 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
777 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
778 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
780 if (cncHeader != null) {
781 cncHeader = cncHeader.ToLower ();
782 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
785 if ((socket != null && !socket.Connected) ||
786 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
791 if (priority_request != null) {
792 SendRequest (priority_request);
793 priority_request = null;
800 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
802 bool foundCR = false;
803 StringBuilder text = new StringBuilder ();
806 while (start < max) {
807 c = (int) buffer [start++];
809 if (c == '\n') { // newline
810 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
815 } else if (foundCR) {
824 text.Append ((char) c);
827 if (c != '\n' && c != '\r')
830 if (text.Length == 0) {
832 return (c == '\n' || c == '\r');
838 output = text.ToString ();
843 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
847 if (Data.request != request)
848 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
854 IAsyncResult result = null;
855 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
857 result = s.BeginRead (buffer, offset, size, cb, state);
859 } catch (Exception) {
860 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
866 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
867 wr.InnerAsyncResult = result;
868 if (result == null) {
869 // Will be completed from the data in ChunkStream
870 wr.SetCompleted (true, (Exception) null);
879 internal int EndRead (HttpWebRequest request, IAsyncResult result)
883 if (Data.request != request)
884 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
886 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
892 WebAsyncResult wr = null;
893 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
894 if (chunkedRead && (nsAsync is WebAsyncResult)) {
895 wr = (WebAsyncResult) nsAsync;
896 IAsyncResult inner = wr.InnerAsyncResult;
897 if (inner != null && !(inner is WebAsyncResult)) {
898 nbytes = s.EndRead (inner);
901 } else if (!(nsAsync is WebAsyncResult)) {
902 nbytes = s.EndRead (nsAsync);
903 wr = (WebAsyncResult) result;
909 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
910 if (!done && nbytes == 0 && chunkStream.WantMore)
911 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
912 } catch (Exception e) {
913 if (e is WebException)
916 throw new WebException ("Invalid chunked data.", e,
917 WebExceptionStatus.ServerProtocolViolation, null);
920 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
921 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
922 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
926 return (nbytes != 0) ? nbytes : -1;
929 // To be called on chunkedRead when we can read no data from the ChunkStream yet
930 int EnsureRead (byte [] buffer, int offset, int size)
932 byte [] morebytes = null;
934 while (nbytes == 0 && chunkStream.WantMore) {
935 int localsize = chunkStream.ChunkLeft;
936 if (localsize <= 0) // not read chunk size yet
938 else if (localsize > 16384)
941 if (morebytes == null || morebytes.Length < localsize)
942 morebytes = new byte [localsize];
944 int nread = nstream.Read (morebytes, 0, localsize);
948 chunkStream.Write (morebytes, 0, nread);
949 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
955 bool CompleteChunkedRead()
957 if (!chunkedRead || chunkStream == null)
960 while (chunkStream.WantMore) {
961 int nbytes = nstream.Read (buffer, 0, buffer.Length);
963 return false; // Socket was disconnected
965 chunkStream.Write (buffer, 0, nbytes);
971 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
975 if (Data.request != request)
976 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
982 IAsyncResult result = null;
984 result = s.BeginWrite (buffer, offset, size, cb, state);
985 } catch (Exception) {
986 status = WebExceptionStatus.SendFailure;
993 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
995 if (request.FinishedReading)
1000 if (status == WebExceptionStatus.RequestCanceled)
1002 if (Data.request != request)
1003 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1004 if (nstream == null)
1005 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1010 s.EndWrite (result);
1012 } catch (Exception exc) {
1013 status = WebExceptionStatus.SendFailure;
1014 if (throwOnError && exc.InnerException != null)
1015 throw exc.InnerException;
1020 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1024 if (Data.request != request)
1025 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1026 if (nstream == null)
1035 result = s.Read (buffer, offset, size);
1036 done = (result == 0);
1041 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1042 if (!done && result == 0 && chunkStream.WantMore)
1043 result = EnsureRead (buffer, offset, size);
1044 } catch (Exception e) {
1045 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1049 if ((done || result == 0) && chunkStream.WantMore) {
1050 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1051 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1054 } catch (Exception e) {
1055 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1061 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1066 if (Data.request != request)
1067 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1074 s.Write (buffer, offset, size);
1075 } catch (Exception e) {
1076 err_msg = e.Message;
1077 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1078 string msg = "Write: " + err_msg;
1079 if (e is WebException) {
1080 HandleError (wes, e, msg);
1084 HandleError (wes, e, msg);
1090 internal void Close (bool sendNext)
1093 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1094 Data.request.ReuseConnection = false;
1098 if (nstream != null) {
1105 if (socket != null) {
1112 if (ntlm_authenticated)
1116 Data.ReadState = ReadState.Aborted;
1120 Data = new WebConnectionData ();
1124 connect_request = null;
1125 connect_ntlm_auth_state = NtlmAuthState.None;
1129 void Abort (object sender, EventArgs args)
1133 HttpWebRequest req = (HttpWebRequest) sender;
1134 if (Data.request == req || Data.request == null) {
1135 if (!req.FinishedReading) {
1136 status = WebExceptionStatus.RequestCanceled;
1138 if (queue.Count > 0) {
1139 Data.request = (HttpWebRequest) queue.Dequeue ();
1140 SendRequest (Data.request);
1146 req.FinishedReading = true;
1147 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1148 if (queue.Count > 0 && queue.Peek () == sender) {
1150 } else if (queue.Count > 0) {
1151 object [] old = queue.ToArray ();
1153 for (int i = old.Length - 1; i >= 0; i--) {
1154 if (old [i] != sender)
1155 queue.Enqueue (old [i]);
1162 internal void ResetNtlm ()
1164 ntlm_authenticated = false;
1165 ntlm_credentials = null;
1166 unsafe_sharing = false;
1169 internal bool Connected {
1172 return (socket != null && socket.Connected);
1177 // -Used for NTLM authentication
1178 internal HttpWebRequest PriorityRequest {
1179 set { priority_request = value; }
1182 internal bool NtlmAuthenticated {
1183 get { return ntlm_authenticated; }
1184 set { ntlm_authenticated = value; }
1187 internal NetworkCredential NtlmCredential {
1188 get { return ntlm_credentials; }
1189 set { ntlm_credentials = value; }
1192 internal bool UnsafeAuthenticatedConnectionSharing {
1193 get { return unsafe_sharing; }
1194 set { unsafe_sharing = value; }