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