Thanks Lluis for noticing this.
[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 //
11
12 using System;
13 using System.Collections;
14 using System.IO;
15 using System.Net.Sockets;
16 using System.Runtime.Remoting.Messaging;
17 using System.Runtime.Serialization;
18 using System.Security.Cryptography.X509Certificates;
19 using System.Text;
20 using System.Threading;
21
22 namespace System.Net 
23 {
24         [Serializable]
25         public class HttpWebRequest : WebRequest, ISerializable
26         {
27                 Uri requestUri;
28                 Uri actualUri;
29                 bool hostChanged;
30                 bool allowAutoRedirect = true;
31                 bool allowBuffering = true;
32                 X509CertificateCollection certificates;
33                 string connectionGroup;
34                 long contentLength = -1;
35                 HttpContinueDelegate continueDelegate;
36                 CookieContainer cookieContainer;
37                 ICredentials credentials;
38                 bool haveResponse;              
39                 bool haveRequest;
40                 bool requestSent;
41                 WebHeaderCollection webHeaders = new WebHeaderCollection (true);
42                 bool keepAlive = true;
43                 int maxAutoRedirect = 50;
44                 string mediaType = String.Empty;
45                 string method = "GET";
46                 string initialMethod = "GET";
47                 bool pipelined = true;
48                 bool preAuthenticate;
49                 Version version = HttpVersion.Version11;
50                 IWebProxy proxy;
51                 bool sendChunked;
52                 ServicePoint servicePoint;
53                 int timeout = 100000;
54                 
55                 WebConnectionStream writeStream;
56                 HttpWebResponse webResponse;
57                 WebAsyncResult asyncWrite;
58                 WebAsyncResult asyncRead;
59                 EventHandler abortHandler;
60                 bool aborted;
61                 bool gotRequestStream;
62                 int redirects;
63                 bool expectContinue;
64                 bool authCompleted;
65                 byte[] bodyBuffer;
66                 int bodyBufferLength;
67                 
68                 // Constructors
69                 
70                 internal HttpWebRequest (Uri uri) 
71                 {
72                         this.requestUri = uri;
73                         this.actualUri = uri;
74                         this.proxy = GlobalProxySelection.Select;
75                 }               
76                 
77                 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext) 
78                 {
79                         SerializationInfo info = serializationInfo;
80
81                         requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
82                         actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
83                         allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
84                         allowBuffering = info.GetBoolean ("allowBuffering");
85                         certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
86                         connectionGroup = info.GetString ("connectionGroup");
87                         contentLength = info.GetInt64 ("contentLength");
88                         webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
89                         keepAlive = info.GetBoolean ("keepAlive");
90                         maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
91                         mediaType = info.GetString ("mediaType");
92                         method = info.GetString ("method");
93                         initialMethod = info.GetString ("initialMethod");
94                         pipelined = info.GetBoolean ("pipelined");
95                         version = (Version) info.GetValue ("version", typeof (Version));
96                         proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
97                         sendChunked = info.GetBoolean ("sendChunked");
98                         timeout = info.GetInt32 ("timeout");
99                         redirects = info.GetInt32 ("redirects");
100                 }
101                 
102                 // Properties
103                 
104                 public string Accept {
105                         get { return webHeaders ["Accept"]; }
106                         set {
107                                 CheckRequestStarted ();
108                                 webHeaders.SetInternal ("Accept", value);
109                         }
110                 }
111                 
112                 public Uri Address {
113                         get { return actualUri; }
114                 }
115                 
116                 public bool AllowAutoRedirect {
117                         get { return allowAutoRedirect; }
118                         set { this.allowAutoRedirect = value; }
119                 }
120                 
121                 public bool AllowWriteStreamBuffering {
122                         get { return allowBuffering; }
123                         set { allowBuffering = value; }
124                 }
125                 
126                 internal bool InternalAllowBuffering {
127                         get {
128                                 return (allowBuffering && (method == "PUT" || method == "POST"));
129                         }
130                 }
131                 
132                 public X509CertificateCollection ClientCertificates {
133                         get {
134                                 if (certificates == null)
135                                         certificates = new X509CertificateCollection ();
136
137                                 return certificates;
138                         }
139                 }
140                 
141                 public string Connection {
142                         get { return webHeaders ["Connection"]; }
143                         set {
144                                 CheckRequestStarted ();
145                                 string val = value;
146                                 if (val != null) 
147                                         val = val.Trim ().ToLower ();
148
149                                 if (val == null || val.Length == 0) {
150                                         webHeaders.RemoveInternal ("Connection");
151                                         return;
152                                 }
153
154                                 if (val == "keep-alive" || val == "close") 
155                                         throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
156
157                                 if (keepAlive && val.IndexOf ("keep-alive") == -1)
158                                         value = value + ", Keep-Alive";
159                                 
160                                 webHeaders.SetInternal ("Connection", value);
161                         }
162                 }               
163                 
164                 public override string ConnectionGroupName { 
165                         get { return connectionGroup; }
166                         set { connectionGroup = value; }
167                 }
168                 
169                 public override long ContentLength { 
170                         get { return contentLength; }
171                         set { 
172                                 CheckRequestStarted ();
173                                 if (value < 0)
174                                         throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
175                                         
176                                 contentLength = value;
177                         }
178                 }
179                 
180                 internal long InternalContentLength {
181                         set { contentLength = value; }
182                 }
183                 
184                 public override string ContentType { 
185                         get { return webHeaders ["Content-Type"]; }
186                         set {
187                                 CheckRequestStarted ();
188                                 if (value == null || value.Trim().Length == 0) {
189                                         webHeaders.RemoveInternal ("Content-Type");
190                                         return;
191                                 }
192                                 webHeaders.SetInternal ("Content-Type", value);
193                         }
194                 }
195                 
196                 public HttpContinueDelegate ContinueDelegate {
197                         get { return continueDelegate; }
198                         set { continueDelegate = value; }
199                 }
200                 
201                 public CookieContainer CookieContainer {
202                         get { return cookieContainer; }
203                         set { cookieContainer = value; }
204                 }
205                 
206                 public override ICredentials Credentials { 
207                         get { return credentials; }
208                         set { credentials = value; }
209                 }
210                 
211                 public string Expect {
212                         get { return webHeaders ["Expect"]; }
213                         set {
214                                 CheckRequestStarted ();
215                                 string val = value;
216                                 if (val != null)
217                                         val = val.Trim ().ToLower ();
218
219                                 if (val == null || val.Length == 0) {
220                                         webHeaders.RemoveInternal ("Expect");
221                                         return;
222                                 }
223
224                                 if (val == "100-continue")
225                                         throw new ArgumentException ("100-Continue cannot be set with this property.",
226                                                                      "value");
227                                 webHeaders.SetInternal ("Expect", value);
228                         }
229                 }
230                 
231                 public bool HaveResponse {
232                         get { return haveResponse; }
233                 }
234                 
235                 public override WebHeaderCollection Headers { 
236                         get { return webHeaders; }
237                         set {
238                                 CheckRequestStarted ();
239                                 WebHeaderCollection newHeaders = new WebHeaderCollection (true);
240                                 int count = value.Count;
241                                 for (int i = 0; i < count; i++) 
242                                         newHeaders.Add (value.GetKey (i), value.Get (i));
243
244                                 webHeaders = newHeaders;
245                         }
246                 }
247                 
248                 public DateTime IfModifiedSince {
249                         get { 
250                                 string str = webHeaders ["If-Modified-Since"];
251                                 if (str == null)
252                                         return DateTime.Now;
253                                 try {
254                                         return MonoHttpDate.Parse (str);
255                                 } catch (Exception) {
256                                         return DateTime.Now;
257                                 }
258                         }
259                         set {
260                                 CheckRequestStarted ();
261                                 // rfc-1123 pattern
262                                 webHeaders.SetInternal ("If-Modified-Since", 
263                                         value.ToUniversalTime ().ToString ("r", null));
264                                 // TODO: check last param when using different locale
265                         }
266                 }
267
268                 public bool KeepAlive {         
269                         get {
270                                 return keepAlive;
271                         }
272                         set {
273                                 keepAlive = value;
274                         }
275                 }
276                 
277                 public int MaximumAutomaticRedirections {
278                         get { return maxAutoRedirect; }
279                         set {
280                                 if (value <= 0)
281                                         throw new ArgumentException ("Must be > 0", "value");
282
283                                 maxAutoRedirect = value;
284                         }                       
285                 }
286                 
287                 public string MediaType {
288                         get { return mediaType; }
289                         set { 
290                                 mediaType = value;
291                         }
292                 }
293                 
294                 public override string Method { 
295                         get { return this.method; }
296                         set { 
297                                 if (value == null || value.Trim () == "")
298                                         throw new ArgumentException ("not a valid method");
299
300                                 method = value;
301                         }
302                 }
303                 
304                 public bool Pipelined {
305                         get { return pipelined; }
306                         set { pipelined = value; }
307                 }               
308                 
309                 public override bool PreAuthenticate { 
310                         get { return preAuthenticate; } //TODO: support preauthentication
311                         set { preAuthenticate = value; }
312                 }
313                 
314                 public Version ProtocolVersion {
315                         get { return version; }
316                         set { 
317                                 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
318                                         throw new ArgumentException ("value");
319
320                                 version = value; 
321                         }
322                 }
323                 
324                 public override IWebProxy Proxy { 
325                         get { return proxy; }
326                         set { 
327                                 CheckRequestStarted ();
328                                 if (value == null)
329                                         throw new ArgumentNullException ("value");
330
331                                 proxy = value;
332                                 servicePoint = null; // we may need a new one
333                         }
334                 }
335                 
336                 public string Referer {
337                         get { return webHeaders ["Referer"]; }
338                         set {
339                                 CheckRequestStarted ();
340                                 if (value == null || value.Trim().Length == 0) {
341                                         webHeaders.RemoveInternal ("Referer");
342                                         return;
343                                 }
344                                 webHeaders.SetInternal ("Referer", value);
345                         }
346                 }
347
348                 public override Uri RequestUri { 
349                         get { return requestUri; }
350                 }
351                 
352                 public bool SendChunked {
353                         get { return sendChunked; }
354                         set {
355                                 CheckRequestStarted ();
356                                 sendChunked = value;
357                         }
358                 }
359                 
360                 public ServicePoint ServicePoint {
361                         get { return GetServicePoint (); }
362                 }
363                 
364                 public override int Timeout { 
365                         get { return timeout; }
366                         set {
367                                 if (value < -1)
368                                         throw new ArgumentOutOfRangeException ("value");
369
370                                 timeout = value;
371                         }
372                 }
373                 
374                 public string TransferEncoding {
375                         get { return webHeaders ["Transfer-Encoding"]; }
376                         set {
377                                 CheckRequestStarted ();
378                                 string val = value;
379                                 if (val != null)
380                                         val = val.Trim ().ToLower ();
381
382                                 if (val == null || val.Length == 0) {
383                                         webHeaders.RemoveInternal ("Transfer-Encoding");
384                                         return;
385                                 }
386
387                                 if (val == "chunked")
388                                         throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
389
390                                 if (!sendChunked)
391                                         throw new ArgumentException ("SendChunked must be True", "value");
392
393                                 webHeaders.SetInternal ("Transfer-Encoding", value);
394                         }
395                 }
396                 
397                 public string UserAgent {
398                         get { return webHeaders ["User-Agent"]; }
399                         set { webHeaders.SetInternal ("User-Agent", value); }
400                 }
401
402 #if NET_1_1
403                 [MonoTODO]
404                 public bool UnsafeAuthenticatedConnectionSharing
405                 {
406                         get { throw new NotImplementedException (); }
407                         set { throw new NotImplementedException (); }
408                 }
409 #endif
410
411                 internal bool GotRequestStream {
412                         get { return gotRequestStream; }
413                 }
414
415                 internal bool ExpectContinue {
416                         get { return expectContinue; }
417                         set { expectContinue = value; }
418                 }
419                 
420                 internal Uri AuthUri {
421                         get { return actualUri; }
422                 }
423                 
424                 internal bool ProxyQuery {
425                         get { return servicePoint.UsesProxy; }
426                 }
427                 
428                 // Methods
429                 
430                 internal ServicePoint GetServicePoint ()
431                 {
432                         if (!hostChanged && servicePoint != null)
433                                 return servicePoint;
434
435                         lock (this) {
436                                 if (hostChanged || servicePoint == null) {
437                                         servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
438                                         hostChanged = false;
439                                 }
440                         }
441
442                         return servicePoint;
443                 }
444                 
445                 public void AddRange (int range)
446                 {
447                         AddRange ("bytes", range);
448                 }
449                 
450                 public void AddRange (int from, int to)
451                 {
452                         AddRange ("bytes", from, to);
453                 }
454                 
455                 public void AddRange (string rangeSpecifier, int range)
456                 {
457                         if (rangeSpecifier == null)
458                                 throw new ArgumentNullException ("rangeSpecifier");
459                         string value = webHeaders ["Range"];
460                         if (value == null || value.Length == 0) 
461                                 value = rangeSpecifier + "=";
462                         else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
463                                 value += ",";
464                         else
465                                 throw new InvalidOperationException ("rangeSpecifier");
466                         webHeaders.SetInternal ("Range", value + range + "-");  
467                 }
468                 
469                 public void AddRange (string rangeSpecifier, int from, int to)
470                 {
471                         if (rangeSpecifier == null)
472                                 throw new ArgumentNullException ("rangeSpecifier");
473                         if (from < 0 || to < 0 || from > to)
474                                 throw new ArgumentOutOfRangeException ();                       
475                         string value = webHeaders ["Range"];
476                         if (value == null || value.Length == 0) 
477                                 value = rangeSpecifier + "=";
478                         else if (value.ToLower ().StartsWith (rangeSpecifier.ToLower () + "="))
479                                 value += ",";
480                         else
481                                 throw new InvalidOperationException ("rangeSpecifier");
482                         webHeaders.SetInternal ("Range", value + from + "-" + to);      
483                 }
484                 
485                 public override int GetHashCode ()
486                 {
487                         return base.GetHashCode ();
488                 }
489                 
490                 void CommonChecks (bool putpost)
491                 {
492                         if (method == null)
493                                 throw new ProtocolViolationException ("Method is null.");
494
495                         if (putpost && ((!keepAlive || (contentLength == -1 && !sendChunked)) && !allowBuffering))
496                                 throw new ProtocolViolationException ("Content-Length not set");
497
498                         string transferEncoding = TransferEncoding;
499                         if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
500                                 throw new ProtocolViolationException ("SendChunked should be true.");
501                 }
502
503                 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state) 
504                 {
505                         if (aborted)
506                                 throw new WebException ("The request was previosly aborted.");
507
508                         bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD");
509                         if (method == null || !send)
510                                 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
511
512                         CommonChecks (send);
513                         Monitor.Enter (this);
514                         if (asyncWrite != null) {
515                                 Monitor.Exit (this);
516                                 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
517                                                         "method while a previous call is still in progress.");
518                         }
519
520                         asyncWrite = new WebAsyncResult (this, callback, state);
521                         initialMethod = method;
522                         if (haveRequest) {
523                                 if (writeStream != null) {
524                                         Monitor.Exit (this);
525                                         asyncWrite.SetCompleted (true, writeStream);
526                                         asyncWrite.DoCallback ();
527                                         return asyncWrite;
528                                 }
529                         }
530                         
531                         gotRequestStream = true;
532                         WebAsyncResult result = asyncWrite;
533                         if (!requestSent) {
534                                 requestSent = true;
535                                 servicePoint = GetServicePoint ();
536                                 abortHandler = servicePoint.SendRequest (this, connectionGroup);
537                         }
538                         Monitor.Exit (this);
539                         return result;
540                 }
541
542                 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
543                 {
544                         if (asyncResult == null)
545                                 throw new ArgumentNullException ("asyncResult");
546
547                         WebAsyncResult result = asyncResult as WebAsyncResult;
548                         if (result == null)
549                                 throw new ArgumentException ("Invalid IAsyncResult");
550
551                         asyncWrite = result;
552                         result.WaitUntilComplete ();
553
554                         Exception e = result.Exception;
555                         if (e != null)
556                                 throw e;
557
558                         return result.WriteStream;
559                 }
560                 
561                 public override Stream GetRequestStream()
562                 {
563                         IAsyncResult asyncResult = BeginGetRequestStream (null, null);
564                         asyncWrite = (WebAsyncResult) asyncResult;
565                         if (!asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
566                                 Abort ();
567                                 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
568                         }
569
570                         return EndGetRequestStream (asyncResult);
571                 }
572                 
573                 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
574                 {
575                         bool send = (method == "PUT" || method == "POST");
576                         if (send) {
577                                 if ((!KeepAlive || (ContentLength == -1 && !SendChunked)) && !AllowWriteStreamBuffering)
578                                         throw new ProtocolViolationException ("Content-Length not set");
579                         }
580
581                         CommonChecks (send);
582                         Monitor.Enter (this);
583                         if (asyncRead != null && !haveResponse) {
584                                 Monitor.Exit (this);
585                                 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
586                                                         "method while a previous call is still in progress.");
587                         }
588
589                         asyncRead = new WebAsyncResult (this, callback, state);
590                         initialMethod = method;
591                         if (haveResponse) {
592                                 if (webResponse != null) {
593                                         Monitor.Exit (this);
594                                         asyncRead.SetCompleted (true, webResponse);
595                                         asyncRead.DoCallback ();
596                                         return asyncRead;
597                                 }
598                         }
599                         
600                         if (!requestSent) {
601                                 requestSent = true;
602                                 servicePoint = GetServicePoint ();
603                                 abortHandler = servicePoint.SendRequest (this, connectionGroup);
604                         }
605
606                         Monitor.Exit (this);
607                         return asyncRead;
608                 }
609                 
610                 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
611                 {
612                         if (asyncResult == null)
613                                 throw new ArgumentNullException ("asyncResult");
614
615                         WebAsyncResult result = asyncResult as WebAsyncResult;
616                         if (result == null)
617                                 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
618
619                         redirects = 0;
620                         bool redirected = false;
621                         asyncRead = result;
622                         do {
623                                 if (redirected) {
624                                         haveResponse = false;
625                                         result.Reset ();
626                                         servicePoint = GetServicePoint ();
627                                         abortHandler = servicePoint.SendRequest (this, connectionGroup);
628                                 }
629
630                                 if (!result.WaitUntilComplete (timeout, false)) {
631                                         Abort ();
632                                         throw new WebException("The request timed out", WebExceptionStatus.Timeout);
633                                 }
634
635                                 redirected = CheckFinalStatus (result);
636                         } while (redirected);
637                         
638                         return result.Response;
639                 }
640                 
641                 public override WebResponse GetResponse()
642                 {
643                         if (haveResponse && webResponse != null)
644                                 return webResponse;
645
646                         WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
647                         return EndGetResponse (result);
648                 }
649                 
650                 public override void Abort ()
651                 {
652                         haveResponse = true;
653                         aborted = true;
654                         if (asyncWrite != null) {
655                                 WebAsyncResult r = asyncWrite;
656                                 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled); 
657                                 r.SetCompleted (false, wexc);
658                                 r.DoCallback ();
659                                 asyncWrite = null;
660                         }                       
661
662                         if (asyncRead != null) {
663                                 WebAsyncResult r = asyncRead;
664                                 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled); 
665                                 r.SetCompleted (false, wexc);
666                                 r.DoCallback ();
667                                 asyncRead = null;
668                         }                       
669
670                         if (abortHandler != null) {
671                                 try {
672                                         abortHandler (this, EventArgs.Empty);
673                                 } catch {}
674                                 abortHandler = null;
675                         }
676
677                         if (writeStream != null) {
678                                 try {
679                                         writeStream.Close ();
680                                         writeStream = null;
681                                 } catch {}
682                         }
683
684                         if (webResponse != null) {
685                                 try {
686                                         webResponse.Close ();
687                                         webResponse = null;
688                                 } catch {}
689                         }
690                 }               
691                 
692                 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
693                                                   StreamingContext streamingContext)
694                 {
695                         SerializationInfo info = serializationInfo;
696
697                         info.AddValue ("requestUri", requestUri, typeof (Uri));
698                         info.AddValue ("actualUri", actualUri, typeof (Uri));
699                         info.AddValue ("allowAutoRedirect", allowAutoRedirect);
700                         info.AddValue ("allowBuffering", allowBuffering);
701                         info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
702                         info.AddValue ("connectionGroup", connectionGroup);
703                         info.AddValue ("contentLength", contentLength);
704                         info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
705                         info.AddValue ("keepAlive", keepAlive);
706                         info.AddValue ("maxAutoRedirect", maxAutoRedirect);
707                         info.AddValue ("mediaType", mediaType);
708                         info.AddValue ("method", method);
709                         info.AddValue ("initialMethod", initialMethod);
710                         info.AddValue ("pipelined", pipelined);
711                         info.AddValue ("version", version, typeof (Version));
712                         info.AddValue ("proxy", proxy, typeof (IWebProxy));
713                         info.AddValue ("sendChunked", sendChunked);
714                         info.AddValue ("timeout", timeout);
715                         info.AddValue ("redirects", redirects);
716                 }
717                 
718                 void CheckRequestStarted () 
719                 {
720                         if (requestSent)
721                                 throw new InvalidOperationException ("request started");
722                 }
723
724                 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
725                 {
726                         if (continueDelegate != null)
727                                 continueDelegate (statusCode, headers);
728                 }
729                 
730                 bool Redirect (WebAsyncResult result, HttpStatusCode code)
731                 {
732                         redirects++;
733                         Exception e = null;
734                         string uriString = null;
735
736                         switch (code) {
737                         case HttpStatusCode.Ambiguous: // 300
738                                 e = new WebException ("Ambiguous redirect.");
739                                 break;
740                         case HttpStatusCode.MovedPermanently: // 301
741                         case HttpStatusCode.Redirect: // 302
742                         case HttpStatusCode.TemporaryRedirect: // 307
743                                 if (method != "GET" && method != "HEAD") // 10.3
744                                         return false;
745
746                                 uriString = webResponse.Headers ["Location"];
747                                 break;
748                         case HttpStatusCode.SeeOther: //303
749                                 method = "GET";
750                                 uriString = webResponse.Headers ["Location"];
751                                 break;
752                         case HttpStatusCode.NotModified: // 304
753                                 return false;
754                         case HttpStatusCode.UseProxy: // 305
755                                 e = new NotImplementedException ("Proxy support not available.");
756                                 break;
757                         case HttpStatusCode.Unused: // 306
758                         default:
759                                 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
760                                 break;
761                         }
762
763                         if (e != null)
764                                 throw e;
765
766                         string host = actualUri.Host;
767                         actualUri = new Uri (actualUri, uriString);
768                         hostChanged = (actualUri.Host != host);
769                         return true;
770                 }
771
772                 string GetHeaders ()
773                 {
774                         bool continue100 = false;
775                         if (gotRequestStream && contentLength != -1) {
776                                 continue100 = true;
777                                 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
778                         } else if (sendChunked) {
779                                 continue100 = true;
780                                 webHeaders.SetInternal ("Transfer-Encoding", "chunked");
781                         }
782
783                         if (version == HttpVersion.Version11 && continue100 &&
784                             servicePoint.SendContinue) { // RFC2616 8.2.3
785                                 webHeaders.SetInternal ("Expect" , "100-continue");
786                                 expectContinue = true;
787                         } else {
788                                 expectContinue = false;
789                         }
790
791                         string connectionHeader = (ProxyQuery) ? "Proxy-Connection" : "Connection";
792                         webHeaders.RemoveInternal ((!ProxyQuery) ? "Proxy-Connection" : "Connection");
793                                 
794                         if (keepAlive && version == HttpVersion.Version10) {
795                                 webHeaders.SetInternal (connectionHeader, "keep-alive");
796                         } else if (!keepAlive && version == HttpVersion.Version11) {
797                                 webHeaders.SetInternal (connectionHeader, "close");
798                         }
799
800                         webHeaders.SetInternal ("Host", actualUri.Host);
801                         if (cookieContainer != null) {
802                                 string cookieHeader = cookieContainer.GetCookieHeader (requestUri);
803                                 if (cookieHeader != "")
804                                         webHeaders.SetInternal ("Cookie", cookieHeader);
805                         }
806
807                         return webHeaders.ToString ();
808                 }
809                 
810                 internal void SetWriteStreamError (WebExceptionStatus status)
811                 {
812                         if (aborted)
813                                 return;
814
815                         WebAsyncResult r = asyncWrite;
816                         if (r == null)
817                                 r = asyncRead;
818
819                         if (r != null) {
820                                 r.SetCompleted (false, new WebException ("Error: " + status, status));
821                                 r.DoCallback ();
822                         }
823                 }
824
825                 internal void SendRequestHeaders ()
826                 {
827                         StringBuilder req = new StringBuilder ();
828                         string query;
829                         if (!ProxyQuery) {
830                                 query = actualUri.PathAndQuery;
831                         } else if (actualUri.IsDefaultPort) {
832                                 query = String.Format ("{0}://{1}{2}",  actualUri.Scheme,
833                                                                         actualUri.Host,
834                                                                         actualUri.PathAndQuery);
835                         } else {
836                                 query = String.Format ("{0}://{1}:{2}{3}", actualUri.Scheme,
837                                                                            actualUri.Host,
838                                                                            actualUri.Port,
839                                                                            actualUri.PathAndQuery);
840                         }
841                         
842                         req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query, version.Major, version.Minor);
843                         req.Append (GetHeaders ());
844                         string reqstr = req.ToString ();
845                         byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
846                         writeStream.SetHeaders (bytes, 0, bytes.Length);
847                 }
848
849                 internal void SetWriteStream (WebConnectionStream stream)
850                 {
851                         if (aborted)
852                                 return;
853                         
854                         writeStream = stream;
855                         if (bodyBuffer != null) {
856                                 webHeaders.RemoveInternal ("Transfer-Encoding");
857                                 contentLength = bodyBufferLength;
858                                 writeStream.SendChunked = false;
859                         }
860                         
861                         SendRequestHeaders ();
862
863                         haveRequest = true;
864                         
865                         if (bodyBuffer != null) {
866                                 // The body has been written and buffered. The request "user"
867                                 // won't write it again, so we must do it.
868                                 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
869                                 bodyBuffer = null;
870                                 writeStream.Close ();
871                         }
872
873                         if (asyncWrite != null) {
874                                 asyncWrite.SetCompleted (false, stream);
875                                 asyncWrite.DoCallback ();
876                                 asyncWrite = null;
877                         }
878                 }
879
880                 internal void SetResponseError (WebExceptionStatus status, Exception e)
881                 {
882                         WebAsyncResult r = asyncRead;
883                         if (r == null)
884                                 r = asyncWrite;
885
886                         if (r != null) {
887                                 WebException wexc = new WebException ("Error getting response stream", e, status, null); 
888                                 r.SetCompleted (false, wexc);
889                                 r.DoCallback ();
890                                 asyncRead = null;
891                                 asyncWrite = null;
892                         }
893                 }
894                 
895                 internal void SetResponseData (WebConnectionData data)
896                 {
897                         if (aborted) {
898                                 if (data.stream != null)
899                                         data.stream.Close ();
900                                 return;
901                         }
902                         
903                         webResponse = new HttpWebResponse (actualUri, method, data, (cookieContainer != null));
904                         haveResponse = true;
905
906                         WebAsyncResult r = asyncRead;
907                         if (r != null) {
908                                 r.SetCompleted (false, webResponse);
909                                 r.DoCallback ();
910                         }
911                 }
912
913                 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
914                 {
915                         authCompleted = false;
916                         if (code == HttpStatusCode.Unauthorized && credentials == null)
917                                 return false;
918
919                         bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
920                         if (isProxy && (proxy == null || proxy.Credentials == null))
921                                 return false;
922
923                         string authHeader = response.Headers [(isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate"];
924                         if (authHeader == null)
925                                 return false;
926
927                         ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
928                         Authorization auth = AuthenticationManager.Authenticate (authHeader, this, creds);
929                         if (auth == null)
930                                 return false;
931
932                         webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
933                         authCompleted = auth.Complete;
934                         return true;
935                 }
936
937                 // Returns true if redirected
938                 bool CheckFinalStatus (WebAsyncResult result)
939                 {
940                         if (result.GotException)
941                                 throw result.Exception;
942
943                         Exception throwMe = result.Exception;
944                         bodyBuffer = null;
945
946                         HttpWebResponse resp = result.Response;
947                         WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
948                         HttpStatusCode code = 0;
949                         if (throwMe == null && webResponse != null) {
950                                 code  = webResponse.StatusCode;
951                                 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
952                                                         code == HttpStatusCode.ProxyAuthenticationRequired)) {
953                                         if (CheckAuthorization (webResponse, code)) {
954                                                 // Keep the written body, so it can be rewritten in the retry
955                                                 if (allowBuffering) {
956                                                         bodyBuffer = writeStream.WriteBuffer;
957                                                         bodyBufferLength = writeStream.WriteBufferLength;
958                                                         return true;
959                                                 }
960                                                 
961                                                 writeStream.InternalClose ();
962                                                 writeStream = null;
963                                                 webResponse = null;
964                                                 throw new WebException ("This request requires buffering " +
965                                                                         "of data for authentication or " +
966                                                                         "redirection to be sucessful.");
967                                         }
968                                 }
969
970                                 if ((int) code >= 400) {
971                                         string err = String.Format ("The remote server returned an error: ({0}) {1}.",
972                                                                     (int) code, webResponse.StatusDescription);
973                                         throwMe = new WebException (err, null, protoError, webResponse);
974                                 } else if ((int) code == 304 && allowAutoRedirect) {
975                                         string err = String.Format ("The remote server returned an error: ({0}) {1}.",
976                                                                     (int) code, webResponse.StatusDescription);
977                                         throwMe = new WebException (err, null, protoError, webResponse);
978                                 } else if ((int) code >= 300 && allowAutoRedirect && redirects > maxAutoRedirect) {
979                                         throwMe = new WebException ("Max. redirections exceeded.", null,
980                                                                     protoError, webResponse);
981                                 }
982                         }
983
984                         if (throwMe == null) {
985                                 bool b = false;
986                                 if (allowAutoRedirect && (int) code >= 300)
987                                         b = Redirect (result, code);
988
989                                 return b;
990                         }
991
992                         if (writeStream != null) {
993                                 writeStream.InternalClose ();
994                                 writeStream = null;
995                         }
996
997                         if (webResponse != null)
998                                 webResponse = null;
999
1000                         throw throwMe;
1001                 }
1002         }
1003 }
1004