2 // System.Net.HttpWebRequest
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // (c) 2002 Lawrence Pit
9 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
10 // (c) 2004 Novell, Inc. (http://www.novell.com)
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:
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
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.
35 using System.Collections;
36 using System.Configuration;
37 using System.Globalization;
39 using System.Net.Cache;
40 using System.Net.Sockets;
41 using System.Runtime.Remoting.Messaging;
42 using System.Runtime.Serialization;
43 using System.Security.Cryptography.X509Certificates;
45 using System.Threading;
50 public class HttpWebRequest : WebRequest, ISerializable {
54 bool allowAutoRedirect = true;
55 bool allowBuffering = true;
56 X509CertificateCollection certificates;
57 string connectionGroup;
58 long contentLength = -1;
59 HttpContinueDelegate continueDelegate;
60 CookieContainer cookieContainer;
61 ICredentials credentials;
65 WebHeaderCollection webHeaders;
66 bool keepAlive = true;
67 int maxAutoRedirect = 50;
68 string mediaType = String.Empty;
69 string method = "GET";
70 string initialMethod = "GET";
71 bool pipelined = true;
74 Version version = HttpVersion.Version11;
76 Version actualVersion;
79 ServicePoint servicePoint;
82 WebConnectionStream writeStream;
83 HttpWebResponse webResponse;
84 WebAsyncResult asyncWrite;
85 WebAsyncResult asyncRead;
86 EventHandler abortHandler;
88 bool gotRequestStream;
94 bool getResponseCalled;
96 object locker = new object ();
97 bool finished_reading;
98 internal WebConnection WebConnection;
99 DecompressionMethods auto_decomp;
100 int maxResponseHeadersLength;
101 static int defaultMaxResponseHeadersLength;
102 int readWriteTimeout = 300000; // ms
109 NtlmAuthState ntlm_auth_state;
113 static HttpWebRequest ()
115 defaultMaxResponseHeadersLength = 64 * 1024;
117 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
118 if (config != null) {
119 int x = config.MaxResponseHeadersLength;
123 defaultMaxResponseHeadersLength = x;
133 HttpWebRequest (Uri uri)
135 this.requestUri = uri;
136 this.actualUri = uri;
137 this.proxy = GlobalProxySelection.Select;
138 this.webHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
142 [Obsolete ("Serialization is obsoleted for this type", false)]
143 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
145 SerializationInfo info = serializationInfo;
147 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
148 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
149 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
150 allowBuffering = info.GetBoolean ("allowBuffering");
151 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
152 connectionGroup = info.GetString ("connectionGroup");
153 contentLength = info.GetInt64 ("contentLength");
154 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
155 keepAlive = info.GetBoolean ("keepAlive");
156 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
157 mediaType = info.GetString ("mediaType");
158 method = info.GetString ("method");
159 initialMethod = info.GetString ("initialMethod");
160 pipelined = info.GetBoolean ("pipelined");
161 version = (Version) info.GetValue ("version", typeof (Version));
162 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
163 sendChunked = info.GetBoolean ("sendChunked");
164 timeout = info.GetInt32 ("timeout");
165 redirects = info.GetInt32 ("redirects");
166 host = info.GetString ("host");
171 public string Accept {
172 get { return webHeaders ["Accept"]; }
174 CheckRequestStarted ();
175 webHeaders.RemoveAndAdd ("Accept", value);
180 get { return actualUri; }
181 internal set { actualUri = value; } // Used by Ftp+proxy
184 public bool AllowAutoRedirect {
185 get { return allowAutoRedirect; }
186 set { this.allowAutoRedirect = value; }
189 public bool AllowWriteStreamBuffering {
190 get { return allowBuffering; }
191 set { allowBuffering = value; }
194 static Exception GetMustImplement ()
196 return new NotImplementedException ();
199 public DecompressionMethods AutomaticDecompression
205 CheckRequestStarted ();
210 internal bool InternalAllowBuffering {
212 return (allowBuffering && (method != "HEAD" && method != "GET" &&
213 method != "MKCOL" && method != "CONNECT" &&
218 public X509CertificateCollection ClientCertificates {
220 if (certificates == null)
221 certificates = new X509CertificateCollection ();
227 throw GetMustImplement ();
231 public string Connection {
232 get { return webHeaders ["Connection"]; }
234 CheckRequestStarted ();
236 if (string.IsNullOrEmpty (value)) {
237 webHeaders.RemoveInternal ("Connection");
241 string val = value.ToLowerInvariant ();
242 if (val.Contains ("keep-alive") || val.Contains ("close"))
243 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
246 value = value + ", Keep-Alive";
248 webHeaders.RemoveAndAdd ("Connection", value);
252 public override string ConnectionGroupName {
253 get { return connectionGroup; }
254 set { connectionGroup = value; }
257 public override long ContentLength {
258 get { return contentLength; }
260 CheckRequestStarted ();
262 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
264 contentLength = value;
268 internal long InternalContentLength {
269 set { contentLength = value; }
272 internal bool ThrowOnError { get; set; }
274 public override string ContentType {
275 get { return webHeaders ["Content-Type"]; }
277 if (value == null || value.Trim().Length == 0) {
278 webHeaders.RemoveInternal ("Content-Type");
281 webHeaders.RemoveAndAdd ("Content-Type", value);
285 public HttpContinueDelegate ContinueDelegate {
286 get { return continueDelegate; }
287 set { continueDelegate = value; }
290 public CookieContainer CookieContainer {
291 get { return cookieContainer; }
292 set { cookieContainer = value; }
295 public override ICredentials Credentials {
296 get { return credentials; }
297 set { credentials = value; }
300 public DateTime Date {
302 string date = webHeaders ["Date"];
304 return DateTime.MinValue;
305 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
308 if (value.Equals (DateTime.MinValue))
309 webHeaders.RemoveInternal ("Date");
311 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
316 public static new RequestCachePolicy DefaultCachePolicy
319 throw GetMustImplement ();
322 throw GetMustImplement ();
327 public static int DefaultMaximumErrorResponseLength
330 throw GetMustImplement ();
333 throw GetMustImplement ();
337 public string Expect {
338 get { return webHeaders ["Expect"]; }
340 CheckRequestStarted ();
343 val = val.Trim ().ToLower ();
345 if (val == null || val.Length == 0) {
346 webHeaders.RemoveInternal ("Expect");
350 if (val == "100-continue")
351 throw new ArgumentException ("100-Continue cannot be set with this property.",
353 webHeaders.RemoveAndAdd ("Expect", value);
357 public bool HaveResponse {
358 get { return haveResponse; }
361 public override WebHeaderCollection Headers {
362 get { return webHeaders; }
364 CheckRequestStarted ();
365 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
366 int count = value.Count;
367 for (int i = 0; i < count; i++)
368 newHeaders.Add (value.GetKey (i), value.Get (i));
370 webHeaders = newHeaders;
382 return actualUri.Authority;
387 throw new ArgumentNullException ("value");
389 if (!CheckValidHost (actualUri.Scheme, value))
390 throw new ArgumentException ("Invalid host: " + value);
396 static bool CheckValidHost (string scheme, string val)
404 int idx = val.IndexOf ('/');
408 string u = scheme + "://" + val + "/";
409 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
412 public DateTime IfModifiedSince {
414 string str = webHeaders ["If-Modified-Since"];
418 return MonoHttpDate.Parse (str);
419 } catch (Exception) {
424 CheckRequestStarted ();
426 webHeaders.SetInternal ("If-Modified-Since",
427 value.ToUniversalTime ().ToString ("r", null));
428 // TODO: check last param when using different locale
432 public bool KeepAlive {
441 public int MaximumAutomaticRedirections {
442 get { return maxAutoRedirect; }
445 throw new ArgumentException ("Must be > 0", "value");
447 maxAutoRedirect = value;
451 [MonoTODO ("Use this")]
452 public int MaximumResponseHeadersLength {
453 get { return maxResponseHeadersLength; }
454 set { maxResponseHeadersLength = value; }
457 [MonoTODO ("Use this")]
458 public static int DefaultMaximumResponseHeadersLength {
459 get { return defaultMaxResponseHeadersLength; }
460 set { defaultMaxResponseHeadersLength = value; }
463 public int ReadWriteTimeout {
464 get { return readWriteTimeout; }
467 throw new InvalidOperationException ("The request has already been sent.");
470 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
472 readWriteTimeout = value;
476 public string MediaType {
477 get { return mediaType; }
483 public override string Method {
484 get { return this.method; }
486 if (value == null || value.Trim () == "")
487 throw new ArgumentException ("not a valid method");
489 method = value.ToUpperInvariant ();
490 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
491 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
498 public bool Pipelined {
499 get { return pipelined; }
500 set { pipelined = value; }
503 public override bool PreAuthenticate {
504 get { return preAuthenticate; }
505 set { preAuthenticate = value; }
508 public Version ProtocolVersion {
509 get { return version; }
511 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
512 throw new ArgumentException ("value");
514 force_version = true;
519 public override IWebProxy Proxy {
520 get { return proxy; }
522 CheckRequestStarted ();
524 servicePoint = null; // we may need a new one
528 public string Referer {
529 get { return webHeaders ["Referer"]; }
531 CheckRequestStarted ();
532 if (value == null || value.Trim().Length == 0) {
533 webHeaders.RemoveInternal ("Referer");
536 webHeaders.SetInternal ("Referer", value);
540 public override Uri RequestUri {
541 get { return requestUri; }
544 public bool SendChunked {
545 get { return sendChunked; }
547 CheckRequestStarted ();
552 public ServicePoint ServicePoint {
553 get { return GetServicePoint (); }
556 internal ServicePoint ServicePointNoLock {
557 get { return servicePoint; }
560 [MonoTODO ("for portable library support")]
561 public bool SupportsCookieContainer {
563 throw new NotImplementedException ();
567 public override int Timeout {
568 get { return timeout; }
571 throw new ArgumentOutOfRangeException ("value");
577 public string TransferEncoding {
578 get { return webHeaders ["Transfer-Encoding"]; }
580 CheckRequestStarted ();
583 val = val.Trim ().ToLower ();
585 if (val == null || val.Length == 0) {
586 webHeaders.RemoveInternal ("Transfer-Encoding");
590 if (val == "chunked")
591 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
594 throw new ArgumentException ("SendChunked must be True", "value");
596 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
600 public override bool UseDefaultCredentials
602 get { return CredentialCache.DefaultCredentials == Credentials; }
603 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
606 public string UserAgent {
607 get { return webHeaders ["User-Agent"]; }
608 set { webHeaders.SetInternal ("User-Agent", value); }
611 bool unsafe_auth_blah;
612 public bool UnsafeAuthenticatedConnectionSharing
614 get { return unsafe_auth_blah; }
615 set { unsafe_auth_blah = value; }
618 internal bool GotRequestStream {
619 get { return gotRequestStream; }
622 internal bool ExpectContinue {
623 get { return expectContinue; }
624 set { expectContinue = value; }
627 internal Uri AuthUri {
628 get { return actualUri; }
631 internal bool ProxyQuery {
632 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
637 internal ServicePoint GetServicePoint ()
640 if (hostChanged || servicePoint == null) {
641 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
649 public void AddRange (int range)
651 AddRange ("bytes", (long) range);
654 public void AddRange (int from, int to)
656 AddRange ("bytes", (long) from, (long) to);
659 public void AddRange (string rangeSpecifier, int range)
661 AddRange (rangeSpecifier, (long) range);
664 public void AddRange (string rangeSpecifier, int from, int to)
666 AddRange (rangeSpecifier, (long) from, (long) to);
673 void AddRange (long range)
675 AddRange ("bytes", (long) range);
683 void AddRange (long from, long to)
685 AddRange ("bytes", from, to);
693 void AddRange (string rangeSpecifier, long range)
695 if (rangeSpecifier == null)
696 throw new ArgumentNullException ("rangeSpecifier");
697 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
698 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
700 string r = webHeaders ["Range"];
702 r = rangeSpecifier + "=";
704 string old_specifier = r.Substring (0, r.IndexOf ('='));
705 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
706 throw new InvalidOperationException ("A different range specifier is already in use");
710 string n = range.ToString (CultureInfo.InvariantCulture);
715 webHeaders.RemoveAndAdd ("Range", r);
723 void AddRange (string rangeSpecifier, long from, long to)
725 if (rangeSpecifier == null)
726 throw new ArgumentNullException ("rangeSpecifier");
727 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
728 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
729 if (from > to || from < 0)
730 throw new ArgumentOutOfRangeException ("from");
732 throw new ArgumentOutOfRangeException ("to");
734 string r = webHeaders ["Range"];
736 r = rangeSpecifier + "=";
740 r = String.Format ("{0}{1}-{2}", r, from, to);
741 webHeaders.RemoveAndAdd ("Range", r);
745 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
748 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
750 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
752 if (method == null || !send)
753 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
755 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
756 throw new ProtocolViolationException ("Content-Length not set");
758 string transferEncoding = TransferEncoding;
759 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
760 throw new ProtocolViolationException ("SendChunked should be true.");
764 if (getResponseCalled)
765 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
767 if (asyncWrite != null) {
768 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
769 "method while a previous call is still in progress.");
772 asyncWrite = new WebAsyncResult (this, callback, state);
773 initialMethod = method;
775 if (writeStream != null) {
776 asyncWrite.SetCompleted (true, writeStream);
777 asyncWrite.DoCallback ();
782 gotRequestStream = true;
783 WebAsyncResult result = asyncWrite;
787 servicePoint = GetServicePoint ();
788 abortHandler = servicePoint.SendRequest (this, connectionGroup);
794 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
796 if (asyncResult == null)
797 throw new ArgumentNullException ("asyncResult");
799 WebAsyncResult result = asyncResult as WebAsyncResult;
801 throw new ArgumentException ("Invalid IAsyncResult");
804 result.WaitUntilComplete ();
806 Exception e = result.Exception;
810 return result.WriteStream;
813 public override Stream GetRequestStream()
815 IAsyncResult asyncResult = asyncWrite;
816 if (asyncResult == null) {
817 asyncResult = BeginGetRequestStream (null, null);
818 asyncWrite = (WebAsyncResult) asyncResult;
821 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
823 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
826 return EndGetRequestStream (asyncResult);
829 void CheckIfForceWrite ()
831 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
834 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
837 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
838 InternalContentLength = writeStream.WriteBufferLength;
840 if (contentLength < 0 && writeStream.CanWrite == true)
844 // This will write the POST/PUT if the write stream already has the expected
845 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
846 // contains data and it has been closed already (xamarin bug #1512).
848 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
849 writeStream.WriteRequest ();
852 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
855 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
858 throw new ProtocolViolationException ("Method is null.");
860 string transferEncoding = TransferEncoding;
861 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
862 throw new ProtocolViolationException ("SendChunked should be true.");
864 Monitor.Enter (locker);
865 getResponseCalled = true;
866 if (asyncRead != null && !haveResponse) {
867 Monitor.Exit (locker);
868 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
869 "method while a previous call is still in progress.");
872 CheckIfForceWrite ();
873 asyncRead = new WebAsyncResult (this, callback, state);
874 WebAsyncResult aread = asyncRead;
875 initialMethod = method;
877 Exception saved = saved_exc;
878 if (webResponse != null) {
879 Monitor.Exit (locker);
881 aread.SetCompleted (true, webResponse);
883 aread.SetCompleted (true, saved);
887 } else if (saved != null) {
888 Monitor.Exit (locker);
889 aread.SetCompleted (true, saved);
898 servicePoint = GetServicePoint ();
899 abortHandler = servicePoint.SendRequest (this, connectionGroup);
902 Monitor.Exit (locker);
906 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
908 if (asyncResult == null)
909 throw new ArgumentNullException ("asyncResult");
911 WebAsyncResult result = asyncResult as WebAsyncResult;
913 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
915 if (!result.WaitUntilComplete (timeout, false)) {
917 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
920 if (result.GotException)
921 throw result.Exception;
923 return result.Response;
926 public override WebResponse GetResponse()
928 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
929 return EndGetResponse (result);
932 internal bool FinishedReading {
933 get { return finished_reading; }
934 set { finished_reading = value; }
937 internal bool Aborted {
938 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
941 public override void Abort ()
943 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
946 if (haveResponse && finished_reading)
950 if (abortHandler != null) {
952 abortHandler (this, EventArgs.Empty);
953 } catch (Exception) {}
957 if (asyncWrite != null) {
958 WebAsyncResult r = asyncWrite;
959 if (!r.IsCompleted) {
961 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
962 r.SetCompleted (false, wexc);
969 if (asyncRead != null) {
970 WebAsyncResult r = asyncRead;
971 if (!r.IsCompleted) {
973 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
974 r.SetCompleted (false, wexc);
981 if (writeStream != null) {
983 writeStream.Close ();
988 if (webResponse != null) {
990 webResponse.Close ();
996 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
997 StreamingContext streamingContext)
999 GetObjectData (serializationInfo, streamingContext);
1002 protected override void GetObjectData (SerializationInfo serializationInfo,
1003 StreamingContext streamingContext)
1005 SerializationInfo info = serializationInfo;
1007 info.AddValue ("requestUri", requestUri, typeof (Uri));
1008 info.AddValue ("actualUri", actualUri, typeof (Uri));
1009 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1010 info.AddValue ("allowBuffering", allowBuffering);
1011 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1012 info.AddValue ("connectionGroup", connectionGroup);
1013 info.AddValue ("contentLength", contentLength);
1014 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1015 info.AddValue ("keepAlive", keepAlive);
1016 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1017 info.AddValue ("mediaType", mediaType);
1018 info.AddValue ("method", method);
1019 info.AddValue ("initialMethod", initialMethod);
1020 info.AddValue ("pipelined", pipelined);
1021 info.AddValue ("version", version, typeof (Version));
1022 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1023 info.AddValue ("sendChunked", sendChunked);
1024 info.AddValue ("timeout", timeout);
1025 info.AddValue ("redirects", redirects);
1026 info.AddValue ("host", host);
1029 void CheckRequestStarted ()
1032 throw new InvalidOperationException ("request started");
1035 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1037 if (continueDelegate != null)
1038 continueDelegate (statusCode, headers);
1041 bool Redirect (WebAsyncResult result, HttpStatusCode code)
1045 string uriString = null;
1048 case HttpStatusCode.Ambiguous: // 300
1049 e = new WebException ("Ambiguous redirect.");
1051 case HttpStatusCode.MovedPermanently: // 301
1052 case HttpStatusCode.Redirect: // 302
1053 case HttpStatusCode.TemporaryRedirect: // 307
1054 /* MS follows the redirect for POST too
1055 if (method != "GET" && method != "HEAD") // 10.3
1060 bodyBufferLength = 0;
1062 if (code != HttpStatusCode.TemporaryRedirect)
1064 uriString = webResponse.Headers ["Location"];
1066 case HttpStatusCode.SeeOther: //303
1068 uriString = webResponse.Headers ["Location"];
1070 case HttpStatusCode.NotModified: // 304
1072 case HttpStatusCode.UseProxy: // 305
1073 e = new NotImplementedException ("Proxy support not available.");
1075 case HttpStatusCode.Unused: // 306
1077 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1084 if (uriString == null)
1085 throw new WebException ("No Location header found for " + (int) code,
1086 WebExceptionStatus.ProtocolError);
1088 Uri prev = actualUri;
1090 actualUri = new Uri (actualUri, uriString);
1091 } catch (Exception) {
1092 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1093 uriString, (int) code),
1094 WebExceptionStatus.ProtocolError);
1097 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1101 string GetHeaders ()
1103 bool continue100 = false;
1106 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1107 webHeaders.RemoveInternal ("Content-Length");
1108 } else if (contentLength != -1) {
1109 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1110 if (contentLength > 0)
1113 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1115 webHeaders.SetInternal ("Content-Length", "0");
1117 webHeaders.RemoveInternal ("Transfer-Encoding");
1119 webHeaders.RemoveInternal ("Content-Length");
1122 if (actualVersion == HttpVersion.Version11 && continue100 &&
1123 servicePoint.SendContinue) { // RFC2616 8.2.3
1124 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1125 expectContinue = true;
1127 webHeaders.RemoveInternal ("Expect");
1128 expectContinue = false;
1131 bool proxy_query = ProxyQuery;
1132 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1133 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1134 Version proto_version = servicePoint.ProtocolVersion;
1135 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1137 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1138 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1139 } else if (!keepAlive && version == HttpVersion.Version11) {
1140 webHeaders.RemoveAndAdd (connectionHeader, "close");
1143 webHeaders.SetInternal ("Host", Host);
1144 if (cookieContainer != null) {
1145 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1146 if (cookieHeader != "")
1147 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1149 webHeaders.RemoveInternal ("Cookie");
1152 string accept_encoding = null;
1153 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1154 accept_encoding = "gzip";
1155 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1156 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1157 if (accept_encoding != null)
1158 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1160 if (!usedPreAuth && preAuthenticate)
1161 DoPreAuthenticate ();
1163 return webHeaders.ToString ();
1166 void DoPreAuthenticate ()
1168 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1169 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1170 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1174 webHeaders.RemoveInternal ("Proxy-Authorization");
1175 webHeaders.RemoveInternal ("Authorization");
1176 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1177 webHeaders [authHeader] = auth.Message;
1181 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1186 WebAsyncResult r = asyncWrite;
1194 msg = "Error: " + status;
1195 wex = new WebException (msg, status);
1197 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1198 wex = new WebException (msg, exc, status);
1200 r.SetCompleted (false, wex);
1205 internal void SendRequestHeaders (bool propagate_error)
1207 StringBuilder req = new StringBuilder ();
1210 query = actualUri.PathAndQuery;
1212 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1214 actualUri.PathAndQuery);
1217 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1218 actualVersion = servicePoint.ProtocolVersion;
1220 actualVersion = version;
1223 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1224 actualVersion.Major, actualVersion.Minor);
1225 req.Append (GetHeaders ());
1226 string reqstr = req.ToString ();
1227 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1229 writeStream.SetHeaders (bytes);
1230 } catch (WebException wexc) {
1231 SetWriteStreamError (wexc.Status, wexc);
1232 if (propagate_error)
1234 } catch (Exception exc) {
1235 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1236 if (propagate_error)
1241 internal void SetWriteStream (WebConnectionStream stream)
1246 writeStream = stream;
1247 if (bodyBuffer != null) {
1248 webHeaders.RemoveInternal ("Transfer-Encoding");
1249 contentLength = bodyBufferLength;
1250 writeStream.SendChunked = false;
1253 SendRequestHeaders (false);
1257 if (bodyBuffer != null) {
1258 // The body has been written and buffered. The request "user"
1259 // won't write it again, so we must do it.
1260 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1261 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1263 writeStream.Close ();
1265 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1266 method != "TRACE") {
1267 if (getResponseCalled && !writeStream.RequestWritten)
1268 writeStream.WriteRequest ();
1271 if (asyncWrite != null) {
1272 asyncWrite.SetCompleted (false, stream);
1273 asyncWrite.DoCallback ();
1278 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1283 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1284 WebAsyncResult r = asyncRead;
1289 if (e is WebException) {
1290 wexc = (WebException) e;
1292 wexc = new WebException (msg, e, status, null);
1295 if (!r.IsCompleted) {
1296 r.SetCompleted (false, wexc);
1298 } else if (r == asyncWrite) {
1301 haveResponse = true;
1305 haveResponse = true;
1311 void CheckSendError (WebConnectionData data)
1313 // Got here, but no one called GetResponse
1314 int status = data.StatusCode;
1315 if (status < 400 || status == 401 || status == 407)
1318 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1319 // The request has not been completely sent and we got here!
1320 // We should probably just close and cause an error in any case,
1321 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1322 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1323 webResponse.ReadAll ();
1325 writeStream.IgnoreIOErrors = true;
1330 void HandleNtlmAuth (WebAsyncResult r)
1332 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1334 WebConnection cnc = wce.Connection;
1335 cnc.PriorityRequest = this;
1336 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1337 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1338 if (creds != null) {
1339 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1340 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1344 finished_reading = false;
1345 haveResponse = false;
1346 webResponse.ReadAll ();
1350 internal void SetResponseData (WebConnectionData data)
1354 if (data.stream != null)
1355 data.stream.Close ();
1359 WebException wexc = null;
1361 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1362 } catch (Exception e) {
1363 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1364 if (data.stream != null)
1365 data.stream.Close ();
1368 if (wexc == null && (method == "POST" || method == "PUT")) {
1369 CheckSendError (data);
1370 if (saved_exc != null)
1371 wexc = (WebException) saved_exc;
1374 WebAsyncResult r = asyncRead;
1376 bool forced = false;
1377 if (r == null && webResponse != null) {
1378 // This is a forced completion (302, 204)...
1380 r = new WebAsyncResult (null, null);
1381 r.SetCompleted (false, webResponse);
1386 haveResponse = true;
1388 r.SetCompleted (false, wexc);
1395 redirected = CheckFinalStatus (r);
1397 if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
1398 && (int)webResponse.StatusCode < 400) {
1399 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1401 WebConnection cnc = wce.Connection;
1402 cnc.NtlmAuthenticated = true;
1406 // clear internal buffer so that it does not
1407 // hold possible big buffer (bug #397627)
1408 if (writeStream != null)
1409 writeStream.KillBuffer ();
1411 haveResponse = true;
1412 r.SetCompleted (false, webResponse);
1415 if (webResponse != null) {
1416 if (ntlm_auth_state != NtlmAuthState.None) {
1420 webResponse.Close ();
1422 finished_reading = false;
1423 haveResponse = false;
1426 servicePoint = GetServicePoint ();
1427 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1429 } catch (WebException wexc2) {
1432 haveResponse = true;
1434 r.SetCompleted (false, wexc2);
1437 } catch (Exception ex) {
1438 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1441 haveResponse = true;
1443 r.SetCompleted (false, wexc);
1451 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1453 authCompleted = false;
1454 if (code == HttpStatusCode.Unauthorized && credentials == null)
1457 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1458 if (isProxy && (proxy == null || proxy.Credentials == null))
1461 string [] authHeaders = response.Headers.GetValues_internal ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1462 if (authHeaders == null || authHeaders.Length == 0)
1465 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1466 Authorization auth = null;
1467 foreach (string authHeader in authHeaders) {
1468 auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1474 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1475 authCompleted = auth.Complete;
1476 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1478 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1482 // Returns true if redirected
1483 bool CheckFinalStatus (WebAsyncResult result)
1485 if (result.GotException) {
1487 throw result.Exception;
1490 Exception throwMe = result.Exception;
1492 HttpWebResponse resp = result.Response;
1493 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1494 HttpStatusCode code = 0;
1495 if (throwMe == null && webResponse != null) {
1496 code = webResponse.StatusCode;
1497 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1498 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1499 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1500 // Keep the written body, so it can be rewritten in the retry
1501 if (InternalAllowBuffering) {
1502 // NTLM: This is to avoid sending data in the 'challenge' request
1503 // We save it in the first request (first 401), don't send anything
1504 // in the challenge request and send it in the response request along
1505 // with the buffers kept form the first request.
1506 if (ntlm_auth_state != NtlmAuthState.Response) {
1507 bodyBuffer = writeStream.WriteBuffer;
1508 bodyBufferLength = writeStream.WriteBufferLength;
1511 } else if (method != "PUT" && method != "POST") {
1519 writeStream.InternalClose ();
1521 webResponse.Close ();
1525 throw new WebException ("This request requires buffering " +
1526 "of data for authentication or " +
1527 "redirection to be sucessful.");
1532 if ((int) code >= 400) {
1533 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1534 (int) code, webResponse.StatusDescription);
1535 throwMe = new WebException (err, null, protoError, webResponse);
1536 webResponse.ReadAll ();
1537 } else if ((int) code == 304 && allowAutoRedirect) {
1538 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1539 (int) code, webResponse.StatusDescription);
1540 throwMe = new WebException (err, null, protoError, webResponse);
1541 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1542 throwMe = new WebException ("Max. redirections exceeded.", null,
1543 protoError, webResponse);
1544 webResponse.ReadAll ();
1549 if (throwMe == null) {
1552 if (allowAutoRedirect && c >= 300) {
1553 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1554 bodyBuffer = writeStream.WriteBuffer;
1555 bodyBufferLength = writeStream.WriteBufferLength;
1557 b = Redirect (result, code);
1558 if (b && ntlm_auth_state != 0)
1559 ntlm_auth_state = 0;
1562 if (resp != null && c >= 300 && c != 304)
1571 if (writeStream != null) {
1572 writeStream.InternalClose ();