Added tests for Task.WhenAll w/ empty list
[mono.git] / mcs / class / System / System.Net / HttpWebRequest.cs
1 //
2 // System.Net.HttpWebRequest
3 //
4 // Authors:
5 //      Lawrence Pit (loz@cable.a2000.nl)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // (c) 2002 Lawrence Pit
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 // (c) 2004 Novell, Inc. (http://www.novell.com)
11 //
12
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 using System;
35 using System.Collections;
36 using System.Configuration;
37 using System.Globalization;
38 using System.IO;
39 using System.Net.Cache;
40 using System.Net.Sockets;
41 using System.Runtime.Remoting.Messaging;
42 using System.Runtime.Serialization;
43 using System.Security.Cryptography.X509Certificates;
44 using System.Text;
45 using System.Threading;
46
47 namespace System.Net 
48 {
49         [Serializable]
50         public class HttpWebRequest : WebRequest, ISerializable {
51                 Uri requestUri;
52                 Uri actualUri;
53                 bool hostChanged;
54                 bool allowAutoRedirect = true;
55                 bool allowBuffering = true;
56                 X509CertificateCollection certificates;
57                 string connectionGroup;
58                 long contentLength = -1;
59                 HttpContinueDelegate continueDelegate;
60                 CookieContainer cookieContainer;
61                 ICredentials credentials;
62                 bool haveResponse;              
63                 bool haveRequest;
64                 bool requestSent;
65                 WebHeaderCollection webHeaders;
66                 bool keepAlive = true;
67                 int maxAutoRedirect = 50;
68                 string mediaType = String.Empty;
69                 string method = "GET";
70                 string initialMethod = "GET";
71                 bool pipelined = true;
72                 bool preAuthenticate;
73                 bool usedPreAuth;
74                 Version version = HttpVersion.Version11;
75                 bool force_version;
76                 Version actualVersion;
77                 IWebProxy proxy;
78                 bool sendChunked;
79                 ServicePoint servicePoint;
80                 int timeout = 100000;
81                 
82                 WebConnectionStream writeStream;
83                 HttpWebResponse webResponse;
84                 WebAsyncResult asyncWrite;
85                 WebAsyncResult asyncRead;
86                 EventHandler abortHandler;
87                 int aborted;
88                 bool gotRequestStream;
89                 int redirects;
90                 bool expectContinue;
91                 bool authCompleted;
92                 byte[] bodyBuffer;
93                 int bodyBufferLength;
94                 bool getResponseCalled;
95                 Exception saved_exc;
96                 object locker = new object ();
97                 bool finished_reading;
98                 internal WebConnection WebConnection;
99                 DecompressionMethods auto_decomp;
100                 int maxResponseHeadersLength;
101                 static int defaultMaxResponseHeadersLength;
102                 int readWriteTimeout = 300000; // ms
103
104                 enum NtlmAuthState {
105                         None,
106                         Challenge,
107                         Response
108                 }
109                 NtlmAuthState ntlm_auth_state;
110                 string host;
111
112                 // Constructors
113                 static HttpWebRequest ()
114                 {
115                         defaultMaxResponseHeadersLength = 64 * 1024;
116 #if !NET_2_1
117                         NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
118                         if (config != null) {
119                                 int x = config.MaxResponseHeadersLength;
120                                 if (x != -1)
121                                         x *= 64;
122
123                                 defaultMaxResponseHeadersLength = x;
124                         }
125 #endif
126                 }
127
128 #if NET_2_1
129                 public
130 #else
131                 internal
132 #endif
133                 HttpWebRequest (Uri uri) 
134                 {
135                         this.requestUri = uri;
136                         this.actualUri = uri;
137                         this.proxy = GlobalProxySelection.Select;
138                         this.webHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
139                         ThrowOnError = true;
140                 }
141                 
142                 [Obsolete ("Serialization is obsoleted for this type", false)]
143                 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext) 
144                 {
145                         SerializationInfo info = serializationInfo;
146
147                         requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
148                         actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
149                         allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
150                         allowBuffering = info.GetBoolean ("allowBuffering");
151                         certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
152                         connectionGroup = info.GetString ("connectionGroup");
153                         contentLength = info.GetInt64 ("contentLength");
154                         webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
155                         keepAlive = info.GetBoolean ("keepAlive");
156                         maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
157                         mediaType = info.GetString ("mediaType");
158                         method = info.GetString ("method");
159                         initialMethod = info.GetString ("initialMethod");
160                         pipelined = info.GetBoolean ("pipelined");
161                         version = (Version) info.GetValue ("version", typeof (Version));
162                         proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
163                         sendChunked = info.GetBoolean ("sendChunked");
164                         timeout = info.GetInt32 ("timeout");
165                         redirects = info.GetInt32 ("redirects");
166                         host = info.GetString ("host");
167                 }
168                 
169                 // Properties
170
171                 public string Accept {
172                         get { return webHeaders ["Accept"]; }
173                         set {
174                                 CheckRequestStarted ();
175                                 webHeaders.RemoveAndAdd ("Accept", value);
176                         }
177                 }
178                 
179                 public Uri Address {
180                         get { return actualUri; }
181                         internal set { actualUri = value; } // Used by Ftp+proxy
182                 }
183                 
184                 public bool AllowAutoRedirect {
185                         get { return allowAutoRedirect; }
186                         set { this.allowAutoRedirect = value; }
187                 }
188                 
189                 public bool AllowWriteStreamBuffering {
190                         get { return allowBuffering; }
191                         set { allowBuffering = value; }
192                 }
193                 
194 #if NET_4_5
195                 public virtual bool AllowReadStreamBuffering {
196                         get { return allowBuffering; }
197                         set { allowBuffering = value; }
198                 }
199 #endif
200
201                 static Exception GetMustImplement ()
202                 {
203                         return new NotImplementedException ();
204                 }
205                 
206                 public DecompressionMethods AutomaticDecompression
207                 {
208                         get {
209                                 return auto_decomp;
210                         }
211                         set {
212                                 CheckRequestStarted ();
213                                 auto_decomp = value;
214                         }
215                 }
216                 
217                 internal bool InternalAllowBuffering {
218                         get {
219                                 return (allowBuffering && (method != "HEAD" && method != "GET" &&
220                                                         method != "MKCOL" && method != "CONNECT" &&
221                                                         method != "TRACE"));
222                         }
223                 }
224                 
225                 public X509CertificateCollection ClientCertificates {
226                         get {
227                                 if (certificates == null)
228                                         certificates = new X509CertificateCollection ();
229
230                                 return certificates;
231                         }
232                         [MonoTODO]
233                         set {
234                                 throw GetMustImplement ();
235                         }
236                 }
237                 
238                 public string Connection {
239                         get { return webHeaders ["Connection"]; }
240                         set {
241                                 CheckRequestStarted ();
242
243                                 if (string.IsNullOrEmpty (value)) {
244                                         webHeaders.RemoveInternal ("Connection");
245                                         return;
246                                 }
247
248                                 string val = value.ToLowerInvariant ();
249                                 if (val.Contains ("keep-alive") || val.Contains ("close"))
250                                         throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
251
252                                 if (keepAlive)
253                                         value = value + ", Keep-Alive";
254                                 
255                                 webHeaders.RemoveAndAdd ("Connection", value);
256                         }
257                 }               
258                 
259                 public override string ConnectionGroupName { 
260                         get { return connectionGroup; }
261                         set { connectionGroup = value; }
262                 }
263                 
264                 public override long ContentLength { 
265                         get { return contentLength; }
266                         set { 
267                                 CheckRequestStarted ();
268                                 if (value < 0)
269                                         throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
270                                         
271                                 contentLength = value;
272                         }
273                 }
274                 
275                 internal long InternalContentLength {
276                         set { contentLength = value; }
277                 }
278                         
279                 internal bool ThrowOnError { get; set; }
280                 
281                 public override string ContentType { 
282                         get { return webHeaders ["Content-Type"]; }
283                         set {
284                                 if (value == null || value.Trim().Length == 0) {
285                                         webHeaders.RemoveInternal ("Content-Type");
286                                         return;
287                                 }
288                                 webHeaders.RemoveAndAdd ("Content-Type", value);
289                         }
290                 }
291                 
292                 public HttpContinueDelegate ContinueDelegate {
293                         get { return continueDelegate; }
294                         set { continueDelegate = value; }
295                 }
296                 
297 #if NET_4_5
298                 virtual
299 #endif
300                 public CookieContainer CookieContainer {
301                         get { return cookieContainer; }
302                         set { cookieContainer = value; }
303                 }
304                 
305                 public override ICredentials Credentials { 
306                         get { return credentials; }
307                         set { credentials = value; }
308                 }
309 #if NET_4_0
310                 public DateTime Date {
311                         get {
312                                 string date = webHeaders ["Date"];
313                                 if (date == null)
314                                         return DateTime.MinValue;
315                                 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
316                         }
317                         set {
318                                 if (value.Equals (DateTime.MinValue))
319                                         webHeaders.RemoveInternal ("Date");
320                                 else
321                                         webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
322                         }
323                 }
324 #endif
325
326 #if !NET_2_1
327                 [MonoTODO]
328                 public static new RequestCachePolicy DefaultCachePolicy
329                 {
330                         get {
331                                 throw GetMustImplement ();
332                         }
333                         set {
334                                 throw GetMustImplement ();
335                         }
336                 }
337 #endif
338                 
339                 [MonoTODO]
340                 public static int DefaultMaximumErrorResponseLength
341                 {
342                         get {
343                                 throw GetMustImplement ();
344                         }
345                         set {
346                                 throw GetMustImplement ();
347                         }
348                 }
349                 
350                 public string Expect {
351                         get { return webHeaders ["Expect"]; }
352                         set {
353                                 CheckRequestStarted ();
354                                 string val = value;
355                                 if (val != null)
356                                         val = val.Trim ().ToLower ();
357
358                                 if (val == null || val.Length == 0) {
359                                         webHeaders.RemoveInternal ("Expect");
360                                         return;
361                                 }
362
363                                 if (val == "100-continue")
364                                         throw new ArgumentException ("100-Continue cannot be set with this property.",
365                                                                      "value");
366                                 webHeaders.RemoveAndAdd ("Expect", value);
367                         }
368                 }
369                 
370 #if NET_4_5
371                 virtual
372 #endif
373                 public bool HaveResponse {
374                         get { return haveResponse; }
375                 }
376                 
377                 public override WebHeaderCollection Headers { 
378                         get { return webHeaders; }
379                         set {
380                                 CheckRequestStarted ();
381                                 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
382                                 int count = value.Count;
383                                 for (int i = 0; i < count; i++) 
384                                         newHeaders.Add (value.GetKey (i), value.Get (i));
385
386                                 webHeaders = newHeaders;
387                         }
388                 }
389                 
390 #if NET_4_0
391                 public
392 #else
393                 internal
394 #endif
395                 string Host {
396                         get {
397                                 if (host == null)
398                                         return actualUri.Authority;
399                                 return host;
400                         }
401                         set {
402                                 if (value == null)
403                                         throw new ArgumentNullException ("value");
404
405                                 if (!CheckValidHost (actualUri.Scheme, value))
406                                         throw new ArgumentException ("Invalid host: " + value);
407
408                                 host = value;
409                         }
410                 }
411
412                 static bool CheckValidHost (string scheme, string val)
413                 {
414                         if (val.Length == 0)
415                                 return false;
416
417                         if (val [0] == '.')
418                                 return false;
419
420                         int idx = val.IndexOf ('/');
421                         if (idx >= 0)
422                                 return false;
423
424                         string u = scheme + "://" + val + "/";
425                         return Uri.IsWellFormedUriString (u, UriKind.Absolute);
426                 }
427
428                 public DateTime IfModifiedSince {
429                         get { 
430                                 string str = webHeaders ["If-Modified-Since"];
431                                 if (str == null)
432                                         return DateTime.Now;
433                                 try {
434                                         return MonoHttpDate.Parse (str);
435                                 } catch (Exception) {
436                                         return DateTime.Now;
437                                 }
438                         }
439                         set {
440                                 CheckRequestStarted ();
441                                 // rfc-1123 pattern
442                                 webHeaders.SetInternal ("If-Modified-Since", 
443                                         value.ToUniversalTime ().ToString ("r", null));
444                                 // TODO: check last param when using different locale
445                         }
446                 }
447
448                 public bool KeepAlive {         
449                         get {
450                                 return keepAlive;
451                         }
452                         set {
453                                 keepAlive = value;
454                         }
455                 }
456                 
457                 public int MaximumAutomaticRedirections {
458                         get { return maxAutoRedirect; }
459                         set {
460                                 if (value <= 0)
461                                         throw new ArgumentException ("Must be > 0", "value");
462
463                                 maxAutoRedirect = value;
464                         }                       
465                 }
466
467                 [MonoTODO ("Use this")]
468                 public int MaximumResponseHeadersLength {
469                         get { return maxResponseHeadersLength; }
470                         set { maxResponseHeadersLength = value; }
471                 }
472
473                 [MonoTODO ("Use this")]
474                 public static int DefaultMaximumResponseHeadersLength {
475                         get { return defaultMaxResponseHeadersLength; }
476                         set { defaultMaxResponseHeadersLength = value; }
477                 }
478
479                 public  int ReadWriteTimeout {
480                         get { return readWriteTimeout; }
481                         set {
482                                 if (requestSent)
483                                         throw new InvalidOperationException ("The request has already been sent.");
484
485                                 if (value < -1)
486                                         throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
487
488                                 readWriteTimeout = value;
489                         }
490                 }
491                 
492 #if NET_4_5
493                 [MonoTODO]
494                 public int ContinueTimeout {
495                         get { throw new NotImplementedException (); }
496                         set { throw new NotImplementedException (); }
497                 }
498 #endif
499                 
500                 public string MediaType {
501                         get { return mediaType; }
502                         set { 
503                                 mediaType = value;
504                         }
505                 }
506                 
507                 public override string Method { 
508                         get { return this.method; }
509                         set { 
510                                 if (value == null || value.Trim () == "")
511                                         throw new ArgumentException ("not a valid method");
512
513                                 method = value.ToUpperInvariant ();
514                                 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
515                                         method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
516                                         method != "MKCOL") {
517                                         method = value;
518                                 }
519                         }
520                 }
521                 
522                 public bool Pipelined {
523                         get { return pipelined; }
524                         set { pipelined = value; }
525                 }               
526                 
527                 public override bool PreAuthenticate { 
528                         get { return preAuthenticate; }
529                         set { preAuthenticate = value; }
530                 }
531                 
532                 public Version ProtocolVersion {
533                         get { return version; }
534                         set { 
535                                 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
536                                         throw new ArgumentException ("value");
537
538                                 force_version = true;
539                                 version = value; 
540                         }
541                 }
542                 
543                 public override IWebProxy Proxy { 
544                         get { return proxy; }
545                         set { 
546                                 CheckRequestStarted ();
547                                 proxy = value;
548                                 servicePoint = null; // we may need a new one
549                         }
550                 }
551                 
552                 public string Referer {
553                         get { return webHeaders ["Referer"]; }
554                         set {
555                                 CheckRequestStarted ();
556                                 if (value == null || value.Trim().Length == 0) {
557                                         webHeaders.RemoveInternal ("Referer");
558                                         return;
559                                 }
560                                 webHeaders.SetInternal ("Referer", value);
561                         }
562                 }
563
564                 public override Uri RequestUri { 
565                         get { return requestUri; }
566                 }
567                 
568                 public bool SendChunked {
569                         get { return sendChunked; }
570                         set {
571                                 CheckRequestStarted ();
572                                 sendChunked = value;
573                         }
574                 }
575                 
576                 public ServicePoint ServicePoint {
577                         get { return GetServicePoint (); }
578                 }
579
580                 internal ServicePoint ServicePointNoLock {
581                         get { return servicePoint; }
582                 }
583 #if NET_4_0
584                 [MonoTODO ("for portable library support")]
585                 public virtual bool SupportsCookieContainer { 
586                         get {
587                                 throw new NotImplementedException ();
588                         }
589                 }
590 #endif
591                 public override int Timeout { 
592                         get { return timeout; }
593                         set {
594                                 if (value < -1)
595                                         throw new ArgumentOutOfRangeException ("value");
596
597                                 timeout = value;
598                         }
599                 }
600                 
601                 public string TransferEncoding {
602                         get { return webHeaders ["Transfer-Encoding"]; }
603                         set {
604                                 CheckRequestStarted ();
605                                 string val = value;
606                                 if (val != null)
607                                         val = val.Trim ().ToLower ();
608
609                                 if (val == null || val.Length == 0) {
610                                         webHeaders.RemoveInternal ("Transfer-Encoding");
611                                         return;
612                                 }
613
614                                 if (val == "chunked")
615                                         throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
616
617                                 if (!sendChunked)
618                                         throw new ArgumentException ("SendChunked must be True", "value");
619
620                                 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
621                         }
622                 }
623
624                 public override bool UseDefaultCredentials
625                 {
626                         get { return CredentialCache.DefaultCredentials == Credentials; }
627                         set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
628                 }
629                 
630                 public string UserAgent {
631                         get { return webHeaders ["User-Agent"]; }
632                         set { webHeaders.SetInternal ("User-Agent", value); }
633                 }
634
635                 bool unsafe_auth_blah;
636                 public bool UnsafeAuthenticatedConnectionSharing
637                 {
638                         get { return unsafe_auth_blah; }
639                         set { unsafe_auth_blah = value; }
640                 }
641
642                 internal bool GotRequestStream {
643                         get { return gotRequestStream; }
644                 }
645
646                 internal bool ExpectContinue {
647                         get { return expectContinue; }
648                         set { expectContinue = value; }
649                 }
650                 
651                 internal Uri AuthUri {
652                         get { return actualUri; }
653                 }
654                 
655                 internal bool ProxyQuery {
656                         get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
657                 }
658                 
659                 // Methods
660                 
661                 internal ServicePoint GetServicePoint ()
662                 {
663                         lock (locker) {
664                                 if (hostChanged || servicePoint == null) {
665                                         servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
666                                         hostChanged = false;
667                                 }
668                         }
669
670                         return servicePoint;
671                 }
672                 
673                 public void AddRange (int range)
674                 {
675                         AddRange ("bytes", (long) range);
676                 }
677                 
678                 public void AddRange (int from, int to)
679                 {
680                         AddRange ("bytes", (long) from, (long) to);
681                 }
682                 
683                 public void AddRange (string rangeSpecifier, int range)
684                 {
685                         AddRange (rangeSpecifier, (long) range);
686                 }
687                 
688                 public void AddRange (string rangeSpecifier, int from, int to)
689                 {
690                         AddRange (rangeSpecifier, (long) from, (long) to);
691                 }
692 #if NET_4_0
693                 public
694 #else
695                 internal
696 #endif
697                 void AddRange (long range)
698                 {
699                         AddRange ("bytes", (long) range);
700                 }
701
702 #if NET_4_0
703                 public
704 #else
705                 internal
706 #endif
707                 void AddRange (long from, long to)
708                 {
709                         AddRange ("bytes", from, to);
710                 }
711
712 #if NET_4_0
713                 public
714 #else
715                 internal
716 #endif
717                 void AddRange (string rangeSpecifier, long range)
718                 {
719                         if (rangeSpecifier == null)
720                                 throw new ArgumentNullException ("rangeSpecifier");
721                         if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
722                                 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
723
724                         string r = webHeaders ["Range"];
725                         if (r == null)
726                                 r = rangeSpecifier + "=";
727                         else {
728                                 string old_specifier = r.Substring (0, r.IndexOf ('='));
729                                 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
730                                         throw new InvalidOperationException ("A different range specifier is already in use");
731                                 r += ",";
732                         }
733
734                         string n = range.ToString (CultureInfo.InvariantCulture);
735                         if (range < 0)
736                                 r = r + "0" + n;
737                         else
738                                 r = r + n + "-";
739                         webHeaders.RemoveAndAdd ("Range", r);
740                 }
741
742 #if NET_4_0
743                 public
744 #else
745                 internal
746 #endif
747                 void AddRange (string rangeSpecifier, long from, long to)
748                 {
749                         if (rangeSpecifier == null)
750                                 throw new ArgumentNullException ("rangeSpecifier");
751                         if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
752                                 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
753                         if (from > to || from < 0)
754                                 throw new ArgumentOutOfRangeException ("from");
755                         if (to < 0)
756                                 throw new ArgumentOutOfRangeException ("to");
757
758                         string r = webHeaders ["Range"];
759                         if (r == null)
760                                 r = rangeSpecifier + "=";
761                         else
762                                 r += ",";
763
764                         r = String.Format ("{0}{1}-{2}", r, from, to);
765                         webHeaders.RemoveAndAdd ("Range", r);
766                 }
767
768                 
769                 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state) 
770                 {
771                         if (Aborted)
772                                 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
773
774                         bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
775                                         method == "TRACE");
776                         if (method == null || !send)
777                                 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
778
779                         if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
780                                 throw new ProtocolViolationException ("Content-Length not set");
781
782                         string transferEncoding = TransferEncoding;
783                         if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
784                                 throw new ProtocolViolationException ("SendChunked should be true.");
785
786                         lock (locker)
787                         {
788                                 if (getResponseCalled)
789                                         throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
790
791                                 if (asyncWrite != null) {
792                                         throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
793                                                                 "method while a previous call is still in progress.");
794                                 }
795         
796                                 asyncWrite = new WebAsyncResult (this, callback, state);
797                                 initialMethod = method;
798                                 if (haveRequest) {
799                                         if (writeStream != null) {
800                                                 asyncWrite.SetCompleted (true, writeStream);
801                                                 asyncWrite.DoCallback ();
802                                                 return asyncWrite;
803                                         }
804                                 }
805                                 
806                                 gotRequestStream = true;
807                                 WebAsyncResult result = asyncWrite;
808                                 if (!requestSent) {
809                                         requestSent = true;
810                                         redirects = 0;
811                                         servicePoint = GetServicePoint ();
812                                         abortHandler = servicePoint.SendRequest (this, connectionGroup);
813                                 }
814                                 return result;
815                         }
816                 }
817
818                 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
819                 {
820                         if (asyncResult == null)
821                                 throw new ArgumentNullException ("asyncResult");
822
823                         WebAsyncResult result = asyncResult as WebAsyncResult;
824                         if (result == null)
825                                 throw new ArgumentException ("Invalid IAsyncResult");
826
827                         asyncWrite = result;
828                         result.WaitUntilComplete ();
829
830                         Exception e = result.Exception;
831                         if (e != null)
832                                 throw e;
833
834                         return result.WriteStream;
835                 }
836                 
837                 public override Stream GetRequestStream()
838                 {
839                         IAsyncResult asyncResult = asyncWrite;
840                         if (asyncResult == null) {
841                                 asyncResult = BeginGetRequestStream (null, null);
842                                 asyncWrite = (WebAsyncResult) asyncResult;
843                         }
844
845                         if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
846                                 Abort ();
847                                 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
848                         }
849
850                         return EndGetRequestStream (asyncResult);
851                 }
852
853                 void CheckIfForceWrite ()
854                 {
855                         if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
856                                 return;
857 #if NET_4_0
858                         if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
859                                 return;
860
861                         if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
862                                 InternalContentLength = writeStream.WriteBufferLength;
863 #else
864                         if (contentLength < 0 && writeStream.CanWrite == true)
865                                 return;
866 #endif
867
868                         // This will write the POST/PUT if the write stream already has the expected
869                         // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
870                         // contains data and it has been closed already (xamarin bug #1512).
871
872                         if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
873                                 writeStream.WriteRequest ();
874                 }
875
876                 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
877                 {
878                         if (Aborted)
879                                 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
880
881                         if (method == null)
882                                 throw new ProtocolViolationException ("Method is null.");
883
884                         string transferEncoding = TransferEncoding;
885                         if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
886                                 throw new ProtocolViolationException ("SendChunked should be true.");
887
888                         Monitor.Enter (locker);
889                         getResponseCalled = true;
890                         if (asyncRead != null && !haveResponse) {
891                                 Monitor.Exit (locker);
892                                 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
893                                                         "method while a previous call is still in progress.");
894                         }
895
896                         CheckIfForceWrite ();
897                         asyncRead = new WebAsyncResult (this, callback, state);
898                         WebAsyncResult aread = asyncRead;
899                         initialMethod = method;
900                         if (haveResponse) {
901                                 Exception saved = saved_exc;
902                                 if (webResponse != null) {
903                                         Monitor.Exit (locker);
904                                         if (saved == null) {
905                                                 aread.SetCompleted (true, webResponse);
906                                         } else {
907                                                 aread.SetCompleted (true, saved);
908                                         }
909                                         aread.DoCallback ();
910                                         return aread;
911                                 } else if (saved != null) {
912                                         Monitor.Exit (locker);
913                                         aread.SetCompleted (true, saved);
914                                         aread.DoCallback ();
915                                         return aread;
916                                 }
917                         }
918                         
919                         if (!requestSent) {
920                                 requestSent = true;
921                                 redirects = 0;
922                                 servicePoint = GetServicePoint ();
923                                 abortHandler = servicePoint.SendRequest (this, connectionGroup);
924                         }
925
926                         Monitor.Exit (locker);
927                         return aread;
928                 }
929                 
930                 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
931                 {
932                         if (asyncResult == null)
933                                 throw new ArgumentNullException ("asyncResult");
934
935                         WebAsyncResult result = asyncResult as WebAsyncResult;
936                         if (result == null)
937                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
938
939                         if (!result.WaitUntilComplete (timeout, false)) {
940                                 Abort ();
941                                 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
942                         }
943
944                         if (result.GotException)
945                                 throw result.Exception;
946
947                         return result.Response;
948                 }
949
950                 public override WebResponse GetResponse()
951                 {
952                         WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
953                         return EndGetResponse (result);
954                 }
955                 
956                 internal bool FinishedReading {
957                         get { return finished_reading; }
958                         set { finished_reading = value; }
959                 }
960
961                 internal bool Aborted {
962                         get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
963                 }
964
965                 public override void Abort ()
966                 {
967                         if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
968                                 return;
969
970                         if (haveResponse && finished_reading)
971                                 return;
972
973                         haveResponse = true;
974                         if (abortHandler != null) {
975                                 try {
976                                         abortHandler (this, EventArgs.Empty);
977                                 } catch (Exception) {}
978                                 abortHandler = null;
979                         }
980
981                         if (asyncWrite != null) {
982                                 WebAsyncResult r = asyncWrite;
983                                 if (!r.IsCompleted) {
984                                         try {
985                                                 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled); 
986                                                 r.SetCompleted (false, wexc);
987                                                 r.DoCallback ();
988                                         } catch {}
989                                 }
990                                 asyncWrite = null;
991                         }                       
992
993                         if (asyncRead != null) {
994                                 WebAsyncResult r = asyncRead;
995                                 if (!r.IsCompleted) {
996                                         try {
997                                                 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled); 
998                                                 r.SetCompleted (false, wexc);
999                                                 r.DoCallback ();
1000                                         } catch {}
1001                                 }
1002                                 asyncRead = null;
1003                         }                       
1004
1005                         if (writeStream != null) {
1006                                 try {
1007                                         writeStream.Close ();
1008                                         writeStream = null;
1009                                 } catch {}
1010                         }
1011
1012                         if (webResponse != null) {
1013                                 try {
1014                                         webResponse.Close ();
1015                                         webResponse = null;
1016                                 } catch {}
1017                         }
1018                 }               
1019                 
1020                 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1021                                                   StreamingContext streamingContext)
1022                 {
1023                         GetObjectData (serializationInfo, streamingContext);
1024                 }
1025
1026                 protected override void GetObjectData (SerializationInfo serializationInfo,
1027                         StreamingContext streamingContext)
1028                 {
1029                         SerializationInfo info = serializationInfo;
1030
1031                         info.AddValue ("requestUri", requestUri, typeof (Uri));
1032                         info.AddValue ("actualUri", actualUri, typeof (Uri));
1033                         info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1034                         info.AddValue ("allowBuffering", allowBuffering);
1035                         info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1036                         info.AddValue ("connectionGroup", connectionGroup);
1037                         info.AddValue ("contentLength", contentLength);
1038                         info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1039                         info.AddValue ("keepAlive", keepAlive);
1040                         info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1041                         info.AddValue ("mediaType", mediaType);
1042                         info.AddValue ("method", method);
1043                         info.AddValue ("initialMethod", initialMethod);
1044                         info.AddValue ("pipelined", pipelined);
1045                         info.AddValue ("version", version, typeof (Version));
1046                         info.AddValue ("proxy", proxy, typeof (IWebProxy));
1047                         info.AddValue ("sendChunked", sendChunked);
1048                         info.AddValue ("timeout", timeout);
1049                         info.AddValue ("redirects", redirects);
1050                         info.AddValue ("host", host);
1051                 }
1052                 
1053                 void CheckRequestStarted () 
1054                 {
1055                         if (requestSent)
1056                                 throw new InvalidOperationException ("request started");
1057                 }
1058
1059                 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1060                 {
1061                         if (continueDelegate != null)
1062                                 continueDelegate (statusCode, headers);
1063                 }
1064                 
1065                 bool Redirect (WebAsyncResult result, HttpStatusCode code)
1066                 {
1067                         redirects++;
1068                         Exception e = null;
1069                         string uriString = null;
1070
1071                         switch (code) {
1072                         case HttpStatusCode.Ambiguous: // 300
1073                                 e = new WebException ("Ambiguous redirect.");
1074                                 break;
1075                         case HttpStatusCode.MovedPermanently: // 301
1076                         case HttpStatusCode.Redirect: // 302
1077                         case HttpStatusCode.TemporaryRedirect: // 307
1078                                 /* MS follows the redirect for POST too
1079                                 if (method != "GET" && method != "HEAD") // 10.3
1080                                         return false;
1081                                 */
1082
1083                                 contentLength = -1;
1084                                 bodyBufferLength = 0;
1085                                 bodyBuffer = null;
1086                                 if (code != HttpStatusCode.TemporaryRedirect)
1087                                         method = "GET";
1088                                 uriString = webResponse.Headers ["Location"];
1089                                 break;
1090                         case HttpStatusCode.SeeOther: //303
1091                                 method = "GET";
1092                                 uriString = webResponse.Headers ["Location"];
1093                                 break;
1094                         case HttpStatusCode.NotModified: // 304
1095                                 return false;
1096                         case HttpStatusCode.UseProxy: // 305
1097                                 e = new NotImplementedException ("Proxy support not available.");
1098                                 break;
1099                         case HttpStatusCode.Unused: // 306
1100                         default:
1101                                 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1102                                 break;
1103                         }
1104
1105                         if (e != null)
1106                                 throw e;
1107
1108                         if (uriString == null)
1109                                 throw new WebException ("No Location header found for " + (int) code,
1110                                                         WebExceptionStatus.ProtocolError);
1111
1112                         Uri prev = actualUri;
1113                         try {
1114                                 actualUri = new Uri (actualUri, uriString);
1115                         } catch (Exception) {
1116                                 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1117                                                                         uriString, (int) code),
1118                                                                         WebExceptionStatus.ProtocolError);
1119                         }
1120
1121                         hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1122                         return true;
1123                 }
1124
1125                 string GetHeaders ()
1126                 {
1127                         bool continue100 = false;
1128                         if (sendChunked) {
1129                                 continue100 = true;
1130                                 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1131                                 webHeaders.RemoveInternal ("Content-Length");
1132                         } else if (contentLength != -1) {
1133                                 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1134                                         if (contentLength > 0)
1135                                                 continue100 = true;
1136
1137                                         webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1138                                 } else {
1139                                         webHeaders.SetInternal ("Content-Length", "0");
1140                                 }
1141                                 webHeaders.RemoveInternal ("Transfer-Encoding");
1142                         } else {
1143                                 webHeaders.RemoveInternal ("Content-Length");
1144                         }
1145
1146                         if (actualVersion == HttpVersion.Version11 && continue100 &&
1147                             servicePoint.SendContinue) { // RFC2616 8.2.3
1148                                 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1149                                 expectContinue = true;
1150                         } else {
1151                                 webHeaders.RemoveInternal ("Expect");
1152                                 expectContinue = false;
1153                         }
1154
1155                         bool proxy_query = ProxyQuery;
1156                         string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1157                         webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1158                         Version proto_version = servicePoint.ProtocolVersion;
1159                         bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1160
1161                         if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1162                                 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1163                         } else if (!keepAlive && version == HttpVersion.Version11) {
1164                                 webHeaders.RemoveAndAdd (connectionHeader, "close");
1165                         }
1166
1167                         webHeaders.SetInternal ("Host", Host);
1168                         if (cookieContainer != null) {
1169                                 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1170                                 if (cookieHeader != "")
1171                                         webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1172                                 else
1173                                         webHeaders.RemoveInternal ("Cookie");
1174                         }
1175
1176                         string accept_encoding = null;
1177                         if ((auto_decomp & DecompressionMethods.GZip) != 0)
1178                                 accept_encoding = "gzip";
1179                         if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1180                                 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1181                         if (accept_encoding != null)
1182                                 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1183
1184                         if (!usedPreAuth && preAuthenticate)
1185                                 DoPreAuthenticate ();
1186
1187                         return webHeaders.ToString ();
1188                 }
1189
1190                 void DoPreAuthenticate ()
1191                 {
1192                         bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1193                         ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1194                         Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1195                         if (auth == null)
1196                                 return;
1197
1198                         webHeaders.RemoveInternal ("Proxy-Authorization");
1199                         webHeaders.RemoveInternal ("Authorization");
1200                         string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1201                         webHeaders [authHeader] = auth.Message;
1202                         usedPreAuth = true;
1203                 }
1204                 
1205                 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1206                 {
1207                         if (Aborted)
1208                                 return;
1209
1210                         WebAsyncResult r = asyncWrite;
1211                         if (r == null)
1212                                 r = asyncRead;
1213
1214                         if (r != null) {
1215                                 string msg;
1216                                 WebException wex;
1217                                 if (exc == null) {
1218                                         msg = "Error: " + status;
1219                                         wex = new WebException (msg, status);
1220                                 } else {
1221                                         msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1222                                         wex = new WebException (msg, exc, status);
1223                                 }
1224                                 r.SetCompleted (false, wex);
1225                                 r.DoCallback ();
1226                         }
1227                 }
1228
1229                 internal void SendRequestHeaders (bool propagate_error)
1230                 {
1231                         StringBuilder req = new StringBuilder ();
1232                         string query;
1233                         if (!ProxyQuery) {
1234                                 query = actualUri.PathAndQuery;
1235                         } else {
1236                                 query = String.Format ("{0}://{1}{2}",  actualUri.Scheme,
1237                                                                         Host,
1238                                                                         actualUri.PathAndQuery);
1239                         }
1240                         
1241                         if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1242                                 actualVersion = servicePoint.ProtocolVersion;
1243                         } else {
1244                                 actualVersion = version;
1245                         }
1246
1247                         req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1248                                                                 actualVersion.Major, actualVersion.Minor);
1249                         req.Append (GetHeaders ());
1250                         string reqstr = req.ToString ();
1251                         byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1252                         try {
1253                                 writeStream.SetHeaders (bytes);
1254                         } catch (WebException wexc) {
1255                                 SetWriteStreamError (wexc.Status, wexc);
1256                                 if (propagate_error)
1257                                         throw;
1258                         } catch (Exception exc) {
1259                                 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1260                                 if (propagate_error)
1261                                         throw;
1262                         }
1263                 }
1264
1265                 internal void SetWriteStream (WebConnectionStream stream)
1266                 {
1267                         if (Aborted)
1268                                 return;
1269                         
1270                         writeStream = stream;
1271                         if (bodyBuffer != null) {
1272                                 webHeaders.RemoveInternal ("Transfer-Encoding");
1273                                 contentLength = bodyBufferLength;
1274                                 writeStream.SendChunked = false;
1275                         }
1276
1277                         SendRequestHeaders (false);
1278
1279                         haveRequest = true;
1280                         
1281                         if (bodyBuffer != null) {
1282                                 // The body has been written and buffered. The request "user"
1283                                 // won't write it again, so we must do it.
1284                                 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1285                                         writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1286                                         bodyBuffer = null;
1287                                         writeStream.Close ();
1288                                 }
1289                         } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1290                                         method != "TRACE") {
1291                                 if (getResponseCalled && !writeStream.RequestWritten)
1292                                         writeStream.WriteRequest ();
1293                         }
1294
1295                         if (asyncWrite != null) {
1296                                 asyncWrite.SetCompleted (false, stream);
1297                                 asyncWrite.DoCallback ();
1298                                 asyncWrite = null;
1299                         }
1300                 }
1301
1302                 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1303                 {
1304                         if (Aborted)
1305                                 return;
1306                         lock (locker) {
1307                         string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1308                         WebAsyncResult r = asyncRead;
1309                         if (r == null)
1310                                 r = asyncWrite;
1311
1312                         WebException wexc;
1313                         if (e is WebException) {
1314                                 wexc = (WebException) e;
1315                         } else {
1316                                 wexc = new WebException (msg, e, status, null); 
1317                         }
1318                         if (r != null) {
1319                                 if (!r.IsCompleted) {
1320                                         r.SetCompleted (false, wexc);
1321                                         r.DoCallback ();
1322                                 } else if (r == asyncWrite) {
1323                                         saved_exc = wexc;
1324                                 }
1325                                 haveResponse = true;
1326                                 asyncRead = null;
1327                                 asyncWrite = null;
1328                         } else {
1329                                 haveResponse = true;
1330                                 saved_exc = wexc;
1331                         }
1332                         }
1333                 }
1334
1335                 void CheckSendError (WebConnectionData data)
1336                 {
1337                         // Got here, but no one called GetResponse
1338                         int status = data.StatusCode;
1339                         if (status < 400 || status == 401 || status == 407)
1340                                 return;
1341
1342                         if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1343                                 // The request has not been completely sent and we got here!
1344                                 // We should probably just close and cause an error in any case,
1345                                 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse); 
1346                                 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1347                                         webResponse.ReadAll ();
1348                                 } else {
1349                                         writeStream.IgnoreIOErrors = true;
1350                                 }
1351                         }
1352                 }
1353
1354                 void HandleNtlmAuth (WebAsyncResult r)
1355                 {
1356                         WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1357                         if (wce != null) {
1358                                 WebConnection cnc = wce.Connection;
1359                                 cnc.PriorityRequest = this;
1360                                 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1361                                 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1362                                 if (creds != null) {
1363                                         cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1364                                         cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1365                                 }
1366                         }
1367                         r.Reset ();
1368                         finished_reading = false;
1369                         haveResponse = false;
1370                         webResponse.ReadAll ();
1371                         webResponse = null;
1372                 }
1373
1374                 internal void SetResponseData (WebConnectionData data)
1375                 {
1376                         lock (locker) {
1377                         if (Aborted) {
1378                                 if (data.stream != null)
1379                                         data.stream.Close ();
1380                                 return;
1381                         }
1382
1383                         WebException wexc = null;
1384                         try {
1385                                 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1386                         } catch (Exception e) {
1387                                 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null); 
1388                                 if (data.stream != null)
1389                                         data.stream.Close ();
1390                         }
1391
1392                         if (wexc == null && (method == "POST" || method == "PUT")) {
1393                                 CheckSendError (data);
1394                                 if (saved_exc != null)
1395                                         wexc = (WebException) saved_exc;
1396                         }
1397
1398                         WebAsyncResult r = asyncRead;
1399
1400                         bool forced = false;
1401                         if (r == null && webResponse != null) {
1402                                 // This is a forced completion (302, 204)...
1403                                 forced = true;
1404                                 r = new WebAsyncResult (null, null);
1405                                 r.SetCompleted (false, webResponse);
1406                         }
1407
1408                         if (r != null) {
1409                                 if (wexc != null) {
1410                                         haveResponse = true;
1411                                         if (!r.IsCompleted)
1412                                                 r.SetCompleted (false, wexc);
1413                                         r.DoCallback ();
1414                                         return;
1415                                 }
1416
1417                                 bool redirected;
1418                                 try {
1419                                         redirected = CheckFinalStatus (r);
1420                                         if (!redirected) {
1421                                                 if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
1422                                                         && (int)webResponse.StatusCode < 400) {
1423                                                         WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1424                                                         if (wce != null) {
1425                                                                 WebConnection cnc = wce.Connection;
1426                                                                 cnc.NtlmAuthenticated = true;
1427                                                         }
1428                                                 }
1429
1430                                                 // clear internal buffer so that it does not
1431                                                 // hold possible big buffer (bug #397627)
1432                                                 if (writeStream != null)
1433                                                         writeStream.KillBuffer ();
1434
1435                                                 haveResponse = true;
1436                                                 r.SetCompleted (false, webResponse);
1437                                                 r.DoCallback ();
1438                                         } else {
1439                                                 if (webResponse != null) {
1440                                                         if (ntlm_auth_state != NtlmAuthState.None) {
1441                                                                 HandleNtlmAuth (r);
1442                                                                 return;
1443                                                         }
1444                                                         webResponse.Close ();
1445                                                 }
1446                                                 finished_reading = false;
1447                                                 haveResponse = false;
1448                                                 webResponse = null;
1449                                                 r.Reset ();
1450                                                 servicePoint = GetServicePoint ();
1451                                                 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1452                                         }
1453                                 } catch (WebException wexc2) {
1454                                         if (forced) {
1455                                                 saved_exc = wexc2;
1456                                                 haveResponse = true;
1457                                         }
1458                                         r.SetCompleted (false, wexc2);
1459                                         r.DoCallback ();
1460                                         return;
1461                                 } catch (Exception ex) {
1462                                         wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null); 
1463                                         if (forced) {
1464                                                 saved_exc = wexc;
1465                                                 haveResponse = true;
1466                                         }
1467                                         r.SetCompleted (false, wexc);
1468                                         r.DoCallback ();
1469                                         return;
1470                                 }
1471                         }
1472                         }
1473                 }
1474
1475                 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1476                 {
1477                         authCompleted = false;
1478                         if (code == HttpStatusCode.Unauthorized && credentials == null)
1479                                 return false;
1480
1481                         bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1482                         if (isProxy && (proxy == null || proxy.Credentials == null))
1483                                 return false;
1484
1485                         string [] authHeaders = response.Headers.GetValues_internal ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1486                         if (authHeaders == null || authHeaders.Length == 0)
1487                                 return false;
1488
1489                         ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1490                         Authorization auth = null;
1491                         foreach (string authHeader in authHeaders) {
1492                                 auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1493                                 if (auth != null)
1494                                         break;
1495                         }
1496                         if (auth == null)
1497                                 return false;
1498                         webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1499                         authCompleted = auth.Complete;
1500                         bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1501                         if (is_ntlm)
1502                                 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1503                         return true;
1504                 }
1505
1506                 // Returns true if redirected
1507                 bool CheckFinalStatus (WebAsyncResult result)
1508                 {
1509                         if (result.GotException) {
1510                                 bodyBuffer = null;
1511                                 throw result.Exception;
1512                         }
1513
1514                         Exception throwMe = result.Exception;
1515
1516                         HttpWebResponse resp = result.Response;
1517                         WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1518                         HttpStatusCode code = 0;
1519                         if (throwMe == null && webResponse != null) {
1520                                 code = webResponse.StatusCode;
1521                                 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1522                                      (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1523                                         if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1524                                                 // Keep the written body, so it can be rewritten in the retry
1525                                                 if (InternalAllowBuffering) {
1526                                                         // NTLM: This is to avoid sending data in the 'challenge' request
1527                                                         // We save it in the first request (first 401), don't send anything
1528                                                         // in the challenge request and send it in the response request along
1529                                                         // with the buffers kept form the first request.
1530                                                         if (ntlm_auth_state != NtlmAuthState.Response) {
1531                                                                 bodyBuffer = writeStream.WriteBuffer;
1532                                                                 bodyBufferLength = writeStream.WriteBufferLength;
1533                                                         }
1534                                                         return true;
1535                                                 } else if (method != "PUT" && method != "POST") {
1536                                                         bodyBuffer = null;
1537                                                         return true;
1538                                                 }
1539
1540                                                 if (!ThrowOnError)
1541                                                         return false;
1542                                                         
1543                                                 writeStream.InternalClose ();
1544                                                 writeStream = null;
1545                                                 webResponse.Close ();
1546                                                 webResponse = null;
1547                                                 bodyBuffer = null;
1548                                                         
1549                                                 throw new WebException ("This request requires buffering " +
1550                                                                         "of data for authentication or " +
1551                                                                         "redirection to be sucessful.");
1552                                         }
1553                                 }
1554
1555                                 bodyBuffer = null;
1556                                 if ((int) code >= 400) {
1557                                         string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1558                                                                     (int) code, webResponse.StatusDescription);
1559                                         throwMe = new WebException (err, null, protoError, webResponse);
1560                                         webResponse.ReadAll ();
1561                                 } else if ((int) code == 304 && allowAutoRedirect) {
1562                                         string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1563                                                                     (int) code, webResponse.StatusDescription);
1564                                         throwMe = new WebException (err, null, protoError, webResponse);
1565                                 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1566                                         throwMe = new WebException ("Max. redirections exceeded.", null,
1567                                                                     protoError, webResponse);
1568                                         webResponse.ReadAll ();
1569                                 }
1570                         }
1571
1572                         bodyBuffer = null;
1573                         if (throwMe == null) {
1574                                 bool b = false;
1575                                 int c = (int) code;
1576                                 if (allowAutoRedirect && c >= 300) {
1577                                         if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1578                                                 bodyBuffer = writeStream.WriteBuffer;
1579                                                 bodyBufferLength = writeStream.WriteBufferLength;
1580                                         }
1581                                         b = Redirect (result, code);
1582                                         if (b && ntlm_auth_state != 0)
1583                                                 ntlm_auth_state = 0;
1584                                 }
1585
1586                                 if (resp != null && c >= 300 && c != 304)
1587                                         resp.ReadAll ();
1588
1589                                 return b;
1590                         }
1591                                 
1592                         if (!ThrowOnError)
1593                                 return false;
1594
1595                         if (writeStream != null) {
1596                                 writeStream.InternalClose ();
1597                                 writeStream = null;
1598                         }
1599
1600                         webResponse = null;
1601
1602                         throw throwMe;
1603                 }
1604         }
1605 }
1606