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