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.
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;
65 internal Socket socket;
66 object socketLock = new object ();
67 WebExceptionStatus status;
68 WaitCallback initConn;
71 static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
72 EventHandler abortHandler;
73 AbortHelper abortHelper;
74 internal WebConnectionData Data;
76 ChunkStream chunkStream;
81 HttpWebRequest priority_request;
82 NetworkCredential ntlm_credentials;
83 bool ntlm_authenticated;
92 NtlmAuthState connect_ntlm_auth_state;
93 HttpWebRequest connect_request;
97 Exception connect_exception;
98 static object classLock = new object ();
99 static Type sslStream;
101 static PropertyInfo piClient;
102 static PropertyInfo piServer;
103 static PropertyInfo piTrustFailure;
107 [System.Runtime.InteropServices.DllImport ("__Internal")]
108 static extern void monotouch_start_wwan (string uri);
111 public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
113 this.sPoint = sPoint;
114 buffer = new byte [4096];
115 Data = new WebConnectionData ();
116 initConn = new WaitCallback (state => {
118 InitConnection (state);
122 abortHelper = new AbortHelper ();
123 abortHelper.Connection = this;
124 abortHandler = new EventHandler (abortHelper.Abort);
128 public WebConnection Connection;
130 public void Abort (object sender, EventArgs args)
132 WebConnection other = ((HttpWebRequest) sender).WebConnection;
135 other.Abort (sender, args);
141 // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
142 // but if there's data pending to read (!) we won't reuse the socket.
143 return (socket.Poll (0, SelectMode.SelectRead) == false);
146 void Connect (HttpWebRequest request)
149 if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
150 // Take the chunked stream to the expected state (State.None)
151 if (CanReuse () && CompleteChunkedRead ()) {
158 if (socket != null) {
164 IPHostEntry hostEntry = sPoint.HostEntry;
166 if (hostEntry == null) {
168 monotouch_start_wwan (sPoint.Address.ToString ());
169 hostEntry = sPoint.HostEntry;
170 if (hostEntry == null) {
172 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
173 WebExceptionStatus.NameResolutionFailure;
180 //WebConnectionData data = Data;
181 foreach (IPAddress address in hostEntry.AddressList) {
183 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
184 } catch (Exception se) {
185 // The Socket ctor can throw if we run out of FD's
186 if (!request.Aborted)
187 status = WebExceptionStatus.ConnectFailure;
188 connect_exception = se;
191 IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
192 socket.NoDelay = !sPoint.UseNagleAlgorithm;
194 sPoint.KeepAliveSetup (socket);
196 // Ignore. Not supported in all platforms.
199 if (!sPoint.CallEndPointDelegate (socket, remote)) {
202 status = WebExceptionStatus.ConnectFailure;
207 socket.Connect (remote);
208 status = WebExceptionStatus.Success;
210 } catch (ThreadAbortException) {
211 // program exiting...
217 } catch (ObjectDisposedException) {
218 // socket closed from another thread
220 } catch (Exception exc) {
225 if (!request.Aborted)
226 status = WebExceptionStatus.ConnectFailure;
227 connect_exception = exc;
234 static void EnsureSSLStreamAvailable ()
237 if (sslStream != null)
240 #if NET_2_1 && SECURITY_DEP
241 sslStream = typeof (HttpsClientStream);
243 // HttpsClientStream is an internal glue class in Mono.Security.dll
244 sslStream = Type.GetType ("Mono.Security.Protocol.Tls.HttpsClientStream, " +
245 Consts.AssemblyMono_Security, false);
247 if (sslStream == null) {
248 string msg = "Missing Mono.Security.dll assembly. " +
249 "Support for SSL/TLS is unavailable.";
251 throw new NotSupportedException (msg);
255 piClient = sslStream.GetProperty ("SelectedClientCertificate");
256 piServer = sslStream.GetProperty ("ServerCertificate");
257 piTrustFailure = sslStream.GetProperty ("TrustFailure");
262 bool CreateTunnel (HttpWebRequest request, Uri connectUri,
263 Stream stream, out byte[] buffer)
265 StringBuilder sb = new StringBuilder ();
266 sb.Append ("CONNECT ");
267 sb.Append (request.Address.Host);
269 sb.Append (request.Address.Port);
270 sb.Append (" HTTP/");
271 if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
276 sb.Append ("\r\nHost: ");
277 sb.Append (request.Address.Authority);
280 var challenge = Data.Challenge;
281 Data.Challenge = null;
282 var auth_header = request.Headers ["Proxy-Authorization"];
283 bool have_auth = auth_header != null;
285 sb.Append ("\r\nProxy-Authorization: ");
286 sb.Append (auth_header);
287 ntlm = auth_header.ToUpper ().Contains ("NTLM");
288 } else if (challenge != null && Data.StatusCode == 407) {
289 ICredentials creds = request.Proxy.Credentials;
292 if (connect_request == null) {
293 // create a CONNECT request to use with Authenticate
294 connect_request = (HttpWebRequest)WebRequest.Create (
295 connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
296 connect_request.Method = "CONNECT";
297 connect_request.Credentials = creds;
300 for (int i = 0; i < challenge.Length; i++) {
301 var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
304 ntlm = (auth.Module.AuthenticationType == "NTLM");
305 sb.Append ("\r\nProxy-Authorization: ");
306 sb.Append (auth.Message);
312 sb.Append ("\r\nProxy-Connection: keep-alive");
313 connect_ntlm_auth_state++;
316 sb.Append ("\r\n\r\n");
319 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
320 stream.Write (connectBytes, 0, connectBytes.Length);
323 WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
324 if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
325 result != null && status == 407) { // Needs proxy auth
326 var connectionHeader = result ["Connection"];
327 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
328 connectionHeader.ToLower() == "close") {
329 // The server is requesting that this connection be closed
334 Data.StatusCode = status;
335 Data.Challenge = result.GetValues_internal ("Proxy-Authenticate", false);
337 } else if (status != 200) {
338 string msg = String.Format ("The remote server returned a {0} status code.", status);
339 HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
343 return (result != null);
346 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
351 byte [] buffer = new byte [1024];
352 MemoryStream ms = new MemoryStream ();
353 bool gotStatus = false;
354 WebHeaderCollection headers = null;
357 int n = stream.Read (buffer, 0, 1024);
359 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
363 ms.Write (buffer, 0, n);
366 headers = new WebHeaderCollection ();
367 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
371 contentLen = int.Parse(headers["Content-Length"]);
377 if (ms.Length - start - contentLen > 0) {
378 // we've read more data than the response header and conents,
379 // give back extra data to the caller
380 retBuffer = new byte[ms.Length - start - contentLen];
381 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
384 // haven't read in some or all of the contents for the response, do so now
385 FlushContents(stream, contentLen - (int)(ms.Length - start));
396 int spaceidx = str.IndexOf (' ');
397 if (spaceidx == -1) {
398 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
402 status = (int) UInt32.Parse (str.Substring (spaceidx + 1, 3));
408 void FlushContents(Stream stream, int contentLength)
410 while (contentLength > 0) {
411 byte[] contentBuffer = new byte[contentLength];
412 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
414 contentLength -= bytesRead;
422 bool CreateStream (HttpWebRequest request)
425 NetworkStream serverStream = new NetworkStream (socket, false);
427 if (request.Address.Scheme == Uri.UriSchemeHttps) {
429 EnsureSSLStreamAvailable ();
430 if (!reused || nstream == null || nstream.GetType () != sslStream) {
431 byte [] buffer = null;
432 if (sPoint.UseConnect) {
433 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
439 nstream = new HttpsClientStream (serverStream, request.ClientCertificates, request, buffer);
441 object[] args = new object [4] { serverStream,
442 request.ClientCertificates,
444 nstream = (Stream) Activator.CreateInstance (sslStream, args);
446 SslClientStream scs = (SslClientStream) nstream;
447 var helper = new ServicePointManager.ChainValidationHelper (request, request.Address.Host);
448 scs.ServerCertValidation2 += new CertificateValidationCallback2 (helper.ValidateChain);
450 certsAvailable = false;
452 // we also need to set ServicePoint.Certificate
453 // and ServicePoint.ClientCertificate but this can
454 // only be done later (after handshake - which is
455 // done only after a read operation).
458 nstream = serverStream;
460 } catch (Exception) {
461 if (!request.Aborted)
462 status = WebExceptionStatus.ConnectFailure;
469 void HandleError (WebExceptionStatus st, Exception e, string where)
473 if (st == WebExceptionStatus.RequestCanceled)
474 Data = new WebConnectionData ();
477 if (e == null) { // At least we now where it comes from
480 throw new Exception ();
482 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
484 } catch (Exception e2) {
489 HttpWebRequest req = null;
490 if (Data != null && Data.request != null)
495 req.FinishedReading = true;
496 req.SetResponseError (st, e, where);
500 static void ReadDone (IAsyncResult result)
502 WebConnection cnc = (WebConnection)result.AsyncState;
503 WebConnectionData data = cnc.Data;
504 Stream ns = cnc.nstream;
512 nread = ns.EndRead (result);
513 } catch (ObjectDisposedException) {
515 } catch (Exception e) {
516 if (e.InnerException is ObjectDisposedException)
519 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
524 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
529 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
534 nread += cnc.position;
535 if (data.ReadState == ReadState.None) {
536 Exception exc = null;
538 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
539 } catch (Exception e) {
543 if (exc != null || pos == -1) {
544 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
549 if (data.ReadState == ReadState.Aborted) {
550 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
554 if (data.ReadState != ReadState.Content) {
556 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
557 byte [] newBuffer = new byte [max];
558 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
559 cnc.buffer = newBuffer;
560 cnc.position = nread;
561 data.ReadState = ReadState.None;
568 WebConnectionStream stream = new WebConnectionStream (cnc, data);
569 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
570 string tencoding = null;
572 tencoding = data.Headers ["Transfer-Encoding"];
574 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
575 if (!cnc.chunkedRead) {
576 stream.ReadBuffer = cnc.buffer;
577 stream.ReadBufferOffset = pos;
578 stream.ReadBufferSize = nread;
580 stream.CheckResponseInBuffer ();
581 } catch (Exception e) {
582 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
584 } else if (cnc.chunkStream == null) {
586 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
587 } catch (Exception e) {
588 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
592 cnc.chunkStream.ResetBuffer ();
594 cnc.chunkStream.Write (cnc.buffer, pos, nread);
595 } catch (Exception e) {
596 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
601 data.stream = stream;
604 stream.ForceCompletion ();
606 data.request.SetResponseData (data);
609 static bool ExpectContent (int statusCode, string method)
611 if (method == "HEAD")
613 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
616 internal void GetCertificates (Stream stream)
618 // here the SSL negotiation have been done
619 #if SECURITY_DEP && MONOTOUCH
620 HttpsClientStream s = (stream as HttpsClientStream);
621 X509Certificate client = s.SelectedClientCertificate;
622 X509Certificate server = s.ServerCertificate;
624 X509Certificate client = (X509Certificate) piClient.GetValue (stream, null);
625 X509Certificate server = (X509Certificate) piServer.GetValue (stream, null);
627 sPoint.SetCertificates (client, server);
628 certsAvailable = (server != null);
631 internal static void InitRead (object state)
633 WebConnection cnc = (WebConnection) state;
634 Stream ns = cnc.nstream;
637 int size = cnc.buffer.Length - cnc.position;
638 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
639 } catch (Exception e) {
640 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
644 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
645 byte [] buffer, int max)
650 bool isContinue = false;
651 bool emptyFirstLine = false;
653 if (data.ReadState == ReadState.Aborted)
656 if (data.ReadState == ReadState.None) {
657 lineok = ReadLine (buffer, ref pos, max, ref line);
662 emptyFirstLine = true;
665 emptyFirstLine = false;
666 data.ReadState = ReadState.Status;
668 string [] parts = line.Split (' ');
669 if (parts.Length < 2)
672 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
673 data.Version = HttpVersion.Version11;
674 sPoint.SetVersion (HttpVersion.Version11);
676 data.Version = HttpVersion.Version10;
677 sPoint.SetVersion (HttpVersion.Version10);
680 data.StatusCode = (int) UInt32.Parse (parts [1]);
681 if (parts.Length >= 3)
682 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
684 data.StatusDescription = "";
690 emptyFirstLine = false;
691 if (data.ReadState == ReadState.Status) {
692 data.ReadState = ReadState.Headers;
693 data.Headers = new WebHeaderCollection ();
694 ArrayList headers = new ArrayList ();
695 bool finished = false;
697 if (ReadLine (buffer, ref pos, max, ref line) == false)
701 // Empty line: end of headers
706 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
707 int count = headers.Count - 1;
711 string prev = (string) headers [count] + line;
712 headers [count] = prev;
721 foreach (string s in headers)
722 data.Headers.SetInternal (s);
724 if (data.StatusCode == (int) HttpStatusCode.Continue) {
725 sPoint.SendContinue = true;
729 if (data.request.ExpectContinue) {
730 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
731 // Prevent double calls when getting the
732 // headers in several packets.
733 data.request.ExpectContinue = false;
736 data.ReadState = ReadState.None;
740 data.ReadState = ReadState.Content;
744 } while (emptyFirstLine || isContinue);
749 void InitConnection (object state)
751 HttpWebRequest request = (HttpWebRequest) state;
752 request.WebConnection = this;
753 if (request.ReuseConnection)
754 request.StoredConnection = this;
759 keepAlive = request.KeepAlive;
760 Data = new WebConnectionData (request);
766 if (status != WebExceptionStatus.Success) {
767 if (!request.Aborted) {
768 request.SetWriteStreamError (status, connect_exception);
774 if (!CreateStream (request)) {
778 WebExceptionStatus st = status;
779 if (Data.Challenge != null)
782 Exception cnc_exc = connect_exception;
783 connect_exception = null;
784 request.SetWriteStreamError (st, cnc_exc);
789 request.SetWriteStream (new WebConnectionStream (this, request));
793 static bool warned_about_queue = false;
796 internal EventHandler SendRequest (HttpWebRequest request)
804 status = WebExceptionStatus.Success;
805 ThreadPool.QueueUserWorkItem (initConn, request);
809 if (!warned_about_queue) {
810 warned_about_queue = true;
811 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
814 queue.Enqueue (request);
825 if (queue.Count > 0) {
826 SendRequest ((HttpWebRequest) queue.Dequeue ());
831 internal void NextRead ()
834 if (Data.request != null)
835 Data.request.FinishedReading = true;
836 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
837 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
838 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
839 if (cncHeader != null) {
840 cncHeader = cncHeader.ToLower ();
841 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
844 if ((socket != null && !socket.Connected) ||
845 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
850 if (priority_request != null) {
851 SendRequest (priority_request);
852 priority_request = null;
859 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
861 bool foundCR = false;
862 StringBuilder text = new StringBuilder ();
865 while (start < max) {
866 c = (int) buffer [start++];
868 if (c == '\n') { // newline
869 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
874 } else if (foundCR) {
883 text.Append ((char) c);
886 if (c != '\n' && c != '\r')
889 if (text.Length == 0) {
891 return (c == '\n' || c == '\r');
897 output = text.ToString ();
902 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
906 if (Data.request != request)
907 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
913 IAsyncResult result = null;
914 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
916 result = s.BeginRead (buffer, offset, size, cb, state);
918 } catch (Exception) {
919 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
925 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
926 wr.InnerAsyncResult = result;
927 if (result == null) {
928 // Will be completed from the data in ChunkStream
929 wr.SetCompleted (true, (Exception) null);
938 internal int EndRead (HttpWebRequest request, IAsyncResult result)
942 if (Data.request != request)
943 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
945 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
951 WebAsyncResult wr = null;
952 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
953 if (chunkedRead && (nsAsync is WebAsyncResult)) {
954 wr = (WebAsyncResult) nsAsync;
955 IAsyncResult inner = wr.InnerAsyncResult;
956 if (inner != null && !(inner is WebAsyncResult)) {
957 nbytes = s.EndRead (inner);
960 } else if (!(nsAsync is WebAsyncResult)) {
961 nbytes = s.EndRead (nsAsync);
962 wr = (WebAsyncResult) result;
968 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
969 if (!done && nbytes == 0 && chunkStream.WantMore)
970 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
971 } catch (Exception e) {
972 if (e is WebException)
975 throw new WebException ("Invalid chunked data.", e,
976 WebExceptionStatus.ServerProtocolViolation, null);
979 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
980 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
981 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
985 return (nbytes != 0) ? nbytes : -1;
988 // To be called on chunkedRead when we can read no data from the ChunkStream yet
989 int EnsureRead (byte [] buffer, int offset, int size)
991 byte [] morebytes = null;
993 while (nbytes == 0 && chunkStream.WantMore) {
994 int localsize = chunkStream.ChunkLeft;
995 if (localsize <= 0) // not read chunk size yet
997 else if (localsize > 16384)
1000 if (morebytes == null || morebytes.Length < localsize)
1001 morebytes = new byte [localsize];
1003 int nread = nstream.Read (morebytes, 0, localsize);
1007 chunkStream.Write (morebytes, 0, nread);
1008 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
1014 bool CompleteChunkedRead()
1016 if (!chunkedRead || chunkStream == null)
1019 while (chunkStream.WantMore) {
1020 int nbytes = nstream.Read (buffer, 0, buffer.Length);
1022 return false; // Socket was disconnected
1024 chunkStream.Write (buffer, 0, nbytes);
1030 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
1034 if (Data.request != request)
1035 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1036 if (nstream == null)
1041 IAsyncResult result = null;
1043 result = s.BeginWrite (buffer, offset, size, cb, state);
1044 } catch (Exception) {
1045 status = WebExceptionStatus.SendFailure;
1052 internal void EndWrite2 (HttpWebRequest request, IAsyncResult result)
1054 if (request.FinishedReading)
1059 if (Data.request != request)
1060 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1061 if (nstream == null)
1062 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1067 s.EndWrite (result);
1068 } catch (Exception exc) {
1069 status = WebExceptionStatus.SendFailure;
1070 if (exc.InnerException != null)
1071 throw exc.InnerException;
1076 internal bool EndWrite (HttpWebRequest request, IAsyncResult result)
1078 if (request.FinishedReading)
1083 if (Data.request != request)
1084 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1085 if (nstream == null)
1086 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1091 s.EndWrite (result);
1094 status = WebExceptionStatus.SendFailure;
1099 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1103 if (Data.request != request)
1104 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1105 if (nstream == null)
1114 result = s.Read (buffer, offset, size);
1115 done = (result == 0);
1120 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1121 if (!done && result == 0 && chunkStream.WantMore)
1122 result = EnsureRead (buffer, offset, size);
1123 } catch (Exception e) {
1124 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1128 if ((done || result == 0) && chunkStream.WantMore) {
1129 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1130 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1133 } catch (Exception e) {
1134 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1140 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1145 if (Data.request != request)
1146 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1153 s.Write (buffer, offset, size);
1154 // here SSL handshake should have been done
1155 if (ssl && !certsAvailable)
1156 GetCertificates (s);
1157 } catch (Exception e) {
1158 err_msg = e.Message;
1159 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1160 string msg = "Write: " + err_msg;
1161 if (e is WebException) {
1162 HandleError (wes, e, msg);
1166 // if SSL is in use then check for TrustFailure
1168 #if SECURITY_DEP && MONOTOUCH
1169 HttpsClientStream https = (s as HttpsClientStream);
1170 if (https.TrustFailure) {
1172 if ((bool) piTrustFailure.GetValue (s , null)) {
1174 wes = WebExceptionStatus.TrustFailure;
1175 msg = "Trust failure";
1179 HandleError (wes, e, msg);
1185 internal void Close (bool sendNext)
1188 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1189 Data.request.ReuseConnection = false;
1193 if (nstream != null) {
1200 if (socket != null) {
1207 if (ntlm_authenticated)
1211 Data.ReadState = ReadState.Aborted;
1215 Data = new WebConnectionData ();
1219 connect_request = null;
1220 connect_ntlm_auth_state = NtlmAuthState.None;
1224 void Abort (object sender, EventArgs args)
1228 HttpWebRequest req = (HttpWebRequest) sender;
1229 if (Data.request == req || Data.request == null) {
1230 if (!req.FinishedReading) {
1231 status = WebExceptionStatus.RequestCanceled;
1233 if (queue.Count > 0) {
1234 Data.request = (HttpWebRequest) queue.Dequeue ();
1235 SendRequest (Data.request);
1241 req.FinishedReading = true;
1242 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1243 if (queue.Count > 0 && queue.Peek () == sender) {
1245 } else if (queue.Count > 0) {
1246 object [] old = queue.ToArray ();
1248 for (int i = old.Length - 1; i >= 0; i--) {
1249 if (old [i] != sender)
1250 queue.Enqueue (old [i]);
1257 internal void ResetNtlm ()
1259 ntlm_authenticated = false;
1260 ntlm_credentials = null;
1261 unsafe_sharing = false;
1264 internal bool Busy {
1265 get { lock (this) return busy; }
1268 internal bool Connected {
1271 return (socket != null && socket.Connected);
1276 // -Used for NTLM authentication
1277 internal HttpWebRequest PriorityRequest {
1278 set { priority_request = value; }
1281 internal bool NtlmAuthenticated {
1282 get { return ntlm_authenticated; }
1283 set { ntlm_authenticated = value; }
1286 internal NetworkCredential NtlmCredential {
1287 get { return ntlm_credentials; }
1288 set { ntlm_credentials = value; }
1291 internal bool UnsafeAuthenticatedConnectionSharing {
1292 get { return unsafe_sharing; }
1293 set { unsafe_sharing = value; }