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;
61 EventHandler abortHandler;
62 AbortHelper abortHelper;
63 internal WebConnectionData Data;
65 MonoChunkStream chunkStream;
69 HttpWebRequest priority_request;
70 NetworkCredential ntlm_credentials;
71 bool ntlm_authenticated;
80 NtlmAuthState connect_ntlm_auth_state;
81 HttpWebRequest connect_request;
83 Exception connect_exception;
84 MonoTlsStream tlsStream;
86 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
87 [System.Runtime.InteropServices.DllImport ("__Internal")]
88 static extern void xamarin_start_wwan (string uri);
91 internal MonoChunkStream MonoChunkStream {
92 get { return chunkStream; }
95 public WebConnection (IWebConnectionState wcs, ServicePoint sPoint)
99 buffer = new byte [4096];
100 Data = new WebConnectionData ();
101 queue = wcs.Group.Queue;
102 abortHelper = new AbortHelper ();
103 abortHelper.Connection = this;
104 abortHandler = new EventHandler (abortHelper.Abort);
108 public WebConnection Connection;
110 public void Abort (object sender, EventArgs args)
112 WebConnection other = ((HttpWebRequest) sender).WebConnection;
115 other.Abort (sender, args);
121 // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
122 // but if there's data pending to read (!) we won't reuse the socket.
123 return (socket.Poll (0, SelectMode.SelectRead) == false);
126 void Connect (HttpWebRequest request)
129 if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
130 // Take the chunked stream to the expected state (State.None)
131 if (CanReuse () && CompleteChunkedRead ()) {
138 if (socket != null) {
144 IPHostEntry hostEntry = sPoint.HostEntry;
146 if (hostEntry == null) {
147 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
148 xamarin_start_wwan (sPoint.Address.ToString ());
149 hostEntry = sPoint.HostEntry;
150 if (hostEntry == null) {
152 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
153 WebExceptionStatus.NameResolutionFailure;
155 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
160 //WebConnectionData data = Data;
161 foreach (IPAddress address in hostEntry.AddressList) {
163 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
164 } catch (Exception se) {
165 // The Socket ctor can throw if we run out of FD's
166 if (!request.Aborted)
167 status = WebExceptionStatus.ConnectFailure;
168 connect_exception = se;
171 IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
172 socket.NoDelay = !sPoint.UseNagleAlgorithm;
174 sPoint.KeepAliveSetup (socket);
176 // Ignore. Not supported in all platforms.
179 if (!sPoint.CallEndPointDelegate (socket, remote)) {
182 status = WebExceptionStatus.ConnectFailure;
187 socket.Connect (remote);
188 status = WebExceptionStatus.Success;
190 } catch (ThreadAbortException) {
191 // program exiting...
197 } catch (ObjectDisposedException) {
198 // socket closed from another thread
200 } catch (Exception exc) {
205 if (!request.Aborted)
206 status = WebExceptionStatus.ConnectFailure;
207 connect_exception = exc;
214 bool CreateTunnel (HttpWebRequest request, Uri connectUri,
215 Stream stream, out byte[] buffer)
217 StringBuilder sb = new StringBuilder ();
218 sb.Append ("CONNECT ");
219 sb.Append (request.Address.Host);
221 sb.Append (request.Address.Port);
222 sb.Append (" HTTP/");
223 if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
228 sb.Append ("\r\nHost: ");
229 sb.Append (request.Address.Authority);
232 var challenge = Data.Challenge;
233 Data.Challenge = null;
234 var auth_header = request.Headers ["Proxy-Authorization"];
235 bool have_auth = auth_header != null;
237 sb.Append ("\r\nProxy-Authorization: ");
238 sb.Append (auth_header);
239 ntlm = auth_header.ToUpper ().Contains ("NTLM");
240 } else if (challenge != null && Data.StatusCode == 407) {
241 ICredentials creds = request.Proxy.Credentials;
244 if (connect_request == null) {
245 // create a CONNECT request to use with Authenticate
246 connect_request = (HttpWebRequest)WebRequest.Create (
247 connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
248 connect_request.Method = "CONNECT";
249 connect_request.Credentials = creds;
253 for (int i = 0; i < challenge.Length; i++) {
254 var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
257 ntlm = (auth.ModuleAuthenticationType == "NTLM");
258 sb.Append ("\r\nProxy-Authorization: ");
259 sb.Append (auth.Message);
266 sb.Append ("\r\nProxy-Connection: keep-alive");
267 connect_ntlm_auth_state++;
270 sb.Append ("\r\n\r\n");
273 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
274 stream.Write (connectBytes, 0, connectBytes.Length);
277 WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
278 if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
279 result != null && status == 407) { // Needs proxy auth
280 var connectionHeader = result ["Connection"];
281 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
282 connectionHeader.ToLower() == "close") {
283 // The server is requesting that this connection be closed
288 Data.StatusCode = status;
289 Data.Challenge = result.GetValues ("Proxy-Authenticate");
290 Data.Headers = result;
295 Data.StatusCode = status;
296 Data.Headers = result;
300 return (result != null);
303 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
308 byte [] buffer = new byte [1024];
309 MemoryStream ms = new MemoryStream ();
312 int n = stream.Read (buffer, 0, 1024);
314 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
318 ms.Write (buffer, 0, n);
321 bool gotStatus = false;
322 WebHeaderCollection headers = new WebHeaderCollection ();
323 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
327 contentLen = int.Parse(headers["Content-Length"]);
333 if (ms.Length - start - contentLen > 0) {
334 // we've read more data than the response header and conents,
335 // give back extra data to the caller
336 retBuffer = new byte[ms.Length - start - contentLen];
337 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
340 // haven't read in some or all of the contents for the response, do so now
341 FlushContents(stream, contentLen - (int)(ms.Length - start));
352 string[] parts = str.Split (' ');
353 if (parts.Length < 2) {
354 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
358 if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
359 Data.ProxyVersion = HttpVersion.Version11;
360 else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
361 Data.ProxyVersion = HttpVersion.Version10;
363 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
367 status = (int)UInt32.Parse (parts [1]);
368 if (parts.Length >= 3)
369 Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
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 void ReadDone (IAsyncResult result)
458 WebConnectionData data = Data;
467 nread = ns.EndRead (result);
468 } catch (ObjectDisposedException) {
470 } catch (Exception e) {
471 if (e.InnerException is ObjectDisposedException)
474 HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
479 HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
484 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
490 if (data.ReadState == ReadState.None) {
491 Exception exc = null;
493 pos = GetResponse (data, sPoint, buffer, nread);
494 } catch (Exception e) {
498 if (exc != null || pos == -1) {
499 HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
504 if (data.ReadState == ReadState.Aborted) {
505 HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
509 if (data.ReadState != ReadState.Content) {
511 int max = (est < buffer.Length) ? buffer.Length : est;
512 byte [] newBuffer = new byte [max];
513 Buffer.BlockCopy (buffer, 0, newBuffer, 0, nread);
516 data.ReadState = ReadState.None;
523 WebConnectionStream stream = new WebConnectionStream (this, data);
524 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
525 string tencoding = null;
527 tencoding = data.Headers ["Transfer-Encoding"];
529 chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
531 stream.ReadBuffer = buffer;
532 stream.ReadBufferOffset = pos;
533 stream.ReadBufferSize = nread;
535 stream.CheckResponseInBuffer ();
536 } catch (Exception e) {
537 HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
539 } else if (chunkStream == null) {
541 chunkStream = new MonoChunkStream (buffer, pos, nread, data.Headers);
542 } catch (Exception e) {
543 HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
547 chunkStream.ResetBuffer ();
549 chunkStream.Write (buffer, pos, nread);
550 } catch (Exception e) {
551 HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
556 data.stream = stream;
559 stream.ForceCompletion ();
561 data.request.SetResponseData (data);
564 static bool ExpectContent (int statusCode, string method)
566 if (method == "HEAD")
568 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
571 internal void InitRead ()
576 int size = buffer.Length - position;
577 ns.BeginRead (buffer, position, size, ReadDone, null);
578 } catch (Exception e) {
579 HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
583 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
584 byte [] buffer, int max)
589 bool isContinue = false;
590 bool emptyFirstLine = false;
592 if (data.ReadState == ReadState.Aborted)
595 if (data.ReadState == ReadState.None) {
596 lineok = ReadLine (buffer, ref pos, max, ref line);
601 emptyFirstLine = true;
604 emptyFirstLine = false;
605 data.ReadState = ReadState.Status;
607 string [] parts = line.Split (' ');
608 if (parts.Length < 2)
611 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
612 data.Version = HttpVersion.Version11;
613 sPoint.SetVersion (HttpVersion.Version11);
615 data.Version = HttpVersion.Version10;
616 sPoint.SetVersion (HttpVersion.Version10);
619 data.StatusCode = (int) UInt32.Parse (parts [1]);
620 if (parts.Length >= 3)
621 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
623 data.StatusDescription = "";
629 emptyFirstLine = false;
630 if (data.ReadState == ReadState.Status) {
631 data.ReadState = ReadState.Headers;
632 data.Headers = new WebHeaderCollection ();
633 ArrayList headers = new ArrayList ();
634 bool finished = false;
636 if (ReadLine (buffer, ref pos, max, ref line) == false)
640 // Empty line: end of headers
645 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
646 int count = headers.Count - 1;
650 string prev = (string) headers [count] + line;
651 headers [count] = prev;
660 // .NET uses ParseHeaders or ParseHeadersStrict which is much better
661 foreach (string s in headers) {
663 int pos_s = s.IndexOf (':');
665 throw new ArgumentException ("no colon found", "header");
667 var header = s.Substring (0, pos_s);
668 var value = s.Substring (pos_s + 1).Trim ();
670 var h = data.Headers;
671 if (WebHeaderCollection.AllowMultiValues (header)) {
672 h.AddInternal (header, value);
674 h.SetInternal (header, value);
678 if (data.StatusCode == (int) HttpStatusCode.Continue) {
679 sPoint.SendContinue = true;
683 if (data.request.ExpectContinue) {
684 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
685 // Prevent double calls when getting the
686 // headers in several packets.
687 data.request.ExpectContinue = false;
690 data.ReadState = ReadState.None;
694 data.ReadState = ReadState.Content;
698 } while (emptyFirstLine || isContinue);
703 void InitConnection (HttpWebRequest request)
705 request.WebConnection = this;
706 if (request.ReuseConnection)
707 request.StoredConnection = this;
712 keepAlive = request.KeepAlive;
713 Data = new WebConnectionData (request);
719 if (status != WebExceptionStatus.Success) {
720 if (!request.Aborted) {
721 request.SetWriteStreamError (status, connect_exception);
727 if (!CreateStream (request)) {
731 WebExceptionStatus st = status;
732 if (Data.Challenge != null)
735 Exception cnc_exc = connect_exception;
736 if (cnc_exc == null && (Data.StatusCode == 401 || Data.StatusCode == 407)) {
737 st = WebExceptionStatus.ProtocolError;
738 if (Data.Headers == null)
739 Data.Headers = new WebHeaderCollection ();
741 var webResponse = new HttpWebResponse (sPoint.Address, "CONNECT", Data, null);
742 cnc_exc = new WebException (Data.StatusCode == 407 ? "(407) Proxy Authentication Required" : "(401) Unauthorized", null, st, webResponse);
745 connect_exception = null;
746 request.SetWriteStreamError (st, cnc_exc);
751 request.SetWriteStream (new WebConnectionStream (this, request));
755 static bool warned_about_queue = false;
758 internal EventHandler SendRequest (HttpWebRequest request)
764 if (state.TrySetBusy ()) {
765 status = WebExceptionStatus.Success;
766 ThreadPool.QueueUserWorkItem (o => { try { InitConnection ((HttpWebRequest) o); } catch {} }, request);
770 if (!warned_about_queue) {
771 warned_about_queue = true;
772 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
775 queue.Enqueue (request);
786 if (queue.Count > 0) {
787 SendRequest ((HttpWebRequest) queue.Dequeue ());
792 internal void NextRead ()
795 if (Data.request != null)
796 Data.request.FinishedReading = true;
797 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
798 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
799 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
800 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
802 if (cncHeader != null) {
803 cncHeader = cncHeader.ToLower ();
804 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
807 if ((socket != null && !socket.Connected) ||
808 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
813 if (priority_request != null) {
814 SendRequest (priority_request);
815 priority_request = null;
822 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
824 bool foundCR = false;
825 StringBuilder text = new StringBuilder ();
828 while (start < max) {
829 c = (int) buffer [start++];
831 if (c == '\n') { // newline
832 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
837 } else if (foundCR) {
846 text.Append ((char) c);
849 if (c != '\n' && c != '\r')
852 if (text.Length == 0) {
854 return (c == '\n' || c == '\r');
860 output = text.ToString ();
865 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
869 if (Data.request != request)
870 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
876 IAsyncResult result = null;
877 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
879 result = s.BeginRead (buffer, offset, size, cb, state);
881 } catch (Exception) {
882 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
888 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
889 wr.InnerAsyncResult = result;
890 if (result == null) {
891 // Will be completed from the data in MonoChunkStream
892 wr.SetCompleted (true, (Exception) null);
901 internal int EndRead (HttpWebRequest request, IAsyncResult result)
906 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
907 if (Data.request != request)
908 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
910 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
916 WebAsyncResult wr = null;
917 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
918 if (chunkedRead && (nsAsync is WebAsyncResult)) {
919 wr = (WebAsyncResult) nsAsync;
920 IAsyncResult inner = wr.InnerAsyncResult;
921 if (inner != null && !(inner is WebAsyncResult)) {
922 nbytes = s.EndRead (inner);
925 } else if (!(nsAsync is WebAsyncResult)) {
926 nbytes = s.EndRead (nsAsync);
927 wr = (WebAsyncResult) result;
933 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
934 if (!done && nbytes == 0 && chunkStream.WantMore)
935 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
936 } catch (Exception e) {
937 if (e is WebException)
940 throw new WebException ("Invalid chunked data.", e,
941 WebExceptionStatus.ServerProtocolViolation, null);
944 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
945 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
946 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
950 return (nbytes != 0) ? nbytes : -1;
953 // To be called on chunkedRead when we can read no data from the MonoChunkStream yet
954 int EnsureRead (byte [] buffer, int offset, int size)
956 byte [] morebytes = null;
958 while (nbytes == 0 && chunkStream.WantMore) {
959 int localsize = chunkStream.ChunkLeft;
960 if (localsize <= 0) // not read chunk size yet
962 else if (localsize > 16384)
965 if (morebytes == null || morebytes.Length < localsize)
966 morebytes = new byte [localsize];
968 int nread = nstream.Read (morebytes, 0, localsize);
972 chunkStream.Write (morebytes, 0, nread);
973 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
979 bool CompleteChunkedRead()
981 if (!chunkedRead || chunkStream == null)
984 while (chunkStream.WantMore) {
985 int nbytes = nstream.Read (buffer, 0, buffer.Length);
987 return false; // Socket was disconnected
989 chunkStream.Write (buffer, 0, nbytes);
995 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
999 if (Data.request != request)
1000 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1001 if (nstream == null)
1006 IAsyncResult result = null;
1008 result = s.BeginWrite (buffer, offset, size, cb, state);
1009 } catch (ObjectDisposedException) {
1011 if (Data.request != request)
1015 } catch (IOException e) {
1016 SocketException se = e.InnerException as SocketException;
1017 if (se != null && se.SocketErrorCode == SocketError.NotConnected) {
1021 } catch (Exception) {
1022 status = WebExceptionStatus.SendFailure;
1029 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1033 if (status == WebExceptionStatus.RequestCanceled)
1035 if (Data.request != request)
1036 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1037 if (nstream == null)
1038 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1043 s.EndWrite (result);
1045 } catch (Exception exc) {
1046 status = WebExceptionStatus.SendFailure;
1047 if (throwOnError && exc.InnerException != null)
1048 throw exc.InnerException;
1053 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1057 if (Data.request != request)
1058 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1059 if (nstream == null)
1068 result = s.Read (buffer, offset, size);
1069 done = (result == 0);
1074 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1075 if (!done && result == 0 && chunkStream.WantMore)
1076 result = EnsureRead (buffer, offset, size);
1077 } catch (Exception e) {
1078 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1082 if ((done || result == 0) && chunkStream.WantMore) {
1083 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1084 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1087 } catch (Exception e) {
1088 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1094 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1099 if (Data.request != request)
1100 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1107 s.Write (buffer, offset, size);
1108 } catch (Exception e) {
1109 err_msg = e.Message;
1110 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1111 string msg = "Write: " + err_msg;
1112 if (e is WebException) {
1113 HandleError (wes, e, msg);
1117 HandleError (wes, e, msg);
1123 internal void Close (bool sendNext)
1126 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1127 Data.request.ReuseConnection = false;
1131 if (nstream != null) {
1138 if (socket != null) {
1145 if (ntlm_authenticated)
1149 Data.ReadState = ReadState.Aborted;
1153 Data = new WebConnectionData ();
1157 connect_request = null;
1158 connect_ntlm_auth_state = NtlmAuthState.None;
1162 void Abort (object sender, EventArgs args)
1166 HttpWebRequest req = (HttpWebRequest) sender;
1167 if (Data.request == req || Data.request == null) {
1168 if (!req.FinishedReading) {
1169 status = WebExceptionStatus.RequestCanceled;
1171 if (queue.Count > 0) {
1172 Data.request = (HttpWebRequest) queue.Dequeue ();
1173 SendRequest (Data.request);
1179 req.FinishedReading = true;
1180 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1181 if (queue.Count > 0 && queue.Peek () == sender) {
1183 } else if (queue.Count > 0) {
1184 object [] old = queue.ToArray ();
1186 for (int i = old.Length - 1; i >= 0; i--) {
1187 if (old [i] != sender)
1188 queue.Enqueue (old [i]);
1195 internal void ResetNtlm ()
1197 ntlm_authenticated = false;
1198 ntlm_credentials = null;
1199 unsafe_sharing = false;
1202 internal bool Connected {
1205 return (socket != null && socket.Connected);
1210 // -Used for NTLM authentication
1211 internal HttpWebRequest PriorityRequest {
1212 set { priority_request = value; }
1215 internal bool NtlmAuthenticated {
1216 get { return ntlm_authenticated; }
1217 set { ntlm_authenticated = value; }
1220 internal NetworkCredential NtlmCredential {
1221 get { return ntlm_credentials; }
1222 set { ntlm_credentials = value; }
1225 internal bool UnsafeAuthenticatedConnectionSharing {
1226 get { return unsafe_sharing; }
1227 set { unsafe_sharing = value; }