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;
40 using System.Net.Cache;
41 using System.Net.Sockets;
42 using System.Runtime.Remoting.Messaging;
43 using System.Runtime.Serialization;
44 using System.Security.Cryptography.X509Certificates;
46 using System.Threading;
51 public class HttpWebRequest : WebRequest, ISerializable {
55 bool allowAutoRedirect = true;
56 bool allowBuffering = true;
57 X509CertificateCollection certificates;
58 string connectionGroup;
59 bool haveContentLength;
60 long contentLength = -1;
61 HttpContinueDelegate continueDelegate;
62 CookieContainer cookieContainer;
63 ICredentials credentials;
67 WebHeaderCollection webHeaders;
68 bool keepAlive = true;
69 int maxAutoRedirect = 50;
70 string mediaType = String.Empty;
71 string method = "GET";
72 string initialMethod = "GET";
73 bool pipelined = true;
76 Version version = HttpVersion.Version11;
78 Version actualVersion;
81 ServicePoint servicePoint;
84 WebConnectionStream writeStream;
85 HttpWebResponse webResponse;
86 WebAsyncResult asyncWrite;
87 WebAsyncResult asyncRead;
88 EventHandler abortHandler;
90 bool gotRequestStream;
95 bool getResponseCalled;
97 object locker = new object ();
98 bool finished_reading;
99 internal WebConnection WebConnection;
100 DecompressionMethods auto_decomp;
101 int maxResponseHeadersLength;
102 static int defaultMaxResponseHeadersLength;
103 int readWriteTimeout = 300000; // ms
110 AuthorizationState auth_state, proxy_auth_state;
114 static HttpWebRequest ()
116 defaultMaxResponseHeadersLength = 64 * 1024;
118 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
119 if (config != null) {
120 int x = config.MaxResponseHeadersLength;
124 defaultMaxResponseHeadersLength = x;
134 HttpWebRequest (Uri uri)
136 this.requestUri = uri;
137 this.actualUri = uri;
138 this.proxy = GlobalProxySelection.Select;
139 this.webHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
141 ResetAuthorization ();
144 [Obsolete ("Serialization is obsoleted for this type", false)]
145 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
147 SerializationInfo info = serializationInfo;
149 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
150 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
151 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
152 allowBuffering = info.GetBoolean ("allowBuffering");
153 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
154 connectionGroup = info.GetString ("connectionGroup");
155 contentLength = info.GetInt64 ("contentLength");
156 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
157 keepAlive = info.GetBoolean ("keepAlive");
158 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
159 mediaType = info.GetString ("mediaType");
160 method = info.GetString ("method");
161 initialMethod = info.GetString ("initialMethod");
162 pipelined = info.GetBoolean ("pipelined");
163 version = (Version) info.GetValue ("version", typeof (Version));
164 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
165 sendChunked = info.GetBoolean ("sendChunked");
166 timeout = info.GetInt32 ("timeout");
167 redirects = info.GetInt32 ("redirects");
168 host = info.GetString ("host");
169 ResetAuthorization ();
172 void ResetAuthorization ()
174 auth_state = new AuthorizationState (this, false);
175 proxy_auth_state = new AuthorizationState (this, true);
180 public string Accept {
181 get { return webHeaders ["Accept"]; }
183 CheckRequestStarted ();
184 webHeaders.RemoveAndAdd ("Accept", value);
189 get { return actualUri; }
190 internal set { actualUri = value; } // Used by Ftp+proxy
193 public bool AllowAutoRedirect {
194 get { return allowAutoRedirect; }
195 set { this.allowAutoRedirect = value; }
198 public bool AllowWriteStreamBuffering {
199 get { return allowBuffering; }
200 set { allowBuffering = value; }
204 public virtual bool AllowReadStreamBuffering {
205 get { return false; }
208 throw new InvalidOperationException ();
213 static Exception GetMustImplement ()
215 return new NotImplementedException ();
218 public DecompressionMethods AutomaticDecompression
224 CheckRequestStarted ();
229 internal bool InternalAllowBuffering {
231 return (allowBuffering && (method != "HEAD" && method != "GET" &&
232 method != "MKCOL" && method != "CONNECT" &&
237 public X509CertificateCollection ClientCertificates {
239 if (certificates == null)
240 certificates = new X509CertificateCollection ();
246 throw GetMustImplement ();
250 public string Connection {
251 get { return webHeaders ["Connection"]; }
253 CheckRequestStarted ();
255 if (string.IsNullOrEmpty (value)) {
256 webHeaders.RemoveInternal ("Connection");
260 string val = value.ToLowerInvariant ();
261 if (val.Contains ("keep-alive") || val.Contains ("close"))
262 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
265 value = value + ", Keep-Alive";
267 webHeaders.RemoveAndAdd ("Connection", value);
271 public override string ConnectionGroupName {
272 get { return connectionGroup; }
273 set { connectionGroup = value; }
276 public override long ContentLength {
277 get { return contentLength; }
279 CheckRequestStarted ();
281 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
283 contentLength = value;
284 haveContentLength = true;
288 internal long InternalContentLength {
289 set { contentLength = value; }
292 internal bool ThrowOnError { get; set; }
294 public override string ContentType {
295 get { return webHeaders ["Content-Type"]; }
297 if (value == null || value.Trim().Length == 0) {
298 webHeaders.RemoveInternal ("Content-Type");
301 webHeaders.RemoveAndAdd ("Content-Type", value);
305 public HttpContinueDelegate ContinueDelegate {
306 get { return continueDelegate; }
307 set { continueDelegate = value; }
313 public CookieContainer CookieContainer {
314 get { return cookieContainer; }
315 set { cookieContainer = value; }
318 public override ICredentials Credentials {
319 get { return credentials; }
320 set { credentials = value; }
322 public DateTime Date {
324 string date = webHeaders ["Date"];
326 return DateTime.MinValue;
327 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
330 if (value.Equals (DateTime.MinValue))
331 webHeaders.RemoveInternal ("Date");
333 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
339 public static new RequestCachePolicy DefaultCachePolicy
342 throw GetMustImplement ();
345 throw GetMustImplement ();
351 public static int DefaultMaximumErrorResponseLength
354 throw GetMustImplement ();
357 throw GetMustImplement ();
361 public string Expect {
362 get { return webHeaders ["Expect"]; }
364 CheckRequestStarted ();
367 val = val.Trim ().ToLower ();
369 if (val == null || val.Length == 0) {
370 webHeaders.RemoveInternal ("Expect");
374 if (val == "100-continue")
375 throw new ArgumentException ("100-Continue cannot be set with this property.",
377 webHeaders.RemoveAndAdd ("Expect", value);
384 public bool HaveResponse {
385 get { return haveResponse; }
388 public override WebHeaderCollection Headers {
389 get { return webHeaders; }
391 CheckRequestStarted ();
392 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
393 int count = value.Count;
394 for (int i = 0; i < count; i++)
395 newHeaders.Add (value.GetKey (i), value.Get (i));
397 webHeaders = newHeaders;
405 return actualUri.Authority;
410 throw new ArgumentNullException ("value");
412 if (!CheckValidHost (actualUri.Scheme, value))
413 throw new ArgumentException ("Invalid host: " + value);
419 static bool CheckValidHost (string scheme, string val)
427 int idx = val.IndexOf ('/');
432 if (IPAddress.TryParse (val, out ipaddr))
435 string u = scheme + "://" + val + "/";
436 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
439 public DateTime IfModifiedSince {
441 string str = webHeaders ["If-Modified-Since"];
445 return MonoHttpDate.Parse (str);
446 } catch (Exception) {
451 CheckRequestStarted ();
453 webHeaders.SetInternal ("If-Modified-Since",
454 value.ToUniversalTime ().ToString ("r", null));
455 // TODO: check last param when using different locale
459 public bool KeepAlive {
468 public int MaximumAutomaticRedirections {
469 get { return maxAutoRedirect; }
472 throw new ArgumentException ("Must be > 0", "value");
474 maxAutoRedirect = value;
478 [MonoTODO ("Use this")]
479 public int MaximumResponseHeadersLength {
480 get { return maxResponseHeadersLength; }
481 set { maxResponseHeadersLength = value; }
484 [MonoTODO ("Use this")]
485 public static int DefaultMaximumResponseHeadersLength {
486 get { return defaultMaxResponseHeadersLength; }
487 set { defaultMaxResponseHeadersLength = value; }
490 public int ReadWriteTimeout {
491 get { return readWriteTimeout; }
494 throw new InvalidOperationException ("The request has already been sent.");
497 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
499 readWriteTimeout = value;
505 public int ContinueTimeout {
506 get { throw new NotImplementedException (); }
507 set { throw new NotImplementedException (); }
511 public string MediaType {
512 get { return mediaType; }
518 public override string Method {
519 get { return this.method; }
521 if (value == null || value.Trim () == "")
522 throw new ArgumentException ("not a valid method");
524 method = value.ToUpperInvariant ();
525 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
526 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
533 public bool Pipelined {
534 get { return pipelined; }
535 set { pipelined = value; }
538 public override bool PreAuthenticate {
539 get { return preAuthenticate; }
540 set { preAuthenticate = value; }
543 public Version ProtocolVersion {
544 get { return version; }
546 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
547 throw new ArgumentException ("value");
549 force_version = true;
554 public override IWebProxy Proxy {
555 get { return proxy; }
557 CheckRequestStarted ();
559 servicePoint = null; // we may need a new one
563 public string Referer {
564 get { return webHeaders ["Referer"]; }
566 CheckRequestStarted ();
567 if (value == null || value.Trim().Length == 0) {
568 webHeaders.RemoveInternal ("Referer");
571 webHeaders.SetInternal ("Referer", value);
575 public override Uri RequestUri {
576 get { return requestUri; }
579 public bool SendChunked {
580 get { return sendChunked; }
582 CheckRequestStarted ();
587 public ServicePoint ServicePoint {
588 get { return GetServicePoint (); }
591 internal ServicePoint ServicePointNoLock {
592 get { return servicePoint; }
594 public virtual bool SupportsCookieContainer {
596 // The managed implementation supports the cookie container
597 // it is only Silverlight that returns false here
601 public override int Timeout {
602 get { return timeout; }
605 throw new ArgumentOutOfRangeException ("value");
611 public string TransferEncoding {
612 get { return webHeaders ["Transfer-Encoding"]; }
614 CheckRequestStarted ();
617 val = val.Trim ().ToLower ();
619 if (val == null || val.Length == 0) {
620 webHeaders.RemoveInternal ("Transfer-Encoding");
624 if (val == "chunked")
625 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
628 throw new ArgumentException ("SendChunked must be True", "value");
630 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
634 public override bool UseDefaultCredentials
636 get { return CredentialCache.DefaultCredentials == Credentials; }
637 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
640 public string UserAgent {
641 get { return webHeaders ["User-Agent"]; }
642 set { webHeaders.SetInternal ("User-Agent", value); }
645 bool unsafe_auth_blah;
646 public bool UnsafeAuthenticatedConnectionSharing
648 get { return unsafe_auth_blah; }
649 set { unsafe_auth_blah = value; }
652 internal bool GotRequestStream {
653 get { return gotRequestStream; }
656 internal bool ExpectContinue {
657 get { return expectContinue; }
658 set { expectContinue = value; }
661 internal Uri AuthUri {
662 get { return actualUri; }
665 internal bool ProxyQuery {
666 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
671 internal ServicePoint GetServicePoint ()
674 if (hostChanged || servicePoint == null) {
675 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
683 public void AddRange (int range)
685 AddRange ("bytes", (long) range);
688 public void AddRange (int from, int to)
690 AddRange ("bytes", (long) from, (long) to);
693 public void AddRange (string rangeSpecifier, int range)
695 AddRange (rangeSpecifier, (long) range);
698 public void AddRange (string rangeSpecifier, int from, int to)
700 AddRange (rangeSpecifier, (long) from, (long) to);
703 void AddRange (long range)
705 AddRange ("bytes", (long) range);
709 void AddRange (long from, long to)
711 AddRange ("bytes", from, to);
715 void AddRange (string rangeSpecifier, long range)
717 if (rangeSpecifier == null)
718 throw new ArgumentNullException ("rangeSpecifier");
719 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
720 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
722 string r = webHeaders ["Range"];
724 r = rangeSpecifier + "=";
726 string old_specifier = r.Substring (0, r.IndexOf ('='));
727 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
728 throw new InvalidOperationException ("A different range specifier is already in use");
732 string n = range.ToString (CultureInfo.InvariantCulture);
737 webHeaders.RemoveAndAdd ("Range", r);
741 void AddRange (string rangeSpecifier, long from, long to)
743 if (rangeSpecifier == null)
744 throw new ArgumentNullException ("rangeSpecifier");
745 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
746 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
747 if (from > to || from < 0)
748 throw new ArgumentOutOfRangeException ("from");
750 throw new ArgumentOutOfRangeException ("to");
752 string r = webHeaders ["Range"];
754 r = rangeSpecifier + "=";
758 r = String.Format ("{0}{1}-{2}", r, from, to);
759 webHeaders.RemoveAndAdd ("Range", r);
763 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
766 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
768 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
770 if (method == null || !send)
771 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
773 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
774 throw new ProtocolViolationException ("Content-Length not set");
776 string transferEncoding = TransferEncoding;
777 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
778 throw new ProtocolViolationException ("SendChunked should be true.");
782 if (getResponseCalled)
783 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
785 if (asyncWrite != null) {
786 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
787 "method while a previous call is still in progress.");
790 asyncWrite = new WebAsyncResult (this, callback, state);
791 initialMethod = method;
793 if (writeStream != null) {
794 asyncWrite.SetCompleted (true, writeStream);
795 asyncWrite.DoCallback ();
800 gotRequestStream = true;
801 WebAsyncResult result = asyncWrite;
805 servicePoint = GetServicePoint ();
806 abortHandler = servicePoint.SendRequest (this, connectionGroup);
812 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
814 if (asyncResult == null)
815 throw new ArgumentNullException ("asyncResult");
817 WebAsyncResult result = asyncResult as WebAsyncResult;
819 throw new ArgumentException ("Invalid IAsyncResult");
822 result.WaitUntilComplete ();
824 Exception e = result.Exception;
828 return result.WriteStream;
831 public override Stream GetRequestStream()
833 IAsyncResult asyncResult = asyncWrite;
834 if (asyncResult == null) {
835 asyncResult = BeginGetRequestStream (null, null);
836 asyncWrite = (WebAsyncResult) asyncResult;
839 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
841 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
844 return EndGetRequestStream (asyncResult);
847 bool CheckIfForceWrite (SimpleAsyncResult result)
849 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
851 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
854 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
855 InternalContentLength = writeStream.WriteBufferLength;
857 // This will write the POST/PUT if the write stream already has the expected
858 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
859 // contains data and it has been closed already (xamarin bug #1512).
861 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
862 return writeStream.WriteRequestAsync (result);
867 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
870 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
873 throw new ProtocolViolationException ("Method is null.");
875 string transferEncoding = TransferEncoding;
876 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
877 throw new ProtocolViolationException ("SendChunked should be true.");
879 Monitor.Enter (locker);
880 getResponseCalled = true;
881 if (asyncRead != null && !haveResponse) {
882 Monitor.Exit (locker);
883 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
884 "method while a previous call is still in progress.");
887 asyncRead = new WebAsyncResult (this, callback, state);
888 WebAsyncResult aread = asyncRead;
889 initialMethod = method;
891 SimpleAsyncResult.RunWithLock (locker, CheckIfForceWrite, inner => {
892 var synch = inner.CompletedSynchronously;
894 if (inner.GotException) {
895 aread.SetCompleted (synch, inner.Exception);
901 Exception saved = saved_exc;
902 if (webResponse != null) {
904 aread.SetCompleted (synch, webResponse);
906 aread.SetCompleted (synch, saved);
910 } else if (saved != null) {
911 aread.SetCompleted (synch, saved);
920 servicePoint = GetServicePoint ();
921 abortHandler = servicePoint.SendRequest (this, connectionGroup);
928 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
930 if (asyncResult == null)
931 throw new ArgumentNullException ("asyncResult");
933 WebAsyncResult result = asyncResult as WebAsyncResult;
935 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
937 if (!result.WaitUntilComplete (timeout, false)) {
939 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
942 if (result.GotException)
943 throw result.Exception;
945 return result.Response;
949 public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
951 transportContext = null;
952 return EndGetRequestStream (asyncResult);
956 public override WebResponse GetResponse()
958 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
959 return EndGetResponse (result);
962 internal bool FinishedReading {
963 get { return finished_reading; }
964 set { finished_reading = value; }
967 internal bool Aborted {
968 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
971 public override void Abort ()
973 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
976 if (haveResponse && finished_reading)
980 if (abortHandler != null) {
982 abortHandler (this, EventArgs.Empty);
983 } catch (Exception) {}
987 if (asyncWrite != null) {
988 WebAsyncResult r = asyncWrite;
989 if (!r.IsCompleted) {
991 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
992 r.SetCompleted (false, wexc);
999 if (asyncRead != null) {
1000 WebAsyncResult r = asyncRead;
1001 if (!r.IsCompleted) {
1003 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1004 r.SetCompleted (false, wexc);
1011 if (writeStream != null) {
1013 writeStream.Close ();
1018 if (webResponse != null) {
1020 webResponse.Close ();
1026 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1027 StreamingContext streamingContext)
1029 GetObjectData (serializationInfo, streamingContext);
1032 protected override void GetObjectData (SerializationInfo serializationInfo,
1033 StreamingContext streamingContext)
1035 SerializationInfo info = serializationInfo;
1037 info.AddValue ("requestUri", requestUri, typeof (Uri));
1038 info.AddValue ("actualUri", actualUri, typeof (Uri));
1039 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1040 info.AddValue ("allowBuffering", allowBuffering);
1041 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1042 info.AddValue ("connectionGroup", connectionGroup);
1043 info.AddValue ("contentLength", contentLength);
1044 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1045 info.AddValue ("keepAlive", keepAlive);
1046 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1047 info.AddValue ("mediaType", mediaType);
1048 info.AddValue ("method", method);
1049 info.AddValue ("initialMethod", initialMethod);
1050 info.AddValue ("pipelined", pipelined);
1051 info.AddValue ("version", version, typeof (Version));
1052 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1053 info.AddValue ("sendChunked", sendChunked);
1054 info.AddValue ("timeout", timeout);
1055 info.AddValue ("redirects", redirects);
1056 info.AddValue ("host", host);
1059 void CheckRequestStarted ()
1062 throw new InvalidOperationException ("request started");
1065 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1067 if (continueDelegate != null)
1068 continueDelegate (statusCode, headers);
1071 void RewriteRedirectToGet ()
1074 webHeaders.RemoveInternal ("Transfer-Encoding");
1075 sendChunked = false;
1078 bool Redirect (WebAsyncResult result, HttpStatusCode code, WebResponse response)
1082 string uriString = null;
1084 case HttpStatusCode.Ambiguous: // 300
1085 e = new WebException ("Ambiguous redirect.");
1087 case HttpStatusCode.MovedPermanently: // 301
1088 case HttpStatusCode.Redirect: // 302
1089 if (method == "POST")
1090 RewriteRedirectToGet ();
1092 case HttpStatusCode.TemporaryRedirect: // 307
1094 case HttpStatusCode.SeeOther: //303
1095 RewriteRedirectToGet ();
1097 case HttpStatusCode.NotModified: // 304
1099 case HttpStatusCode.UseProxy: // 305
1100 e = new NotImplementedException ("Proxy support not available.");
1102 case HttpStatusCode.Unused: // 306
1104 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1108 if (method != "GET" && !InternalAllowBuffering)
1109 e = new WebException ("The request requires buffering data to succeed.", null, WebExceptionStatus.ProtocolError, webResponse);
1115 uriString = webResponse.Headers ["Location"];
1117 if (uriString == null)
1118 throw new WebException ("No Location header found for " + (int) code,
1119 WebExceptionStatus.ProtocolError);
1121 Uri prev = actualUri;
1123 actualUri = new Uri (actualUri, uriString);
1124 } catch (Exception) {
1125 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1126 uriString, (int) code),
1127 WebExceptionStatus.ProtocolError);
1130 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1134 string GetHeaders ()
1136 bool continue100 = false;
1139 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1140 webHeaders.RemoveInternal ("Content-Length");
1141 } else if (contentLength != -1) {
1142 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1143 // We don't send any body with the NTLM Challenge request.
1144 if (haveContentLength || gotRequestStream || contentLength > 0)
1145 webHeaders.SetInternal ("Content-Length", "0");
1147 webHeaders.RemoveInternal ("Content-Length");
1149 if (contentLength > 0)
1152 if (haveContentLength || gotRequestStream || contentLength > 0)
1153 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1155 webHeaders.RemoveInternal ("Transfer-Encoding");
1157 webHeaders.RemoveInternal ("Content-Length");
1160 if (actualVersion == HttpVersion.Version11 && continue100 &&
1161 servicePoint.SendContinue) { // RFC2616 8.2.3
1162 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1163 expectContinue = true;
1165 webHeaders.RemoveInternal ("Expect");
1166 expectContinue = false;
1169 bool proxy_query = ProxyQuery;
1170 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1171 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1172 Version proto_version = servicePoint.ProtocolVersion;
1173 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1175 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1176 if (webHeaders[connectionHeader] == null
1177 || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
1178 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1179 } else if (!keepAlive && version == HttpVersion.Version11) {
1180 webHeaders.RemoveAndAdd (connectionHeader, "close");
1183 webHeaders.SetInternal ("Host", Host);
1184 if (cookieContainer != null) {
1185 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1186 if (cookieHeader != "")
1187 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1189 webHeaders.RemoveInternal ("Cookie");
1192 string accept_encoding = null;
1193 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1194 accept_encoding = "gzip";
1195 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1196 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1197 if (accept_encoding != null)
1198 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1200 if (!usedPreAuth && preAuthenticate)
1201 DoPreAuthenticate ();
1203 return webHeaders.ToString ();
1206 void DoPreAuthenticate ()
1208 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1209 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1210 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1214 webHeaders.RemoveInternal ("Proxy-Authorization");
1215 webHeaders.RemoveInternal ("Authorization");
1216 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1217 webHeaders [authHeader] = auth.Message;
1221 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1226 WebAsyncResult r = asyncWrite;
1234 msg = "Error: " + status;
1235 wex = new WebException (msg, status);
1237 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1238 wex = new WebException (msg, exc, status);
1240 r.SetCompleted (false, wex);
1245 internal byte[] GetRequestHeaders ()
1247 StringBuilder req = new StringBuilder ();
1250 query = actualUri.PathAndQuery;
1252 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1254 actualUri.PathAndQuery);
1257 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1258 actualVersion = servicePoint.ProtocolVersion;
1260 actualVersion = version;
1263 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1264 actualVersion.Major, actualVersion.Minor);
1265 req.Append (GetHeaders ());
1266 string reqstr = req.ToString ();
1267 return Encoding.UTF8.GetBytes (reqstr);
1270 internal void SetWriteStream (WebConnectionStream stream)
1275 writeStream = stream;
1276 if (bodyBuffer != null) {
1277 webHeaders.RemoveInternal ("Transfer-Encoding");
1278 contentLength = bodyBufferLength;
1279 writeStream.SendChunked = false;
1282 writeStream.SetHeadersAsync (false, result => {
1283 if (result.GotException) {
1284 SetWriteStreamError (result.Exception);
1290 SetWriteStreamInner (inner => {
1291 if (inner.GotException) {
1292 SetWriteStreamError (inner.Exception);
1296 if (asyncWrite != null) {
1297 asyncWrite.SetCompleted (inner.CompletedSynchronously, writeStream);
1298 asyncWrite.DoCallback ();
1305 void SetWriteStreamInner (SimpleAsyncCallback callback)
1307 SimpleAsyncResult.Run (result => {
1308 if (bodyBuffer != null) {
1309 // The body has been written and buffered. The request "user"
1310 // won't write it again, so we must do it.
1311 if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
1312 // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
1313 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1315 writeStream.Close ();
1317 } else if (method != "HEAD" && method != "GET" && method != "MKCOL" && method != "CONNECT" &&
1318 method != "TRACE") {
1319 if (getResponseCalled && !writeStream.RequestWritten)
1320 return writeStream.WriteRequestAsync (result);
1327 void SetWriteStreamError (Exception exc)
1329 WebException wexc = exc as WebException;
1331 SetWriteStreamError (wexc.Status, wexc);
1333 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1336 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1341 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1342 WebAsyncResult r = asyncRead;
1347 if (e is WebException) {
1348 wexc = (WebException) e;
1350 wexc = new WebException (msg, e, status, null);
1353 if (!r.IsCompleted) {
1354 r.SetCompleted (false, wexc);
1356 } else if (r == asyncWrite) {
1359 haveResponse = true;
1363 haveResponse = true;
1369 void CheckSendError (WebConnectionData data)
1371 // Got here, but no one called GetResponse
1372 int status = data.StatusCode;
1373 if (status < 400 || status == 401 || status == 407)
1376 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1377 // The request has not been completely sent and we got here!
1378 // We should probably just close and cause an error in any case,
1379 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1380 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1381 webResponse.ReadAll ();
1383 writeStream.IgnoreIOErrors = true;
1388 bool HandleNtlmAuth (WebAsyncResult r)
1390 bool isProxy = webResponse.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;
1391 if ((isProxy ? proxy_auth_state.NtlmAuthState : auth_state.NtlmAuthState) == NtlmAuthState.None)
1394 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1396 WebConnection cnc = wce.Connection;
1397 cnc.PriorityRequest = this;
1398 ICredentials creds = !isProxy ? credentials : proxy.Credentials;
1399 if (creds != null) {
1400 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1401 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1405 finished_reading = false;
1406 haveResponse = false;
1407 webResponse.ReadAll ();
1412 internal void SetResponseData (WebConnectionData data)
1416 if (data.stream != null)
1417 data.stream.Close ();
1421 WebException wexc = null;
1423 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1424 } catch (Exception e) {
1425 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1426 if (data.stream != null)
1427 data.stream.Close ();
1430 if (wexc == null && (method == "POST" || method == "PUT")) {
1431 CheckSendError (data);
1432 if (saved_exc != null)
1433 wexc = (WebException) saved_exc;
1436 WebAsyncResult r = asyncRead;
1438 bool forced = false;
1439 if (r == null && webResponse != null) {
1440 // This is a forced completion (302, 204)...
1442 r = new WebAsyncResult (null, null);
1443 r.SetCompleted (false, webResponse);
1448 haveResponse = true;
1450 r.SetCompleted (false, wexc);
1455 bool isProxy = ProxyQuery && !proxy.IsBypassed (actualUri);
1459 redirected = CheckFinalStatus (r);
1461 if ((isProxy ? proxy_auth_state.IsNtlmAuthenticated : auth_state.IsNtlmAuthenticated) &&
1462 webResponse != null && (int)webResponse.StatusCode < 400) {
1463 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1465 WebConnection cnc = wce.Connection;
1466 cnc.NtlmAuthenticated = true;
1470 // clear internal buffer so that it does not
1471 // hold possible big buffer (bug #397627)
1472 if (writeStream != null)
1473 writeStream.KillBuffer ();
1475 haveResponse = true;
1476 r.SetCompleted (false, webResponse);
1480 sendChunked = false;
1481 webHeaders.RemoveInternal ("Transfer-Encoding");
1484 if (webResponse != null) {
1485 if (HandleNtlmAuth (r))
1487 webResponse.Close ();
1489 finished_reading = false;
1490 haveResponse = false;
1493 servicePoint = GetServicePoint ();
1494 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1496 } catch (WebException wexc2) {
1499 haveResponse = true;
1501 r.SetCompleted (false, wexc2);
1504 } catch (Exception ex) {
1505 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1508 haveResponse = true;
1510 r.SetCompleted (false, wexc);
1518 struct AuthorizationState
1520 readonly HttpWebRequest request;
1521 readonly bool isProxy;
1523 NtlmAuthState ntlm_auth_state;
1525 public bool IsCompleted {
1526 get { return isCompleted; }
1529 public NtlmAuthState NtlmAuthState {
1530 get { return ntlm_auth_state; }
1533 public bool IsNtlmAuthenticated {
1534 get { return isCompleted && ntlm_auth_state != NtlmAuthState.None; }
1537 public AuthorizationState (HttpWebRequest request, bool isProxy)
1539 this.request = request;
1540 this.isProxy = isProxy;
1541 isCompleted = false;
1542 ntlm_auth_state = NtlmAuthState.None;
1545 public bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1547 isCompleted = false;
1548 if (code == HttpStatusCode.Unauthorized && request.credentials == null)
1551 // FIXME: This should never happen!
1552 if (isProxy != (code == HttpStatusCode.ProxyAuthenticationRequired))
1555 if (isProxy && (request.proxy == null || request.proxy.Credentials == null))
1558 string [] authHeaders = response.Headers.GetValues_internal (isProxy ? "Proxy-Authenticate" : "WWW-Authenticate", false);
1559 if (authHeaders == null || authHeaders.Length == 0)
1562 ICredentials creds = (!isProxy) ? request.credentials : request.proxy.Credentials;
1563 Authorization auth = null;
1564 foreach (string authHeader in authHeaders) {
1565 auth = AuthenticationManager.Authenticate (authHeader, request, creds);
1571 request.webHeaders [isProxy ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1572 isCompleted = auth.Complete;
1573 bool is_ntlm = (auth.Module.AuthenticationType == "NTLM");
1575 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1579 public void Reset ()
1581 isCompleted = false;
1582 ntlm_auth_state = NtlmAuthState.None;
1583 request.webHeaders.RemoveInternal (isProxy ? "Proxy-Authorization" : "Authorization");
1586 public override string ToString ()
1588 return string.Format ("{0}AuthState [{1}:{2}]", isProxy ? "Proxy" : "", isCompleted, ntlm_auth_state);
1592 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1594 bool isProxy = code == HttpStatusCode.ProxyAuthenticationRequired;
1595 return isProxy ? proxy_auth_state.CheckAuthorization (response, code) : auth_state.CheckAuthorization (response, code);
1598 // Returns true if redirected
1599 bool CheckFinalStatus (WebAsyncResult result)
1601 if (result.GotException) {
1603 throw result.Exception;
1606 Exception throwMe = result.Exception;
1608 HttpWebResponse resp = result.Response;
1609 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1610 HttpStatusCode code = 0;
1611 if (throwMe == null && webResponse != null) {
1612 code = webResponse.StatusCode;
1613 if ((!auth_state.IsCompleted && code == HttpStatusCode.Unauthorized && credentials != null) ||
1614 (ProxyQuery && !proxy_auth_state.IsCompleted && code == HttpStatusCode.ProxyAuthenticationRequired)) {
1615 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1616 // Keep the written body, so it can be rewritten in the retry
1617 if (InternalAllowBuffering) {
1618 if (writeStream.WriteBufferLength > 0) {
1619 bodyBuffer = writeStream.WriteBuffer;
1620 bodyBufferLength = writeStream.WriteBufferLength;
1623 } else if (method != "PUT" && method != "POST") {
1631 writeStream.InternalClose ();
1633 webResponse.Close ();
1637 throw new WebException ("This request requires buffering " +
1638 "of data for authentication or " +
1639 "redirection to be sucessful.");
1644 if ((int) code >= 400) {
1645 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1646 (int) code, webResponse.StatusDescription);
1647 throwMe = new WebException (err, null, protoError, webResponse);
1648 webResponse.ReadAll ();
1649 } else if ((int) code == 304 && allowAutoRedirect) {
1650 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1651 (int) code, webResponse.StatusDescription);
1652 throwMe = new WebException (err, null, protoError, webResponse);
1653 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1654 throwMe = new WebException ("Max. redirections exceeded.", null,
1655 protoError, webResponse);
1656 webResponse.ReadAll ();
1661 if (throwMe == null) {
1664 if (allowAutoRedirect && c >= 300) {
1665 b = Redirect (result, code, webResponse);
1666 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1667 bodyBuffer = writeStream.WriteBuffer;
1668 bodyBufferLength = writeStream.WriteBufferLength;
1670 if (b && !unsafe_auth_blah) {
1671 auth_state.Reset ();
1672 proxy_auth_state.Reset ();
1676 if (resp != null && c >= 300 && c != 304)
1685 if (writeStream != null) {
1686 writeStream.InternalClose ();
1695 internal bool ReuseConnection {
1700 internal WebConnection StoredConnection;