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