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