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;
80 Exception connect_exception;
81 static object classLock = new object ();
82 static Type sslStream;
83 static PropertyInfo piClient;
84 static PropertyInfo piServer;
85 static PropertyInfo piTrustFailure;
88 static MethodInfo start_wwan;
90 static WebConnection ()
92 Type type = Type.GetType ("MonoTouch.ObjCRuntime.Runtime, monotouch");
94 start_wwan = type.GetMethod ("StartWWAN", new Type [] { typeof (System.Uri) });
98 public WebConnection (WebConnectionGroup group, ServicePoint sPoint)
100 this.sPoint = sPoint;
101 buffer = new byte [4096];
102 readState = ReadState.None;
103 Data = new WebConnectionData ();
104 initConn = new WaitCallback (state => {
106 InitConnection (state);
110 abortHelper = new AbortHelper ();
111 abortHelper.Connection = this;
112 abortHandler = new EventHandler (abortHelper.Abort);
116 public WebConnection Connection;
118 public void Abort (object sender, EventArgs args)
120 WebConnection other = ((HttpWebRequest) sender).WebConnection;
123 other.Abort (sender, args);
129 // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
130 // but if there's data pending to read (!) we won't reuse the socket.
131 return (socket.Poll (0, SelectMode.SelectRead) == false);
134 void Connect (HttpWebRequest request)
137 if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
138 // Take the chunked stream to the expected state (State.None)
139 if (CanReuse () && CompleteChunkedRead ()) {
146 if (socket != null) {
152 IPHostEntry hostEntry = sPoint.HostEntry;
154 if (hostEntry == null) {
156 if (start_wwan != null) {
157 start_wwan.Invoke (null, new object [1] { sPoint.Address });
158 hostEntry = sPoint.HostEntry;
160 if (hostEntry == null) {
162 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
163 WebExceptionStatus.NameResolutionFailure;
170 //WebConnectionData data = Data;
171 foreach (IPAddress address in hostEntry.AddressList) {
173 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
174 } catch (Exception se) {
175 // The Socket ctor can throw if we run out of FD's
176 if (!request.Aborted)
177 status = WebExceptionStatus.ConnectFailure;
178 connect_exception = se;
181 IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
182 socket.NoDelay = !sPoint.UseNagleAlgorithm;
184 sPoint.KeepAliveSetup (socket);
186 // Ignore. Not supported in all platforms.
189 if (!sPoint.CallEndPointDelegate (socket, remote)) {
192 status = WebExceptionStatus.ConnectFailure;
197 socket.Connect (remote);
198 status = WebExceptionStatus.Success;
200 } catch (ThreadAbortException) {
201 // program exiting...
207 } catch (ObjectDisposedException) {
208 // socket closed from another thread
210 } catch (Exception exc) {
215 if (!request.Aborted)
216 status = WebExceptionStatus.ConnectFailure;
217 connect_exception = exc;
224 static void EnsureSSLStreamAvailable ()
227 if (sslStream != null)
230 #if NET_2_1 && SECURITY_DEP
231 sslStream = typeof (Mono.Security.Protocol.Tls.HttpsClientStream);
233 // HttpsClientStream is an internal glue class in Mono.Security.dll
234 sslStream = Type.GetType ("Mono.Security.Protocol.Tls.HttpsClientStream, " +
235 Consts.AssemblyMono_Security, false);
237 if (sslStream == null) {
238 string msg = "Missing Mono.Security.dll assembly. " +
239 "Support for SSL/TLS is unavailable.";
241 throw new NotSupportedException (msg);
244 piClient = sslStream.GetProperty ("SelectedClientCertificate");
245 piServer = sslStream.GetProperty ("ServerCertificate");
246 piTrustFailure = sslStream.GetProperty ("TrustFailure");
250 bool CreateTunnel (HttpWebRequest request, Stream stream, out byte [] buffer)
252 StringBuilder sb = new StringBuilder ();
253 sb.Append ("CONNECT ");
254 sb.Append (request.Address.Host);
256 sb.Append (request.Address.Port);
257 sb.Append (" HTTP/");
258 if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
263 sb.Append ("\r\nHost: ");
264 sb.Append (request.Address.Authority);
265 string challenge = Data.Challenge;
266 Data.Challenge = null;
267 bool have_auth = (request.Headers ["Proxy-Authorization"] != null);
269 sb.Append ("\r\nProxy-Authorization: ");
270 sb.Append (request.Headers ["Proxy-Authorization"]);
271 } else if (challenge != null && Data.StatusCode == 407) {
273 ICredentials creds = request.Proxy.Credentials;
274 Authorization auth = AuthenticationManager.Authenticate (challenge, request, creds);
276 sb.Append ("\r\nProxy-Authorization: ");
277 sb.Append (auth.Message);
280 sb.Append ("\r\n\r\n");
283 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
284 stream.Write (connectBytes, 0, connectBytes.Length);
287 WebHeaderCollection result = ReadHeaders (request, stream, out buffer, out status);
288 if (!have_auth && result != null && status == 407) { // Needs proxy auth
289 Data.StatusCode = status;
290 Data.Challenge = result ["Proxy-Authenticate"];
292 } else if (status != 200) {
293 string msg = String.Format ("The remote server returned a {0} status code.", status);
294 HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
298 return (result != null);
301 WebHeaderCollection ReadHeaders (HttpWebRequest request, Stream stream, out byte [] retBuffer, out int status)
306 byte [] buffer = new byte [1024];
307 MemoryStream ms = new MemoryStream ();
308 bool gotStatus = false;
309 WebHeaderCollection headers = null;
312 int n = stream.Read (buffer, 0, 1024);
314 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
318 ms.Write (buffer, 0, n);
321 headers = new WebHeaderCollection ();
322 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
324 if (ms.Length - start > 0) {
325 retBuffer = new byte [ms.Length - start];
326 Buffer.BlockCopy (ms.GetBuffer (), start, retBuffer, 0, retBuffer.Length);
336 int spaceidx = str.IndexOf (' ');
337 if (spaceidx == -1) {
338 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
342 status = (int) UInt32.Parse (str.Substring (spaceidx + 1, 3));
348 bool CreateStream (HttpWebRequest request)
351 NetworkStream serverStream = new NetworkStream (socket, false);
353 if (request.Address.Scheme == Uri.UriSchemeHttps) {
355 EnsureSSLStreamAvailable ();
356 if (!reused || nstream == null || nstream.GetType () != sslStream) {
357 byte [] buffer = null;
358 if (sPoint.UseConnect) {
359 bool ok = CreateTunnel (request, serverStream, out buffer);
364 object[] args = new object [4] { serverStream,
365 request.ClientCertificates,
367 nstream = (Stream) Activator.CreateInstance (sslStream, args);
369 SslClientStream scs = (SslClientStream) nstream;
370 var helper = new ServicePointManager.ChainValidationHelper (request);
371 scs.ServerCertValidation2 += new CertificateValidationCallback2 (helper.ValidateChain);
373 certsAvailable = false;
375 // we also need to set ServicePoint.Certificate
376 // and ServicePoint.ClientCertificate but this can
377 // only be done later (after handshake - which is
378 // done only after a read operation).
381 nstream = serverStream;
383 } catch (Exception) {
384 if (!request.Aborted)
385 status = WebExceptionStatus.ConnectFailure;
392 void HandleError (WebExceptionStatus st, Exception e, string where)
396 if (st == WebExceptionStatus.RequestCanceled)
397 Data = new WebConnectionData ();
400 if (e == null) { // At least we now where it comes from
403 throw new Exception ();
405 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
407 } catch (Exception e2) {
412 HttpWebRequest req = null;
413 if (Data != null && Data.request != null)
418 req.FinishedReading = true;
419 req.SetResponseError (st, e, where);
423 static void ReadDone (IAsyncResult result)
425 WebConnection cnc = (WebConnection) result.AsyncState;
426 WebConnectionData data = cnc.Data;
427 Stream ns = cnc.nstream;
435 nread = ns.EndRead (result);
436 } catch (ObjectDisposedException) {
438 } catch (Exception e) {
439 if (e.InnerException is ObjectDisposedException)
442 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
447 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
452 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
457 nread += cnc.position;
458 if (cnc.readState == ReadState.None) {
459 Exception exc = null;
461 pos = cnc.GetResponse (cnc.buffer, nread);
462 } catch (Exception e) {
466 if (exc != null || pos == -1) {
467 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
472 if (cnc.readState != ReadState.Content) {
474 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
475 byte [] newBuffer = new byte [max];
476 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
477 cnc.buffer = newBuffer;
478 cnc.position = nread;
479 cnc.readState = ReadState.None;
486 WebConnectionStream stream = new WebConnectionStream (cnc);
487 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
488 string tencoding = null;
490 tencoding = data.Headers ["Transfer-Encoding"];
492 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
493 if (!cnc.chunkedRead) {
494 stream.ReadBuffer = cnc.buffer;
495 stream.ReadBufferOffset = pos;
496 stream.ReadBufferSize = nread;
498 stream.CheckResponseInBuffer ();
499 } catch (Exception e) {
500 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
502 } else if (cnc.chunkStream == null) {
504 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
505 } catch (Exception e) {
506 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
510 cnc.chunkStream.ResetBuffer ();
512 cnc.chunkStream.Write (cnc.buffer, pos, nread);
513 } catch (Exception e) {
514 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
519 data.stream = stream;
522 stream.ForceCompletion ();
524 data.request.SetResponseData (data);
527 static bool ExpectContent (int statusCode, string method)
529 if (method == "HEAD")
531 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
534 internal void GetCertificates ()
536 // here the SSL negotiation have been done
537 X509Certificate client = (X509Certificate) piClient.GetValue (nstream, null);
538 X509Certificate server = (X509Certificate) piServer.GetValue (nstream, null);
539 sPoint.SetCertificates (client, server);
540 certsAvailable = (server != null);
543 internal static void InitRead (object state)
545 WebConnection cnc = (WebConnection) state;
546 Stream ns = cnc.nstream;
549 int size = cnc.buffer.Length - cnc.position;
550 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
551 } catch (Exception e) {
552 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
556 int GetResponse (byte [] buffer, int max)
561 bool isContinue = false;
562 bool emptyFirstLine = false;
564 if (readState == ReadState.None) {
565 lineok = ReadLine (buffer, ref pos, max, ref line);
570 emptyFirstLine = true;
573 emptyFirstLine = false;
575 readState = ReadState.Status;
577 string [] parts = line.Split (' ');
578 if (parts.Length < 2)
581 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
582 Data.Version = HttpVersion.Version11;
583 sPoint.SetVersion (HttpVersion.Version11);
585 Data.Version = HttpVersion.Version10;
586 sPoint.SetVersion (HttpVersion.Version10);
589 Data.StatusCode = (int) UInt32.Parse (parts [1]);
590 if (parts.Length >= 3)
591 Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
593 Data.StatusDescription = "";
599 emptyFirstLine = false;
600 if (readState == ReadState.Status) {
601 readState = ReadState.Headers;
602 Data.Headers = new WebHeaderCollection ();
603 ArrayList headers = new ArrayList ();
604 bool finished = false;
606 if (ReadLine (buffer, ref pos, max, ref line) == false)
610 // Empty line: end of headers
615 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
616 int count = headers.Count - 1;
620 string prev = (string) headers [count] + line;
621 headers [count] = prev;
630 foreach (string s in headers)
631 Data.Headers.SetInternal (s);
633 if (Data.StatusCode == (int) HttpStatusCode.Continue) {
634 sPoint.SendContinue = true;
638 if (Data.request.ExpectContinue) {
639 Data.request.DoContinueDelegate (Data.StatusCode, Data.Headers);
640 // Prevent double calls when getting the
641 // headers in several packets.
642 Data.request.ExpectContinue = false;
645 readState = ReadState.None;
649 readState = ReadState.Content;
653 } while (emptyFirstLine || isContinue);
658 void InitConnection (object state)
660 HttpWebRequest request = (HttpWebRequest) state;
661 request.WebConnection = this;
666 keepAlive = request.KeepAlive;
667 Data = new WebConnectionData (request);
673 if (status != WebExceptionStatus.Success) {
674 if (!request.Aborted) {
675 request.SetWriteStreamError (status, connect_exception);
681 if (!CreateStream (request)) {
685 WebExceptionStatus st = status;
686 if (Data.Challenge != null)
689 Exception cnc_exc = connect_exception;
690 connect_exception = null;
691 request.SetWriteStreamError (st, cnc_exc);
696 readState = ReadState.None;
697 request.SetWriteStream (new WebConnectionStream (this, request));
700 internal EventHandler SendRequest (HttpWebRequest request)
708 status = WebExceptionStatus.Success;
709 ThreadPool.QueueUserWorkItem (initConn, request);
712 queue.Enqueue (request);
723 if (queue.Count > 0) {
724 Data.request = (HttpWebRequest) queue.Dequeue ();
725 SendRequest (Data.request);
730 internal void NextRead ()
733 if (Data.request != null)
734 Data.request.FinishedReading = true;
735 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
736 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
737 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
738 if (cncHeader != null) {
739 cncHeader = cncHeader.ToLower ();
740 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
743 if ((socket != null && !socket.Connected) ||
744 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
749 if (priority_request != null) {
750 SendRequest (priority_request);
751 priority_request = null;
758 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
760 bool foundCR = false;
761 StringBuilder text = new StringBuilder ();
764 while (start < max) {
765 c = (int) buffer [start++];
767 if (c == '\n') { // newline
768 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
773 } else if (foundCR) {
782 text.Append ((char) c);
785 if (c != '\n' && c != '\r')
788 if (text.Length == 0) {
790 return (c == '\n' || c == '\r');
796 output = text.ToString ();
801 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
805 if (Data.request != request)
806 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
812 IAsyncResult result = null;
813 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
815 result = s.BeginRead (buffer, offset, size, cb, state);
817 } catch (Exception) {
818 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
824 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
825 wr.InnerAsyncResult = result;
826 if (result == null) {
827 // Will be completed from the data in ChunkStream
828 wr.SetCompleted (true, (Exception) null);
837 internal int EndRead (HttpWebRequest request, IAsyncResult result)
841 if (Data.request != request)
842 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
844 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
849 WebAsyncResult wr = null;
850 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
851 if (chunkedRead && (nsAsync is WebAsyncResult)) {
852 wr = (WebAsyncResult) nsAsync;
853 IAsyncResult inner = wr.InnerAsyncResult;
854 if (inner != null && !(inner is WebAsyncResult))
855 nbytes = s.EndRead (inner);
856 } else if (!(nsAsync is WebAsyncResult)) {
857 nbytes = s.EndRead (nsAsync);
858 wr = (WebAsyncResult) result;
862 bool done = (nbytes == 0);
864 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
865 if (!done && nbytes == 0 && chunkStream.WantMore)
866 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
867 } catch (Exception e) {
868 if (e is WebException)
871 throw new WebException ("Invalid chunked data.", e,
872 WebExceptionStatus.ServerProtocolViolation, null);
875 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
876 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
877 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
881 return (nbytes != 0) ? nbytes : -1;
884 // To be called on chunkedRead when we can read no data from the ChunkStream yet
885 int EnsureRead (byte [] buffer, int offset, int size)
887 byte [] morebytes = null;
889 while (nbytes == 0 && chunkStream.WantMore) {
890 int localsize = chunkStream.ChunkLeft;
891 if (localsize <= 0) // not read chunk size yet
893 else if (localsize > 16384)
896 if (morebytes == null || morebytes.Length < localsize)
897 morebytes = new byte [localsize];
899 int nread = nstream.Read (morebytes, 0, localsize);
903 chunkStream.Write (morebytes, 0, nread);
904 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
910 bool CompleteChunkedRead()
912 if (!chunkedRead || chunkStream == null)
915 while (chunkStream.WantMore) {
916 int nbytes = nstream.Read (buffer, 0, buffer.Length);
918 return false; // Socket was disconnected
920 chunkStream.Write (buffer, 0, nbytes);
926 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
930 if (Data.request != request)
931 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
937 IAsyncResult result = null;
939 result = s.BeginWrite (buffer, offset, size, cb, state);
940 } catch (Exception) {
941 status = WebExceptionStatus.SendFailure;
948 internal void EndWrite2 (HttpWebRequest request, IAsyncResult result)
950 if (request.FinishedReading)
955 if (Data.request != request)
956 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
958 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
964 } catch (Exception exc) {
965 status = WebExceptionStatus.SendFailure;
966 if (exc.InnerException != null)
967 throw exc.InnerException;
972 internal bool EndWrite (HttpWebRequest request, IAsyncResult result)
974 if (request.FinishedReading)
979 if (Data.request != request)
980 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
982 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
990 status = WebExceptionStatus.SendFailure;
995 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
999 if (Data.request != request)
1000 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1001 if (nstream == null)
1010 result = s.Read (buffer, offset, size);
1011 done = (result == 0);
1016 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1017 if (!done && result == 0 && chunkStream.WantMore)
1018 result = EnsureRead (buffer, offset, size);
1019 } catch (Exception e) {
1020 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1024 if ((done || result == 0) && chunkStream.WantMore) {
1025 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1026 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1029 } catch (Exception e) {
1030 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1036 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1041 if (Data.request != request)
1042 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1043 if (nstream == null)
1049 s.Write (buffer, offset, size);
1050 // here SSL handshake should have been done
1051 if (ssl && !certsAvailable)
1053 } catch (Exception e) {
1054 err_msg = e.Message;
1055 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1056 string msg = "Write: " + err_msg;
1057 if (e is WebException) {
1058 HandleError (wes, e, msg);
1062 // if SSL is in use then check for TrustFailure
1063 if (ssl && (bool) piTrustFailure.GetValue (nstream, null)) {
1064 wes = WebExceptionStatus.TrustFailure;
1065 msg = "Trust failure";
1068 HandleError (wes, e, msg);
1074 internal void Close (bool sendNext)
1077 if (nstream != null) {
1084 if (socket != null) {
1091 if (ntlm_authenticated)
1094 Data = new WebConnectionData ();
1100 void Abort (object sender, EventArgs args)
1104 HttpWebRequest req = (HttpWebRequest) sender;
1105 if (Data.request == req || Data.request == null) {
1106 if (!req.FinishedReading) {
1107 status = WebExceptionStatus.RequestCanceled;
1109 if (queue.Count > 0) {
1110 Data.request = (HttpWebRequest) queue.Dequeue ();
1111 SendRequest (Data.request);
1117 req.FinishedReading = true;
1118 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1119 if (queue.Count > 0 && queue.Peek () == sender) {
1121 } else if (queue.Count > 0) {
1122 object [] old = queue.ToArray ();
1124 for (int i = old.Length - 1; i >= 0; i--) {
1125 if (old [i] != sender)
1126 queue.Enqueue (old [i]);
1133 internal void ResetNtlm ()
1135 ntlm_authenticated = false;
1136 ntlm_credentials = null;
1137 unsafe_sharing = false;
1140 internal bool Busy {
1141 get { lock (this) return busy; }
1144 internal bool Connected {
1147 return (socket != null && socket.Connected);
1152 // -Used for NTLM authentication
1153 internal HttpWebRequest PriorityRequest {
1154 set { priority_request = value; }
1157 internal bool NtlmAuthenticated {
1158 get { return ntlm_authenticated; }
1159 set { ntlm_authenticated = value; }
1162 internal NetworkCredential NtlmCredential {
1163 get { return ntlm_credentials; }
1164 set { ntlm_credentials = value; }
1167 internal bool UnsafeAuthenticatedConnectionSharing {
1168 get { return unsafe_sharing; }
1169 set { unsafe_sharing = value; }