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.
33 #if MONOTOUCH || MONODROID
34 using Mono.Security.Protocol.Tls;
36 extern alias MonoSecurity;
37 using MonoSecurity::Mono.Security.Protocol.Tls;
43 using System.Collections;
44 using System.Net.Sockets;
45 using System.Reflection;
46 using System.Security.Cryptography.X509Certificates;
48 using System.Threading;
49 using System.Diagnostics;
66 internal Socket socket;
67 object socketLock = new object ();
68 IWebConnectionState state;
69 WebExceptionStatus status;
70 WaitCallback initConn;
73 static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
74 EventHandler abortHandler;
75 AbortHelper abortHelper;
76 internal WebConnectionData Data;
78 ChunkStream chunkStream;
82 HttpWebRequest priority_request;
83 NetworkCredential ntlm_credentials;
84 bool ntlm_authenticated;
93 NtlmAuthState connect_ntlm_auth_state;
94 HttpWebRequest connect_request;
98 Exception connect_exception;
99 static object classLock = new object ();
100 static Type sslStream;
101 #if !MONOTOUCH && !MONODROID
102 static PropertyInfo piClient;
103 static PropertyInfo piServer;
104 static PropertyInfo piTrustFailure;
108 [System.Runtime.InteropServices.DllImport ("__Internal")]
109 static extern void monotouch_start_wwan (string uri);
112 internal ChunkStream ChunkStream {
113 get { return chunkStream; }
116 public WebConnection (IWebConnectionState wcs, ServicePoint sPoint)
119 this.sPoint = sPoint;
120 buffer = new byte [4096];
121 Data = new WebConnectionData ();
122 initConn = new WaitCallback (state => {
124 InitConnection (state);
127 queue = wcs.Group.Queue;
128 abortHelper = new AbortHelper ();
129 abortHelper.Connection = this;
130 abortHandler = new EventHandler (abortHelper.Abort);
134 public WebConnection Connection;
136 public void Abort (object sender, EventArgs args)
138 WebConnection other = ((HttpWebRequest) sender).WebConnection;
141 other.Abort (sender, args);
147 // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
148 // but if there's data pending to read (!) we won't reuse the socket.
149 return (socket.Poll (0, SelectMode.SelectRead) == false);
152 void Connect (HttpWebRequest request)
155 if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
156 // Take the chunked stream to the expected state (State.None)
157 if (CanReuse () && CompleteChunkedRead ()) {
164 if (socket != null) {
170 IPHostEntry hostEntry = sPoint.HostEntry;
172 if (hostEntry == null) {
174 monotouch_start_wwan (sPoint.Address.ToString ());
175 hostEntry = sPoint.HostEntry;
176 if (hostEntry == null) {
178 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
179 WebExceptionStatus.NameResolutionFailure;
186 //WebConnectionData data = Data;
187 foreach (IPAddress address in hostEntry.AddressList) {
189 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
190 } catch (Exception se) {
191 // The Socket ctor can throw if we run out of FD's
192 if (!request.Aborted)
193 status = WebExceptionStatus.ConnectFailure;
194 connect_exception = se;
197 IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
198 socket.NoDelay = !sPoint.UseNagleAlgorithm;
200 sPoint.KeepAliveSetup (socket);
202 // Ignore. Not supported in all platforms.
205 if (!sPoint.CallEndPointDelegate (socket, remote)) {
208 status = WebExceptionStatus.ConnectFailure;
213 socket.Connect (remote);
214 status = WebExceptionStatus.Success;
216 } catch (ThreadAbortException) {
217 // program exiting...
223 } catch (ObjectDisposedException) {
224 // socket closed from another thread
226 } catch (Exception exc) {
231 if (!request.Aborted)
232 status = WebExceptionStatus.ConnectFailure;
233 connect_exception = exc;
240 static void EnsureSSLStreamAvailable ()
243 if (sslStream != null)
246 #if NET_2_1 && SECURITY_DEP
247 sslStream = typeof (HttpsClientStream);
249 // HttpsClientStream is an internal glue class in Mono.Security.dll
250 sslStream = Type.GetType ("Mono.Security.Protocol.Tls.HttpsClientStream, " +
251 Consts.AssemblyMono_Security, false);
253 if (sslStream == null) {
254 string msg = "Missing Mono.Security.dll assembly. " +
255 "Support for SSL/TLS is unavailable.";
257 throw new NotSupportedException (msg);
260 #if !MONOTOUCH && !MONODROID
261 piClient = sslStream.GetProperty ("SelectedClientCertificate");
262 piServer = sslStream.GetProperty ("ServerCertificate");
263 piTrustFailure = sslStream.GetProperty ("TrustFailure");
268 bool CreateTunnel (HttpWebRequest request, Uri connectUri,
269 Stream stream, out byte[] buffer)
271 StringBuilder sb = new StringBuilder ();
272 sb.Append ("CONNECT ");
273 sb.Append (request.Address.Host);
275 sb.Append (request.Address.Port);
276 sb.Append (" HTTP/");
277 if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
282 sb.Append ("\r\nHost: ");
283 sb.Append (request.Address.Authority);
286 var challenge = Data.Challenge;
287 Data.Challenge = null;
288 var auth_header = request.Headers ["Proxy-Authorization"];
289 bool have_auth = auth_header != null;
291 sb.Append ("\r\nProxy-Authorization: ");
292 sb.Append (auth_header);
293 ntlm = auth_header.ToUpper ().Contains ("NTLM");
294 } else if (challenge != null && Data.StatusCode == 407) {
295 ICredentials creds = request.Proxy.Credentials;
298 if (connect_request == null) {
299 // create a CONNECT request to use with Authenticate
300 connect_request = (HttpWebRequest)WebRequest.Create (
301 connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
302 connect_request.Method = "CONNECT";
303 connect_request.Credentials = creds;
306 for (int i = 0; i < challenge.Length; i++) {
307 var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
310 ntlm = (auth.Module.AuthenticationType == "NTLM");
311 sb.Append ("\r\nProxy-Authorization: ");
312 sb.Append (auth.Message);
318 sb.Append ("\r\nProxy-Connection: keep-alive");
319 connect_ntlm_auth_state++;
322 sb.Append ("\r\n\r\n");
325 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
326 stream.Write (connectBytes, 0, connectBytes.Length);
329 WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
330 if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
331 result != null && status == 407) { // Needs proxy auth
332 var connectionHeader = result ["Connection"];
333 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
334 connectionHeader.ToLower() == "close") {
335 // The server is requesting that this connection be closed
340 Data.StatusCode = status;
341 Data.Challenge = result.GetValues_internal ("Proxy-Authenticate", false);
343 } else if (status != 200) {
344 string msg = String.Format ("The remote server returned a {0} status code.", status);
345 HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
349 return (result != null);
352 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
357 byte [] buffer = new byte [1024];
358 MemoryStream ms = new MemoryStream ();
361 int n = stream.Read (buffer, 0, 1024);
363 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
367 ms.Write (buffer, 0, n);
370 bool gotStatus = false;
371 WebHeaderCollection headers = new WebHeaderCollection ();
372 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
376 contentLen = int.Parse(headers["Content-Length"]);
382 if (ms.Length - start - contentLen > 0) {
383 // we've read more data than the response header and conents,
384 // give back extra data to the caller
385 retBuffer = new byte[ms.Length - start - contentLen];
386 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
389 // haven't read in some or all of the contents for the response, do so now
390 FlushContents(stream, contentLen - (int)(ms.Length - start));
401 string[] parts = str.Split (' ');
402 if (parts.Length < 2) {
403 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
407 if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
408 Data.ProxyVersion = HttpVersion.Version11;
409 else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
410 Data.ProxyVersion = HttpVersion.Version10;
412 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
416 status = (int)UInt32.Parse (parts [1]);
422 void FlushContents(Stream stream, int contentLength)
424 while (contentLength > 0) {
425 byte[] contentBuffer = new byte[contentLength];
426 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
428 contentLength -= bytesRead;
436 bool CreateStream (HttpWebRequest request)
439 NetworkStream serverStream = new NetworkStream (socket, false);
441 if (request.Address.Scheme == Uri.UriSchemeHttps) {
443 EnsureSSLStreamAvailable ();
444 if (!reused || nstream == null || nstream.GetType () != sslStream) {
445 byte [] buffer = null;
446 if (sPoint.UseConnect) {
447 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
452 #if MONOTOUCH || MONODROID
453 nstream = new HttpsClientStream (serverStream, request.ClientCertificates, request, buffer);
455 object[] args = new object [4] { serverStream,
456 request.ClientCertificates,
458 nstream = (Stream) Activator.CreateInstance (sslStream, args);
460 SslClientStream scs = (SslClientStream) nstream;
461 var helper = new ServicePointManager.ChainValidationHelper (request, request.Address.Host);
462 scs.ServerCertValidation2 += new CertificateValidationCallback2 (helper.ValidateChain);
464 certsAvailable = false;
466 // we also need to set ServicePoint.Certificate
467 // and ServicePoint.ClientCertificate but this can
468 // only be done later (after handshake - which is
469 // done only after a read operation).
472 nstream = serverStream;
474 } catch (Exception) {
475 if (!request.Aborted)
476 status = WebExceptionStatus.ConnectFailure;
483 void HandleError (WebExceptionStatus st, Exception e, string where)
487 if (st == WebExceptionStatus.RequestCanceled)
488 Data = new WebConnectionData ();
491 if (e == null) { // At least we now where it comes from
494 throw new Exception ();
496 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
498 } catch (Exception e2) {
503 HttpWebRequest req = null;
504 if (Data != null && Data.request != null)
509 req.FinishedReading = true;
510 req.SetResponseError (st, e, where);
514 static void ReadDone (IAsyncResult result)
516 WebConnection cnc = (WebConnection)result.AsyncState;
517 WebConnectionData data = cnc.Data;
518 Stream ns = cnc.nstream;
526 nread = ns.EndRead (result);
527 } catch (ObjectDisposedException) {
529 } catch (Exception e) {
530 if (e.InnerException is ObjectDisposedException)
533 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
538 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
543 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
548 nread += cnc.position;
549 if (data.ReadState == ReadState.None) {
550 Exception exc = null;
552 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
553 } catch (Exception e) {
557 if (exc != null || pos == -1) {
558 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
563 if (data.ReadState == ReadState.Aborted) {
564 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
568 if (data.ReadState != ReadState.Content) {
570 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
571 byte [] newBuffer = new byte [max];
572 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
573 cnc.buffer = newBuffer;
574 cnc.position = nread;
575 data.ReadState = ReadState.None;
582 WebConnectionStream stream = new WebConnectionStream (cnc, data);
583 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
584 string tencoding = null;
586 tencoding = data.Headers ["Transfer-Encoding"];
588 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
589 if (!cnc.chunkedRead) {
590 stream.ReadBuffer = cnc.buffer;
591 stream.ReadBufferOffset = pos;
592 stream.ReadBufferSize = nread;
594 stream.CheckResponseInBuffer ();
595 } catch (Exception e) {
596 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
598 } else if (cnc.chunkStream == null) {
600 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
601 } catch (Exception e) {
602 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
606 cnc.chunkStream.ResetBuffer ();
608 cnc.chunkStream.Write (cnc.buffer, pos, nread);
609 } catch (Exception e) {
610 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
615 data.stream = stream;
618 stream.ForceCompletion ();
620 data.request.SetResponseData (data);
623 static bool ExpectContent (int statusCode, string method)
625 if (method == "HEAD")
627 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
630 internal void GetCertificates (Stream stream)
632 // here the SSL negotiation have been done
633 #if SECURITY_DEP && (MONOTOUCH || MONODROID)
634 HttpsClientStream s = (stream as HttpsClientStream);
635 X509Certificate client = s.SelectedClientCertificate;
636 X509Certificate server = s.ServerCertificate;
638 X509Certificate client = (X509Certificate) piClient.GetValue (stream, null);
639 X509Certificate server = (X509Certificate) piServer.GetValue (stream, null);
641 sPoint.SetCertificates (client, server);
642 certsAvailable = (server != null);
645 internal static void InitRead (object state)
647 WebConnection cnc = (WebConnection) state;
648 Stream ns = cnc.nstream;
651 int size = cnc.buffer.Length - cnc.position;
652 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
653 } catch (Exception e) {
654 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
658 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
659 byte [] buffer, int max)
664 bool isContinue = false;
665 bool emptyFirstLine = false;
667 if (data.ReadState == ReadState.Aborted)
670 if (data.ReadState == ReadState.None) {
671 lineok = ReadLine (buffer, ref pos, max, ref line);
676 emptyFirstLine = true;
679 emptyFirstLine = false;
680 data.ReadState = ReadState.Status;
682 string [] parts = line.Split (' ');
683 if (parts.Length < 2)
686 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
687 data.Version = HttpVersion.Version11;
688 sPoint.SetVersion (HttpVersion.Version11);
690 data.Version = HttpVersion.Version10;
691 sPoint.SetVersion (HttpVersion.Version10);
694 data.StatusCode = (int) UInt32.Parse (parts [1]);
695 if (parts.Length >= 3)
696 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
698 data.StatusDescription = "";
704 emptyFirstLine = false;
705 if (data.ReadState == ReadState.Status) {
706 data.ReadState = ReadState.Headers;
707 data.Headers = new WebHeaderCollection ();
708 ArrayList headers = new ArrayList ();
709 bool finished = false;
711 if (ReadLine (buffer, ref pos, max, ref line) == false)
715 // Empty line: end of headers
720 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
721 int count = headers.Count - 1;
725 string prev = (string) headers [count] + line;
726 headers [count] = prev;
735 foreach (string s in headers)
736 data.Headers.SetInternal (s);
738 if (data.StatusCode == (int) HttpStatusCode.Continue) {
739 sPoint.SendContinue = true;
743 if (data.request.ExpectContinue) {
744 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
745 // Prevent double calls when getting the
746 // headers in several packets.
747 data.request.ExpectContinue = false;
750 data.ReadState = ReadState.None;
754 data.ReadState = ReadState.Content;
758 } while (emptyFirstLine || isContinue);
763 void InitConnection (object state)
765 HttpWebRequest request = (HttpWebRequest) state;
766 request.WebConnection = this;
767 if (request.ReuseConnection)
768 request.StoredConnection = this;
773 keepAlive = request.KeepAlive;
774 Data = new WebConnectionData (request);
780 if (status != WebExceptionStatus.Success) {
781 if (!request.Aborted) {
782 request.SetWriteStreamError (status, connect_exception);
788 if (!CreateStream (request)) {
792 WebExceptionStatus st = status;
793 if (Data.Challenge != null)
796 Exception cnc_exc = connect_exception;
797 connect_exception = null;
798 request.SetWriteStreamError (st, cnc_exc);
803 request.SetWriteStream (new WebConnectionStream (this, request));
807 static bool warned_about_queue = false;
810 internal EventHandler SendRequest (HttpWebRequest request)
816 if (state.TrySetBusy ()) {
817 status = WebExceptionStatus.Success;
818 ThreadPool.QueueUserWorkItem (initConn, request);
822 if (!warned_about_queue) {
823 warned_about_queue = true;
824 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
827 queue.Enqueue (request);
838 if (queue.Count > 0) {
839 SendRequest ((HttpWebRequest) queue.Dequeue ());
844 internal void NextRead ()
847 if (Data.request != null)
848 Data.request.FinishedReading = true;
849 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
850 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
851 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
852 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
854 if (cncHeader != null) {
855 cncHeader = cncHeader.ToLower ();
856 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
859 if ((socket != null && !socket.Connected) ||
860 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
865 if (priority_request != null) {
866 SendRequest (priority_request);
867 priority_request = null;
874 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
876 bool foundCR = false;
877 StringBuilder text = new StringBuilder ();
880 while (start < max) {
881 c = (int) buffer [start++];
883 if (c == '\n') { // newline
884 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
889 } else if (foundCR) {
898 text.Append ((char) c);
901 if (c != '\n' && c != '\r')
904 if (text.Length == 0) {
906 return (c == '\n' || c == '\r');
912 output = text.ToString ();
917 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
921 if (Data.request != request)
922 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
928 IAsyncResult result = null;
929 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
931 result = s.BeginRead (buffer, offset, size, cb, state);
933 } catch (Exception) {
934 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
940 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
941 wr.InnerAsyncResult = result;
942 if (result == null) {
943 // Will be completed from the data in ChunkStream
944 wr.SetCompleted (true, (Exception) null);
953 internal int EndRead (HttpWebRequest request, IAsyncResult result)
957 if (Data.request != request)
958 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
960 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
966 WebAsyncResult wr = null;
967 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
968 if (chunkedRead && (nsAsync is WebAsyncResult)) {
969 wr = (WebAsyncResult) nsAsync;
970 IAsyncResult inner = wr.InnerAsyncResult;
971 if (inner != null && !(inner is WebAsyncResult)) {
972 nbytes = s.EndRead (inner);
975 } else if (!(nsAsync is WebAsyncResult)) {
976 nbytes = s.EndRead (nsAsync);
977 wr = (WebAsyncResult) result;
983 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
984 if (!done && nbytes == 0 && chunkStream.WantMore)
985 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
986 } catch (Exception e) {
987 if (e is WebException)
990 throw new WebException ("Invalid chunked data.", e,
991 WebExceptionStatus.ServerProtocolViolation, null);
994 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
995 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
996 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1000 return (nbytes != 0) ? nbytes : -1;
1003 // To be called on chunkedRead when we can read no data from the ChunkStream yet
1004 int EnsureRead (byte [] buffer, int offset, int size)
1006 byte [] morebytes = null;
1008 while (nbytes == 0 && chunkStream.WantMore) {
1009 int localsize = chunkStream.ChunkLeft;
1010 if (localsize <= 0) // not read chunk size yet
1012 else if (localsize > 16384)
1015 if (morebytes == null || morebytes.Length < localsize)
1016 morebytes = new byte [localsize];
1018 int nread = nstream.Read (morebytes, 0, localsize);
1022 chunkStream.Write (morebytes, 0, nread);
1023 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
1029 bool CompleteChunkedRead()
1031 if (!chunkedRead || chunkStream == null)
1034 while (chunkStream.WantMore) {
1035 int nbytes = nstream.Read (buffer, 0, buffer.Length);
1037 return false; // Socket was disconnected
1039 chunkStream.Write (buffer, 0, nbytes);
1045 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
1049 if (Data.request != request)
1050 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1051 if (nstream == null)
1056 IAsyncResult result = null;
1058 result = s.BeginWrite (buffer, offset, size, cb, state);
1059 } catch (Exception) {
1060 status = WebExceptionStatus.SendFailure;
1067 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1069 if (request.FinishedReading)
1074 if (Data.request != request)
1075 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1076 if (nstream == null)
1077 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1082 s.EndWrite (result);
1084 } catch (Exception exc) {
1085 status = WebExceptionStatus.SendFailure;
1086 if (throwOnError && exc.InnerException != null)
1087 throw exc.InnerException;
1092 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1096 if (Data.request != request)
1097 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1098 if (nstream == null)
1107 result = s.Read (buffer, offset, size);
1108 done = (result == 0);
1113 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1114 if (!done && result == 0 && chunkStream.WantMore)
1115 result = EnsureRead (buffer, offset, size);
1116 } catch (Exception e) {
1117 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1121 if ((done || result == 0) && chunkStream.WantMore) {
1122 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1123 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1126 } catch (Exception e) {
1127 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1133 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1138 if (Data.request != request)
1139 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1146 s.Write (buffer, offset, size);
1147 // here SSL handshake should have been done
1148 if (ssl && !certsAvailable)
1149 GetCertificates (s);
1150 } catch (Exception e) {
1151 err_msg = e.Message;
1152 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1153 string msg = "Write: " + err_msg;
1154 if (e is WebException) {
1155 HandleError (wes, e, msg);
1159 // if SSL is in use then check for TrustFailure
1161 #if SECURITY_DEP && (MONOTOUCH || MONODROID)
1162 HttpsClientStream https = (s as HttpsClientStream);
1163 if (https.TrustFailure) {
1165 if ((bool) piTrustFailure.GetValue (s , null)) {
1167 wes = WebExceptionStatus.TrustFailure;
1168 msg = "Trust failure";
1172 HandleError (wes, e, msg);
1178 internal void Close (bool sendNext)
1181 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1182 Data.request.ReuseConnection = false;
1186 if (nstream != null) {
1193 if (socket != null) {
1200 if (ntlm_authenticated)
1204 Data.ReadState = ReadState.Aborted;
1208 Data = new WebConnectionData ();
1212 connect_request = null;
1213 connect_ntlm_auth_state = NtlmAuthState.None;
1217 void Abort (object sender, EventArgs args)
1221 HttpWebRequest req = (HttpWebRequest) sender;
1222 if (Data.request == req || Data.request == null) {
1223 if (!req.FinishedReading) {
1224 status = WebExceptionStatus.RequestCanceled;
1226 if (queue.Count > 0) {
1227 Data.request = (HttpWebRequest) queue.Dequeue ();
1228 SendRequest (Data.request);
1234 req.FinishedReading = true;
1235 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1236 if (queue.Count > 0 && queue.Peek () == sender) {
1238 } else if (queue.Count > 0) {
1239 object [] old = queue.ToArray ();
1241 for (int i = old.Length - 1; i >= 0; i--) {
1242 if (old [i] != sender)
1243 queue.Enqueue (old [i]);
1250 internal void ResetNtlm ()
1252 ntlm_authenticated = false;
1253 ntlm_credentials = null;
1254 unsafe_sharing = false;
1257 internal bool Connected {
1260 return (socket != null && socket.Connected);
1265 // -Used for NTLM authentication
1266 internal HttpWebRequest PriorityRequest {
1267 set { priority_request = value; }
1270 internal bool NtlmAuthenticated {
1271 get { return ntlm_authenticated; }
1272 set { ntlm_authenticated = value; }
1275 internal NetworkCredential NtlmCredential {
1276 get { return ntlm_credentials; }
1277 set { ntlm_credentials = value; }
1280 internal bool UnsafeAuthenticatedConnectionSharing {
1281 get { return unsafe_sharing; }
1282 set { unsafe_sharing = value; }