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