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