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