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.Reflection;
35 using System.Security.Cryptography.X509Certificates;
37 using System.Threading;
39 using Mono.Security.Protocol.Tls;
57 object socketLock = new object ();
58 WebExceptionStatus status;
59 WaitCallback initConn;
62 static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
63 EventHandler abortHandler;
64 AbortHelper abortHelper;
66 internal WebConnectionData Data;
68 ChunkStream chunkStream;
73 HttpWebRequest priority_request;
74 NetworkCredential ntlm_credentials;
75 bool ntlm_authenticated;
84 NtlmAuthState connect_ntlm_auth_state;
85 HttpWebRequest connect_request;
89 Exception connect_exception;
90 static object classLock = new object ();
91 static Type sslStream;
92 static PropertyInfo piClient;
93 static PropertyInfo piServer;
94 static PropertyInfo piTrustFailure;
97 static MethodInfo start_wwan;
99 static WebConnection ()
101 Type type = Type.GetType ("MonoTouch.ObjCRuntime.Runtime, monotouch");
103 start_wwan = type.GetMethod ("StartWWAN", new Type [] { typeof (System.Uri) });
107 public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
109 this.sPoint = sPoint;
110 buffer = new byte [4096];
111 readState = ReadState.None;
112 Data = new WebConnectionData ();
113 initConn = new WaitCallback (state => {
115 InitConnection (state);
119 abortHelper = new AbortHelper ();
120 abortHelper.Connection = this;
121 abortHandler = new EventHandler (abortHelper.Abort);
125 public WebConnection Connection;
127 public void Abort (object sender, EventArgs args)
129 WebConnection other = ((HttpWebRequest) sender).WebConnection;
132 other.Abort (sender, args);
138 // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
139 // but if there's data pending to read (!) we won't reuse the socket.
140 return (socket.Poll (0, SelectMode.SelectRead) == false);
143 void Connect (HttpWebRequest request)
146 if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
147 // Take the chunked stream to the expected state (State.None)
148 if (CanReuse () && CompleteChunkedRead ()) {
155 if (socket != null) {
161 IPHostEntry hostEntry = sPoint.HostEntry;
163 if (hostEntry == null) {
165 if (start_wwan != null) {
166 start_wwan.Invoke (null, new object [1] { sPoint.Address });
167 hostEntry = sPoint.HostEntry;
169 if (hostEntry == null) {
171 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
172 WebExceptionStatus.NameResolutionFailure;
179 //WebConnectionData data = Data;
180 foreach (IPAddress address in hostEntry.AddressList) {
182 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
183 } catch (Exception se) {
184 // The Socket ctor can throw if we run out of FD's
185 if (!request.Aborted)
186 status = WebExceptionStatus.ConnectFailure;
187 connect_exception = se;
190 IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
191 socket.NoDelay = !sPoint.UseNagleAlgorithm;
193 sPoint.KeepAliveSetup (socket);
195 // Ignore. Not supported in all platforms.
198 if (!sPoint.CallEndPointDelegate (socket, remote)) {
201 status = WebExceptionStatus.ConnectFailure;
206 socket.Connect (remote);
207 status = WebExceptionStatus.Success;
209 } catch (ThreadAbortException) {
210 // program exiting...
216 } catch (ObjectDisposedException) {
217 // socket closed from another thread
219 } catch (Exception exc) {
224 if (!request.Aborted)
225 status = WebExceptionStatus.ConnectFailure;
226 connect_exception = exc;
233 static void EnsureSSLStreamAvailable ()
236 if (sslStream != null)
239 #if NET_2_1 && SECURITY_DEP
240 sslStream = typeof (Mono.Security.Protocol.Tls.HttpsClientStream);
242 // HttpsClientStream is an internal glue class in Mono.Security.dll
243 sslStream = Type.GetType ("Mono.Security.Protocol.Tls.HttpsClientStream, " +
244 Consts.AssemblyMono_Security, false);
246 if (sslStream == null) {
247 string msg = "Missing Mono.Security.dll assembly. " +
248 "Support for SSL/TLS is unavailable.";
250 throw new NotSupportedException (msg);
253 piClient = sslStream.GetProperty ("SelectedClientCertificate");
254 piServer = sslStream.GetProperty ("ServerCertificate");
255 piTrustFailure = sslStream.GetProperty ("TrustFailure");
259 bool CreateTunnel (HttpWebRequest request, Uri connectUri,
260 Stream stream, out byte[] buffer)
262 StringBuilder sb = new StringBuilder ();
263 sb.Append ("CONNECT ");
264 sb.Append (request.Address.Host);
266 sb.Append (request.Address.Port);
267 sb.Append (" HTTP/");
268 if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
273 sb.Append ("\r\nHost: ");
274 sb.Append (request.Address.Authority);
277 var challenge = Data.Challenge;
278 Data.Challenge = null;
279 var auth_header = request.Headers ["Proxy-Authorization"];
280 bool have_auth = auth_header != null;
282 sb.Append ("\r\nProxy-Authorization: ");
283 sb.Append (auth_header);
284 ntlm = auth_header.ToUpper ().Contains ("NTLM");
285 } else if (challenge != null && Data.StatusCode == 407) {
286 ICredentials creds = request.Proxy.Credentials;
289 if (connect_request == null) {
290 // create a CONNECT request to use with Authenticate
291 connect_request = (HttpWebRequest)WebRequest.Create (
292 connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
293 connect_request.Method = "CONNECT";
294 connect_request.Credentials = creds;
297 for (int i = 0; i < challenge.Length; i++) {
298 var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
301 ntlm = (auth.Module.AuthenticationType == "NTLM");
302 sb.Append ("\r\nProxy-Authorization: ");
303 sb.Append (auth.Message);
309 sb.Append ("\r\nProxy-Connection: keep-alive");
310 connect_ntlm_auth_state++;
313 sb.Append ("\r\n\r\n");
316 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
317 stream.Write (connectBytes, 0, connectBytes.Length);
320 WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
321 if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
322 result != null && status == 407) { // Needs proxy auth
323 var connectionHeader = result ["Connection"];
324 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
325 connectionHeader.ToLower() == "close") {
326 // The server is requesting that this connection be closed
331 Data.StatusCode = status;
332 Data.Challenge = result.GetValues_internal ("Proxy-Authenticate", false);
334 } else if (status != 200) {
335 string msg = String.Format ("The remote server returned a {0} status code.", status);
336 HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
340 return (result != null);
343 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
348 byte [] buffer = new byte [1024];
349 MemoryStream ms = new MemoryStream ();
350 bool gotStatus = false;
351 WebHeaderCollection headers = null;
354 int n = stream.Read (buffer, 0, 1024);
356 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
360 ms.Write (buffer, 0, n);
363 headers = new WebHeaderCollection ();
364 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
368 contentLen = int.Parse(headers["Content-Length"]);
374 if (ms.Length - start - contentLen > 0) {
375 // we've read more data than the response header and conents,
376 // give back extra data to the caller
377 retBuffer = new byte[ms.Length - start - contentLen];
378 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
381 // haven't read in some or all of the contents for the response, do so now
382 FlushContents(stream, contentLen - (int)(ms.Length - start));
393 int spaceidx = str.IndexOf (' ');
394 if (spaceidx == -1) {
395 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
399 status = (int) UInt32.Parse (str.Substring (spaceidx + 1, 3));
405 void FlushContents(Stream stream, int contentLength)
407 while (contentLength > 0) {
408 byte[] contentBuffer = new byte[contentLength];
409 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
411 contentLength -= bytesRead;
419 bool CreateStream (HttpWebRequest request)
422 NetworkStream serverStream = new NetworkStream (socket, false);
424 if (request.Address.Scheme == Uri.UriSchemeHttps) {
426 EnsureSSLStreamAvailable ();
427 if (!reused || nstream == null || nstream.GetType () != sslStream) {
428 byte [] buffer = null;
429 if (sPoint.UseConnect) {
430 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
435 object[] args = new object [4] { serverStream,
436 request.ClientCertificates,
438 nstream = (Stream) Activator.CreateInstance (sslStream, args);
440 SslClientStream scs = (SslClientStream) nstream;
441 var helper = new ServicePointManager.ChainValidationHelper (request);
442 scs.ServerCertValidation2 += new CertificateValidationCallback2 (helper.ValidateChain);
444 certsAvailable = false;
446 // we also need to set ServicePoint.Certificate
447 // and ServicePoint.ClientCertificate but this can
448 // only be done later (after handshake - which is
449 // done only after a read operation).
452 nstream = serverStream;
454 } catch (Exception) {
455 if (!request.Aborted)
456 status = WebExceptionStatus.ConnectFailure;
463 void HandleError (WebExceptionStatus st, Exception e, string where)
467 if (st == WebExceptionStatus.RequestCanceled)
468 Data = new WebConnectionData ();
471 if (e == null) { // At least we now where it comes from
474 throw new Exception ();
476 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
478 } catch (Exception e2) {
483 HttpWebRequest req = null;
484 if (Data != null && Data.request != null)
489 req.FinishedReading = true;
490 req.SetResponseError (st, e, where);
494 static void ReadDone (IAsyncResult result)
496 WebConnection cnc = (WebConnection) result.AsyncState;
497 WebConnectionData data = cnc.Data;
498 Stream ns = cnc.nstream;
506 nread = ns.EndRead (result);
507 } catch (ObjectDisposedException) {
509 } catch (Exception e) {
510 if (e.InnerException is ObjectDisposedException)
513 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
518 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
523 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
528 nread += cnc.position;
529 if (cnc.readState == ReadState.None) {
530 Exception exc = null;
532 pos = cnc.GetResponse (cnc.buffer, nread);
533 } catch (Exception e) {
537 if (exc != null || pos == -1) {
538 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
543 if (cnc.readState != ReadState.Content) {
545 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
546 byte [] newBuffer = new byte [max];
547 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
548 cnc.buffer = newBuffer;
549 cnc.position = nread;
550 cnc.readState = ReadState.None;
557 WebConnectionStream stream = new WebConnectionStream (cnc);
558 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
559 string tencoding = null;
561 tencoding = data.Headers ["Transfer-Encoding"];
563 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
564 if (!cnc.chunkedRead) {
565 stream.ReadBuffer = cnc.buffer;
566 stream.ReadBufferOffset = pos;
567 stream.ReadBufferSize = nread;
569 stream.CheckResponseInBuffer ();
570 } catch (Exception e) {
571 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
573 } else if (cnc.chunkStream == null) {
575 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
576 } catch (Exception e) {
577 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
581 cnc.chunkStream.ResetBuffer ();
583 cnc.chunkStream.Write (cnc.buffer, pos, nread);
584 } catch (Exception e) {
585 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
590 data.stream = stream;
593 stream.ForceCompletion ();
595 data.request.SetResponseData (data);
598 static bool ExpectContent (int statusCode, string method)
600 if (method == "HEAD")
602 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
605 internal void GetCertificates ()
607 // here the SSL negotiation have been done
608 X509Certificate client = (X509Certificate) piClient.GetValue (nstream, null);
609 X509Certificate server = (X509Certificate) piServer.GetValue (nstream, null);
610 sPoint.SetCertificates (client, server);
611 certsAvailable = (server != null);
614 internal static void InitRead (object state)
616 WebConnection cnc = (WebConnection) state;
617 Stream ns = cnc.nstream;
620 int size = cnc.buffer.Length - cnc.position;
621 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
622 } catch (Exception e) {
623 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
627 int GetResponse (byte [] buffer, int max)
632 bool isContinue = false;
633 bool emptyFirstLine = false;
635 if (readState == ReadState.None) {
636 lineok = ReadLine (buffer, ref pos, max, ref line);
641 emptyFirstLine = true;
644 emptyFirstLine = false;
646 readState = ReadState.Status;
648 string [] parts = line.Split (' ');
649 if (parts.Length < 2)
652 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
653 Data.Version = HttpVersion.Version11;
654 sPoint.SetVersion (HttpVersion.Version11);
656 Data.Version = HttpVersion.Version10;
657 sPoint.SetVersion (HttpVersion.Version10);
660 Data.StatusCode = (int) UInt32.Parse (parts [1]);
661 if (parts.Length >= 3)
662 Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
664 Data.StatusDescription = "";
670 emptyFirstLine = false;
671 if (readState == ReadState.Status) {
672 readState = ReadState.Headers;
673 Data.Headers = new WebHeaderCollection ();
674 ArrayList headers = new ArrayList ();
675 bool finished = false;
677 if (ReadLine (buffer, ref pos, max, ref line) == false)
681 // Empty line: end of headers
686 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
687 int count = headers.Count - 1;
691 string prev = (string) headers [count] + line;
692 headers [count] = prev;
701 foreach (string s in headers)
702 Data.Headers.SetInternal (s);
704 if (Data.StatusCode == (int) HttpStatusCode.Continue) {
705 sPoint.SendContinue = true;
709 if (Data.request.ExpectContinue) {
710 Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
711 // Prevent double calls when getting the
712 // headers in several packets.
713 Data.request.ExpectContinue = false;
716 readState = ReadState.None;
720 readState = ReadState.Content;
724 } while (emptyFirstLine || isContinue);
729 void InitConnection (object state)
731 HttpWebRequest request = (HttpWebRequest) state;
732 request.WebConnection = this;
737 keepAlive = request.KeepAlive;
738 Data = new WebConnectionData (request);
744 if (status != WebExceptionStatus.Success) {
745 if (!request.Aborted) {
746 request.SetWriteStreamError (status, connect_exception);
752 if (!CreateStream (request)) {
756 WebExceptionStatus st = status;
757 if (Data.Challenge != null)
760 Exception cnc_exc = connect_exception;
761 connect_exception = null;
762 request.SetWriteStreamError (st, cnc_exc);
767 readState = ReadState.None;
768 request.SetWriteStream (new WebConnectionStream (this, request));
771 internal EventHandler SendRequest (HttpWebRequest request)
779 status = WebExceptionStatus.Success;
780 ThreadPool.QueueUserWorkItem (initConn, request);
783 queue.Enqueue (request);
794 if (queue.Count > 0) {
795 SendRequest ((HttpWebRequest) queue.Dequeue ());
800 internal void NextRead ()
803 if (Data.request != null)
804 Data.request.FinishedReading = true;
805 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
806 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
807 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
808 if (cncHeader != null) {
809 cncHeader = cncHeader.ToLower ();
810 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
813 if ((socket != null && !socket.Connected) ||
814 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
819 if (priority_request != null) {
820 SendRequest (priority_request);
821 priority_request = null;
828 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
830 bool foundCR = false;
831 StringBuilder text = new StringBuilder ();
834 while (start < max) {
835 c = (int) buffer [start++];
837 if (c == '\n') { // newline
838 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
843 } else if (foundCR) {
852 text.Append ((char) c);
855 if (c != '\n' && c != '\r')
858 if (text.Length == 0) {
860 return (c == '\n' || c == '\r');
866 output = text.ToString ();
871 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
875 if (Data.request != request)
876 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
882 IAsyncResult result = null;
883 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
885 result = s.BeginRead (buffer, offset, size, cb, state);
887 } catch (Exception) {
888 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
894 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
895 wr.InnerAsyncResult = result;
896 if (result == null) {
897 // Will be completed from the data in ChunkStream
898 wr.SetCompleted (true, (Exception) null);
907 internal int EndRead (HttpWebRequest request, IAsyncResult result)
911 if (Data.request != request)
912 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
914 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
919 WebAsyncResult wr = null;
920 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
921 if (chunkedRead && (nsAsync is WebAsyncResult)) {
922 wr = (WebAsyncResult) nsAsync;
923 IAsyncResult inner = wr.InnerAsyncResult;
924 if (inner != null && !(inner is WebAsyncResult))
925 nbytes = s.EndRead (inner);
926 } else if (!(nsAsync is WebAsyncResult)) {
927 nbytes = s.EndRead (nsAsync);
928 wr = (WebAsyncResult) result;
932 bool done = (nbytes == 0);
934 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
935 if (!done && nbytes == 0 && chunkStream.WantMore)
936 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
937 } catch (Exception e) {
938 if (e is WebException)
941 throw new WebException ("Invalid chunked data.", e,
942 WebExceptionStatus.ServerProtocolViolation, null);
945 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
946 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
947 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
951 return (nbytes != 0) ? nbytes : -1;
954 // To be called on chunkedRead when we can read no data from the ChunkStream yet
955 int EnsureRead (byte [] buffer, int offset, int size)
957 byte [] morebytes = null;
959 while (nbytes == 0 && chunkStream.WantMore) {
960 int localsize = chunkStream.ChunkLeft;
961 if (localsize <= 0) // not read chunk size yet
963 else if (localsize > 16384)
966 if (morebytes == null || morebytes.Length < localsize)
967 morebytes = new byte [localsize];
969 int nread = nstream.Read (morebytes, 0, localsize);
973 chunkStream.Write (morebytes, 0, nread);
974 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
980 bool CompleteChunkedRead()
982 if (!chunkedRead || chunkStream == null)
985 while (chunkStream.WantMore) {
986 int nbytes = nstream.Read (buffer, 0, buffer.Length);
988 return false; // Socket was disconnected
990 chunkStream.Write (buffer, 0, nbytes);
996 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
1000 if (Data.request != request)
1001 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1002 if (nstream == null)
1007 IAsyncResult result = null;
1009 result = s.BeginWrite (buffer, offset, size, cb, state);
1010 } catch (Exception) {
1011 status = WebExceptionStatus.SendFailure;
1018 internal void EndWrite2 (HttpWebRequest request, IAsyncResult result)
1020 if (request.FinishedReading)
1025 if (Data.request != request)
1026 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1027 if (nstream == null)
1028 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1033 s.EndWrite (result);
1034 } catch (Exception exc) {
1035 status = WebExceptionStatus.SendFailure;
1036 if (exc.InnerException != null)
1037 throw exc.InnerException;
1042 internal bool EndWrite (HttpWebRequest request, IAsyncResult result)
1044 if (request.FinishedReading)
1049 if (Data.request != request)
1050 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1051 if (nstream == null)
1052 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1057 s.EndWrite (result);
1060 status = WebExceptionStatus.SendFailure;
1065 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1069 if (Data.request != request)
1070 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1071 if (nstream == null)
1080 result = s.Read (buffer, offset, size);
1081 done = (result == 0);
1086 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1087 if (!done && result == 0 && chunkStream.WantMore)
1088 result = EnsureRead (buffer, offset, size);
1089 } catch (Exception e) {
1090 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1094 if ((done || result == 0) && chunkStream.WantMore) {
1095 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1096 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1099 } catch (Exception e) {
1100 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1106 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1111 if (Data.request != request)
1112 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1113 if (nstream == null)
1119 s.Write (buffer, offset, size);
1120 // here SSL handshake should have been done
1121 if (ssl && !certsAvailable)
1123 } catch (Exception e) {
1124 err_msg = e.Message;
1125 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1126 string msg = "Write: " + err_msg;
1127 if (e is WebException) {
1128 HandleError (wes, e, msg);
1132 // if SSL is in use then check for TrustFailure
1133 if (ssl && (bool) piTrustFailure.GetValue (nstream, null)) {
1134 wes = WebExceptionStatus.TrustFailure;
1135 msg = "Trust failure";
1138 HandleError (wes, e, msg);
1144 internal void Close (bool sendNext)
1147 if (nstream != null) {
1154 if (socket != null) {
1161 if (ntlm_authenticated)
1164 Data = new WebConnectionData ();
1168 connect_request = null;
1169 connect_ntlm_auth_state = NtlmAuthState.None;
1173 void Abort (object sender, EventArgs args)
1177 HttpWebRequest req = (HttpWebRequest) sender;
1178 if (Data.request == req || Data.request == null) {
1179 if (!req.FinishedReading) {
1180 status = WebExceptionStatus.RequestCanceled;
1182 if (queue.Count > 0) {
1183 Data.request = (HttpWebRequest) queue.Dequeue ();
1184 SendRequest (Data.request);
1190 req.FinishedReading = true;
1191 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1192 if (queue.Count > 0 && queue.Peek () == sender) {
1194 } else if (queue.Count > 0) {
1195 object [] old = queue.ToArray ();
1197 for (int i = old.Length - 1; i >= 0; i--) {
1198 if (old [i] != sender)
1199 queue.Enqueue (old [i]);
1206 internal void ResetNtlm ()
1208 ntlm_authenticated = false;
1209 ntlm_credentials = null;
1210 unsafe_sharing = false;
1213 internal bool Busy {
1214 get { lock (this) return busy; }
1217 internal bool Connected {
1220 return (socket != null && socket.Connected);
1225 // -Used for NTLM authentication
1226 internal HttpWebRequest PriorityRequest {
1227 set { priority_request = value; }
1230 internal bool NtlmAuthenticated {
1231 get { return ntlm_authenticated; }
1232 set { ntlm_authenticated = value; }
1235 internal NetworkCredential NtlmCredential {
1236 get { return ntlm_credentials; }
1237 set { ntlm_credentials = value; }
1240 internal bool UnsafeAuthenticatedConnectionSharing {
1241 get { return unsafe_sharing; }
1242 set { unsafe_sharing = value; }