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.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;
422 connect_exception = ex;
429 void HandleError (WebExceptionStatus st, Exception e, string where)
433 if (st == WebExceptionStatus.RequestCanceled)
434 Data = new WebConnectionData ();
437 if (e == null) { // At least we now where it comes from
439 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
440 } catch (Exception e2) {
445 HttpWebRequest req = null;
446 if (Data != null && Data.request != null)
451 req.FinishedReading = true;
452 req.SetResponseError (st, e, where);
456 static void ReadDone (IAsyncResult result)
458 WebConnection cnc = (WebConnection)result.AsyncState;
459 WebConnectionData data = cnc.Data;
460 Stream ns = cnc.nstream;
468 nread = ns.EndRead (result);
469 } catch (ObjectDisposedException) {
471 } catch (Exception e) {
472 if (e.InnerException is ObjectDisposedException)
475 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
480 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
485 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
490 nread += cnc.position;
491 if (data.ReadState == ReadState.None) {
492 Exception exc = null;
494 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
495 } catch (Exception e) {
499 if (exc != null || pos == -1) {
500 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
505 if (data.ReadState == ReadState.Aborted) {
506 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
510 if (data.ReadState != ReadState.Content) {
512 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
513 byte [] newBuffer = new byte [max];
514 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
515 cnc.buffer = newBuffer;
516 cnc.position = nread;
517 data.ReadState = ReadState.None;
524 WebConnectionStream stream = new WebConnectionStream (cnc, data);
525 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
526 string tencoding = null;
528 tencoding = data.Headers ["Transfer-Encoding"];
530 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
531 if (!cnc.chunkedRead) {
532 stream.ReadBuffer = cnc.buffer;
533 stream.ReadBufferOffset = pos;
534 stream.ReadBufferSize = nread;
536 stream.CheckResponseInBuffer ();
537 } catch (Exception e) {
538 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
540 } else if (cnc.chunkStream == null) {
542 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
543 } catch (Exception e) {
544 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
548 cnc.chunkStream.ResetBuffer ();
550 cnc.chunkStream.Write (cnc.buffer, pos, nread);
551 } catch (Exception e) {
552 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
557 data.stream = stream;
560 stream.ForceCompletion ();
562 data.request.SetResponseData (data);
565 static bool ExpectContent (int statusCode, string method)
567 if (method == "HEAD")
569 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
572 internal static void InitRead (object state)
574 WebConnection cnc = (WebConnection) state;
575 Stream ns = cnc.nstream;
578 int size = cnc.buffer.Length - cnc.position;
579 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
580 } catch (Exception e) {
581 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
585 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
586 byte [] buffer, int max)
591 bool isContinue = false;
592 bool emptyFirstLine = false;
594 if (data.ReadState == ReadState.Aborted)
597 if (data.ReadState == ReadState.None) {
598 lineok = ReadLine (buffer, ref pos, max, ref line);
603 emptyFirstLine = true;
606 emptyFirstLine = false;
607 data.ReadState = ReadState.Status;
609 string [] parts = line.Split (' ');
610 if (parts.Length < 2)
613 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
614 data.Version = HttpVersion.Version11;
615 sPoint.SetVersion (HttpVersion.Version11);
617 data.Version = HttpVersion.Version10;
618 sPoint.SetVersion (HttpVersion.Version10);
621 data.StatusCode = (int) UInt32.Parse (parts [1]);
622 if (parts.Length >= 3)
623 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
625 data.StatusDescription = "";
631 emptyFirstLine = false;
632 if (data.ReadState == ReadState.Status) {
633 data.ReadState = ReadState.Headers;
634 data.Headers = new WebHeaderCollection ();
635 ArrayList headers = new ArrayList ();
636 bool finished = false;
638 if (ReadLine (buffer, ref pos, max, ref line) == false)
642 // Empty line: end of headers
647 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
648 int count = headers.Count - 1;
652 string prev = (string) headers [count] + line;
653 headers [count] = prev;
662 foreach (string s in headers)
663 data.Headers.SetInternal (s);
665 if (data.StatusCode == (int) HttpStatusCode.Continue) {
666 sPoint.SendContinue = true;
670 if (data.request.ExpectContinue) {
671 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
672 // Prevent double calls when getting the
673 // headers in several packets.
674 data.request.ExpectContinue = false;
677 data.ReadState = ReadState.None;
681 data.ReadState = ReadState.Content;
685 } while (emptyFirstLine || isContinue);
690 void InitConnection (object state)
692 HttpWebRequest request = (HttpWebRequest) state;
693 request.WebConnection = this;
694 if (request.ReuseConnection)
695 request.StoredConnection = this;
700 keepAlive = request.KeepAlive;
701 Data = new WebConnectionData (request);
707 if (status != WebExceptionStatus.Success) {
708 if (!request.Aborted) {
709 request.SetWriteStreamError (status, connect_exception);
715 if (!CreateStream (request)) {
719 WebExceptionStatus st = status;
720 if (Data.Challenge != null)
723 Exception cnc_exc = connect_exception;
724 connect_exception = null;
725 request.SetWriteStreamError (st, cnc_exc);
730 request.SetWriteStream (new WebConnectionStream (this, request));
734 static bool warned_about_queue = false;
737 internal EventHandler SendRequest (HttpWebRequest request)
743 if (state.TrySetBusy ()) {
744 status = WebExceptionStatus.Success;
745 ThreadPool.QueueUserWorkItem (initConn, request);
749 if (!warned_about_queue) {
750 warned_about_queue = true;
751 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
754 queue.Enqueue (request);
765 if (queue.Count > 0) {
766 SendRequest ((HttpWebRequest) queue.Dequeue ());
771 internal void NextRead ()
774 if (Data.request != null)
775 Data.request.FinishedReading = true;
776 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
777 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
778 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
779 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
781 if (cncHeader != null) {
782 cncHeader = cncHeader.ToLower ();
783 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
786 if ((socket != null && !socket.Connected) ||
787 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
792 if (priority_request != null) {
793 SendRequest (priority_request);
794 priority_request = null;
801 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
803 bool foundCR = false;
804 StringBuilder text = new StringBuilder ();
807 while (start < max) {
808 c = (int) buffer [start++];
810 if (c == '\n') { // newline
811 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
816 } else if (foundCR) {
825 text.Append ((char) c);
828 if (c != '\n' && c != '\r')
831 if (text.Length == 0) {
833 return (c == '\n' || c == '\r');
839 output = text.ToString ();
844 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
848 if (Data.request != request)
849 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
855 IAsyncResult result = null;
856 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
858 result = s.BeginRead (buffer, offset, size, cb, state);
860 } catch (Exception) {
861 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
867 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
868 wr.InnerAsyncResult = result;
869 if (result == null) {
870 // Will be completed from the data in ChunkStream
871 wr.SetCompleted (true, (Exception) null);
880 internal int EndRead (HttpWebRequest request, IAsyncResult result)
884 if (Data.request != request)
885 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
887 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
893 WebAsyncResult wr = null;
894 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
895 if (chunkedRead && (nsAsync is WebAsyncResult)) {
896 wr = (WebAsyncResult) nsAsync;
897 IAsyncResult inner = wr.InnerAsyncResult;
898 if (inner != null && !(inner is WebAsyncResult)) {
899 nbytes = s.EndRead (inner);
902 } else if (!(nsAsync is WebAsyncResult)) {
903 nbytes = s.EndRead (nsAsync);
904 wr = (WebAsyncResult) result;
910 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
911 if (!done && nbytes == 0 && chunkStream.WantMore)
912 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
913 } catch (Exception e) {
914 if (e is WebException)
917 throw new WebException ("Invalid chunked data.", e,
918 WebExceptionStatus.ServerProtocolViolation, null);
921 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
922 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
923 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
927 return (nbytes != 0) ? nbytes : -1;
930 // To be called on chunkedRead when we can read no data from the ChunkStream yet
931 int EnsureRead (byte [] buffer, int offset, int size)
933 byte [] morebytes = null;
935 while (nbytes == 0 && chunkStream.WantMore) {
936 int localsize = chunkStream.ChunkLeft;
937 if (localsize <= 0) // not read chunk size yet
939 else if (localsize > 16384)
942 if (morebytes == null || morebytes.Length < localsize)
943 morebytes = new byte [localsize];
945 int nread = nstream.Read (morebytes, 0, localsize);
949 chunkStream.Write (morebytes, 0, nread);
950 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
956 bool CompleteChunkedRead()
958 if (!chunkedRead || chunkStream == null)
961 while (chunkStream.WantMore) {
962 int nbytes = nstream.Read (buffer, 0, buffer.Length);
964 return false; // Socket was disconnected
966 chunkStream.Write (buffer, 0, nbytes);
972 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
976 if (Data.request != request)
977 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
983 IAsyncResult result = null;
985 result = s.BeginWrite (buffer, offset, size, cb, state);
986 } catch (Exception) {
987 status = WebExceptionStatus.SendFailure;
994 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
998 if (status == WebExceptionStatus.RequestCanceled)
1000 if (Data.request != request)
1001 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1002 if (nstream == null)
1003 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1008 s.EndWrite (result);
1010 } catch (Exception exc) {
1011 status = WebExceptionStatus.SendFailure;
1012 if (throwOnError && exc.InnerException != null)
1013 throw exc.InnerException;
1018 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1022 if (Data.request != request)
1023 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1024 if (nstream == null)
1033 result = s.Read (buffer, offset, size);
1034 done = (result == 0);
1039 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1040 if (!done && result == 0 && chunkStream.WantMore)
1041 result = EnsureRead (buffer, offset, size);
1042 } catch (Exception e) {
1043 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1047 if ((done || result == 0) && chunkStream.WantMore) {
1048 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1049 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1052 } catch (Exception e) {
1053 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1059 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1064 if (Data.request != request)
1065 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1072 s.Write (buffer, offset, size);
1073 } catch (Exception e) {
1074 err_msg = e.Message;
1075 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1076 string msg = "Write: " + err_msg;
1077 if (e is WebException) {
1078 HandleError (wes, e, msg);
1082 HandleError (wes, e, msg);
1088 internal void Close (bool sendNext)
1091 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1092 Data.request.ReuseConnection = false;
1096 if (nstream != null) {
1103 if (socket != null) {
1110 if (ntlm_authenticated)
1114 Data.ReadState = ReadState.Aborted;
1118 Data = new WebConnectionData ();
1122 connect_request = null;
1123 connect_ntlm_auth_state = NtlmAuthState.None;
1127 void Abort (object sender, EventArgs args)
1131 HttpWebRequest req = (HttpWebRequest) sender;
1132 if (Data.request == req || Data.request == null) {
1133 if (!req.FinishedReading) {
1134 status = WebExceptionStatus.RequestCanceled;
1136 if (queue.Count > 0) {
1137 Data.request = (HttpWebRequest) queue.Dequeue ();
1138 SendRequest (Data.request);
1144 req.FinishedReading = true;
1145 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1146 if (queue.Count > 0 && queue.Peek () == sender) {
1148 } else if (queue.Count > 0) {
1149 object [] old = queue.ToArray ();
1151 for (int i = old.Length - 1; i >= 0; i--) {
1152 if (old [i] != sender)
1153 queue.Enqueue (old [i]);
1160 internal void ResetNtlm ()
1162 ntlm_authenticated = false;
1163 ntlm_credentials = null;
1164 unsafe_sharing = false;
1167 internal bool Connected {
1170 return (socket != null && socket.Connected);
1175 // -Used for NTLM authentication
1176 internal HttpWebRequest PriorityRequest {
1177 set { priority_request = value; }
1180 internal bool NtlmAuthenticated {
1181 get { return ntlm_authenticated; }
1182 set { ntlm_authenticated = value; }
1185 internal NetworkCredential NtlmCredential {
1186 get { return ntlm_credentials; }
1187 set { ntlm_credentials = value; }
1190 internal bool UnsafeAuthenticatedConnectionSharing {
1191 get { return unsafe_sharing; }
1192 set { unsafe_sharing = value; }