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