Fix bug #311: On LinkedList.Clear, detach each node instead of dropping them en masse.
[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 = new WebHeaderCollection (true);
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                 }               
143                 
144                 [Obsolete ("Serialization is obsoleted for this type", false)]
145                 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext) 
146                 {
147                         SerializationInfo info = serializationInfo;
148
149                         requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
150                         actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
151                         allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
152                         allowBuffering = info.GetBoolean ("allowBuffering");
153                         certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
154                         connectionGroup = info.GetString ("connectionGroup");
155                         contentLength = info.GetInt64 ("contentLength");
156                         webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
157                         keepAlive = info.GetBoolean ("keepAlive");
158                         maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
159                         mediaType = info.GetString ("mediaType");
160                         method = info.GetString ("method");
161                         initialMethod = info.GetString ("initialMethod");
162                         pipelined = info.GetBoolean ("pipelined");
163                         version = (Version) info.GetValue ("version", typeof (Version));
164                         proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
165                         sendChunked = info.GetBoolean ("sendChunked");
166                         timeout = info.GetInt32 ("timeout");
167                         redirects = info.GetInt32 ("redirects");
168                         host = info.GetString ("host");
169                 }
170                 
171                 // Properties
172
173                 public string Accept {
174                         get { return webHeaders ["Accept"]; }
175                         set {
176                                 CheckRequestStarted ();
177                                 webHeaders.RemoveAndAdd ("Accept", value);
178                         }
179                 }
180                 
181                 public Uri Address {
182                         get { return actualUri; }
183                         internal set { actualUri = value; } // Used by Ftp+proxy
184                 }
185                 
186                 public bool AllowAutoRedirect {
187                         get { return allowAutoRedirect; }
188                         set { this.allowAutoRedirect = value; }
189                 }
190                 
191                 public bool AllowWriteStreamBuffering {
192                         get { return allowBuffering; }
193                         set { allowBuffering = value; }
194                 }
195
196                 static Exception GetMustImplement ()
197                 {
198                         return new NotImplementedException ();
199                 }
200                 
201                 public DecompressionMethods AutomaticDecompression
202                 {
203                         get {
204                                 return auto_decomp;
205                         }
206                         set {
207                                 CheckRequestStarted ();
208                                 auto_decomp = value;
209                         }
210                 }
211                 
212                 internal bool InternalAllowBuffering {
213                         get {
214                                 return (allowBuffering && (method != "HEAD" && method != "GET" &&
215                                                         method != "MKCOL" && method != "CONNECT" &&
216                                                         method != "TRACE"));
217                         }
218                 }
219                 
220                 public X509CertificateCollection ClientCertificates {
221                         get {
222                                 if (certificates == null)
223                                         certificates = new X509CertificateCollection ();
224
225                                 return certificates;
226                         }
227                         [MonoTODO]
228                         set {
229                                 throw GetMustImplement ();
230                         }
231                 }
232                 
233                 public string Connection {
234                         get { return webHeaders ["Connection"]; }
235                         set {
236                                 CheckRequestStarted ();
237                                 string val = value;
238                                 if (val != null) 
239                                         val = val.Trim ().ToLower ();
240
241                                 if (val == null || val.Length == 0) {
242                                         webHeaders.RemoveInternal ("Connection");
243                                         return;
244                                 }
245
246                                 if (val == "keep-alive" || val == "close") 
247                                         throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
248
249                                 if (keepAlive && val.IndexOf ("keep-alive", StringComparison.Ordinal) == -1)
250                                         value = value + ", Keep-Alive";
251                                 
252                                 webHeaders.RemoveAndAdd ("Connection", value);
253                         }
254                 }               
255                 
256                 public override string ConnectionGroupName { 
257                         get { return connectionGroup; }
258                         set { connectionGroup = value; }
259                 }
260                 
261                 public override long ContentLength { 
262                         get { return contentLength; }
263                         set { 
264                                 CheckRequestStarted ();
265                                 if (value < 0)
266                                         throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
267                                         
268                                 contentLength = value;
269                         }
270                 }
271                 
272                 internal long InternalContentLength {
273                         set { contentLength = value; }
274                 }
275                 
276                 public override string ContentType { 
277                         get { return webHeaders ["Content-Type"]; }
278                         set {
279                                 if (value == null || value.Trim().Length == 0) {
280                                         webHeaders.RemoveInternal ("Content-Type");
281                                         return;
282                                 }
283                                 webHeaders.RemoveAndAdd ("Content-Type", value);
284                         }
285                 }
286                 
287                 public HttpContinueDelegate ContinueDelegate {
288                         get { return continueDelegate; }
289                         set { continueDelegate = value; }
290                 }
291                 
292                 public CookieContainer CookieContainer {
293                         get { return cookieContainer; }
294                         set { cookieContainer = value; }
295                 }
296                 
297                 public override ICredentials Credentials { 
298                         get { return credentials; }
299                         set { credentials = value; }
300                 }
301 #if NET_4_0
302                 public DateTime Date {
303                         get {
304                                 string date = webHeaders ["Date"];
305                                 if (date == null)
306                                         return DateTime.MinValue;
307                                 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
308                         }
309                         set {
310                                 if (value == null) {
311                                         webHeaders.RemoveInternal ("Date");
312                                 } else {
313                                         webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
314                                 }
315                         }
316                 }
317 #endif
318                 [MonoTODO]
319                 public static new RequestCachePolicy DefaultCachePolicy
320                 {
321                         get {
322                                 throw GetMustImplement ();
323                         }
324                         set {
325                                 throw GetMustImplement ();
326                         }
327                 }
328                 
329                 [MonoTODO]
330                 public static int DefaultMaximumErrorResponseLength
331                 {
332                         get {
333                                 throw GetMustImplement ();
334                         }
335                         set {
336                                 throw GetMustImplement ();
337                         }
338                 }
339                 
340                 public string Expect {
341                         get { return webHeaders ["Expect"]; }
342                         set {
343                                 CheckRequestStarted ();
344                                 string val = value;
345                                 if (val != null)
346                                         val = val.Trim ().ToLower ();
347
348                                 if (val == null || val.Length == 0) {
349                                         webHeaders.RemoveInternal ("Expect");
350                                         return;
351                                 }
352
353                                 if (val == "100-continue")
354                                         throw new ArgumentException ("100-Continue cannot be set with this property.",
355                                                                      "value");
356                                 webHeaders.RemoveAndAdd ("Expect", value);
357                         }
358                 }
359                 
360                 public bool HaveResponse {
361                         get { return haveResponse; }
362                 }
363                 
364                 public override WebHeaderCollection Headers { 
365                         get { return webHeaders; }
366                         set {
367                                 CheckRequestStarted ();
368                                 WebHeaderCollection newHeaders = new WebHeaderCollection (true);
369                                 int count = value.Count;
370                                 for (int i = 0; i < count; i++) 
371                                         newHeaders.Add (value.GetKey (i), value.Get (i));
372
373                                 webHeaders = newHeaders;
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 || !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).
827                         if (writeStream.WriteBufferLength == contentLength)
828                                 writeStream.WriteRequest ();
829                 }
830
831                 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
832                 {
833                         if (Aborted)
834                                 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
835
836                         if (method == null)
837                                 throw new ProtocolViolationException ("Method is null.");
838
839                         string transferEncoding = TransferEncoding;
840                         if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
841                                 throw new ProtocolViolationException ("SendChunked should be true.");
842
843                         Monitor.Enter (locker);
844                         getResponseCalled = true;
845                         if (asyncRead != null && !haveResponse) {
846                                 Monitor.Exit (locker);
847                                 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
848                                                         "method while a previous call is still in progress.");
849                         }
850
851                         CheckIfForceWrite ();
852                         asyncRead = new WebAsyncResult (this, callback, state);
853                         WebAsyncResult aread = asyncRead;
854                         initialMethod = method;
855                         if (haveResponse) {
856                                 Exception saved = saved_exc;
857                                 if (webResponse != null) {
858                                         Monitor.Exit (locker);
859                                         if (saved == null) {
860                                                 aread.SetCompleted (true, webResponse);
861                                         } else {
862                                                 aread.SetCompleted (true, saved);
863                                         }
864                                         aread.DoCallback ();
865                                         return aread;
866                                 } else if (saved != null) {
867                                         Monitor.Exit (locker);
868                                         aread.SetCompleted (true, saved);
869                                         aread.DoCallback ();
870                                         return aread;
871                                 }
872                         }
873                         
874                         if (!requestSent) {
875                                 requestSent = true;
876                                 redirects = 0;
877                                 servicePoint = GetServicePoint ();
878                                 abortHandler = servicePoint.SendRequest (this, connectionGroup);
879                         }
880
881                         Monitor.Exit (locker);
882                         return aread;
883                 }
884                 
885                 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
886                 {
887                         if (asyncResult == null)
888                                 throw new ArgumentNullException ("asyncResult");
889
890                         WebAsyncResult result = asyncResult as WebAsyncResult;
891                         if (result == null)
892                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
893
894                         if (!result.WaitUntilComplete (timeout, false)) {
895                                 Abort ();
896                                 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
897                         }
898
899                         if (result.GotException)
900                                 throw result.Exception;
901
902                         return result.Response;
903                 }
904
905                 public override WebResponse GetResponse()
906                 {
907                         WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
908                         return EndGetResponse (result);
909                 }
910                 
911                 internal bool FinishedReading {
912                         get { return finished_reading; }
913                         set { finished_reading = value; }
914                 }
915
916                 internal bool Aborted {
917                         get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
918                 }
919
920                 public override void Abort ()
921                 {
922                         if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
923                                 return;
924
925                         if (haveResponse && finished_reading)
926                                 return;
927
928                         haveResponse = true;
929                         if (abortHandler != null) {
930                                 try {
931                                         abortHandler (this, EventArgs.Empty);
932                                 } catch (Exception) {}
933                                 abortHandler = null;
934                         }
935
936                         if (asyncWrite != null) {
937                                 WebAsyncResult r = asyncWrite;
938                                 if (!r.IsCompleted) {
939                                         try {
940                                                 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled); 
941                                                 r.SetCompleted (false, wexc);
942                                                 r.DoCallback ();
943                                         } catch {}
944                                 }
945                                 asyncWrite = null;
946                         }                       
947
948                         if (asyncRead != null) {
949                                 WebAsyncResult r = asyncRead;
950                                 if (!r.IsCompleted) {
951                                         try {
952                                                 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled); 
953                                                 r.SetCompleted (false, wexc);
954                                                 r.DoCallback ();
955                                         } catch {}
956                                 }
957                                 asyncRead = null;
958                         }                       
959
960                         if (writeStream != null) {
961                                 try {
962                                         writeStream.Close ();
963                                         writeStream = null;
964                                 } catch {}
965                         }
966
967                         if (webResponse != null) {
968                                 try {
969                                         webResponse.Close ();
970                                         webResponse = null;
971                                 } catch {}
972                         }
973                 }               
974                 
975                 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
976                                                   StreamingContext streamingContext)
977                 {
978                         GetObjectData (serializationInfo, streamingContext);
979                 }
980
981                 protected override void GetObjectData (SerializationInfo serializationInfo,
982                         StreamingContext streamingContext)
983                 {
984                         SerializationInfo info = serializationInfo;
985
986                         info.AddValue ("requestUri", requestUri, typeof (Uri));
987                         info.AddValue ("actualUri", actualUri, typeof (Uri));
988                         info.AddValue ("allowAutoRedirect", allowAutoRedirect);
989                         info.AddValue ("allowBuffering", allowBuffering);
990                         info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
991                         info.AddValue ("connectionGroup", connectionGroup);
992                         info.AddValue ("contentLength", contentLength);
993                         info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
994                         info.AddValue ("keepAlive", keepAlive);
995                         info.AddValue ("maxAutoRedirect", maxAutoRedirect);
996                         info.AddValue ("mediaType", mediaType);
997                         info.AddValue ("method", method);
998                         info.AddValue ("initialMethod", initialMethod);
999                         info.AddValue ("pipelined", pipelined);
1000                         info.AddValue ("version", version, typeof (Version));
1001                         info.AddValue ("proxy", proxy, typeof (IWebProxy));
1002                         info.AddValue ("sendChunked", sendChunked);
1003                         info.AddValue ("timeout", timeout);
1004                         info.AddValue ("redirects", redirects);
1005                         info.AddValue ("host", host);
1006                 }
1007                 
1008                 void CheckRequestStarted () 
1009                 {
1010                         if (requestSent)
1011                                 throw new InvalidOperationException ("request started");
1012                 }
1013
1014                 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1015                 {
1016                         if (continueDelegate != null)
1017                                 continueDelegate (statusCode, headers);
1018                 }
1019                 
1020                 bool Redirect (WebAsyncResult result, HttpStatusCode code)
1021                 {
1022                         redirects++;
1023                         Exception e = null;
1024                         string uriString = null;
1025
1026                         switch (code) {
1027                         case HttpStatusCode.Ambiguous: // 300
1028                                 e = new WebException ("Ambiguous redirect.");
1029                                 break;
1030                         case HttpStatusCode.MovedPermanently: // 301
1031                         case HttpStatusCode.Redirect: // 302
1032                         case HttpStatusCode.TemporaryRedirect: // 307
1033                                 /* MS follows the redirect for POST too
1034                                 if (method != "GET" && method != "HEAD") // 10.3
1035                                         return false;
1036                                 */
1037
1038                                 contentLength = -1;
1039                                 bodyBufferLength = 0;
1040                                 bodyBuffer = null;
1041                                 if (code != HttpStatusCode.TemporaryRedirect)
1042                                         method = "GET";
1043                                 uriString = webResponse.Headers ["Location"];
1044                                 break;
1045                         case HttpStatusCode.SeeOther: //303
1046                                 method = "GET";
1047                                 uriString = webResponse.Headers ["Location"];
1048                                 break;
1049                         case HttpStatusCode.NotModified: // 304
1050                                 return false;
1051                         case HttpStatusCode.UseProxy: // 305
1052                                 e = new NotImplementedException ("Proxy support not available.");
1053                                 break;
1054                         case HttpStatusCode.Unused: // 306
1055                         default:
1056                                 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1057                                 break;
1058                         }
1059
1060                         if (e != null)
1061                                 throw e;
1062
1063                         if (uriString == null)
1064                                 throw new WebException ("No Location header found for " + (int) code,
1065                                                         WebExceptionStatus.ProtocolError);
1066
1067                         Uri prev = actualUri;
1068                         try {
1069                                 actualUri = new Uri (actualUri, uriString);
1070                         } catch (Exception) {
1071                                 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1072                                                                         uriString, (int) code),
1073                                                                         WebExceptionStatus.ProtocolError);
1074                         }
1075
1076                         hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1077                         return true;
1078                 }
1079
1080                 string GetHeaders ()
1081                 {
1082                         bool continue100 = false;
1083                         if (sendChunked) {
1084                                 continue100 = true;
1085                                 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1086                                 webHeaders.RemoveInternal ("Content-Length");
1087                         } else if (contentLength != -1) {
1088                                 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1089                                         if (contentLength > 0)
1090                                                 continue100 = true;
1091
1092                                         webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1093                                 } else {
1094                                         webHeaders.SetInternal ("Content-Length", "0");
1095                                 }
1096                                 webHeaders.RemoveInternal ("Transfer-Encoding");
1097                         } else {
1098                                 webHeaders.RemoveInternal ("Content-Length");
1099                         }
1100
1101                         if (actualVersion == HttpVersion.Version11 && continue100 &&
1102                             servicePoint.SendContinue) { // RFC2616 8.2.3
1103                                 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1104                                 expectContinue = true;
1105                         } else {
1106                                 webHeaders.RemoveInternal ("Expect");
1107                                 expectContinue = false;
1108                         }
1109
1110                         bool proxy_query = ProxyQuery;
1111                         string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1112                         webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1113                         Version proto_version = servicePoint.ProtocolVersion;
1114                         bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1115
1116                         if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1117                                 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1118                         } else if (!keepAlive && version == HttpVersion.Version11) {
1119                                 webHeaders.RemoveAndAdd (connectionHeader, "close");
1120                         }
1121
1122                         webHeaders.SetInternal ("Host", Host);
1123                         if (cookieContainer != null) {
1124                                 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1125                                 if (cookieHeader != "")
1126                                         webHeaders.SetInternal ("Cookie", cookieHeader);
1127                         }
1128
1129                         string accept_encoding = null;
1130                         if ((auto_decomp & DecompressionMethods.GZip) != 0)
1131                                 accept_encoding = "gzip";
1132                         if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1133                                 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1134                         if (accept_encoding != null)
1135                                 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1136
1137                         if (!usedPreAuth && preAuthenticate)
1138                                 DoPreAuthenticate ();
1139
1140                         return webHeaders.ToString ();
1141                 }
1142
1143                 void DoPreAuthenticate ()
1144                 {
1145                         bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1146                         ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1147                         Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1148                         if (auth == null)
1149                                 return;
1150
1151                         webHeaders.RemoveInternal ("Proxy-Authorization");
1152                         webHeaders.RemoveInternal ("Authorization");
1153                         string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1154                         webHeaders [authHeader] = auth.Message;
1155                         usedPreAuth = true;
1156                 }
1157                 
1158                 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1159                 {
1160                         if (Aborted)
1161                                 return;
1162
1163                         WebAsyncResult r = asyncWrite;
1164                         if (r == null)
1165                                 r = asyncRead;
1166
1167                         if (r != null) {
1168                                 string msg;
1169                                 WebException wex;
1170                                 if (exc == null) {
1171                                         msg = "Error: " + status;
1172                                         wex = new WebException (msg, status);
1173                                 } else {
1174                                         msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1175                                         wex = new WebException (msg, exc, status);
1176                                 }
1177                                 r.SetCompleted (false, wex);
1178                                 r.DoCallback ();
1179                         }
1180                 }
1181
1182                 internal void SendRequestHeaders (bool propagate_error)
1183                 {
1184                         StringBuilder req = new StringBuilder ();
1185                         string query;
1186                         if (!ProxyQuery) {
1187                                 query = actualUri.PathAndQuery;
1188                         } else {
1189                                 query = String.Format ("{0}://{1}{2}",  actualUri.Scheme,
1190                                                                         Host,
1191                                                                         actualUri.PathAndQuery);
1192                         }
1193                         
1194                         if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1195                                 actualVersion = servicePoint.ProtocolVersion;
1196                         } else {
1197                                 actualVersion = version;
1198                         }
1199
1200                         req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1201                                                                 actualVersion.Major, actualVersion.Minor);
1202                         req.Append (GetHeaders ());
1203                         string reqstr = req.ToString ();
1204                         byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1205                         try {
1206                                 writeStream.SetHeaders (bytes);
1207                         } catch (WebException wexc) {
1208                                 SetWriteStreamError (wexc.Status, wexc);
1209                                 if (propagate_error)
1210                                         throw;
1211                         } catch (Exception exc) {
1212                                 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1213                                 if (propagate_error)
1214                                         throw;
1215                         }
1216                 }
1217
1218                 internal void SetWriteStream (WebConnectionStream stream)
1219                 {
1220                         if (Aborted)
1221                                 return;
1222                         
1223                         writeStream = stream;
1224                         if (bodyBuffer != null) {
1225                                 webHeaders.RemoveInternal ("Transfer-Encoding");
1226                                 contentLength = bodyBufferLength;
1227                                 writeStream.SendChunked = false;
1228                         }
1229
1230                         SendRequestHeaders (false);
1231
1232                         haveRequest = true;
1233                         
1234                         if (bodyBuffer != null) {
1235                                 // The body has been written and buffered. The request "user"
1236                                 // won't write it again, so we must do it.
1237                                 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1238                                         writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1239                                         bodyBuffer = null;
1240                                         writeStream.Close ();
1241                                 }
1242                         } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1243                                         method != "TRACE") {
1244                                 if (getResponseCalled && !writeStream.RequestWritten)
1245                                         writeStream.WriteRequest ();
1246                         }
1247
1248                         if (asyncWrite != null) {
1249                                 asyncWrite.SetCompleted (false, stream);
1250                                 asyncWrite.DoCallback ();
1251                                 asyncWrite = null;
1252                         }
1253                 }
1254
1255                 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1256                 {
1257                         if (Aborted)
1258                                 return;
1259                         lock (locker) {
1260                         string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1261                         WebAsyncResult r = asyncRead;
1262                         if (r == null)
1263                                 r = asyncWrite;
1264
1265                         WebException wexc;
1266                         if (e is WebException) {
1267                                 wexc = (WebException) e;
1268                         } else {
1269                                 wexc = new WebException (msg, e, status, null); 
1270                         }
1271                         if (r != null) {
1272                                 if (!r.IsCompleted) {
1273                                         r.SetCompleted (false, wexc);
1274                                         r.DoCallback ();
1275                                 } else if (r == asyncWrite) {
1276                                         saved_exc = wexc;
1277                                 }
1278                                 haveResponse = true;
1279                                 asyncRead = null;
1280                                 asyncWrite = null;
1281                         } else {
1282                                 haveResponse = true;
1283                                 saved_exc = wexc;
1284                         }
1285                         }
1286                 }
1287
1288                 void CheckSendError (WebConnectionData data)
1289                 {
1290                         // Got here, but no one called GetResponse
1291                         int status = data.StatusCode;
1292                         if (status < 400 || status == 401 || status == 407)
1293                                 return;
1294
1295                         if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1296                                 // The request has not been completely sent and we got here!
1297                                 // We should probably just close and cause an error in any case,
1298                                 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse); 
1299                                 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1300                                         webResponse.ReadAll ();
1301                                 } else {
1302                                         writeStream.IgnoreIOErrors = true;
1303                                 }
1304                         }
1305                 }
1306
1307                 void HandleNtlmAuth (WebAsyncResult r)
1308                 {
1309                         WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1310                         if (wce != null) {
1311                                 WebConnection cnc = wce.Connection;
1312                                 cnc.PriorityRequest = this;
1313                                 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1314                                 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1315                                 if (creds != null) {
1316                                         cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1317                                         cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1318                                 }
1319                         }
1320                         r.Reset ();
1321                         finished_reading = false;
1322                         haveResponse = false;
1323                         webResponse.ReadAll ();
1324                         webResponse = null;
1325                 }
1326
1327                 internal void SetResponseData (WebConnectionData data)
1328                 {
1329                         lock (locker) {
1330                         if (Aborted) {
1331                                 if (data.stream != null)
1332                                         data.stream.Close ();
1333                                 return;
1334                         }
1335
1336                         WebException wexc = null;
1337                         try {
1338                                 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1339                         } catch (Exception e) {
1340                                 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null); 
1341                                 if (data.stream != null)
1342                                         data.stream.Close ();
1343                         }
1344
1345                         if (wexc == null && (method == "POST" || method == "PUT")) {
1346                                 CheckSendError (data);
1347                                 if (saved_exc != null)
1348                                         wexc = (WebException) saved_exc;
1349                         }
1350
1351                         WebAsyncResult r = asyncRead;
1352
1353                         bool forced = false;
1354                         if (r == null && webResponse != null) {
1355                                 // This is a forced completion (302, 204)...
1356                                 forced = true;
1357                                 r = new WebAsyncResult (null, null);
1358                                 r.SetCompleted (false, webResponse);
1359                         }
1360
1361                         if (r != null) {
1362                                 if (wexc != null) {
1363                                         haveResponse = true;
1364                                         if (!r.IsCompleted)
1365                                                 r.SetCompleted (false, wexc);
1366                                         r.DoCallback ();
1367                                         return;
1368                                 }
1369
1370                                 bool redirected;
1371                                 try {
1372                                         redirected = CheckFinalStatus (r);
1373                                         if (!redirected) {
1374                                                 if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
1375                                                         && (int)webResponse.StatusCode < 400) {
1376                                                         WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1377                                                         if (wce != null) {
1378                                                                 WebConnection cnc = wce.Connection;
1379                                                                 cnc.NtlmAuthenticated = true;
1380                                                         }
1381                                                 }
1382
1383                                                 // clear internal buffer so that it does not
1384                                                 // hold possible big buffer (bug #397627)
1385                                                 if (writeStream != null)
1386                                                         writeStream.KillBuffer ();
1387
1388                                                 haveResponse = true;
1389                                                 r.SetCompleted (false, webResponse);
1390                                                 r.DoCallback ();
1391                                         } else {
1392                                                 if (webResponse != null) {
1393                                                         if (ntlm_auth_state != NtlmAuthState.None) {
1394                                                                 HandleNtlmAuth (r);
1395                                                                 return;
1396                                                         }
1397                                                         webResponse.Close ();
1398                                                 }
1399                                                 finished_reading = false;
1400                                                 haveResponse = false;
1401                                                 webResponse = null;
1402                                                 r.Reset ();
1403                                                 servicePoint = GetServicePoint ();
1404                                                 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1405                                         }
1406                                 } catch (WebException wexc2) {
1407                                         if (forced) {
1408                                                 saved_exc = wexc2;
1409                                                 haveResponse = true;
1410                                         }
1411                                         r.SetCompleted (false, wexc2);
1412                                         r.DoCallback ();
1413                                         return;
1414                                 } catch (Exception ex) {
1415                                         wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null); 
1416                                         if (forced) {
1417                                                 saved_exc = wexc;
1418                                                 haveResponse = true;
1419                                         }
1420                                         r.SetCompleted (false, wexc);
1421                                         r.DoCallback ();
1422                                         return;
1423                                 }
1424                         }
1425                         }
1426                 }
1427
1428                 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1429                 {
1430                         authCompleted = false;
1431                         if (code == HttpStatusCode.Unauthorized && credentials == null)
1432                                 return false;
1433
1434                         bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1435                         if (isProxy && (proxy == null || proxy.Credentials == null))
1436                                 return false;
1437
1438                         string [] authHeaders = response.Headers.GetValues ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate");
1439                         if (authHeaders == null || authHeaders.Length == 0)
1440                                 return false;
1441
1442                         ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1443                         Authorization auth = null;
1444                         foreach (string authHeader in authHeaders) {
1445                                 auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1446                                 if (auth != null)
1447                                         break;
1448                         }
1449                         if (auth == null)
1450                                 return false;
1451                         webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1452                         authCompleted = auth.Complete;
1453                         bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1454                         if (is_ntlm)
1455                                 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1456                         return true;
1457                 }
1458
1459                 // Returns true if redirected
1460                 bool CheckFinalStatus (WebAsyncResult result)
1461                 {
1462                         if (result.GotException) {
1463                                 bodyBuffer = null;
1464                                 throw result.Exception;
1465                         }
1466
1467                         Exception throwMe = result.Exception;
1468
1469                         HttpWebResponse resp = result.Response;
1470                         WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1471                         HttpStatusCode code = 0;
1472                         if (throwMe == null && webResponse != null) {
1473                                 code = webResponse.StatusCode;
1474                                 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1475                                      (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1476                                         if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1477                                                 // Keep the written body, so it can be rewritten in the retry
1478                                                 if (InternalAllowBuffering) {
1479                                                         // NTLM: This is to avoid sending data in the 'challenge' request
1480                                                         // We save it in the first request (first 401), don't send anything
1481                                                         // in the challenge request and send it in the response request along
1482                                                         // with the buffers kept form the first request.
1483                                                         if (ntlm_auth_state != NtlmAuthState.Response) {
1484                                                                 bodyBuffer = writeStream.WriteBuffer;
1485                                                                 bodyBufferLength = writeStream.WriteBufferLength;
1486                                                         }
1487                                                         return true;
1488                                                 } else if (method != "PUT" && method != "POST") {
1489                                                         bodyBuffer = null;
1490                                                         return true;
1491                                                 }
1492                                                 
1493                                                 writeStream.InternalClose ();
1494                                                 writeStream = null;
1495                                                 webResponse.Close ();
1496                                                 webResponse = null;
1497                                                 bodyBuffer = null;
1498
1499                                                 throw new WebException ("This request requires buffering " +
1500                                                                         "of data for authentication or " +
1501                                                                         "redirection to be sucessful.");
1502                                         }
1503                                 }
1504
1505                                 bodyBuffer = null;
1506                                 if ((int) code >= 400) {
1507                                         string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1508                                                                     (int) code, webResponse.StatusDescription);
1509                                         throwMe = new WebException (err, null, protoError, webResponse);
1510                                         webResponse.ReadAll ();
1511                                 } else if ((int) code == 304 && allowAutoRedirect) {
1512                                         string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1513                                                                     (int) code, webResponse.StatusDescription);
1514                                         throwMe = new WebException (err, null, protoError, webResponse);
1515                                 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1516                                         throwMe = new WebException ("Max. redirections exceeded.", null,
1517                                                                     protoError, webResponse);
1518                                         webResponse.ReadAll ();
1519                                 }
1520                         }
1521
1522                         bodyBuffer = null;
1523                         if (throwMe == null) {
1524                                 bool b = false;
1525                                 int c = (int) code;
1526                                 if (allowAutoRedirect && c >= 300) {
1527                                         if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1528                                                 bodyBuffer = writeStream.WriteBuffer;
1529                                                 bodyBufferLength = writeStream.WriteBufferLength;
1530                                         }
1531                                         b = Redirect (result, code);
1532                                 }
1533
1534                                 if (resp != null && c >= 300 && c != 304)
1535                                         resp.ReadAll ();
1536
1537                                 return b;
1538                         }
1539
1540                         if (writeStream != null) {
1541                                 writeStream.InternalClose ();
1542                                 writeStream = null;
1543                         }
1544
1545                         webResponse = null;
1546
1547                         throw throwMe;
1548                 }
1549         }
1550 }
1551