2 // System.Net.WebConnection
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
33 #if MONOTOUCH || MONODROID
34 using Mono.Security.Protocol.Tls;
36 extern alias MonoSecurity;
37 using MonoSecurity::Mono.Security.Protocol.Tls;
43 using System.Collections;
44 using System.Net.Sockets;
45 using System.Reflection;
46 using System.Security.Cryptography.X509Certificates;
48 using System.Threading;
49 using System.Diagnostics;
51 using Mono.Net.Security;
68 internal Socket socket;
69 object socketLock = new object ();
70 IWebConnectionState state;
71 WebExceptionStatus status;
72 WaitCallback initConn;
75 static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
76 EventHandler abortHandler;
77 AbortHelper abortHelper;
78 internal WebConnectionData Data;
80 ChunkStream chunkStream;
84 HttpWebRequest priority_request;
85 NetworkCredential ntlm_credentials;
86 bool ntlm_authenticated;
95 NtlmAuthState connect_ntlm_auth_state;
96 HttpWebRequest connect_request;
100 Exception connect_exception;
101 static object classLock = new object ();
102 static Type sslStream;
103 #if !MONOTOUCH && !MONODROID
104 static PropertyInfo piClient;
105 static PropertyInfo piServer;
106 static PropertyInfo piTrustFailure;
110 [System.Runtime.InteropServices.DllImport ("__Internal")]
111 static extern void xamarin_start_wwan (string uri);
114 internal ChunkStream ChunkStream {
115 get { return chunkStream; }
118 public WebConnection (IWebConnectionState wcs, ServicePoint sPoint)
121 this.sPoint = sPoint;
122 buffer = new byte [4096];
123 Data = new WebConnectionData ();
124 initConn = new WaitCallback (state => {
126 InitConnection (state);
129 queue = wcs.Group.Queue;
130 abortHelper = new AbortHelper ();
131 abortHelper.Connection = this;
132 abortHandler = new EventHandler (abortHelper.Abort);
136 public WebConnection Connection;
138 public void Abort (object sender, EventArgs args)
140 WebConnection other = ((HttpWebRequest) sender).WebConnection;
143 other.Abort (sender, args);
149 // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
150 // but if there's data pending to read (!) we won't reuse the socket.
151 return (socket.Poll (0, SelectMode.SelectRead) == false);
154 void Connect (HttpWebRequest request)
157 if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
158 // Take the chunked stream to the expected state (State.None)
159 if (CanReuse () && CompleteChunkedRead ()) {
166 if (socket != null) {
172 IPHostEntry hostEntry = sPoint.HostEntry;
174 if (hostEntry == null) {
176 xamarin_start_wwan (sPoint.Address.ToString ());
177 hostEntry = sPoint.HostEntry;
178 if (hostEntry == null) {
180 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
181 WebExceptionStatus.NameResolutionFailure;
188 //WebConnectionData data = Data;
189 foreach (IPAddress address in hostEntry.AddressList) {
191 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
192 } catch (Exception se) {
193 // The Socket ctor can throw if we run out of FD's
194 if (!request.Aborted)
195 status = WebExceptionStatus.ConnectFailure;
196 connect_exception = se;
199 IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
200 socket.NoDelay = !sPoint.UseNagleAlgorithm;
202 sPoint.KeepAliveSetup (socket);
204 // Ignore. Not supported in all platforms.
207 if (!sPoint.CallEndPointDelegate (socket, remote)) {
210 status = WebExceptionStatus.ConnectFailure;
215 socket.Connect (remote);
216 status = WebExceptionStatus.Success;
218 } catch (ThreadAbortException) {
219 // program exiting...
225 } catch (ObjectDisposedException) {
226 // socket closed from another thread
228 } catch (Exception exc) {
233 if (!request.Aborted)
234 status = WebExceptionStatus.ConnectFailure;
235 connect_exception = exc;
242 static void EnsureSSLStreamAvailable ()
245 if (sslStream != null)
248 #if NET_2_1 && SECURITY_DEP
249 sslStream = typeof (HttpsClientStream);
251 // HttpsClientStream is an internal glue class in Mono.Security.dll
252 sslStream = Type.GetType ("Mono.Security.Protocol.Tls.HttpsClientStream, " +
253 Consts.AssemblyMono_Security, false);
255 if (sslStream == null) {
256 string msg = "Missing Mono.Security.dll assembly. " +
257 "Support for SSL/TLS is unavailable.";
259 throw new NotSupportedException (msg);
262 #if !MONOTOUCH && !MONODROID
263 piClient = sslStream.GetProperty ("SelectedClientCertificate");
264 piServer = sslStream.GetProperty ("ServerCertificate");
265 piTrustFailure = sslStream.GetProperty ("TrustFailure");
270 bool CreateTunnel (HttpWebRequest request, Uri connectUri,
271 Stream stream, out byte[] buffer)
273 StringBuilder sb = new StringBuilder ();
274 sb.Append ("CONNECT ");
275 sb.Append (request.Address.Host);
277 sb.Append (request.Address.Port);
278 sb.Append (" HTTP/");
279 if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
284 sb.Append ("\r\nHost: ");
285 sb.Append (request.Address.Authority);
288 var challenge = Data.Challenge;
289 Data.Challenge = null;
290 var auth_header = request.Headers ["Proxy-Authorization"];
291 bool have_auth = auth_header != null;
293 sb.Append ("\r\nProxy-Authorization: ");
294 sb.Append (auth_header);
295 ntlm = auth_header.ToUpper ().Contains ("NTLM");
296 } else if (challenge != null && Data.StatusCode == 407) {
297 ICredentials creds = request.Proxy.Credentials;
300 if (connect_request == null) {
301 // create a CONNECT request to use with Authenticate
302 connect_request = (HttpWebRequest)WebRequest.Create (
303 connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
304 connect_request.Method = "CONNECT";
305 connect_request.Credentials = creds;
308 for (int i = 0; i < challenge.Length; i++) {
309 var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
312 ntlm = (auth.Module.AuthenticationType == "NTLM");
313 sb.Append ("\r\nProxy-Authorization: ");
314 sb.Append (auth.Message);
320 sb.Append ("\r\nProxy-Connection: keep-alive");
321 connect_ntlm_auth_state++;
324 sb.Append ("\r\n\r\n");
327 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
328 stream.Write (connectBytes, 0, connectBytes.Length);
331 WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
332 if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
333 result != null && status == 407) { // Needs proxy auth
334 var connectionHeader = result ["Connection"];
335 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
336 connectionHeader.ToLower() == "close") {
337 // The server is requesting that this connection be closed
342 Data.StatusCode = status;
343 Data.Challenge = result.GetValues_internal ("Proxy-Authenticate", false);
345 } else if (status != 200) {
346 string msg = String.Format ("The remote server returned a {0} status code.", status);
347 HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
351 return (result != null);
354 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
359 byte [] buffer = new byte [1024];
360 MemoryStream ms = new MemoryStream ();
363 int n = stream.Read (buffer, 0, 1024);
365 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
369 ms.Write (buffer, 0, n);
372 bool gotStatus = false;
373 WebHeaderCollection headers = new WebHeaderCollection ();
374 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
378 contentLen = int.Parse(headers["Content-Length"]);
384 if (ms.Length - start - contentLen > 0) {
385 // we've read more data than the response header and conents,
386 // give back extra data to the caller
387 retBuffer = new byte[ms.Length - start - contentLen];
388 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
391 // haven't read in some or all of the contents for the response, do so now
392 FlushContents(stream, contentLen - (int)(ms.Length - start));
403 string[] parts = str.Split (' ');
404 if (parts.Length < 2) {
405 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
409 if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
410 Data.ProxyVersion = HttpVersion.Version11;
411 else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
412 Data.ProxyVersion = HttpVersion.Version10;
414 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
418 status = (int)UInt32.Parse (parts [1]);
424 void FlushContents(Stream stream, int contentLength)
426 while (contentLength > 0) {
427 byte[] contentBuffer = new byte[contentLength];
428 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
430 contentLength -= bytesRead;
438 bool CreateStream (HttpWebRequest request)
441 NetworkStream serverStream = new NetworkStream (socket, false);
443 if (request.Address.Scheme == Uri.UriSchemeHttps) {
445 EnsureSSLStreamAvailable ();
446 if (!reused || nstream == null || nstream.GetType () != sslStream) {
447 byte [] buffer = null;
448 if (sPoint.UseConnect) {
449 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
454 #if MONOTOUCH || MONODROID
455 nstream = new HttpsClientStream (serverStream, request.ClientCertificates, request, buffer);
457 object[] args = new object [4] { serverStream,
458 request.ClientCertificates,
460 nstream = (Stream) Activator.CreateInstance (sslStream, args);
462 SslClientStream scs = (SslClientStream) nstream;
463 var helper = new ChainValidationHelper (request);
464 scs.ServerCertValidation2 += (certs) => helper.ValidateChain (request.Address.Host, certs);
466 certsAvailable = false;
468 // we also need to set ServicePoint.Certificate
469 // and ServicePoint.ClientCertificate but this can
470 // only be done later (after handshake - which is
471 // done only after a read operation).
474 nstream = serverStream;
476 } catch (Exception) {
477 if (!request.Aborted)
478 status = WebExceptionStatus.ConnectFailure;
485 void HandleError (WebExceptionStatus st, Exception e, string where)
489 if (st == WebExceptionStatus.RequestCanceled)
490 Data = new WebConnectionData ();
493 if (e == null) { // At least we now where it comes from
495 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
496 } catch (Exception e2) {
501 HttpWebRequest req = null;
502 if (Data != null && Data.request != null)
507 req.FinishedReading = true;
508 req.SetResponseError (st, e, where);
512 static void ReadDone (IAsyncResult result)
514 WebConnection cnc = (WebConnection)result.AsyncState;
515 WebConnectionData data = cnc.Data;
516 Stream ns = cnc.nstream;
524 nread = ns.EndRead (result);
525 } catch (ObjectDisposedException) {
527 } catch (Exception e) {
528 if (e.InnerException is ObjectDisposedException)
531 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
536 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
541 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
546 nread += cnc.position;
547 if (data.ReadState == ReadState.None) {
548 Exception exc = null;
550 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
551 } catch (Exception e) {
555 if (exc != null || pos == -1) {
556 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
561 if (data.ReadState == ReadState.Aborted) {
562 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
566 if (data.ReadState != ReadState.Content) {
568 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
569 byte [] newBuffer = new byte [max];
570 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
571 cnc.buffer = newBuffer;
572 cnc.position = nread;
573 data.ReadState = ReadState.None;
580 WebConnectionStream stream = new WebConnectionStream (cnc, data);
581 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
582 string tencoding = null;
584 tencoding = data.Headers ["Transfer-Encoding"];
586 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
587 if (!cnc.chunkedRead) {
588 stream.ReadBuffer = cnc.buffer;
589 stream.ReadBufferOffset = pos;
590 stream.ReadBufferSize = nread;
592 stream.CheckResponseInBuffer ();
593 } catch (Exception e) {
594 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
596 } else if (cnc.chunkStream == null) {
598 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
599 } catch (Exception e) {
600 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
604 cnc.chunkStream.ResetBuffer ();
606 cnc.chunkStream.Write (cnc.buffer, pos, nread);
607 } catch (Exception e) {
608 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
613 data.stream = stream;
616 stream.ForceCompletion ();
618 data.request.SetResponseData (data);
621 static bool ExpectContent (int statusCode, string method)
623 if (method == "HEAD")
625 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
628 internal void GetCertificates (Stream stream)
630 // here the SSL negotiation have been done
631 #if SECURITY_DEP && (MONOTOUCH || MONODROID)
632 HttpsClientStream s = (stream as HttpsClientStream);
633 X509Certificate client = s.SelectedClientCertificate;
634 X509Certificate server = s.ServerCertificate;
636 X509Certificate client = (X509Certificate) piClient.GetValue (stream, null);
637 X509Certificate server = (X509Certificate) piServer.GetValue (stream, null);
639 sPoint.SetCertificates (client, server);
640 certsAvailable = (server != null);
643 internal static void InitRead (object state)
645 WebConnection cnc = (WebConnection) state;
646 Stream ns = cnc.nstream;
649 int size = cnc.buffer.Length - cnc.position;
650 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
651 } catch (Exception e) {
652 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
656 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
657 byte [] buffer, int max)
662 bool isContinue = false;
663 bool emptyFirstLine = false;
665 if (data.ReadState == ReadState.Aborted)
668 if (data.ReadState == ReadState.None) {
669 lineok = ReadLine (buffer, ref pos, max, ref line);
674 emptyFirstLine = true;
677 emptyFirstLine = false;
678 data.ReadState = ReadState.Status;
680 string [] parts = line.Split (' ');
681 if (parts.Length < 2)
684 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
685 data.Version = HttpVersion.Version11;
686 sPoint.SetVersion (HttpVersion.Version11);
688 data.Version = HttpVersion.Version10;
689 sPoint.SetVersion (HttpVersion.Version10);
692 data.StatusCode = (int) UInt32.Parse (parts [1]);
693 if (parts.Length >= 3)
694 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
696 data.StatusDescription = "";
702 emptyFirstLine = false;
703 if (data.ReadState == ReadState.Status) {
704 data.ReadState = ReadState.Headers;
705 data.Headers = new WebHeaderCollection ();
706 ArrayList headers = new ArrayList ();
707 bool finished = false;
709 if (ReadLine (buffer, ref pos, max, ref line) == false)
713 // Empty line: end of headers
718 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
719 int count = headers.Count - 1;
723 string prev = (string) headers [count] + line;
724 headers [count] = prev;
733 foreach (string s in headers)
734 data.Headers.SetInternal (s);
736 if (data.StatusCode == (int) HttpStatusCode.Continue) {
737 sPoint.SendContinue = true;
741 if (data.request.ExpectContinue) {
742 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
743 // Prevent double calls when getting the
744 // headers in several packets.
745 data.request.ExpectContinue = false;
748 data.ReadState = ReadState.None;
752 data.ReadState = ReadState.Content;
756 } while (emptyFirstLine || isContinue);
761 void InitConnection (object state)
763 HttpWebRequest request = (HttpWebRequest) state;
764 request.WebConnection = this;
765 if (request.ReuseConnection)
766 request.StoredConnection = this;
771 keepAlive = request.KeepAlive;
772 Data = new WebConnectionData (request);
778 if (status != WebExceptionStatus.Success) {
779 if (!request.Aborted) {
780 request.SetWriteStreamError (status, connect_exception);
786 if (!CreateStream (request)) {
790 WebExceptionStatus st = status;
791 if (Data.Challenge != null)
794 Exception cnc_exc = connect_exception;
795 connect_exception = null;
796 request.SetWriteStreamError (st, cnc_exc);
801 request.SetWriteStream (new WebConnectionStream (this, request));
805 static bool warned_about_queue = false;
808 internal EventHandler SendRequest (HttpWebRequest request)
814 if (state.TrySetBusy ()) {
815 status = WebExceptionStatus.Success;
816 ThreadPool.QueueUserWorkItem (initConn, request);
820 if (!warned_about_queue) {
821 warned_about_queue = true;
822 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
825 queue.Enqueue (request);
836 if (queue.Count > 0) {
837 SendRequest ((HttpWebRequest) queue.Dequeue ());
842 internal void NextRead ()
845 if (Data.request != null)
846 Data.request.FinishedReading = true;
847 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
848 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
849 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
850 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
852 if (cncHeader != null) {
853 cncHeader = cncHeader.ToLower ();
854 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
857 if ((socket != null && !socket.Connected) ||
858 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
863 if (priority_request != null) {
864 SendRequest (priority_request);
865 priority_request = null;
872 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
874 bool foundCR = false;
875 StringBuilder text = new StringBuilder ();
878 while (start < max) {
879 c = (int) buffer [start++];
881 if (c == '\n') { // newline
882 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
887 } else if (foundCR) {
896 text.Append ((char) c);
899 if (c != '\n' && c != '\r')
902 if (text.Length == 0) {
904 return (c == '\n' || c == '\r');
910 output = text.ToString ();
915 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
919 if (Data.request != request)
920 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
926 IAsyncResult result = null;
927 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
929 result = s.BeginRead (buffer, offset, size, cb, state);
931 } catch (Exception) {
932 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
938 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
939 wr.InnerAsyncResult = result;
940 if (result == null) {
941 // Will be completed from the data in ChunkStream
942 wr.SetCompleted (true, (Exception) null);
951 internal int EndRead (HttpWebRequest request, IAsyncResult result)
955 if (Data.request != request)
956 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
958 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
964 WebAsyncResult wr = null;
965 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
966 if (chunkedRead && (nsAsync is WebAsyncResult)) {
967 wr = (WebAsyncResult) nsAsync;
968 IAsyncResult inner = wr.InnerAsyncResult;
969 if (inner != null && !(inner is WebAsyncResult)) {
970 nbytes = s.EndRead (inner);
973 } else if (!(nsAsync is WebAsyncResult)) {
974 nbytes = s.EndRead (nsAsync);
975 wr = (WebAsyncResult) result;
981 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
982 if (!done && nbytes == 0 && chunkStream.WantMore)
983 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
984 } catch (Exception e) {
985 if (e is WebException)
988 throw new WebException ("Invalid chunked data.", e,
989 WebExceptionStatus.ServerProtocolViolation, null);
992 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
993 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
994 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
998 return (nbytes != 0) ? nbytes : -1;
1001 // To be called on chunkedRead when we can read no data from the ChunkStream yet
1002 int EnsureRead (byte [] buffer, int offset, int size)
1004 byte [] morebytes = null;
1006 while (nbytes == 0 && chunkStream.WantMore) {
1007 int localsize = chunkStream.ChunkLeft;
1008 if (localsize <= 0) // not read chunk size yet
1010 else if (localsize > 16384)
1013 if (morebytes == null || morebytes.Length < localsize)
1014 morebytes = new byte [localsize];
1016 int nread = nstream.Read (morebytes, 0, localsize);
1020 chunkStream.Write (morebytes, 0, nread);
1021 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
1027 bool CompleteChunkedRead()
1029 if (!chunkedRead || chunkStream == null)
1032 while (chunkStream.WantMore) {
1033 int nbytes = nstream.Read (buffer, 0, buffer.Length);
1035 return false; // Socket was disconnected
1037 chunkStream.Write (buffer, 0, nbytes);
1043 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
1047 if (Data.request != request)
1048 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1049 if (nstream == null)
1054 IAsyncResult result = null;
1056 result = s.BeginWrite (buffer, offset, size, cb, state);
1057 } catch (Exception) {
1058 status = WebExceptionStatus.SendFailure;
1065 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1067 if (request.FinishedReading)
1072 if (status == WebExceptionStatus.RequestCanceled)
1074 if (Data.request != request)
1075 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1076 if (nstream == null)
1077 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1082 s.EndWrite (result);
1084 } catch (Exception exc) {
1085 status = WebExceptionStatus.SendFailure;
1086 if (throwOnError && exc.InnerException != null)
1087 throw exc.InnerException;
1092 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1096 if (Data.request != request)
1097 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1098 if (nstream == null)
1107 result = s.Read (buffer, offset, size);
1108 done = (result == 0);
1113 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1114 if (!done && result == 0 && chunkStream.WantMore)
1115 result = EnsureRead (buffer, offset, size);
1116 } catch (Exception e) {
1117 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1121 if ((done || result == 0) && chunkStream.WantMore) {
1122 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1123 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1126 } catch (Exception e) {
1127 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1133 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1138 if (Data.request != request)
1139 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1146 s.Write (buffer, offset, size);
1147 // here SSL handshake should have been done
1148 if (ssl && !certsAvailable)
1149 GetCertificates (s);
1150 } catch (Exception e) {
1151 err_msg = e.Message;
1152 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1153 string msg = "Write: " + err_msg;
1154 if (e is WebException) {
1155 HandleError (wes, e, msg);
1159 // if SSL is in use then check for TrustFailure
1161 #if SECURITY_DEP && (MONOTOUCH || MONODROID)
1162 HttpsClientStream https = (s as HttpsClientStream);
1163 if (https.TrustFailure) {
1165 if ((bool) piTrustFailure.GetValue (s , null)) {
1167 wes = WebExceptionStatus.TrustFailure;
1168 msg = "Trust failure";
1172 HandleError (wes, e, msg);
1178 internal void Close (bool sendNext)
1181 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1182 Data.request.ReuseConnection = false;
1186 if (nstream != null) {
1193 if (socket != null) {
1200 if (ntlm_authenticated)
1204 Data.ReadState = ReadState.Aborted;
1208 Data = new WebConnectionData ();
1212 connect_request = null;
1213 connect_ntlm_auth_state = NtlmAuthState.None;
1217 void Abort (object sender, EventArgs args)
1221 HttpWebRequest req = (HttpWebRequest) sender;
1222 if (Data.request == req || Data.request == null) {
1223 if (!req.FinishedReading) {
1224 status = WebExceptionStatus.RequestCanceled;
1226 if (queue.Count > 0) {
1227 Data.request = (HttpWebRequest) queue.Dequeue ();
1228 SendRequest (Data.request);
1234 req.FinishedReading = true;
1235 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1236 if (queue.Count > 0 && queue.Peek () == sender) {
1238 } else if (queue.Count > 0) {
1239 object [] old = queue.ToArray ();
1241 for (int i = old.Length - 1; i >= 0; i--) {
1242 if (old [i] != sender)
1243 queue.Enqueue (old [i]);
1250 internal void ResetNtlm ()
1252 ntlm_authenticated = false;
1253 ntlm_credentials = null;
1254 unsafe_sharing = false;
1257 internal bool Connected {
1260 return (socket != null && socket.Connected);
1265 // -Used for NTLM authentication
1266 internal HttpWebRequest PriorityRequest {
1267 set { priority_request = value; }
1270 internal bool NtlmAuthenticated {
1271 get { return ntlm_authenticated; }
1272 set { ntlm_authenticated = value; }
1275 internal NetworkCredential NtlmCredential {
1276 get { return ntlm_credentials; }
1277 set { ntlm_credentials = value; }
1280 internal bool UnsafeAuthenticatedConnectionSharing {
1281 get { return unsafe_sharing; }
1282 set { unsafe_sharing = value; }