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 internal class HttpWebRequest : WebRequest, ISerializable {
53 public class HttpWebRequest : WebRequest, ISerializable {
58 bool allowAutoRedirect = true;
59 bool allowBuffering = true;
60 X509CertificateCollection certificates;
61 string connectionGroup;
62 long contentLength = -1;
63 HttpContinueDelegate continueDelegate;
64 CookieContainer cookieContainer;
65 ICredentials credentials;
69 WebHeaderCollection webHeaders;
70 bool keepAlive = true;
71 int maxAutoRedirect = 50;
72 string mediaType = String.Empty;
73 string method = "GET";
74 string initialMethod = "GET";
75 bool pipelined = true;
78 Version version = HttpVersion.Version11;
80 Version actualVersion;
83 ServicePoint servicePoint;
86 WebConnectionStream writeStream;
87 HttpWebResponse webResponse;
88 WebAsyncResult asyncWrite;
89 WebAsyncResult asyncRead;
90 EventHandler abortHandler;
92 bool gotRequestStream;
98 bool getResponseCalled;
100 object locker = new object ();
101 bool finished_reading;
102 internal WebConnection WebConnection;
103 DecompressionMethods auto_decomp;
104 int maxResponseHeadersLength;
105 static int defaultMaxResponseHeadersLength;
106 int readWriteTimeout = 300000; // ms
113 NtlmAuthState ntlm_auth_state;
117 static HttpWebRequest ()
119 defaultMaxResponseHeadersLength = 64 * 1024;
121 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
122 if (config != null) {
123 int x = config.MaxResponseHeadersLength;
127 defaultMaxResponseHeadersLength = x;
137 HttpWebRequest (Uri uri)
139 this.requestUri = uri;
140 this.actualUri = uri;
141 this.proxy = GlobalProxySelection.Select;
142 this.webHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
146 [Obsolete ("Serialization is obsoleted for this type", false)]
147 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
149 SerializationInfo info = serializationInfo;
151 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
152 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
153 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
154 allowBuffering = info.GetBoolean ("allowBuffering");
155 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
156 connectionGroup = info.GetString ("connectionGroup");
157 contentLength = info.GetInt64 ("contentLength");
158 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
159 keepAlive = info.GetBoolean ("keepAlive");
160 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
161 mediaType = info.GetString ("mediaType");
162 method = info.GetString ("method");
163 initialMethod = info.GetString ("initialMethod");
164 pipelined = info.GetBoolean ("pipelined");
165 version = (Version) info.GetValue ("version", typeof (Version));
166 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
167 sendChunked = info.GetBoolean ("sendChunked");
168 timeout = info.GetInt32 ("timeout");
169 redirects = info.GetInt32 ("redirects");
170 host = info.GetString ("host");
175 public string Accept {
176 get { return webHeaders ["Accept"]; }
178 CheckRequestStarted ();
179 webHeaders.RemoveAndAdd ("Accept", value);
184 get { return actualUri; }
185 internal set { actualUri = value; } // Used by Ftp+proxy
188 public bool AllowAutoRedirect {
189 get { return allowAutoRedirect; }
190 set { this.allowAutoRedirect = value; }
193 public bool AllowWriteStreamBuffering {
194 get { return allowBuffering; }
195 set { allowBuffering = value; }
198 static Exception GetMustImplement ()
200 return new NotImplementedException ();
203 public DecompressionMethods AutomaticDecompression
209 CheckRequestStarted ();
214 internal bool InternalAllowBuffering {
216 return (allowBuffering && (method != "HEAD" && method != "GET" &&
217 method != "MKCOL" && method != "CONNECT" &&
222 public X509CertificateCollection ClientCertificates {
224 if (certificates == null)
225 certificates = new X509CertificateCollection ();
231 throw GetMustImplement ();
235 public string Connection {
236 get { return webHeaders ["Connection"]; }
238 CheckRequestStarted ();
240 if (string.IsNullOrEmpty (value)) {
241 webHeaders.RemoveInternal ("Connection");
245 string val = value.ToLowerInvariant ();
246 if (val.Contains ("keep-alive") || val.Contains ("close"))
247 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
250 value = value + ", Keep-Alive";
252 webHeaders.RemoveAndAdd ("Connection", value);
256 public override string ConnectionGroupName {
257 get { return connectionGroup; }
258 set { connectionGroup = value; }
261 public override long ContentLength {
262 get { return contentLength; }
264 CheckRequestStarted ();
266 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
268 contentLength = value;
272 internal long InternalContentLength {
273 set { contentLength = value; }
276 internal bool ThrowOnError { get; set; }
278 public override string ContentType {
279 get { return webHeaders ["Content-Type"]; }
281 if (value == null || value.Trim().Length == 0) {
282 webHeaders.RemoveInternal ("Content-Type");
285 webHeaders.RemoveAndAdd ("Content-Type", value);
289 public HttpContinueDelegate ContinueDelegate {
290 get { return continueDelegate; }
291 set { continueDelegate = value; }
294 public CookieContainer CookieContainer {
295 get { return cookieContainer; }
296 set { cookieContainer = value; }
299 public override ICredentials Credentials {
300 get { return credentials; }
301 set { credentials = value; }
304 public DateTime Date {
306 string date = webHeaders ["Date"];
308 return DateTime.MinValue;
309 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
312 if (value.Equals (DateTime.MinValue))
313 webHeaders.RemoveInternal ("Date");
315 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
320 public static new RequestCachePolicy DefaultCachePolicy
323 throw GetMustImplement ();
326 throw GetMustImplement ();
331 public static int DefaultMaximumErrorResponseLength
334 throw GetMustImplement ();
337 throw GetMustImplement ();
341 public string Expect {
342 get { return webHeaders ["Expect"]; }
344 CheckRequestStarted ();
347 val = val.Trim ().ToLower ();
349 if (val == null || val.Length == 0) {
350 webHeaders.RemoveInternal ("Expect");
354 if (val == "100-continue")
355 throw new ArgumentException ("100-Continue cannot be set with this property.",
357 webHeaders.RemoveAndAdd ("Expect", value);
361 public bool HaveResponse {
362 get { return haveResponse; }
365 public override WebHeaderCollection Headers {
366 get { return webHeaders; }
368 CheckRequestStarted ();
369 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
370 int count = value.Count;
371 for (int i = 0; i < count; i++)
372 newHeaders.Add (value.GetKey (i), value.Get (i));
374 webHeaders = newHeaders;
386 return actualUri.Authority;
391 throw new ArgumentNullException ("value");
393 if (!CheckValidHost (actualUri.Scheme, value))
394 throw new ArgumentException ("Invalid host: " + value);
400 static bool CheckValidHost (string scheme, string val)
408 int idx = val.IndexOf ('/');
412 string u = scheme + "://" + val + "/";
413 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
416 public DateTime IfModifiedSince {
418 string str = webHeaders ["If-Modified-Since"];
422 return MonoHttpDate.Parse (str);
423 } catch (Exception) {
428 CheckRequestStarted ();
430 webHeaders.SetInternal ("If-Modified-Since",
431 value.ToUniversalTime ().ToString ("r", null));
432 // TODO: check last param when using different locale
436 public bool KeepAlive {
445 public int MaximumAutomaticRedirections {
446 get { return maxAutoRedirect; }
449 throw new ArgumentException ("Must be > 0", "value");
451 maxAutoRedirect = value;
455 [MonoTODO ("Use this")]
456 public int MaximumResponseHeadersLength {
457 get { return maxResponseHeadersLength; }
458 set { maxResponseHeadersLength = value; }
461 [MonoTODO ("Use this")]
462 public static int DefaultMaximumResponseHeadersLength {
463 get { return defaultMaxResponseHeadersLength; }
464 set { defaultMaxResponseHeadersLength = value; }
467 public int ReadWriteTimeout {
468 get { return readWriteTimeout; }
471 throw new InvalidOperationException ("The request has already been sent.");
474 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
476 readWriteTimeout = value;
480 public string MediaType {
481 get { return mediaType; }
487 public override string Method {
488 get { return this.method; }
490 if (value == null || value.Trim () == "")
491 throw new ArgumentException ("not a valid method");
493 method = value.ToUpperInvariant ();
494 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
495 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
502 public bool Pipelined {
503 get { return pipelined; }
504 set { pipelined = value; }
507 public override bool PreAuthenticate {
508 get { return preAuthenticate; }
509 set { preAuthenticate = value; }
512 public Version ProtocolVersion {
513 get { return version; }
515 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
516 throw new ArgumentException ("value");
518 force_version = true;
523 public override IWebProxy Proxy {
524 get { return proxy; }
526 CheckRequestStarted ();
528 servicePoint = null; // we may need a new one
532 public string Referer {
533 get { return webHeaders ["Referer"]; }
535 CheckRequestStarted ();
536 if (value == null || value.Trim().Length == 0) {
537 webHeaders.RemoveInternal ("Referer");
540 webHeaders.SetInternal ("Referer", value);
544 public override Uri RequestUri {
545 get { return requestUri; }
548 public bool SendChunked {
549 get { return sendChunked; }
551 CheckRequestStarted ();
556 public ServicePoint ServicePoint {
557 get { return GetServicePoint (); }
560 internal ServicePoint ServicePointNoLock {
561 get { return servicePoint; }
563 #if NET_4_5 || MOBILE
564 [MonoTODO ("for portable library support")]
565 public bool SupportsCookieContainer {
567 throw new NotImplementedException ();
571 public override int Timeout {
572 get { return timeout; }
575 throw new ArgumentOutOfRangeException ("value");
581 public string TransferEncoding {
582 get { return webHeaders ["Transfer-Encoding"]; }
584 CheckRequestStarted ();
587 val = val.Trim ().ToLower ();
589 if (val == null || val.Length == 0) {
590 webHeaders.RemoveInternal ("Transfer-Encoding");
594 if (val == "chunked")
595 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
598 throw new ArgumentException ("SendChunked must be True", "value");
600 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
604 public override bool UseDefaultCredentials
606 get { return CredentialCache.DefaultCredentials == Credentials; }
607 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
610 public string UserAgent {
611 get { return webHeaders ["User-Agent"]; }
612 set { webHeaders.SetInternal ("User-Agent", value); }
615 bool unsafe_auth_blah;
616 public bool UnsafeAuthenticatedConnectionSharing
618 get { return unsafe_auth_blah; }
619 set { unsafe_auth_blah = value; }
622 internal bool GotRequestStream {
623 get { return gotRequestStream; }
626 internal bool ExpectContinue {
627 get { return expectContinue; }
628 set { expectContinue = value; }
631 internal Uri AuthUri {
632 get { return actualUri; }
635 internal bool ProxyQuery {
636 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
641 internal ServicePoint GetServicePoint ()
644 if (hostChanged || servicePoint == null) {
645 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
653 public void AddRange (int range)
655 AddRange ("bytes", (long) range);
658 public void AddRange (int from, int to)
660 AddRange ("bytes", (long) from, (long) to);
663 public void AddRange (string rangeSpecifier, int range)
665 AddRange (rangeSpecifier, (long) range);
668 public void AddRange (string rangeSpecifier, int from, int to)
670 AddRange (rangeSpecifier, (long) from, (long) to);
677 void AddRange (long range)
679 AddRange ("bytes", (long) range);
687 void AddRange (long from, long to)
689 AddRange ("bytes", from, to);
697 void AddRange (string rangeSpecifier, long range)
699 if (rangeSpecifier == null)
700 throw new ArgumentNullException ("rangeSpecifier");
701 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
702 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
704 string r = webHeaders ["Range"];
706 r = rangeSpecifier + "=";
708 string old_specifier = r.Substring (0, r.IndexOf ('='));
709 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
710 throw new InvalidOperationException ("A different range specifier is already in use");
714 string n = range.ToString (CultureInfo.InvariantCulture);
719 webHeaders.RemoveAndAdd ("Range", r);
727 void AddRange (string rangeSpecifier, long from, long to)
729 if (rangeSpecifier == null)
730 throw new ArgumentNullException ("rangeSpecifier");
731 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
732 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
733 if (from > to || from < 0)
734 throw new ArgumentOutOfRangeException ("from");
736 throw new ArgumentOutOfRangeException ("to");
738 string r = webHeaders ["Range"];
740 r = rangeSpecifier + "=";
744 r = String.Format ("{0}{1}-{2}", r, from, to);
745 webHeaders.RemoveAndAdd ("Range", r);
749 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
752 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
754 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
756 if (method == null || !send)
757 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
759 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
760 throw new ProtocolViolationException ("Content-Length not set");
762 string transferEncoding = TransferEncoding;
763 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
764 throw new ProtocolViolationException ("SendChunked should be true.");
768 if (getResponseCalled)
769 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
771 if (asyncWrite != null) {
772 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
773 "method while a previous call is still in progress.");
776 asyncWrite = new WebAsyncResult (this, callback, state);
777 initialMethod = method;
779 if (writeStream != null) {
780 asyncWrite.SetCompleted (true, writeStream);
781 asyncWrite.DoCallback ();
786 gotRequestStream = true;
787 WebAsyncResult result = asyncWrite;
791 servicePoint = GetServicePoint ();
792 abortHandler = servicePoint.SendRequest (this, connectionGroup);
798 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
800 if (asyncResult == null)
801 throw new ArgumentNullException ("asyncResult");
803 WebAsyncResult result = asyncResult as WebAsyncResult;
805 throw new ArgumentException ("Invalid IAsyncResult");
808 result.WaitUntilComplete ();
810 Exception e = result.Exception;
814 return result.WriteStream;
817 public override Stream GetRequestStream()
819 IAsyncResult asyncResult = asyncWrite;
820 if (asyncResult == null) {
821 asyncResult = BeginGetRequestStream (null, null);
822 asyncWrite = (WebAsyncResult) asyncResult;
825 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
827 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
830 return EndGetRequestStream (asyncResult);
833 void CheckIfForceWrite ()
835 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
838 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength <= 0)
841 if (contentLength < 0 && writeStream.WriteBufferLength > 0)
842 InternalContentLength = writeStream.WriteBufferLength;
844 if (contentLength < 0 && writeStream.CanWrite == true)
848 // This will write the POST/PUT if the write stream already has the expected
849 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
850 // contains data and it has been closed already (xamarin bug #1512).
852 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
853 writeStream.WriteRequest ();
856 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
859 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
862 throw new ProtocolViolationException ("Method is null.");
864 string transferEncoding = TransferEncoding;
865 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
866 throw new ProtocolViolationException ("SendChunked should be true.");
868 Monitor.Enter (locker);
869 getResponseCalled = true;
870 if (asyncRead != null && !haveResponse) {
871 Monitor.Exit (locker);
872 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
873 "method while a previous call is still in progress.");
876 CheckIfForceWrite ();
877 asyncRead = new WebAsyncResult (this, callback, state);
878 WebAsyncResult aread = asyncRead;
879 initialMethod = method;
881 Exception saved = saved_exc;
882 if (webResponse != null) {
883 Monitor.Exit (locker);
885 aread.SetCompleted (true, webResponse);
887 aread.SetCompleted (true, saved);
891 } else if (saved != null) {
892 Monitor.Exit (locker);
893 aread.SetCompleted (true, saved);
902 servicePoint = GetServicePoint ();
903 abortHandler = servicePoint.SendRequest (this, connectionGroup);
906 Monitor.Exit (locker);
910 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
912 if (asyncResult == null)
913 throw new ArgumentNullException ("asyncResult");
915 WebAsyncResult result = asyncResult as WebAsyncResult;
917 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
919 if (!result.WaitUntilComplete (timeout, false)) {
921 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
924 if (result.GotException)
925 throw result.Exception;
927 return result.Response;
930 public override WebResponse GetResponse()
932 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
933 return EndGetResponse (result);
936 internal bool FinishedReading {
937 get { return finished_reading; }
938 set { finished_reading = value; }
941 internal bool Aborted {
942 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
945 public override void Abort ()
947 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
950 if (haveResponse && finished_reading)
954 if (abortHandler != null) {
956 abortHandler (this, EventArgs.Empty);
957 } catch (Exception) {}
961 if (asyncWrite != null) {
962 WebAsyncResult r = asyncWrite;
963 if (!r.IsCompleted) {
965 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
966 r.SetCompleted (false, wexc);
973 if (asyncRead != null) {
974 WebAsyncResult r = asyncRead;
975 if (!r.IsCompleted) {
977 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
978 r.SetCompleted (false, wexc);
985 if (writeStream != null) {
987 writeStream.Close ();
992 if (webResponse != null) {
994 webResponse.Close ();
1000 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1001 StreamingContext streamingContext)
1003 GetObjectData (serializationInfo, streamingContext);
1006 protected override void GetObjectData (SerializationInfo serializationInfo,
1007 StreamingContext streamingContext)
1009 SerializationInfo info = serializationInfo;
1011 info.AddValue ("requestUri", requestUri, typeof (Uri));
1012 info.AddValue ("actualUri", actualUri, typeof (Uri));
1013 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1014 info.AddValue ("allowBuffering", allowBuffering);
1015 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1016 info.AddValue ("connectionGroup", connectionGroup);
1017 info.AddValue ("contentLength", contentLength);
1018 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1019 info.AddValue ("keepAlive", keepAlive);
1020 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1021 info.AddValue ("mediaType", mediaType);
1022 info.AddValue ("method", method);
1023 info.AddValue ("initialMethod", initialMethod);
1024 info.AddValue ("pipelined", pipelined);
1025 info.AddValue ("version", version, typeof (Version));
1026 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1027 info.AddValue ("sendChunked", sendChunked);
1028 info.AddValue ("timeout", timeout);
1029 info.AddValue ("redirects", redirects);
1030 info.AddValue ("host", host);
1033 void CheckRequestStarted ()
1036 throw new InvalidOperationException ("request started");
1039 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1041 if (continueDelegate != null)
1042 continueDelegate (statusCode, headers);
1045 bool Redirect (WebAsyncResult result, HttpStatusCode code)
1049 string uriString = null;
1052 case HttpStatusCode.Ambiguous: // 300
1053 e = new WebException ("Ambiguous redirect.");
1055 case HttpStatusCode.MovedPermanently: // 301
1056 case HttpStatusCode.Redirect: // 302
1057 case HttpStatusCode.TemporaryRedirect: // 307
1058 /* MS follows the redirect for POST too
1059 if (method != "GET" && method != "HEAD") // 10.3
1064 bodyBufferLength = 0;
1066 if (code != HttpStatusCode.TemporaryRedirect)
1068 uriString = webResponse.Headers ["Location"];
1070 case HttpStatusCode.SeeOther: //303
1072 uriString = webResponse.Headers ["Location"];
1074 case HttpStatusCode.NotModified: // 304
1076 case HttpStatusCode.UseProxy: // 305
1077 e = new NotImplementedException ("Proxy support not available.");
1079 case HttpStatusCode.Unused: // 306
1081 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1088 if (uriString == null)
1089 throw new WebException ("No Location header found for " + (int) code,
1090 WebExceptionStatus.ProtocolError);
1092 Uri prev = actualUri;
1094 actualUri = new Uri (actualUri, uriString);
1095 } catch (Exception) {
1096 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1097 uriString, (int) code),
1098 WebExceptionStatus.ProtocolError);
1101 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1105 string GetHeaders ()
1107 bool continue100 = false;
1110 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1111 webHeaders.RemoveInternal ("Content-Length");
1112 } else if (contentLength != -1) {
1113 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1114 if (contentLength > 0)
1117 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1119 webHeaders.SetInternal ("Content-Length", "0");
1121 webHeaders.RemoveInternal ("Transfer-Encoding");
1123 webHeaders.RemoveInternal ("Content-Length");
1126 if (actualVersion == HttpVersion.Version11 && continue100 &&
1127 servicePoint.SendContinue) { // RFC2616 8.2.3
1128 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1129 expectContinue = true;
1131 webHeaders.RemoveInternal ("Expect");
1132 expectContinue = false;
1135 bool proxy_query = ProxyQuery;
1136 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1137 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1138 Version proto_version = servicePoint.ProtocolVersion;
1139 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1141 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1142 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1143 } else if (!keepAlive && version == HttpVersion.Version11) {
1144 webHeaders.RemoveAndAdd (connectionHeader, "close");
1147 webHeaders.SetInternal ("Host", Host);
1148 if (cookieContainer != null) {
1149 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1150 if (cookieHeader != "")
1151 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1153 webHeaders.RemoveInternal ("Cookie");
1156 string accept_encoding = null;
1157 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1158 accept_encoding = "gzip";
1159 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1160 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1161 if (accept_encoding != null)
1162 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1164 if (!usedPreAuth && preAuthenticate)
1165 DoPreAuthenticate ();
1167 return webHeaders.ToString ();
1170 void DoPreAuthenticate ()
1172 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1173 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1174 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1178 webHeaders.RemoveInternal ("Proxy-Authorization");
1179 webHeaders.RemoveInternal ("Authorization");
1180 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1181 webHeaders [authHeader] = auth.Message;
1185 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1190 WebAsyncResult r = asyncWrite;
1198 msg = "Error: " + status;
1199 wex = new WebException (msg, status);
1201 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1202 wex = new WebException (msg, exc, status);
1204 r.SetCompleted (false, wex);
1209 internal void SendRequestHeaders (bool propagate_error)
1211 StringBuilder req = new StringBuilder ();
1214 query = actualUri.PathAndQuery;
1216 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1218 actualUri.PathAndQuery);
1221 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1222 actualVersion = servicePoint.ProtocolVersion;
1224 actualVersion = version;
1227 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1228 actualVersion.Major, actualVersion.Minor);
1229 req.Append (GetHeaders ());
1230 string reqstr = req.ToString ();
1231 byte [] bytes = Encoding.UTF8.GetBytes (reqstr);
1233 writeStream.SetHeaders (bytes);
1234 } catch (WebException wexc) {
1235 SetWriteStreamError (wexc.Status, wexc);
1236 if (propagate_error)
1238 } catch (Exception exc) {
1239 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1240 if (propagate_error)
1245 internal void SetWriteStream (WebConnectionStream stream)
1250 writeStream = stream;
1251 if (bodyBuffer != null) {
1252 webHeaders.RemoveInternal ("Transfer-Encoding");
1253 contentLength = bodyBufferLength;
1254 writeStream.SendChunked = false;
1257 SendRequestHeaders (false);
1261 if (bodyBuffer != null) {
1262 // The body has been written and buffered. The request "user"
1263 // won't write it again, so we must do it.
1264 if (ntlm_auth_state != NtlmAuthState.Challenge) {
1265 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1267 writeStream.Close ();
1269 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1270 method != "TRACE") {
1271 if (getResponseCalled && !writeStream.RequestWritten)
1272 writeStream.WriteRequest ();
1275 if (asyncWrite != null) {
1276 asyncWrite.SetCompleted (false, stream);
1277 asyncWrite.DoCallback ();
1282 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1287 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1288 WebAsyncResult r = asyncRead;
1293 if (e is WebException) {
1294 wexc = (WebException) e;
1296 wexc = new WebException (msg, e, status, null);
1299 if (!r.IsCompleted) {
1300 r.SetCompleted (false, wexc);
1302 } else if (r == asyncWrite) {
1305 haveResponse = true;
1309 haveResponse = true;
1315 void CheckSendError (WebConnectionData data)
1317 // Got here, but no one called GetResponse
1318 int status = data.StatusCode;
1319 if (status < 400 || status == 401 || status == 407)
1322 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1323 // The request has not been completely sent and we got here!
1324 // We should probably just close and cause an error in any case,
1325 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1326 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1327 webResponse.ReadAll ();
1329 writeStream.IgnoreIOErrors = true;
1334 void HandleNtlmAuth (WebAsyncResult r)
1336 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1338 WebConnection cnc = wce.Connection;
1339 cnc.PriorityRequest = this;
1340 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1341 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1342 if (creds != null) {
1343 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1344 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1348 finished_reading = false;
1349 haveResponse = false;
1350 webResponse.ReadAll ();
1354 internal void SetResponseData (WebConnectionData data)
1358 if (data.stream != null)
1359 data.stream.Close ();
1363 WebException wexc = null;
1365 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1366 } catch (Exception e) {
1367 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1368 if (data.stream != null)
1369 data.stream.Close ();
1372 if (wexc == null && (method == "POST" || method == "PUT")) {
1373 CheckSendError (data);
1374 if (saved_exc != null)
1375 wexc = (WebException) saved_exc;
1378 WebAsyncResult r = asyncRead;
1380 bool forced = false;
1381 if (r == null && webResponse != null) {
1382 // This is a forced completion (302, 204)...
1384 r = new WebAsyncResult (null, null);
1385 r.SetCompleted (false, webResponse);
1390 haveResponse = true;
1392 r.SetCompleted (false, wexc);
1399 redirected = CheckFinalStatus (r);
1401 if (ntlm_auth_state != NtlmAuthState.None && authCompleted && webResponse != null
1402 && (int)webResponse.StatusCode < 400) {
1403 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1405 WebConnection cnc = wce.Connection;
1406 cnc.NtlmAuthenticated = true;
1410 // clear internal buffer so that it does not
1411 // hold possible big buffer (bug #397627)
1412 if (writeStream != null)
1413 writeStream.KillBuffer ();
1415 haveResponse = true;
1416 r.SetCompleted (false, webResponse);
1419 if (webResponse != null) {
1420 if (ntlm_auth_state != NtlmAuthState.None) {
1424 webResponse.Close ();
1426 finished_reading = false;
1427 haveResponse = false;
1430 servicePoint = GetServicePoint ();
1431 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1433 } catch (WebException wexc2) {
1436 haveResponse = true;
1438 r.SetCompleted (false, wexc2);
1441 } catch (Exception ex) {
1442 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1445 haveResponse = true;
1447 r.SetCompleted (false, wexc);
1455 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1457 authCompleted = false;
1458 if (code == HttpStatusCode.Unauthorized && credentials == null)
1461 bool isProxy = (code == HttpStatusCode.ProxyAuthenticationRequired);
1462 if (isProxy && (proxy == null || proxy.Credentials == null))
1465 string [] authHeaders = response.Headers.GetValues ( (isProxy) ? "Proxy-Authenticate" : "WWW-Authenticate");
1466 if (authHeaders == null || authHeaders.Length == 0)
1469 ICredentials creds = (!isProxy) ? credentials : proxy.Credentials;
1470 Authorization auth = null;
1471 foreach (string authHeader in authHeaders) {
1472 auth = AuthenticationManager.Authenticate (authHeader, this, creds);
1478 webHeaders [(isProxy) ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1479 authCompleted = auth.Complete;
1480 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1482 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1486 // Returns true if redirected
1487 bool CheckFinalStatus (WebAsyncResult result)
1489 if (result.GotException) {
1491 throw result.Exception;
1494 Exception throwMe = result.Exception;
1496 HttpWebResponse resp = result.Response;
1497 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1498 HttpStatusCode code = 0;
1499 if (throwMe == null && webResponse != null) {
1500 code = webResponse.StatusCode;
1501 if (!authCompleted && ((code == HttpStatusCode.Unauthorized && credentials != null) ||
1502 (ProxyQuery && code == HttpStatusCode.ProxyAuthenticationRequired))) {
1503 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1504 // Keep the written body, so it can be rewritten in the retry
1505 if (InternalAllowBuffering) {
1506 // NTLM: This is to avoid sending data in the 'challenge' request
1507 // We save it in the first request (first 401), don't send anything
1508 // in the challenge request and send it in the response request along
1509 // with the buffers kept form the first request.
1510 if (ntlm_auth_state != NtlmAuthState.Response) {
1511 bodyBuffer = writeStream.WriteBuffer;
1512 bodyBufferLength = writeStream.WriteBufferLength;
1515 } else if (method != "PUT" && method != "POST") {
1523 writeStream.InternalClose ();
1525 webResponse.Close ();
1529 throw new WebException ("This request requires buffering " +
1530 "of data for authentication or " +
1531 "redirection to be sucessful.");
1536 if ((int) code >= 400) {
1537 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1538 (int) code, webResponse.StatusDescription);
1539 throwMe = new WebException (err, null, protoError, webResponse);
1540 webResponse.ReadAll ();
1541 } else if ((int) code == 304 && allowAutoRedirect) {
1542 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1543 (int) code, webResponse.StatusDescription);
1544 throwMe = new WebException (err, null, protoError, webResponse);
1545 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1546 throwMe = new WebException ("Max. redirections exceeded.", null,
1547 protoError, webResponse);
1548 webResponse.ReadAll ();
1553 if (throwMe == null) {
1556 if (allowAutoRedirect && c >= 300) {
1557 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1558 bodyBuffer = writeStream.WriteBuffer;
1559 bodyBufferLength = writeStream.WriteBufferLength;
1561 b = Redirect (result, code);
1562 if (b && ntlm_auth_state != 0)
1563 ntlm_auth_state = 0;
1566 if (resp != null && c >= 300 && c != 304)
1575 if (writeStream != null) {
1576 writeStream.InternalClose ();