[WebConnection] Fix race condition between Close and BeginWrite (#4694)
[mono-project.git] / mcs / class / System / System.Net / WebConnection.cs
blobf8922a4df5b638f3e357a4317fd09a312f09d8fc
1 //
2 // System.Net.WebConnection
3 //
4 // Authors:
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2003 Ximian, Inc (http://www.ximian.com)
8 //
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:
18 //
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 //
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.
31 using System.IO;
32 using System.Collections;
33 using System.Net.Sockets;
34 using System.Security.Cryptography.X509Certificates;
35 using System.Text;
36 using System.Threading;
37 using System.Diagnostics;
38 using Mono.Net.Security;
40 namespace System.Net
42 enum ReadState
44 None,
45 Status,
46 Headers,
47 Content,
48 Aborted
51 class WebConnection
53 ServicePoint sPoint;
54 Stream nstream;
55 internal Socket socket;
56 object socketLock = new object ();
57 IWebConnectionState state;
58 WebExceptionStatus status;
59 WaitCallback initConn;
60 bool keepAlive;
61 byte [] buffer;
62 static AsyncCallback readDoneDelegate = new AsyncCallback (ReadDone);
63 EventHandler abortHandler;
64 AbortHelper abortHelper;
65 internal WebConnectionData Data;
66 bool chunkedRead;
67 ChunkStream chunkStream;
68 Queue queue;
69 bool reused;
70 int position;
71 HttpWebRequest priority_request;
72 NetworkCredential ntlm_credentials;
73 bool ntlm_authenticated;
74 bool unsafe_sharing;
76 enum NtlmAuthState
78 None,
79 Challenge,
80 Response
82 NtlmAuthState connect_ntlm_auth_state;
83 HttpWebRequest connect_request;
85 Exception connect_exception;
86 MonoTlsStream tlsStream;
88 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
89 [System.Runtime.InteropServices.DllImport ("__Internal")]
90 static extern void xamarin_start_wwan (string uri);
91 #endif
93 internal ChunkStream ChunkStream {
94 get { return chunkStream; }
97 public WebConnection (IWebConnectionState wcs, ServicePoint sPoint)
99 this.state = wcs;
100 this.sPoint = sPoint;
101 buffer = new byte [4096];
102 Data = new WebConnectionData ();
103 initConn = new WaitCallback (state => {
104 try {
105 InitConnection (state);
106 } catch {}
108 queue = wcs.Group.Queue;
109 abortHelper = new AbortHelper ();
110 abortHelper.Connection = this;
111 abortHandler = new EventHandler (abortHelper.Abort);
114 class AbortHelper {
115 public WebConnection Connection;
117 public void Abort (object sender, EventArgs args)
119 WebConnection other = ((HttpWebRequest) sender).WebConnection;
120 if (other == null)
121 other = Connection;
122 other.Abort (sender, args);
126 bool CanReuse ()
128 // The real condition is !(socket.Poll (0, SelectMode.SelectRead) || socket.Available != 0)
129 // but if there's data pending to read (!) we won't reuse the socket.
130 return (socket.Poll (0, SelectMode.SelectRead) == false);
133 void Connect (HttpWebRequest request)
135 lock (socketLock) {
136 if (socket != null && socket.Connected && status == WebExceptionStatus.Success) {
137 // Take the chunked stream to the expected state (State.None)
138 if (CanReuse () && CompleteChunkedRead ()) {
139 reused = true;
140 return;
144 reused = false;
145 if (socket != null) {
146 socket.Close();
147 socket = null;
150 chunkStream = null;
151 IPHostEntry hostEntry = sPoint.HostEntry;
153 if (hostEntry == null) {
154 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
155 xamarin_start_wwan (sPoint.Address.ToString ());
156 hostEntry = sPoint.HostEntry;
157 if (hostEntry == null) {
158 #endif
159 status = sPoint.UsesProxy ? WebExceptionStatus.ProxyNameResolutionFailure :
160 WebExceptionStatus.NameResolutionFailure;
161 return;
162 #if MONOTOUCH && !MONOTOUCH_TV && !MONOTOUCH_WATCH
164 #endif
167 //WebConnectionData data = Data;
168 foreach (IPAddress address in hostEntry.AddressList) {
169 try {
170 socket = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
171 } catch (Exception se) {
172 // The Socket ctor can throw if we run out of FD's
173 if (!request.Aborted)
174 status = WebExceptionStatus.ConnectFailure;
175 connect_exception = se;
176 return;
178 IPEndPoint remote = new IPEndPoint (address, sPoint.Address.Port);
179 socket.NoDelay = !sPoint.UseNagleAlgorithm;
180 try {
181 sPoint.KeepAliveSetup (socket);
182 } catch {
183 // Ignore. Not supported in all platforms.
186 if (!sPoint.CallEndPointDelegate (socket, remote)) {
187 socket.Close ();
188 socket = null;
189 status = WebExceptionStatus.ConnectFailure;
190 } else {
191 try {
192 if (request.Aborted)
193 return;
194 socket.Connect (remote);
195 status = WebExceptionStatus.Success;
196 break;
197 } catch (ThreadAbortException) {
198 // program exiting...
199 Socket s = socket;
200 socket = null;
201 if (s != null)
202 s.Close ();
203 return;
204 } catch (ObjectDisposedException) {
205 // socket closed from another thread
206 return;
207 } catch (Exception exc) {
208 Socket s = socket;
209 socket = null;
210 if (s != null)
211 s.Close ();
212 if (!request.Aborted)
213 status = WebExceptionStatus.ConnectFailure;
214 connect_exception = exc;
221 bool CreateTunnel (HttpWebRequest request, Uri connectUri,
222 Stream stream, out byte[] buffer)
224 StringBuilder sb = new StringBuilder ();
225 sb.Append ("CONNECT ");
226 sb.Append (request.Address.Host);
227 sb.Append (':');
228 sb.Append (request.Address.Port);
229 sb.Append (" HTTP/");
230 if (request.ServicePoint.ProtocolVersion == HttpVersion.Version11)
231 sb.Append ("1.1");
232 else
233 sb.Append ("1.0");
235 sb.Append ("\r\nHost: ");
236 sb.Append (request.Address.Authority);
238 bool ntlm = false;
239 var challenge = Data.Challenge;
240 Data.Challenge = null;
241 var auth_header = request.Headers ["Proxy-Authorization"];
242 bool have_auth = auth_header != null;
243 if (have_auth) {
244 sb.Append ("\r\nProxy-Authorization: ");
245 sb.Append (auth_header);
246 ntlm = auth_header.ToUpper ().Contains ("NTLM");
247 } else if (challenge != null && Data.StatusCode == 407) {
248 ICredentials creds = request.Proxy.Credentials;
249 have_auth = true;
251 if (connect_request == null) {
252 // create a CONNECT request to use with Authenticate
253 connect_request = (HttpWebRequest)WebRequest.Create (
254 connectUri.Scheme + "://" + connectUri.Host + ":" + connectUri.Port + "/");
255 connect_request.Method = "CONNECT";
256 connect_request.Credentials = creds;
259 if (creds != null) {
260 for (int i = 0; i < challenge.Length; i++) {
261 var auth = AuthenticationManager.Authenticate (challenge [i], connect_request, creds);
262 if (auth == null)
263 continue;
264 ntlm = (auth.ModuleAuthenticationType == "NTLM");
265 sb.Append ("\r\nProxy-Authorization: ");
266 sb.Append (auth.Message);
267 break;
272 if (ntlm) {
273 sb.Append ("\r\nProxy-Connection: keep-alive");
274 connect_ntlm_auth_state++;
277 sb.Append ("\r\n\r\n");
279 Data.StatusCode = 0;
280 byte [] connectBytes = Encoding.Default.GetBytes (sb.ToString ());
281 stream.Write (connectBytes, 0, connectBytes.Length);
283 int status;
284 WebHeaderCollection result = ReadHeaders (stream, out buffer, out status);
285 if ((!have_auth || connect_ntlm_auth_state == NtlmAuthState.Challenge) &&
286 result != null && status == 407) { // Needs proxy auth
287 var connectionHeader = result ["Connection"];
288 if (socket != null && !string.IsNullOrEmpty (connectionHeader) &&
289 connectionHeader.ToLower() == "close") {
290 // The server is requesting that this connection be closed
291 socket.Close();
292 socket = null;
295 Data.StatusCode = status;
296 Data.Challenge = result.GetValues ("Proxy-Authenticate");
297 Data.Headers = result;
298 return false;
301 if (status != 200) {
302 Data.StatusCode = status;
303 Data.Headers = result;
304 return false;
307 return (result != null);
310 WebHeaderCollection ReadHeaders (Stream stream, out byte [] retBuffer, out int status)
312 retBuffer = null;
313 status = 200;
315 byte [] buffer = new byte [1024];
316 MemoryStream ms = new MemoryStream ();
318 while (true) {
319 int n = stream.Read (buffer, 0, 1024);
320 if (n == 0) {
321 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders");
322 return null;
325 ms.Write (buffer, 0, n);
326 int start = 0;
327 string str = null;
328 bool gotStatus = false;
329 WebHeaderCollection headers = new WebHeaderCollection ();
330 while (ReadLine (ms.GetBuffer (), ref start, (int) ms.Length, ref str)) {
331 if (str == null) {
332 int contentLen = 0;
333 try {
334 contentLen = int.Parse(headers["Content-Length"]);
336 catch {
337 contentLen = 0;
340 if (ms.Length - start - contentLen > 0) {
341 // we've read more data than the response header and conents,
342 // give back extra data to the caller
343 retBuffer = new byte[ms.Length - start - contentLen];
344 Buffer.BlockCopy(ms.GetBuffer(), start + contentLen, retBuffer, 0, retBuffer.Length);
346 else {
347 // haven't read in some or all of the contents for the response, do so now
348 FlushContents(stream, contentLen - (int)(ms.Length - start));
351 return headers;
354 if (gotStatus) {
355 headers.Add (str);
356 continue;
359 string[] parts = str.Split (' ');
360 if (parts.Length < 2) {
361 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
362 return null;
365 if (String.Compare (parts [0], "HTTP/1.1", true) == 0)
366 Data.ProxyVersion = HttpVersion.Version11;
367 else if (String.Compare (parts [0], "HTTP/1.0", true) == 0)
368 Data.ProxyVersion = HttpVersion.Version10;
369 else {
370 HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadHeaders2");
371 return null;
374 status = (int)UInt32.Parse (parts [1]);
375 if (parts.Length >= 3)
376 Data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
378 gotStatus = true;
383 void FlushContents(Stream stream, int contentLength)
385 while (contentLength > 0) {
386 byte[] contentBuffer = new byte[contentLength];
387 int bytesRead = stream.Read(contentBuffer, 0, contentLength);
388 if (bytesRead > 0) {
389 contentLength -= bytesRead;
391 else {
392 break;
397 bool CreateStream (HttpWebRequest request)
399 try {
400 NetworkStream serverStream = new NetworkStream (socket, false);
402 if (request.Address.Scheme == Uri.UriSchemeHttps) {
403 #if SECURITY_DEP
404 if (!reused || nstream == null || tlsStream == null) {
405 byte [] buffer = null;
406 if (sPoint.UseConnect) {
407 bool ok = CreateTunnel (request, sPoint.Address, serverStream, out buffer);
408 if (!ok)
409 return false;
411 tlsStream = new MonoTlsStream (request, serverStream);
412 nstream = tlsStream.CreateStream (buffer);
414 // we also need to set ServicePoint.Certificate
415 // and ServicePoint.ClientCertificate but this can
416 // only be done later (after handshake - which is
417 // done only after a read operation).
418 #else
419 throw new NotSupportedException ();
420 #endif
421 } else {
422 nstream = serverStream;
424 } catch (Exception ex) {
425 if (tlsStream != null)
426 status = tlsStream.ExceptionStatus;
427 else if (!request.Aborted)
428 status = WebExceptionStatus.ConnectFailure;
429 connect_exception = ex;
430 return false;
433 return true;
436 void HandleError (WebExceptionStatus st, Exception e, string where)
438 status = st;
439 lock (this) {
440 if (st == WebExceptionStatus.RequestCanceled)
441 Data = new WebConnectionData ();
444 if (e == null) { // At least we now where it comes from
445 try {
446 throw new Exception (new System.Diagnostics.StackTrace ().ToString ());
447 } catch (Exception e2) {
448 e = e2;
452 HttpWebRequest req = null;
453 if (Data != null && Data.request != null)
454 req = Data.request;
456 Close (true);
457 if (req != null) {
458 req.FinishedReading = true;
459 req.SetResponseError (st, e, where);
463 static void ReadDone (IAsyncResult result)
465 WebConnection cnc = (WebConnection)result.AsyncState;
466 WebConnectionData data = cnc.Data;
467 Stream ns = cnc.nstream;
468 if (ns == null) {
469 cnc.Close (true);
470 return;
473 int nread = -1;
474 try {
475 nread = ns.EndRead (result);
476 } catch (ObjectDisposedException) {
477 return;
478 } catch (Exception e) {
479 if (e.InnerException is ObjectDisposedException)
480 return;
482 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone1");
483 return;
486 if (nread == 0) {
487 cnc.HandleError (WebExceptionStatus.ReceiveFailure, null, "ReadDone2");
488 return;
491 if (nread < 0) {
492 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, null, "ReadDone3");
493 return;
496 int pos = -1;
497 nread += cnc.position;
498 if (data.ReadState == ReadState.None) {
499 Exception exc = null;
500 try {
501 pos = GetResponse (data, cnc.sPoint, cnc.buffer, nread);
502 } catch (Exception e) {
503 exc = e;
506 if (exc != null || pos == -1) {
507 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, exc, "ReadDone4");
508 return;
512 if (data.ReadState == ReadState.Aborted) {
513 cnc.HandleError (WebExceptionStatus.RequestCanceled, null, "ReadDone");
514 return;
517 if (data.ReadState != ReadState.Content) {
518 int est = nread * 2;
519 int max = (est < cnc.buffer.Length) ? cnc.buffer.Length : est;
520 byte [] newBuffer = new byte [max];
521 Buffer.BlockCopy (cnc.buffer, 0, newBuffer, 0, nread);
522 cnc.buffer = newBuffer;
523 cnc.position = nread;
524 data.ReadState = ReadState.None;
525 InitRead (cnc);
526 return;
529 cnc.position = 0;
531 WebConnectionStream stream = new WebConnectionStream (cnc, data);
532 bool expect_content = ExpectContent (data.StatusCode, data.request.Method);
533 string tencoding = null;
534 if (expect_content)
535 tencoding = data.Headers ["Transfer-Encoding"];
537 cnc.chunkedRead = (tencoding != null && tencoding.IndexOf ("chunked", StringComparison.OrdinalIgnoreCase) != -1);
538 if (!cnc.chunkedRead) {
539 stream.ReadBuffer = cnc.buffer;
540 stream.ReadBufferOffset = pos;
541 stream.ReadBufferSize = nread;
542 try {
543 stream.CheckResponseInBuffer ();
544 } catch (Exception e) {
545 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "ReadDone7");
547 } else if (cnc.chunkStream == null) {
548 try {
549 cnc.chunkStream = new ChunkStream (cnc.buffer, pos, nread, data.Headers);
550 } catch (Exception e) {
551 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone5");
552 return;
554 } else {
555 cnc.chunkStream.ResetBuffer ();
556 try {
557 cnc.chunkStream.Write (cnc.buffer, pos, nread);
558 } catch (Exception e) {
559 cnc.HandleError (WebExceptionStatus.ServerProtocolViolation, e, "ReadDone6");
560 return;
564 data.stream = stream;
566 if (!expect_content)
567 stream.ForceCompletion ();
569 data.request.SetResponseData (data);
572 static bool ExpectContent (int statusCode, string method)
574 if (method == "HEAD")
575 return false;
576 return (statusCode >= 200 && statusCode != 204 && statusCode != 304);
579 internal static void InitRead (object state)
581 WebConnection cnc = (WebConnection) state;
582 Stream ns = cnc.nstream;
584 try {
585 int size = cnc.buffer.Length - cnc.position;
586 ns.BeginRead (cnc.buffer, cnc.position, size, readDoneDelegate, cnc);
587 } catch (Exception e) {
588 cnc.HandleError (WebExceptionStatus.ReceiveFailure, e, "InitRead");
592 static int GetResponse (WebConnectionData data, ServicePoint sPoint,
593 byte [] buffer, int max)
595 int pos = 0;
596 string line = null;
597 bool lineok = false;
598 bool isContinue = false;
599 bool emptyFirstLine = false;
600 do {
601 if (data.ReadState == ReadState.Aborted)
602 return -1;
604 if (data.ReadState == ReadState.None) {
605 lineok = ReadLine (buffer, ref pos, max, ref line);
606 if (!lineok)
607 return 0;
609 if (line == null) {
610 emptyFirstLine = true;
611 continue;
613 emptyFirstLine = false;
614 data.ReadState = ReadState.Status;
616 string [] parts = line.Split (' ');
617 if (parts.Length < 2)
618 return -1;
620 if (String.Compare (parts [0], "HTTP/1.1", true) == 0) {
621 data.Version = HttpVersion.Version11;
622 sPoint.SetVersion (HttpVersion.Version11);
623 } else {
624 data.Version = HttpVersion.Version10;
625 sPoint.SetVersion (HttpVersion.Version10);
628 data.StatusCode = (int) UInt32.Parse (parts [1]);
629 if (parts.Length >= 3)
630 data.StatusDescription = String.Join (" ", parts, 2, parts.Length - 2);
631 else
632 data.StatusDescription = "";
634 if (pos >= max)
635 return pos;
638 emptyFirstLine = false;
639 if (data.ReadState == ReadState.Status) {
640 data.ReadState = ReadState.Headers;
641 data.Headers = new WebHeaderCollection ();
642 ArrayList headers = new ArrayList ();
643 bool finished = false;
644 while (!finished) {
645 if (ReadLine (buffer, ref pos, max, ref line) == false)
646 break;
648 if (line == null) {
649 // Empty line: end of headers
650 finished = true;
651 continue;
654 if (line.Length > 0 && (line [0] == ' ' || line [0] == '\t')) {
655 int count = headers.Count - 1;
656 if (count < 0)
657 break;
659 string prev = (string) headers [count] + line;
660 headers [count] = prev;
661 } else {
662 headers.Add (line);
666 if (!finished)
667 return 0;
669 // .NET uses ParseHeaders or ParseHeadersStrict which is much better
670 foreach (string s in headers) {
672 int pos_s = s.IndexOf (':');
673 if (pos_s == -1)
674 throw new ArgumentException ("no colon found", "header");
676 var header = s.Substring (0, pos_s);
677 var value = s.Substring (pos_s + 1).Trim ();
679 var h = data.Headers;
680 if (WebHeaderCollection.AllowMultiValues (header)) {
681 h.AddInternal (header, value);
682 } else {
683 h.SetInternal (header, value);
687 if (data.StatusCode == (int) HttpStatusCode.Continue) {
688 sPoint.SendContinue = true;
689 if (pos >= max)
690 return pos;
692 if (data.request.ExpectContinue) {
693 data.request.DoContinueDelegate (data.StatusCode, data.Headers);
694 // Prevent double calls when getting the
695 // headers in several packets.
696 data.request.ExpectContinue = false;
699 data.ReadState = ReadState.None;
700 isContinue = true;
702 else {
703 data.ReadState = ReadState.Content;
704 return pos;
707 } while (emptyFirstLine || isContinue);
709 return -1;
712 void InitConnection (object state)
714 HttpWebRequest request = (HttpWebRequest) state;
715 request.WebConnection = this;
716 if (request.ReuseConnection)
717 request.StoredConnection = this;
719 if (request.Aborted)
720 return;
722 keepAlive = request.KeepAlive;
723 Data = new WebConnectionData (request);
724 retry:
725 Connect (request);
726 if (request.Aborted)
727 return;
729 if (status != WebExceptionStatus.Success) {
730 if (!request.Aborted) {
731 request.SetWriteStreamError (status, connect_exception);
732 Close (true);
734 return;
737 if (!CreateStream (request)) {
738 if (request.Aborted)
739 return;
741 WebExceptionStatus st = status;
742 if (Data.Challenge != null)
743 goto retry;
745 Exception cnc_exc = connect_exception;
746 if (cnc_exc == null && (Data.StatusCode == 401 || Data.StatusCode == 407)) {
747 st = WebExceptionStatus.ProtocolError;
748 if (Data.Headers == null)
749 Data.Headers = new WebHeaderCollection ();
751 var webResponse = new HttpWebResponse (sPoint.Address, "CONNECT", Data, null);
752 cnc_exc = new WebException (Data.StatusCode == 407 ? "(407) Proxy Authentication Required" : "(401) Unauthorized", null, st, webResponse);
755 connect_exception = null;
756 request.SetWriteStreamError (st, cnc_exc);
757 Close (true);
758 return;
761 request.SetWriteStream (new WebConnectionStream (this, request));
764 #if MONOTOUCH
765 static bool warned_about_queue = false;
766 #endif
768 internal EventHandler SendRequest (HttpWebRequest request)
770 if (request.Aborted)
771 return null;
773 lock (this) {
774 if (state.TrySetBusy ()) {
775 status = WebExceptionStatus.Success;
776 ThreadPool.QueueUserWorkItem (initConn, request);
777 } else {
778 lock (queue) {
779 #if MONOTOUCH
780 if (!warned_about_queue) {
781 warned_about_queue = true;
782 Console.WriteLine ("WARNING: An HttpWebRequest was added to the ConnectionGroup queue because the connection limit was reached.");
784 #endif
785 queue.Enqueue (request);
790 return abortHandler;
793 void SendNext ()
795 lock (queue) {
796 if (queue.Count > 0) {
797 SendRequest ((HttpWebRequest) queue.Dequeue ());
802 internal void NextRead ()
804 lock (this) {
805 if (Data.request != null)
806 Data.request.FinishedReading = true;
807 string header = (sPoint.UsesProxy) ? "Proxy-Connection" : "Connection";
808 string cncHeader = (Data.Headers != null) ? Data.Headers [header] : null;
809 bool keepAlive = (Data.Version == HttpVersion.Version11 && this.keepAlive);
810 if (Data.ProxyVersion != null && Data.ProxyVersion != HttpVersion.Version11)
811 keepAlive = false;
812 if (cncHeader != null) {
813 cncHeader = cncHeader.ToLower ();
814 keepAlive = (this.keepAlive && cncHeader.IndexOf ("keep-alive", StringComparison.Ordinal) != -1);
817 if ((socket != null && !socket.Connected) ||
818 (!keepAlive || (cncHeader != null && cncHeader.IndexOf ("close", StringComparison.Ordinal) != -1))) {
819 Close (false);
822 state.SetIdle ();
823 if (priority_request != null) {
824 SendRequest (priority_request);
825 priority_request = null;
826 } else {
827 SendNext ();
832 static bool ReadLine (byte [] buffer, ref int start, int max, ref string output)
834 bool foundCR = false;
835 StringBuilder text = new StringBuilder ();
837 int c = 0;
838 while (start < max) {
839 c = (int) buffer [start++];
841 if (c == '\n') { // newline
842 if ((text.Length > 0) && (text [text.Length - 1] == '\r'))
843 text.Length--;
845 foundCR = false;
846 break;
847 } else if (foundCR) {
848 text.Length--;
849 break;
852 if (c == '\r')
853 foundCR = true;
856 text.Append ((char) c);
859 if (c != '\n' && c != '\r')
860 return false;
862 if (text.Length == 0) {
863 output = null;
864 return (c == '\n' || c == '\r');
867 if (foundCR)
868 text.Length--;
870 output = text.ToString ();
871 return true;
875 internal IAsyncResult BeginRead (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
877 Stream s = null;
878 lock (this) {
879 if (Data.request != request)
880 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
881 if (nstream == null)
882 return null;
883 s = nstream;
886 IAsyncResult result = null;
887 if (!chunkedRead || (!chunkStream.DataAvailable && chunkStream.WantMore)) {
888 try {
889 result = s.BeginRead (buffer, offset, size, cb, state);
890 cb = null;
891 } catch (Exception) {
892 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked BeginRead");
893 throw;
897 if (chunkedRead) {
898 WebAsyncResult wr = new WebAsyncResult (cb, state, buffer, offset, size);
899 wr.InnerAsyncResult = result;
900 if (result == null) {
901 // Will be completed from the data in ChunkStream
902 wr.SetCompleted (true, (Exception) null);
903 wr.DoCallback ();
905 return wr;
908 return result;
911 internal int EndRead (HttpWebRequest request, IAsyncResult result)
913 Stream s = null;
914 lock (this) {
915 if (request.Aborted)
916 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
917 if (Data.request != request)
918 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
919 if (nstream == null)
920 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
921 s = nstream;
924 int nbytes = 0;
925 bool done = false;
926 WebAsyncResult wr = null;
927 IAsyncResult nsAsync = ((WebAsyncResult) result).InnerAsyncResult;
928 if (chunkedRead && (nsAsync is WebAsyncResult)) {
929 wr = (WebAsyncResult) nsAsync;
930 IAsyncResult inner = wr.InnerAsyncResult;
931 if (inner != null && !(inner is WebAsyncResult)) {
932 nbytes = s.EndRead (inner);
933 done = nbytes == 0;
935 } else if (!(nsAsync is WebAsyncResult)) {
936 nbytes = s.EndRead (nsAsync);
937 wr = (WebAsyncResult) result;
938 done = nbytes == 0;
941 if (chunkedRead) {
942 try {
943 chunkStream.WriteAndReadBack (wr.Buffer, wr.Offset, wr.Size, ref nbytes);
944 if (!done && nbytes == 0 && chunkStream.WantMore)
945 nbytes = EnsureRead (wr.Buffer, wr.Offset, wr.Size);
946 } catch (Exception e) {
947 if (e is WebException)
948 throw e;
950 throw new WebException ("Invalid chunked data.", e,
951 WebExceptionStatus.ServerProtocolViolation, null);
954 if ((done || nbytes == 0) && chunkStream.ChunkLeft != 0) {
955 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked EndRead");
956 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
960 return (nbytes != 0) ? nbytes : -1;
963 // To be called on chunkedRead when we can read no data from the ChunkStream yet
964 int EnsureRead (byte [] buffer, int offset, int size)
966 byte [] morebytes = null;
967 int nbytes = 0;
968 while (nbytes == 0 && chunkStream.WantMore) {
969 int localsize = chunkStream.ChunkLeft;
970 if (localsize <= 0) // not read chunk size yet
971 localsize = 1024;
972 else if (localsize > 16384)
973 localsize = 16384;
975 if (morebytes == null || morebytes.Length < localsize)
976 morebytes = new byte [localsize];
978 int nread = nstream.Read (morebytes, 0, localsize);
979 if (nread <= 0)
980 return 0; // Error
982 chunkStream.Write (morebytes, 0, nread);
983 nbytes += chunkStream.Read (buffer, offset + nbytes, size - nbytes);
986 return nbytes;
989 bool CompleteChunkedRead()
991 if (!chunkedRead || chunkStream == null)
992 return true;
994 while (chunkStream.WantMore) {
995 int nbytes = nstream.Read (buffer, 0, buffer.Length);
996 if (nbytes <= 0)
997 return false; // Socket was disconnected
999 chunkStream.Write (buffer, 0, nbytes);
1002 return true;
1005 internal IAsyncResult BeginWrite (HttpWebRequest request, byte [] buffer, int offset, int size, AsyncCallback cb, object state)
1007 Stream s = null;
1008 lock (this) {
1009 if (Data.request != request)
1010 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1011 if (nstream == null)
1012 return null;
1013 s = nstream;
1016 IAsyncResult result = null;
1017 try {
1018 result = s.BeginWrite (buffer, offset, size, cb, state);
1019 } catch (ObjectDisposedException) {
1020 lock (this) {
1021 if (Data.request != request)
1022 return null;
1024 throw;
1025 } catch (IOException e) {
1026 SocketException se = e.InnerException as SocketException;
1027 if (se != null && se.SocketErrorCode == SocketError.NotConnected) {
1028 return null;
1030 throw;
1031 } catch (Exception) {
1032 status = WebExceptionStatus.SendFailure;
1033 throw;
1036 return result;
1039 internal bool EndWrite (HttpWebRequest request, bool throwOnError, IAsyncResult result)
1041 Stream s = null;
1042 lock (this) {
1043 if (status == WebExceptionStatus.RequestCanceled)
1044 return true;
1045 if (Data.request != request)
1046 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1047 if (nstream == null)
1048 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1049 s = nstream;
1052 try {
1053 s.EndWrite (result);
1054 return true;
1055 } catch (Exception exc) {
1056 status = WebExceptionStatus.SendFailure;
1057 if (throwOnError && exc.InnerException != null)
1058 throw exc.InnerException;
1059 return false;
1063 internal int Read (HttpWebRequest request, byte [] buffer, int offset, int size)
1065 Stream s = null;
1066 lock (this) {
1067 if (Data.request != request)
1068 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1069 if (nstream == null)
1070 return 0;
1071 s = nstream;
1074 int result = 0;
1075 try {
1076 bool done = false;
1077 if (!chunkedRead) {
1078 result = s.Read (buffer, offset, size);
1079 done = (result == 0);
1082 if (chunkedRead) {
1083 try {
1084 chunkStream.WriteAndReadBack (buffer, offset, size, ref result);
1085 if (!done && result == 0 && chunkStream.WantMore)
1086 result = EnsureRead (buffer, offset, size);
1087 } catch (Exception e) {
1088 HandleError (WebExceptionStatus.ReceiveFailure, e, "chunked Read1");
1089 throw;
1092 if ((done || result == 0) && chunkStream.WantMore) {
1093 HandleError (WebExceptionStatus.ReceiveFailure, null, "chunked Read2");
1094 throw new WebException ("Read error", null, WebExceptionStatus.ReceiveFailure, null);
1097 } catch (Exception e) {
1098 HandleError (WebExceptionStatus.ReceiveFailure, e, "Read");
1101 return result;
1104 internal bool Write (HttpWebRequest request, byte [] buffer, int offset, int size, ref string err_msg)
1106 err_msg = null;
1107 Stream s = null;
1108 lock (this) {
1109 if (Data.request != request)
1110 throw new ObjectDisposedException (typeof (NetworkStream).FullName);
1111 s = nstream;
1112 if (s == null)
1113 return false;
1116 try {
1117 s.Write (buffer, offset, size);
1118 } catch (Exception e) {
1119 err_msg = e.Message;
1120 WebExceptionStatus wes = WebExceptionStatus.SendFailure;
1121 string msg = "Write: " + err_msg;
1122 if (e is WebException) {
1123 HandleError (wes, e, msg);
1124 return false;
1127 HandleError (wes, e, msg);
1128 return false;
1130 return true;
1133 internal void Close (bool sendNext)
1135 lock (this) {
1136 if (Data != null && Data.request != null && Data.request.ReuseConnection) {
1137 Data.request.ReuseConnection = false;
1138 return;
1141 if (nstream != null) {
1142 try {
1143 nstream.Close ();
1144 } catch {}
1145 nstream = null;
1148 if (socket != null) {
1149 try {
1150 socket.Close ();
1151 } catch {}
1152 socket = null;
1155 if (ntlm_authenticated)
1156 ResetNtlm ();
1157 if (Data != null) {
1158 lock (Data) {
1159 Data.ReadState = ReadState.Aborted;
1162 state.SetIdle ();
1163 Data = new WebConnectionData ();
1164 if (sendNext)
1165 SendNext ();
1167 connect_request = null;
1168 connect_ntlm_auth_state = NtlmAuthState.None;
1172 void Abort (object sender, EventArgs args)
1174 lock (this) {
1175 lock (queue) {
1176 HttpWebRequest req = (HttpWebRequest) sender;
1177 if (Data.request == req || Data.request == null) {
1178 if (!req.FinishedReading) {
1179 status = WebExceptionStatus.RequestCanceled;
1180 Close (false);
1181 if (queue.Count > 0) {
1182 Data.request = (HttpWebRequest) queue.Dequeue ();
1183 SendRequest (Data.request);
1186 return;
1189 req.FinishedReading = true;
1190 req.SetResponseError (WebExceptionStatus.RequestCanceled, null, "User aborted");
1191 if (queue.Count > 0 && queue.Peek () == sender) {
1192 queue.Dequeue ();
1193 } else if (queue.Count > 0) {
1194 object [] old = queue.ToArray ();
1195 queue.Clear ();
1196 for (int i = old.Length - 1; i >= 0; i--) {
1197 if (old [i] != sender)
1198 queue.Enqueue (old [i]);
1205 internal void ResetNtlm ()
1207 ntlm_authenticated = false;
1208 ntlm_credentials = null;
1209 unsafe_sharing = false;
1212 internal bool Connected {
1213 get {
1214 lock (this) {
1215 return (socket != null && socket.Connected);
1220 // -Used for NTLM authentication
1221 internal HttpWebRequest PriorityRequest {
1222 set { priority_request = value; }
1225 internal bool NtlmAuthenticated {
1226 get { return ntlm_authenticated; }
1227 set { ntlm_authenticated = value; }
1230 internal NetworkCredential NtlmCredential {
1231 get { return ntlm_credentials; }
1232 set { ntlm_credentials = value; }
1235 internal bool UnsafeAuthenticatedConnectionSharing {
1236 get { return unsafe_sharing; }
1237 set { unsafe_sharing = value; }
1239 // -