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.Security.Cryptography.X509Certificates;
36 using System.Threading;
37 using System.Diagnostics;
38 using Mono.Net.Security;
55 internal Socket socket;
56 object socketLock = new object ();
57 IWebConnectionState state;
58 WebExceptionStatus status;
59 WaitCallback initConn;
62 static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
63 EventHandler abortHandler;
64 AbortHelper abortHelper;
65 internal WebConnectionData Data;
67 ChunkStream chunkStream;
71 HttpWebRequest priority_request;
72 NetworkCredential ntlm_credentials;
73 bool ntlm_authenticated;
82 NtlmAuthState connect_ntlm_auth_state;
83 HttpWebRequest connect_request;
85 Exception connect_exception;
86 static object classLock = new object ();
87 MonoTlsStream tlsStream;
89 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
90 [System.Runtime.InteropServices.DllImport ("__Internal")]
91 static extern void xamarin_start_wwan (string uri);
94 internal ChunkStream ChunkStream {
95 get { return chunkStream; }
98 public WebConnection (IWebConnectionState wcs, ServicePoint sPoint)
101 this.sPoint = sPoint;
102 buffer = new byte [4096];
103 Data = new WebConnectionData ();
104 initConn = new WaitCallback (state => {
106 InitConnection (state);
109 queue = wcs.Group.Queue;
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) {
155 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
156 xamarin_start_wwan (sPoint.Address.ToString ());
157 hostEntry = sPoint.HostEntry;
158 if (hostEntry == null) {
160 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
161 WebExceptionStatus.NameResolutionFailure;
163 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
168 //WebConnectionData data = Data;
169 foreach (IPAddress address in hostEntry.AddressList) {
171 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
172 } catch (Exception se) {
173 // The Socket ctor can throw if we run out of FD's
174 if (!request.Aborted)
175 status = WebExceptionStatus.ConnectFailure;
176 connect_exception = se;
179 IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
180 socket.NoDelay = !sPoint.UseNagleAlgorithm;
182 sPoint.KeepAliveSetup (socket);
184 // Ignore. Not supported in all platforms.
187 if (!sPoint.CallEndPointDelegate (socket, remote)) {
190 status = WebExceptionStatus.ConnectFailure;
195 socket.Connect (remote);
196 status = WebExceptionStatus.Success;
198 } catch (ThreadAbortException) {
199 // program exiting...
205 } catch (ObjectDisposedException) {
206 // socket closed from another thread
208 } catch (Exception exc) {
213 if (!request.Aborted)
214 status = WebExceptionStatus.ConnectFailure;
215 connect_exception = exc;
222 bool CreateTunnel (HttpWebRequest request, Uri connectUri,
223 Stream stream, out byte[] buffer)
225 StringBuilder sb = new StringBuilder ();
226 sb.Append ("CONNECT ");
227 sb.Append (request.Address.Host);
229 sb.Append (request.Address.Port);
230 sb.Append (" HTTP/");
231 if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
236 sb.Append ("\r\nHost: ");
237 sb.Append (request.Address.Authority);
240 var challenge = Data.Challenge;
241 Data.Challenge = null;
242 var auth_header = request.Headers ["Proxy-Authorization"];
243 bool have_auth = auth_header != null;
245 sb.Append ("\r\nProxy-Authorization: ");
246 sb.Append (auth_header);
247 ntlm = auth_header.ToUpper ().Contains ("NTLM");
248 } else if (challenge != null && Data.StatusCode == 407) {
249 ICredentials creds = request.Proxy.Credentials;
252 if (connect_request == null) {
253 // create a CONNECT request to use with Authenticate
254 connect_request = (HttpWebRequest)WebRequest.Create (
255 connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
256 connect_request.Method = "CONNECT";
257 connect_request.Credentials = creds;
260 for (int i = 0; i < challenge.Length; i++) {
261 var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
264 ntlm = (auth.ModuleAuthenticationType == "NTLM");
265 sb.Append ("\r\nProxy-Authorization: ");
266 sb.Append (auth.Message);
272 sb.Append ("\r\nProxy-Connection: keep-alive");
273 connect_ntlm_auth_state++;
276 sb.Append ("\r\n\r\n");
279 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
280 stream.Write (connectBytes, 0, connectBytes.Length);
283 WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
284 if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
285 result != null && status == 407) { // Needs proxy auth
286 var connectionHeader = result ["Connection"];
287 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
288 connectionHeader.ToLower() == "close") {
289 // The server is requesting that this connection be closed
294 Data.StatusCode = status;
295 Data.Challenge = result.GetValues ("Proxy-Authentic");
297 } else if (status != 200) {
298 string msg = String.Format ("The remote server returned a {0} status code.", status);
299 HandleError (WebExceptionStatus.SecureChannelFailure, null, msg);
303 return (result != null);
306 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
311 byte [] buffer = new byte [1024];
312 MemoryStream ms = new MemoryStream ();
315 int n = stream.Read (buffer, 0, 1024);
317 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
321 ms.Write (buffer, 0, n);
324 bool gotStatus = false;
325 WebHeaderCollection headers = new WebHeaderCollection ();
326 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
330 contentLen = int.Parse(headers["Content-Length"]);
336 if (ms.Length - start - contentLen > 0) {
337 // we've read more data than the response header and conents,
338 // give back extra data to the caller
339 retBuffer = new byte[ms.Length - start - contentLen];
340 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
343 // haven't read in some or all of the contents for the response, do so now
344 FlushContents(stream, contentLen - (int)(ms.Length - start));
355 string[] parts = str.Split (' ');
356 if (parts.Length < 2) {
357 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
361 if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
362 Data.ProxyVersion = HttpVersion.Version11;
363 else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
364 Data.ProxyVersion = HttpVersion.Version10;
366 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
370 status = (int)UInt32.Parse (parts [1]);
376 void FlushContents(Stream stream, int contentLength)
378 while (contentLength > 0) {
379 byte[] contentBuffer = new byte[contentLength];
380 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
382 contentLength -= bytesRead;
390 bool CreateStream (HttpWebRequest request)
393 NetworkStream serverStream = new NetworkStream (socket, false);
395 if (request.Address.Scheme == Uri.UriSchemeHttps) {
397 if (!reused || nstream == null || tlsStream == null) {
398 byte [] buffer = null;
399 if (sPoint.UseConnect) {
400 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
404 tlsStream = new MonoTlsStream (request, serverStream);
405 nstream = tlsStream.CreateStream (buffer);
407 // we also need to set ServicePoint.Certificate
408 // and ServicePoint.ClientCertificate but this can
409 // only be done later (after handshake - which is
410 // done only after a read operation).
412 throw new NotSupportedException ();
415 nstream = serverStream;
417 } catch (Exception ex) {
418 if (tlsStream != null)
419 status = tlsStream.ExceptionStatus;
420 else if (!request.Aborted)
421 status = WebExceptionStatus.ConnectFailure;
422 connect_exception = ex;
429 void HandleError (WebExceptionStatus st, Exception e, string where)
433 if (st == WebExceptionStatus.RequestCanceled)
434 Data = new WebConnectionData ();
437 if (e == null) { // At least we now where it comes from
439 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
440 } catch (Exception e2) {
445 HttpWebRequest req = null;
446 if (Data != null && Data.request != null)
451 req.FinishedReading = true;
452 req.SetResponseError (st, e, where);
456 static void ReadDone (IAsyncResult result)
458 WebConnection cnc = (WebConnection)result.AsyncState;
459 WebConnectionData data = cnc.Data;
460 Stream ns = cnc.nstream;
468 nread = ns.EndRead (result);
469 } catch (ObjectDisposedException) {
471 } catch (Exception e) {
472 if (e.InnerException is ObjectDisposedException)
475 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
480 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
485 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
490 nread += cnc.position;
491 if (data.ReadState == ReadState.None) {
492 Exception exc = null;
494 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
495 } catch (Exception e) {
499 if (exc != null || pos == -1) {
500 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
505 if (data.ReadState == ReadState.Aborted) {
506 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
510 if (data.ReadState != ReadState.Content) {
512 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
513 byte [] newBuffer = new byte [max];
514 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
515 cnc.buffer = newBuffer;
516 cnc.position = nread;
517 data.ReadState = ReadState.None;
524 WebConnectionStream stream = new WebConnectionStream (cnc, data);
525 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
526 string tencoding = null;
528 tencoding = data.Headers ["Transfer-Encoding"];
530 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
531 if (!cnc.chunkedRead) {
532 stream.ReadBuffer = cnc.buffer;
533 stream.ReadBufferOffset = pos;
534 stream.ReadBufferSize = nread;
536 stream.CheckResponseInBuffer ();
537 } catch (Exception e) {
538 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
540 } else if (cnc.chunkStream == null) {
542 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
543 } catch (Exception e) {
544 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
548 cnc.chunkStream.ResetBuffer ();
550 cnc.chunkStream.Write (cnc.buffer, pos, nread);
551 } catch (Exception e) {
552 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
557 data.stream = stream;
560 stream.ForceCompletion ();
562 data.request.SetResponseData (data);
565 static bool ExpectContent (int statusCode, string method)
567 if (method == "HEAD")
569 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
572 internal static void InitRead (object state)
574 WebConnection cnc = (WebConnection) state;
575 Stream ns = cnc.nstream;
578 int size = cnc.buffer.Length - cnc.position;
579 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
580 } catch (Exception e) {
581 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
585 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
586 byte [] buffer, int max)
591 bool isContinue = false;
592 bool emptyFirstLine = false;
594 if (data.ReadState == ReadState.Aborted)
597 if (data.ReadState == ReadState.None) {
598 lineok = ReadLine (buffer, ref pos, max, ref line);
603 emptyFirstLine = true;
606 emptyFirstLine = false;
607 data.ReadState = ReadState.Status;
609 string [] parts = line.Split (' ');
610 if (parts.Length < 2)
613 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
614 data.Version = HttpVersion.Version11;
615 sPoint.SetVersion (HttpVersion.Version11);
617 data.Version = HttpVersion.Version10;
618 sPoint.SetVersion (HttpVersion.Version10);
621 data.StatusCode = (int) UInt32.Parse (parts [1]);
622 if (parts.Length >= 3)
623 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
625 data.StatusDescription = "";
631 emptyFirstLine = false;
632 if (data.ReadState == ReadState.Status) {
633 data.ReadState = ReadState.Headers;
634 data.Headers = new WebHeaderCollection ();
635 ArrayList headers = new ArrayList ();
636 bool finished = false;
638 if (ReadLine (buffer, ref pos, max, ref line) == false)
642 // Empty line: end of headers
647 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
648 int count = headers.Count - 1;
652 string prev = (string) headers [count] + line;
653 headers [count] = prev;
662 // .NET uses ParseHeaders or ParseHeadersStrict which is much better
663 foreach (string s in headers) {
665 int pos_s = s.IndexOf (':');
667 throw new ArgumentException ("no colon found", "header");
669 var header = s.Substring (0, pos_s);
670 var value = s.Substring (pos_s + 1).Trim ();
672 var h = data.Headers;
673 if (h.AllowMultiValues (header)) {
674 h.AddInternal (header, value);
676 h.SetInternal (header, value);
680 if (data.StatusCode == (int) HttpStatusCode.Continue) {
681 sPoint.SendContinue = true;
685 if (data.request.ExpectContinue) {
686 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
687 // Prevent double calls when getting the
688 // headers in several packets.
689 data.request.ExpectContinue = false;
692 data.ReadState = ReadState.None;
696 data.ReadState = ReadState.Content;
700 } while (emptyFirstLine || isContinue);
705 void InitConnection (object state)
707 HttpWebRequest request = (HttpWebRequest) state;
708 request.WebConnection = this;
709 if (request.ReuseConnection)
710 request.StoredConnection = this;
715 keepAlive = request.KeepAlive;
716 Data = new WebConnectionData (request);
722 if (status != WebExceptionStatus.Success) {
723 if (!request.Aborted) {
724 request.SetWriteStreamError (status, connect_exception);
730 if (!CreateStream (request)) {
734 WebExceptionStatus st = status;
735 if (Data.Challenge != null)
738 Exception cnc_exc = connect_exception;
739 connect_exception = null;
740 request.SetWriteStreamError (st, cnc_exc);
745 request.SetWriteStream (new WebConnectionStream (this, request));
749 static bool warned_about_queue = false;
752 internal EventHandler SendRequest (HttpWebRequest request)
758 if (state.TrySetBusy ()) {
759 status = WebExceptionStatus.Success;
760 ThreadPool.QueueUserWorkItem (initConn, request);
764 if (!warned_about_queue) {
765 warned_about_queue = true;
766 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
769 queue.Enqueue (request);
780 if (queue.Count > 0) {
781 SendRequest ((HttpWebRequest) queue.Dequeue ());
786 internal void NextRead ()
789 if (Data.request != null)
790 Data.request.FinishedReading = true;
791 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
792 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
793 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
794 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
796 if (cncHeader != null) {
797 cncHeader = cncHeader.ToLower ();
798 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
801 if ((socket != null && !socket.Connected) ||
802 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
807 if (priority_request != null) {
808 SendRequest (priority_request);
809 priority_request = null;
816 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
818 bool foundCR = false;
819 StringBuilder text = new StringBuilder ();
822 while (start < max) {
823 c = (int) buffer [start++];
825 if (c == '\n') { // newline
826 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
831 } else if (foundCR) {
840 text.Append ((char) c);
843 if (c != '\n' && c != '\r')
846 if (text.Length == 0) {
848 return (c == '\n' || c == '\r');
854 output = text.ToString ();
859 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
863 if (Data.request != request)
864 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
870 IAsyncResult result = null;
871 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
873 result = s.BeginRead (buffer, offset, size, cb, state);
875 } catch (Exception) {
876 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
882 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
883 wr.InnerAsyncResult = result;
884 if (result == null) {
885 // Will be completed from the data in ChunkStream
886 wr.SetCompleted (true, (Exception) null);
895 internal int EndRead (HttpWebRequest request, IAsyncResult result)
899 if (Data.request != request)
900 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
902 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
908 WebAsyncResult wr = null;
909 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
910 if (chunkedRead && (nsAsync is WebAsyncResult)) {
911 wr = (WebAsyncResult) nsAsync;
912 IAsyncResult inner = wr.InnerAsyncResult;
913 if (inner != null && !(inner is WebAsyncResult)) {
914 nbytes = s.EndRead (inner);
917 } else if (!(nsAsync is WebAsyncResult)) {
918 nbytes = s.EndRead (nsAsync);
919 wr = (WebAsyncResult) result;
925 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
926 if (!done && nbytes == 0 && chunkStream.WantMore)
927 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
928 } catch (Exception e) {
929 if (e is WebException)
932 throw new WebException ("Invalid chunked data.", e,
933 WebExceptionStatus.ServerProtocolViolation, null);
936 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
937 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
938 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
942 return (nbytes != 0) ? nbytes : -1;
945 // To be called on chunkedRead when we can read no data from the ChunkStream yet
946 int EnsureRead (byte [] buffer, int offset, int size)
948 byte [] morebytes = null;
950 while (nbytes == 0 && chunkStream.WantMore) {
951 int localsize = chunkStream.ChunkLeft;
952 if (localsize <= 0) // not read chunk size yet
954 else if (localsize > 16384)
957 if (morebytes == null || morebytes.Length < localsize)
958 morebytes = new byte [localsize];
960 int nread = nstream.Read (morebytes, 0, localsize);
964 chunkStream.Write (morebytes, 0, nread);
965 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
971 bool CompleteChunkedRead()
973 if (!chunkedRead || chunkStream == null)
976 while (chunkStream.WantMore) {
977 int nbytes = nstream.Read (buffer, 0, buffer.Length);
979 return false; // Socket was disconnected
981 chunkStream.Write (buffer, 0, nbytes);
987 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
991 if (Data.request != request)
992 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
998 IAsyncResult result = null;
1000 result = s.BeginWrite (buffer, offset, size, cb, state);
1001 } catch (Exception) {
1002 status = WebExceptionStatus.SendFailure;
1009 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1013 if (status == WebExceptionStatus.RequestCanceled)
1015 if (Data.request != request)
1016 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1017 if (nstream == null)
1018 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1023 s.EndWrite (result);
1025 } catch (Exception exc) {
1026 status = WebExceptionStatus.SendFailure;
1027 if (throwOnError && exc.InnerException != null)
1028 throw exc.InnerException;
1033 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1037 if (Data.request != request)
1038 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1039 if (nstream == null)
1048 result = s.Read (buffer, offset, size);
1049 done = (result == 0);
1054 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1055 if (!done && result == 0 && chunkStream.WantMore)
1056 result = EnsureRead (buffer, offset, size);
1057 } catch (Exception e) {
1058 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1062 if ((done || result == 0) && chunkStream.WantMore) {
1063 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1064 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1067 } catch (Exception e) {
1068 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1074 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1079 if (Data.request != request)
1080 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1087 s.Write (buffer, offset, size);
1088 } catch (Exception e) {
1089 err_msg = e.Message;
1090 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1091 string msg = "Write: " + err_msg;
1092 if (e is WebException) {
1093 HandleError (wes, e, msg);
1097 HandleError (wes, e, msg);
1103 internal void Close (bool sendNext)
1106 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1107 Data.request.ReuseConnection = false;
1111 if (nstream != null) {
1118 if (socket != null) {
1125 if (ntlm_authenticated)
1129 Data.ReadState = ReadState.Aborted;
1133 Data = new WebConnectionData ();
1137 connect_request = null;
1138 connect_ntlm_auth_state = NtlmAuthState.None;
1142 void Abort (object sender, EventArgs args)
1146 HttpWebRequest req = (HttpWebRequest) sender;
1147 if (Data.request == req || Data.request == null) {
1148 if (!req.FinishedReading) {
1149 status = WebExceptionStatus.RequestCanceled;
1151 if (queue.Count > 0) {
1152 Data.request = (HttpWebRequest) queue.Dequeue ();
1153 SendRequest (Data.request);
1159 req.FinishedReading = true;
1160 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1161 if (queue.Count > 0 && queue.Peek () == sender) {
1163 } else if (queue.Count > 0) {
1164 object [] old = queue.ToArray ();
1166 for (int i = old.Length - 1; i >= 0; i--) {
1167 if (old [i] != sender)
1168 queue.Enqueue (old [i]);
1175 internal void ResetNtlm ()
1177 ntlm_authenticated = false;
1178 ntlm_credentials = null;
1179 unsafe_sharing = false;
1182 internal bool Connected {
1185 return (socket != null && socket.Connected);
1190 // -Used for NTLM authentication
1191 internal HttpWebRequest PriorityRequest {
1192 set { priority_request = value; }
1195 internal bool NtlmAuthenticated {
1196 get { return ntlm_authenticated; }
1197 set { ntlm_authenticated = value; }
1200 internal NetworkCredential NtlmCredential {
1201 get { return ntlm_credentials; }
1202 set { ntlm_credentials = value; }
1205 internal bool UnsafeAuthenticatedConnectionSharing {
1206 get { return unsafe_sharing; }
1207 set { unsafe_sharing = value; }