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;
261 for (int i = 0; i < challenge.Length; i++) {
262 var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
265 ntlm = (auth.ModuleAuthenticationType == "NTLM");
266 sb.Append ("\r\nProxy-Authorization: ");
267 sb.Append (auth.Message);
274 sb.Append ("\r\nProxy-Connection: keep-alive");
275 connect_ntlm_auth_state++;
278 sb.Append ("\r\n\r\n");
281 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
282 stream.Write (connectBytes, 0, connectBytes.Length);
285 WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
286 if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
287 result != null && status == 407) { // Needs proxy auth
288 var connectionHeader = result ["Connection"];
289 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
290 connectionHeader.ToLower() == "close") {
291 // The server is requesting that this connection be closed
296 Data.StatusCode = status;
297 Data.Challenge = result.GetValues ("Proxy-Authenticate");
298 Data.Headers = result;
303 Data.StatusCode = status;
304 Data.Headers = result;
308 return (result != null);
311 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
316 byte [] buffer = new byte [1024];
317 MemoryStream ms = new MemoryStream ();
320 int n = stream.Read (buffer, 0, 1024);
322 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
326 ms.Write (buffer, 0, n);
329 bool gotStatus = false;
330 WebHeaderCollection headers = new WebHeaderCollection ();
331 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
335 contentLen = int.Parse(headers["Content-Length"]);
341 if (ms.Length - start - contentLen > 0) {
342 // we've read more data than the response header and conents,
343 // give back extra data to the caller
344 retBuffer = new byte[ms.Length - start - contentLen];
345 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
348 // haven't read in some or all of the contents for the response, do so now
349 FlushContents(stream, contentLen - (int)(ms.Length - start));
360 string[] parts = str.Split (' ');
361 if (parts.Length < 2) {
362 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
366 if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
367 Data.ProxyVersion = HttpVersion.Version11;
368 else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
369 Data.ProxyVersion = HttpVersion.Version10;
371 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
375 status = (int)UInt32.Parse (parts [1]);
376 if (parts.Length >= 3)
377 Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
384 void FlushContents(Stream stream, int contentLength)
386 while (contentLength > 0) {
387 byte[] contentBuffer = new byte[contentLength];
388 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
390 contentLength -= bytesRead;
398 bool CreateStream (HttpWebRequest request)
401 NetworkStream serverStream = new NetworkStream (socket, false);
403 if (request.Address.Scheme == Uri.UriSchemeHttps) {
405 if (!reused || nstream == null || tlsStream == null) {
406 byte [] buffer = null;
407 if (sPoint.UseConnect) {
408 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
412 tlsStream = new MonoTlsStream (request, serverStream);
413 nstream = tlsStream.CreateStream (buffer);
415 // we also need to set ServicePoint.Certificate
416 // and ServicePoint.ClientCertificate but this can
417 // only be done later (after handshake - which is
418 // done only after a read operation).
420 throw new NotSupportedException ();
423 nstream = serverStream;
425 } catch (Exception ex) {
426 if (tlsStream != null)
427 status = tlsStream.ExceptionStatus;
428 else if (!request.Aborted)
429 status = WebExceptionStatus.ConnectFailure;
430 connect_exception = ex;
437 void HandleError (WebExceptionStatus st, Exception e, string where)
441 if (st == WebExceptionStatus.RequestCanceled)
442 Data = new WebConnectionData ();
445 if (e == null) { // At least we now where it comes from
447 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
448 } catch (Exception e2) {
453 HttpWebRequest req = null;
454 if (Data != null && Data.request != null)
459 req.FinishedReading = true;
460 req.SetResponseError (st, e, where);
464 static void ReadDone (IAsyncResult result)
466 WebConnection cnc = (WebConnection)result.AsyncState;
467 WebConnectionData data = cnc.Data;
468 Stream ns = cnc.nstream;
476 nread = ns.EndRead (result);
477 } catch (ObjectDisposedException) {
479 } catch (Exception e) {
480 if (e.InnerException is ObjectDisposedException)
483 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
488 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
493 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
498 nread += cnc.position;
499 if (data.ReadState == ReadState.None) {
500 Exception exc = null;
502 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
503 } catch (Exception e) {
507 if (exc != null || pos == -1) {
508 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
513 if (data.ReadState == ReadState.Aborted) {
514 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
518 if (data.ReadState != ReadState.Content) {
520 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
521 byte [] newBuffer = new byte [max];
522 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
523 cnc.buffer = newBuffer;
524 cnc.position = nread;
525 data.ReadState = ReadState.None;
532 WebConnectionStream stream = new WebConnectionStream (cnc, data);
533 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
534 string tencoding = null;
536 tencoding = data.Headers ["Transfer-Encoding"];
538 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
539 if (!cnc.chunkedRead) {
540 stream.ReadBuffer = cnc.buffer;
541 stream.ReadBufferOffset = pos;
542 stream.ReadBufferSize = nread;
544 stream.CheckResponseInBuffer ();
545 } catch (Exception e) {
546 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
548 } else if (cnc.chunkStream == null) {
550 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
551 } catch (Exception e) {
552 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
556 cnc.chunkStream.ResetBuffer ();
558 cnc.chunkStream.Write (cnc.buffer, pos, nread);
559 } catch (Exception e) {
560 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
565 data.stream = stream;
568 stream.ForceCompletion ();
570 data.request.SetResponseData (data);
573 static bool ExpectContent (int statusCode, string method)
575 if (method == "HEAD")
577 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
580 internal static void InitRead (object state)
582 WebConnection cnc = (WebConnection) state;
583 Stream ns = cnc.nstream;
586 int size = cnc.buffer.Length - cnc.position;
587 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
588 } catch (Exception e) {
589 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
593 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
594 byte [] buffer, int max)
599 bool isContinue = false;
600 bool emptyFirstLine = false;
602 if (data.ReadState == ReadState.Aborted)
605 if (data.ReadState == ReadState.None) {
606 lineok = ReadLine (buffer, ref pos, max, ref line);
611 emptyFirstLine = true;
614 emptyFirstLine = false;
615 data.ReadState = ReadState.Status;
617 string [] parts = line.Split (' ');
618 if (parts.Length < 2)
621 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
622 data.Version = HttpVersion.Version11;
623 sPoint.SetVersion (HttpVersion.Version11);
625 data.Version = HttpVersion.Version10;
626 sPoint.SetVersion (HttpVersion.Version10);
629 data.StatusCode = (int) UInt32.Parse (parts [1]);
630 if (parts.Length >= 3)
631 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
633 data.StatusDescription = "";
639 emptyFirstLine = false;
640 if (data.ReadState == ReadState.Status) {
641 data.ReadState = ReadState.Headers;
642 data.Headers = new WebHeaderCollection ();
643 ArrayList headers = new ArrayList ();
644 bool finished = false;
646 if (ReadLine (buffer, ref pos, max, ref line) == false)
650 // Empty line: end of headers
655 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
656 int count = headers.Count - 1;
660 string prev = (string) headers [count] + line;
661 headers [count] = prev;
670 // .NET uses ParseHeaders or ParseHeadersStrict which is much better
671 foreach (string s in headers) {
673 int pos_s = s.IndexOf (':');
675 throw new ArgumentException ("no colon found", "header");
677 var header = s.Substring (0, pos_s);
678 var value = s.Substring (pos_s + 1).Trim ();
680 var h = data.Headers;
681 if (WebHeaderCollection.AllowMultiValues (header)) {
682 h.AddInternal (header, value);
684 h.SetInternal (header, value);
688 if (data.StatusCode == (int) HttpStatusCode.Continue) {
689 sPoint.SendContinue = true;
693 if (data.request.ExpectContinue) {
694 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
695 // Prevent double calls when getting the
696 // headers in several packets.
697 data.request.ExpectContinue = false;
700 data.ReadState = ReadState.None;
704 data.ReadState = ReadState.Content;
708 } while (emptyFirstLine || isContinue);
713 void InitConnection (object state)
715 HttpWebRequest request = (HttpWebRequest) state;
716 request.WebConnection = this;
717 if (request.ReuseConnection)
718 request.StoredConnection = this;
723 keepAlive = request.KeepAlive;
724 Data = new WebConnectionData (request);
730 if (status != WebExceptionStatus.Success) {
731 if (!request.Aborted) {
732 request.SetWriteStreamError (status, connect_exception);
738 if (!CreateStream (request)) {
742 WebExceptionStatus st = status;
743 if (Data.Challenge != null)
746 Exception cnc_exc = connect_exception;
747 if (cnc_exc == null && (Data.StatusCode == 401 || Data.StatusCode == 407)) {
748 st = WebExceptionStatus.ProtocolError;
749 if (Data.Headers == null)
750 Data.Headers = new WebHeaderCollection ();
752 var webResponse = new HttpWebResponse (sPoint.Address, "CONNECT", Data, null);
753 cnc_exc = new WebException (Data.StatusCode == 407 ? "(407) Proxy Authentication Required" : "(401) Unauthorized", null, st, webResponse);
756 connect_exception = null;
757 request.SetWriteStreamError (st, cnc_exc);
762 request.SetWriteStream (new WebConnectionStream (this, request));
766 static bool warned_about_queue = false;
769 internal EventHandler SendRequest (HttpWebRequest request)
775 if (state.TrySetBusy ()) {
776 status = WebExceptionStatus.Success;
777 ThreadPool.QueueUserWorkItem (initConn, request);
781 if (!warned_about_queue) {
782 warned_about_queue = true;
783 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
786 queue.Enqueue (request);
797 if (queue.Count > 0) {
798 SendRequest ((HttpWebRequest) queue.Dequeue ());
803 internal void NextRead ()
806 if (Data.request != null)
807 Data.request.FinishedReading = true;
808 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
809 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
810 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
811 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
813 if (cncHeader != null) {
814 cncHeader = cncHeader.ToLower ();
815 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
818 if ((socket != null && !socket.Connected) ||
819 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
824 if (priority_request != null) {
825 SendRequest (priority_request);
826 priority_request = null;
833 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
835 bool foundCR = false;
836 StringBuilder text = new StringBuilder ();
839 while (start < max) {
840 c = (int) buffer [start++];
842 if (c == '\n') { // newline
843 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
848 } else if (foundCR) {
857 text.Append ((char) c);
860 if (c != '\n' && c != '\r')
863 if (text.Length == 0) {
865 return (c == '\n' || c == '\r');
871 output = text.ToString ();
876 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
880 if (Data.request != request)
881 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
887 IAsyncResult result = null;
888 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
890 result = s.BeginRead (buffer, offset, size, cb, state);
892 } catch (Exception) {
893 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
899 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
900 wr.InnerAsyncResult = result;
901 if (result == null) {
902 // Will be completed from the data in ChunkStream
903 wr.SetCompleted (true, (Exception) null);
912 internal int EndRead (HttpWebRequest request, IAsyncResult result)
917 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
918 if (Data.request != request)
919 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
921 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
927 WebAsyncResult wr = null;
928 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
929 if (chunkedRead && (nsAsync is WebAsyncResult)) {
930 wr = (WebAsyncResult) nsAsync;
931 IAsyncResult inner = wr.InnerAsyncResult;
932 if (inner != null && !(inner is WebAsyncResult)) {
933 nbytes = s.EndRead (inner);
936 } else if (!(nsAsync is WebAsyncResult)) {
937 nbytes = s.EndRead (nsAsync);
938 wr = (WebAsyncResult) result;
944 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
945 if (!done && nbytes == 0 && chunkStream.WantMore)
946 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
947 } catch (Exception e) {
948 if (e is WebException)
951 throw new WebException ("Invalid chunked data.", e,
952 WebExceptionStatus.ServerProtocolViolation, null);
955 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
956 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
957 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
961 return (nbytes != 0) ? nbytes : -1;
964 // To be called on chunkedRead when we can read no data from the ChunkStream yet
965 int EnsureRead (byte [] buffer, int offset, int size)
967 byte [] morebytes = null;
969 while (nbytes == 0 && chunkStream.WantMore) {
970 int localsize = chunkStream.ChunkLeft;
971 if (localsize <= 0) // not read chunk size yet
973 else if (localsize > 16384)
976 if (morebytes == null || morebytes.Length < localsize)
977 morebytes = new byte [localsize];
979 int nread = nstream.Read (morebytes, 0, localsize);
983 chunkStream.Write (morebytes, 0, nread);
984 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
990 bool CompleteChunkedRead()
992 if (!chunkedRead || chunkStream == null)
995 while (chunkStream.WantMore) {
996 int nbytes = nstream.Read (buffer, 0, buffer.Length);
998 return false; // Socket was disconnected
1000 chunkStream.Write (buffer, 0, nbytes);
1006 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
1010 if (Data.request != request)
1011 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1012 if (nstream == null)
1017 IAsyncResult result = null;
1019 result = s.BeginWrite (buffer, offset, size, cb, state);
1020 } catch (Exception) {
1021 status = WebExceptionStatus.SendFailure;
1028 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1032 if (status == WebExceptionStatus.RequestCanceled)
1034 if (Data.request != request)
1035 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1036 if (nstream == null)
1037 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1042 s.EndWrite (result);
1044 } catch (Exception exc) {
1045 status = WebExceptionStatus.SendFailure;
1046 if (throwOnError && exc.InnerException != null)
1047 throw exc.InnerException;
1052 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1056 if (Data.request != request)
1057 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1058 if (nstream == null)
1067 result = s.Read (buffer, offset, size);
1068 done = (result == 0);
1073 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1074 if (!done && result == 0 && chunkStream.WantMore)
1075 result = EnsureRead (buffer, offset, size);
1076 } catch (Exception e) {
1077 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1081 if ((done || result == 0) && chunkStream.WantMore) {
1082 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1083 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1086 } catch (Exception e) {
1087 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1093 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1098 if (Data.request != request)
1099 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1106 s.Write (buffer, offset, size);
1107 } catch (Exception e) {
1108 err_msg = e.Message;
1109 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1110 string msg = "Write: " + err_msg;
1111 if (e is WebException) {
1112 HandleError (wes, e, msg);
1116 HandleError (wes, e, msg);
1122 internal void Close (bool sendNext)
1125 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1126 Data.request.ReuseConnection = false;
1130 if (nstream != null) {
1137 if (socket != null) {
1144 if (ntlm_authenticated)
1148 Data.ReadState = ReadState.Aborted;
1152 Data = new WebConnectionData ();
1156 connect_request = null;
1157 connect_ntlm_auth_state = NtlmAuthState.None;
1161 void Abort (object sender, EventArgs args)
1165 HttpWebRequest req = (HttpWebRequest) sender;
1166 if (Data.request == req || Data.request == null) {
1167 if (!req.FinishedReading) {
1168 status = WebExceptionStatus.RequestCanceled;
1170 if (queue.Count > 0) {
1171 Data.request = (HttpWebRequest) queue.Dequeue ();
1172 SendRequest (Data.request);
1178 req.FinishedReading = true;
1179 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1180 if (queue.Count > 0 && queue.Peek () == sender) {
1182 } else if (queue.Count > 0) {
1183 object [] old = queue.ToArray ();
1185 for (int i = old.Length - 1; i >= 0; i--) {
1186 if (old [i] != sender)
1187 queue.Enqueue (old [i]);
1194 internal void ResetNtlm ()
1196 ntlm_authenticated = false;
1197 ntlm_credentials = null;
1198 unsafe_sharing = false;
1201 internal bool Connected {
1204 return (socket != null && socket.Connected);
1209 // -Used for NTLM authentication
1210 internal HttpWebRequest PriorityRequest {
1211 set { priority_request = value; }
1214 internal bool NtlmAuthenticated {
1215 get { return ntlm_authenticated; }
1216 set { ntlm_authenticated = value; }
1219 internal NetworkCredential NtlmCredential {
1220 get { return ntlm_credentials; }
1221 set { ntlm_credentials = value; }
1224 internal bool UnsafeAuthenticatedConnectionSharing {
1225 get { return unsafe_sharing; }
1226 set { unsafe_sharing = value; }