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;
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;
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);
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 ();
359 bool gotStatus = false;
360 WebHeaderCollection headers = null;
363 int n = stream.Read (buffer, 0, 1024);
365 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
369 ms.Write (buffer, 0, n);
372 headers = new WebHeaderCollection ();
373 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
377 contentLen = int.Parse(headers["Content-Length"]);
383 if (ms.Length - start - contentLen > 0) {
384 // we've read more data than the response header and conents,
385 // give back extra data to the caller
386 retBuffer = new byte[ms.Length - start - contentLen];
387 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
390 // haven't read in some or all of the contents for the response, do so now
391 FlushContents(stream, contentLen - (int)(ms.Length - start));
402 int spaceidx = str.IndexOf (' ');
403 if (spaceidx == -1) {
404 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
408 status = (int) UInt32.Parse (str.Substring (spaceidx + 1, 3));
414 void FlushContents(Stream stream, int contentLength)
416 while (contentLength > 0) {
417 byte[] contentBuffer = new byte[contentLength];
418 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
420 contentLength -= bytesRead;
428 bool CreateStream (HttpWebRequest request)
431 NetworkStream serverStream = new NetworkStream (socket, false);
433 if (request.Address.Scheme == Uri.UriSchemeHttps) {
435 EnsureSSLStreamAvailable ();
436 if (!reused || nstream == null || nstream.GetType () != sslStream) {
437 byte [] buffer = null;
438 if (sPoint.UseConnect) {
439 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
445 nstream = new HttpsClientStream (serverStream, request.ClientCertificates, request, buffer);
447 object[] args = new object [4] { serverStream,
448 request.ClientCertificates,
450 nstream = (Stream) Activator.CreateInstance (sslStream, args);
452 SslClientStream scs = (SslClientStream) nstream;
453 var helper = new ServicePointManager.ChainValidationHelper (request, request.Address.Host);
454 scs.ServerCertValidation2 += new CertificateValidationCallback2 (helper.ValidateChain);
456 certsAvailable = false;
458 // we also need to set ServicePoint.Certificate
459 // and ServicePoint.ClientCertificate but this can
460 // only be done later (after handshake - which is
461 // done only after a read operation).
464 nstream = serverStream;
466 } catch (Exception) {
467 if (!request.Aborted)
468 status = WebExceptionStatus.ConnectFailure;
475 void HandleError (WebExceptionStatus st, Exception e, string where)
479 if (st == WebExceptionStatus.RequestCanceled)
480 Data = new WebConnectionData ();
483 if (e == null) { // At least we now where it comes from
486 throw new Exception ();
488 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
490 } catch (Exception e2) {
495 HttpWebRequest req = null;
496 if (Data != null && Data.request != null)
501 req.FinishedReading = true;
502 req.SetResponseError (st, e, where);
506 static void ReadDone (IAsyncResult result)
508 WebConnection cnc = (WebConnection)result.AsyncState;
509 WebConnectionData data = cnc.Data;
510 Stream ns = cnc.nstream;
518 nread = ns.EndRead (result);
519 } catch (ObjectDisposedException) {
521 } catch (Exception e) {
522 if (e.InnerException is ObjectDisposedException)
525 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
530 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
535 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
540 nread += cnc.position;
541 if (data.ReadState == ReadState.None) {
542 Exception exc = null;
544 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
545 } catch (Exception e) {
549 if (exc != null || pos == -1) {
550 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
555 if (data.ReadState == ReadState.Aborted) {
556 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
560 if (data.ReadState != ReadState.Content) {
562 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
563 byte [] newBuffer = new byte [max];
564 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
565 cnc.buffer = newBuffer;
566 cnc.position = nread;
567 data.ReadState = ReadState.None;
574 WebConnectionStream stream = new WebConnectionStream (cnc, data);
575 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
576 string tencoding = null;
578 tencoding = data.Headers ["Transfer-Encoding"];
580 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
581 if (!cnc.chunkedRead) {
582 stream.ReadBuffer = cnc.buffer;
583 stream.ReadBufferOffset = pos;
584 stream.ReadBufferSize = nread;
586 stream.CheckResponseInBuffer ();
587 } catch (Exception e) {
588 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
590 } else if (cnc.chunkStream == null) {
592 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
593 } catch (Exception e) {
594 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
598 cnc.chunkStream.ResetBuffer ();
600 cnc.chunkStream.Write (cnc.buffer, pos, nread);
601 } catch (Exception e) {
602 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
607 data.stream = stream;
610 stream.ForceCompletion ();
612 data.request.SetResponseData (data);
615 static bool ExpectContent (int statusCode, string method)
617 if (method == "HEAD")
619 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
622 internal void GetCertificates (Stream stream)
624 // here the SSL negotiation have been done
625 #if SECURITY_DEP && MONOTOUCH
626 HttpsClientStream s = (stream as HttpsClientStream);
627 X509Certificate client = s.SelectedClientCertificate;
628 X509Certificate server = s.ServerCertificate;
630 X509Certificate client = (X509Certificate) piClient.GetValue (stream, null);
631 X509Certificate server = (X509Certificate) piServer.GetValue (stream, null);
633 sPoint.SetCertificates (client, server);
634 certsAvailable = (server != null);
637 internal static void InitRead (object state)
639 WebConnection cnc = (WebConnection) state;
640 Stream ns = cnc.nstream;
643 int size = cnc.buffer.Length - cnc.position;
644 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
645 } catch (Exception e) {
646 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
650 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
651 byte [] buffer, int max)
656 bool isContinue = false;
657 bool emptyFirstLine = false;
659 if (data.ReadState == ReadState.Aborted)
662 if (data.ReadState == ReadState.None) {
663 lineok = ReadLine (buffer, ref pos, max, ref line);
668 emptyFirstLine = true;
671 emptyFirstLine = false;
672 data.ReadState = ReadState.Status;
674 string [] parts = line.Split (' ');
675 if (parts.Length < 2)
678 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
679 data.Version = HttpVersion.Version11;
680 sPoint.SetVersion (HttpVersion.Version11);
682 data.Version = HttpVersion.Version10;
683 sPoint.SetVersion (HttpVersion.Version10);
686 data.StatusCode = (int) UInt32.Parse (parts [1]);
687 if (parts.Length >= 3)
688 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
690 data.StatusDescription = "";
696 emptyFirstLine = false;
697 if (data.ReadState == ReadState.Status) {
698 data.ReadState = ReadState.Headers;
699 data.Headers = new WebHeaderCollection ();
700 ArrayList headers = new ArrayList ();
701 bool finished = false;
703 if (ReadLine (buffer, ref pos, max, ref line) == false)
707 // Empty line: end of headers
712 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
713 int count = headers.Count - 1;
717 string prev = (string) headers [count] + line;
718 headers [count] = prev;
727 foreach (string s in headers)
728 data.Headers.SetInternal (s);
730 if (data.StatusCode == (int) HttpStatusCode.Continue) {
731 sPoint.SendContinue = true;
735 if (data.request.ExpectContinue) {
736 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
737 // Prevent double calls when getting the
738 // headers in several packets.
739 data.request.ExpectContinue = false;
742 data.ReadState = ReadState.None;
746 data.ReadState = ReadState.Content;
750 } while (emptyFirstLine || isContinue);
755 void InitConnection (object state)
757 HttpWebRequest request = (HttpWebRequest) state;
758 request.WebConnection = this;
759 if (request.ReuseConnection)
760 request.StoredConnection = this;
765 keepAlive = request.KeepAlive;
766 Data = new WebConnectionData (request);
772 if (status != WebExceptionStatus.Success) {
773 if (!request.Aborted) {
774 request.SetWriteStreamError (status, connect_exception);
780 if (!CreateStream (request)) {
784 WebExceptionStatus st = status;
785 if (Data.Challenge != null)
788 Exception cnc_exc = connect_exception;
789 connect_exception = null;
790 request.SetWriteStreamError (st, cnc_exc);
795 request.SetWriteStream (new WebConnectionStream (this, request));
799 static bool warned_about_queue = false;
802 internal EventHandler SendRequest (HttpWebRequest request)
808 if (state.TrySetBusy ()) {
809 status = WebExceptionStatus.Success;
810 ThreadPool.QueueUserWorkItem (initConn, request);
814 if (!warned_about_queue) {
815 warned_about_queue = true;
816 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
819 queue.Enqueue (request);
830 if (queue.Count > 0) {
831 SendRequest ((HttpWebRequest) queue.Dequeue ());
836 internal void NextRead ()
839 if (Data.request != null)
840 Data.request.FinishedReading = true;
841 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
842 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
843 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
844 if (cncHeader != null) {
845 cncHeader = cncHeader.ToLower ();
846 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
849 if ((socket != null && !socket.Connected) ||
850 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
855 if (priority_request != null) {
856 SendRequest (priority_request);
857 priority_request = null;
864 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
866 bool foundCR = false;
867 StringBuilder text = new StringBuilder ();
870 while (start < max) {
871 c = (int) buffer [start++];
873 if (c == '\n') { // newline
874 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
879 } else if (foundCR) {
888 text.Append ((char) c);
891 if (c != '\n' && c != '\r')
894 if (text.Length == 0) {
896 return (c == '\n' || c == '\r');
902 output = text.ToString ();
907 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
911 if (Data.request != request)
912 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
918 IAsyncResult result = null;
919 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
921 result = s.BeginRead (buffer, offset, size, cb, state);
923 } catch (Exception) {
924 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
930 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
931 wr.InnerAsyncResult = result;
932 if (result == null) {
933 // Will be completed from the data in ChunkStream
934 wr.SetCompleted (true, (Exception) null);
943 internal int EndRead (HttpWebRequest request, IAsyncResult result)
947 if (Data.request != request)
948 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
950 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
956 WebAsyncResult wr = null;
957 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
958 if (chunkedRead && (nsAsync is WebAsyncResult)) {
959 wr = (WebAsyncResult) nsAsync;
960 IAsyncResult inner = wr.InnerAsyncResult;
961 if (inner != null && !(inner is WebAsyncResult)) {
962 nbytes = s.EndRead (inner);
965 } else if (!(nsAsync is WebAsyncResult)) {
966 nbytes = s.EndRead (nsAsync);
967 wr = (WebAsyncResult) result;
973 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
974 if (!done && nbytes == 0 && chunkStream.WantMore)
975 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
976 } catch (Exception e) {
977 if (e is WebException)
980 throw new WebException ("Invalid chunked data.", e,
981 WebExceptionStatus.ServerProtocolViolation, null);
984 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
985 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
986 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
990 return (nbytes != 0) ? nbytes : -1;
993 // To be called on chunkedRead when we can read no data from the ChunkStream yet
994 int EnsureRead (byte [] buffer, int offset, int size)
996 byte [] morebytes = null;
998 while (nbytes == 0 && chunkStream.WantMore) {
999 int localsize = chunkStream.ChunkLeft;
1000 if (localsize <= 0) // not read chunk size yet
1002 else if (localsize > 16384)
1005 if (morebytes == null || morebytes.Length < localsize)
1006 morebytes = new byte [localsize];
1008 int nread = nstream.Read (morebytes, 0, localsize);
1012 chunkStream.Write (morebytes, 0, nread);
1013 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
1019 bool CompleteChunkedRead()
1021 if (!chunkedRead || chunkStream == null)
1024 while (chunkStream.WantMore) {
1025 int nbytes = nstream.Read (buffer, 0, buffer.Length);
1027 return false; // Socket was disconnected
1029 chunkStream.Write (buffer, 0, nbytes);
1035 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
1039 if (Data.request != request)
1040 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1041 if (nstream == null)
1046 IAsyncResult result = null;
1048 result = s.BeginWrite (buffer, offset, size, cb, state);
1049 } catch (Exception) {
1050 status = WebExceptionStatus.SendFailure;
1057 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1059 if (request.FinishedReading)
1064 if (Data.request != request)
1065 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1066 if (nstream == null)
1067 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1072 s.EndWrite (result);
1074 } catch (Exception exc) {
1075 status = WebExceptionStatus.SendFailure;
1076 if (throwOnError && exc.InnerException != null)
1077 throw exc.InnerException;
1082 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1086 if (Data.request != request)
1087 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1088 if (nstream == null)
1097 result = s.Read (buffer, offset, size);
1098 done = (result == 0);
1103 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1104 if (!done && result == 0 && chunkStream.WantMore)
1105 result = EnsureRead (buffer, offset, size);
1106 } catch (Exception e) {
1107 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1111 if ((done || result == 0) && chunkStream.WantMore) {
1112 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1113 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1116 } catch (Exception e) {
1117 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1123 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1128 if (Data.request != request)
1129 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1136 s.Write (buffer, offset, size);
1137 // here SSL handshake should have been done
1138 if (ssl && !certsAvailable)
1139 GetCertificates (s);
1140 } catch (Exception e) {
1141 err_msg = e.Message;
1142 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1143 string msg = "Write: " + err_msg;
1144 if (e is WebException) {
1145 HandleError (wes, e, msg);
1149 // if SSL is in use then check for TrustFailure
1151 #if SECURITY_DEP && MONOTOUCH
1152 HttpsClientStream https = (s as HttpsClientStream);
1153 if (https.TrustFailure) {
1155 if ((bool) piTrustFailure.GetValue (s , null)) {
1157 wes = WebExceptionStatus.TrustFailure;
1158 msg = "Trust failure";
1162 HandleError (wes, e, msg);
1168 internal void Close (bool sendNext)
1171 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1172 Data.request.ReuseConnection = false;
1176 if (nstream != null) {
1183 if (socket != null) {
1190 if (ntlm_authenticated)
1194 Data.ReadState = ReadState.Aborted;
1198 Data = new WebConnectionData ();
1202 connect_request = null;
1203 connect_ntlm_auth_state = NtlmAuthState.None;
1207 void Abort (object sender, EventArgs args)
1211 HttpWebRequest req = (HttpWebRequest) sender;
1212 if (Data.request == req || Data.request == null) {
1213 if (!req.FinishedReading) {
1214 status = WebExceptionStatus.RequestCanceled;
1216 if (queue.Count > 0) {
1217 Data.request = (HttpWebRequest) queue.Dequeue ();
1218 SendRequest (Data.request);
1224 req.FinishedReading = true;
1225 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1226 if (queue.Count > 0 && queue.Peek () == sender) {
1228 } else if (queue.Count > 0) {
1229 object [] old = queue.ToArray ();
1231 for (int i = old.Length - 1; i >= 0; i--) {
1232 if (old [i] != sender)
1233 queue.Enqueue (old [i]);
1240 internal void ResetNtlm ()
1242 ntlm_authenticated = false;
1243 ntlm_credentials = null;
1244 unsafe_sharing = false;
1247 internal bool Connected {
1250 return (socket != null && socket.Connected);
1255 // -Used for NTLM authentication
1256 internal HttpWebRequest PriorityRequest {
1257 set { priority_request = value; }
1260 internal bool NtlmAuthenticated {
1261 get { return ntlm_authenticated; }
1262 set { ntlm_authenticated = value; }
1265 internal NetworkCredential NtlmCredential {
1266 get { return ntlm_credentials; }
1267 set { ntlm_credentials = value; }
1270 internal bool UnsafeAuthenticatedConnectionSharing {
1271 get { return unsafe_sharing; }
1272 set { unsafe_sharing = value; }