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 internal Action<Stream> ResendContentFactory;
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);
144 ResetAuthorization ();
147 [Obsolete ("Serialization is obsoleted for this type", false)]
148 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
150 SerializationInfo info = serializationInfo;
152 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
153 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
154 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
155 allowBuffering = info.GetBoolean ("allowBuffering");
156 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
157 connectionGroup = info.GetString ("connectionGroup");
158 contentLength = info.GetInt64 ("contentLength");
159 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
160 keepAlive = info.GetBoolean ("keepAlive");
161 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
162 mediaType = info.GetString ("mediaType");
163 method = info.GetString ("method");
164 initialMethod = info.GetString ("initialMethod");
165 pipelined = info.GetBoolean ("pipelined");
166 version = (Version) info.GetValue ("version", typeof (Version));
167 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
168 sendChunked = info.GetBoolean ("sendChunked");
169 timeout = info.GetInt32 ("timeout");
170 redirects = info.GetInt32 ("redirects");
171 host = info.GetString ("host");
172 ResetAuthorization ();
175 void ResetAuthorization ()
177 auth_state = new AuthorizationState (this, false);
178 proxy_auth_state = new AuthorizationState (this, true);
183 public string Accept {
184 get { return webHeaders ["Accept"]; }
186 CheckRequestStarted ();
187 webHeaders.RemoveAndAdd ("Accept", value);
192 get { return actualUri; }
193 internal set { actualUri = value; } // Used by Ftp+proxy
196 public bool AllowAutoRedirect {
197 get { return allowAutoRedirect; }
198 set { this.allowAutoRedirect = value; }
201 public bool AllowWriteStreamBuffering {
202 get { return allowBuffering; }
203 set { allowBuffering = value; }
206 public virtual bool AllowReadStreamBuffering {
207 get { return false; }
210 throw new InvalidOperationException ();
214 static Exception GetMustImplement ()
216 return new NotImplementedException ();
219 public DecompressionMethods AutomaticDecompression
225 CheckRequestStarted ();
230 internal bool InternalAllowBuffering {
232 return allowBuffering && MethodWithBuffer;
236 bool MethodWithBuffer {
238 return method != "HEAD" && method != "GET" &&
239 method != "MKCOL" && method != "CONNECT" &&
244 public X509CertificateCollection ClientCertificates {
246 if (certificates == null)
247 certificates = new X509CertificateCollection ();
253 throw GetMustImplement ();
257 public string Connection {
258 get { return webHeaders ["Connection"]; }
260 CheckRequestStarted ();
262 if (string.IsNullOrEmpty (value)) {
263 webHeaders.RemoveInternal ("Connection");
267 string val = value.ToLowerInvariant ();
268 if (val.Contains ("keep-alive") || val.Contains ("close"))
269 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
272 value = value + ", Keep-Alive";
274 webHeaders.RemoveAndAdd ("Connection", value);
278 public override string ConnectionGroupName {
279 get { return connectionGroup; }
280 set { connectionGroup = value; }
283 public override long ContentLength {
284 get { return contentLength; }
286 CheckRequestStarted ();
288 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
290 contentLength = value;
291 haveContentLength = true;
295 internal long InternalContentLength {
296 set { contentLength = value; }
299 internal bool ThrowOnError { get; set; }
301 public override string ContentType {
302 get { return webHeaders ["Content-Type"]; }
304 if (value == null || value.Trim().Length == 0) {
305 webHeaders.RemoveInternal ("Content-Type");
308 webHeaders.RemoveAndAdd ("Content-Type", value);
312 public HttpContinueDelegate ContinueDelegate {
313 get { return continueDelegate; }
314 set { continueDelegate = value; }
318 public CookieContainer CookieContainer {
319 get { return cookieContainer; }
320 set { cookieContainer = value; }
323 public override ICredentials Credentials {
324 get { return credentials; }
325 set { credentials = value; }
327 public DateTime Date {
329 string date = webHeaders ["Date"];
331 return DateTime.MinValue;
332 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
335 if (value.Equals (DateTime.MinValue))
336 webHeaders.RemoveInternal ("Date");
338 webHeaders.RemoveAndAdd ("Date", value.ToUniversalTime ().ToString ("r", CultureInfo.InvariantCulture));
344 public static new RequestCachePolicy DefaultCachePolicy
347 throw GetMustImplement ();
350 throw GetMustImplement ();
356 public static int DefaultMaximumErrorResponseLength
359 throw GetMustImplement ();
362 throw GetMustImplement ();
366 public string Expect {
367 get { return webHeaders ["Expect"]; }
369 CheckRequestStarted ();
372 val = val.Trim ().ToLower ();
374 if (val == null || val.Length == 0) {
375 webHeaders.RemoveInternal ("Expect");
379 if (val == "100-continue")
380 throw new ArgumentException ("100-Continue cannot be set with this property.",
382 webHeaders.RemoveAndAdd ("Expect", value);
387 public bool HaveResponse {
388 get { return haveResponse; }
391 public override WebHeaderCollection Headers {
392 get { return webHeaders; }
394 CheckRequestStarted ();
395 WebHeaderCollection newHeaders = new WebHeaderCollection (WebHeaderCollection.HeaderInfo.Request);
396 int count = value.Count;
397 for (int i = 0; i < count; i++)
398 newHeaders.Add (value.GetKey (i), value.Get (i));
400 webHeaders = newHeaders;
408 return actualUri.Authority;
413 throw new ArgumentNullException ("value");
415 if (!CheckValidHost (actualUri.Scheme, value))
416 throw new ArgumentException ("Invalid host: " + value);
422 static bool CheckValidHost (string scheme, string val)
430 int idx = val.IndexOf ('/');
435 if (IPAddress.TryParse (val, out ipaddr))
438 string u = scheme + "://" + val + "/";
439 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
442 public DateTime IfModifiedSince {
444 string str = webHeaders ["If-Modified-Since"];
448 return MonoHttpDate.Parse (str);
449 } catch (Exception) {
454 CheckRequestStarted ();
456 webHeaders.SetInternal ("If-Modified-Since",
457 value.ToUniversalTime ().ToString ("r", null));
458 // TODO: check last param when using different locale
462 public bool KeepAlive {
471 public int MaximumAutomaticRedirections {
472 get { return maxAutoRedirect; }
475 throw new ArgumentException ("Must be > 0", "value");
477 maxAutoRedirect = value;
481 [MonoTODO ("Use this")]
482 public int MaximumResponseHeadersLength {
483 get { return maxResponseHeadersLength; }
484 set { maxResponseHeadersLength = value; }
487 [MonoTODO ("Use this")]
488 public static int DefaultMaximumResponseHeadersLength {
489 get { return defaultMaxResponseHeadersLength; }
490 set { defaultMaxResponseHeadersLength = value; }
493 public int ReadWriteTimeout {
494 get { return readWriteTimeout; }
497 throw new InvalidOperationException ("The request has already been sent.");
500 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
502 readWriteTimeout = value;
507 public int ContinueTimeout {
508 get { throw new NotImplementedException (); }
509 set { throw new NotImplementedException (); }
512 public string MediaType {
513 get { return mediaType; }
519 public override string Method {
520 get { return this.method; }
522 if (value == null || value.Trim () == "")
523 throw new ArgumentException ("not a valid method");
525 method = value.ToUpperInvariant ();
526 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
527 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
534 public bool Pipelined {
535 get { return pipelined; }
536 set { pipelined = value; }
539 public override bool PreAuthenticate {
540 get { return preAuthenticate; }
541 set { preAuthenticate = value; }
544 public Version ProtocolVersion {
545 get { return version; }
547 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
548 throw new ArgumentException ("value");
550 force_version = true;
555 public override IWebProxy Proxy {
556 get { return proxy; }
558 CheckRequestStarted ();
560 servicePoint = null; // we may need a new one
564 public string Referer {
565 get { return webHeaders ["Referer"]; }
567 CheckRequestStarted ();
568 if (value == null || value.Trim().Length == 0) {
569 webHeaders.RemoveInternal ("Referer");
572 webHeaders.SetInternal ("Referer", value);
576 public override Uri RequestUri {
577 get { return requestUri; }
580 public bool SendChunked {
581 get { return sendChunked; }
583 CheckRequestStarted ();
588 public ServicePoint ServicePoint {
589 get { return GetServicePoint (); }
592 internal ServicePoint ServicePointNoLock {
593 get { return servicePoint; }
595 public virtual bool SupportsCookieContainer {
597 // The managed implementation supports the cookie container
598 // it is only Silverlight that returns false here
602 public override int Timeout {
603 get { return timeout; }
606 throw new ArgumentOutOfRangeException ("value");
612 public string TransferEncoding {
613 get { return webHeaders ["Transfer-Encoding"]; }
615 CheckRequestStarted ();
618 val = val.Trim ().ToLower ();
620 if (val == null || val.Length == 0) {
621 webHeaders.RemoveInternal ("Transfer-Encoding");
625 if (val == "chunked")
626 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
629 throw new ArgumentException ("SendChunked must be True", "value");
631 webHeaders.RemoveAndAdd ("Transfer-Encoding", value);
635 public override bool UseDefaultCredentials
637 get { return CredentialCache.DefaultCredentials == Credentials; }
638 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
641 public string UserAgent {
642 get { return webHeaders ["User-Agent"]; }
643 set { webHeaders.SetInternal ("User-Agent", value); }
646 bool unsafe_auth_blah;
647 public bool UnsafeAuthenticatedConnectionSharing
649 get { return unsafe_auth_blah; }
650 set { unsafe_auth_blah = value; }
653 internal bool GotRequestStream {
654 get { return gotRequestStream; }
657 internal bool ExpectContinue {
658 get { return expectContinue; }
659 set { expectContinue = value; }
662 internal Uri AuthUri {
663 get { return actualUri; }
666 internal bool ProxyQuery {
667 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
672 internal ServicePoint GetServicePoint ()
675 if (hostChanged || servicePoint == null) {
676 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
684 public void AddRange (int range)
686 AddRange ("bytes", (long) range);
689 public void AddRange (int from, int to)
691 AddRange ("bytes", (long) from, (long) to);
694 public void AddRange (string rangeSpecifier, int range)
696 AddRange (rangeSpecifier, (long) range);
699 public void AddRange (string rangeSpecifier, int from, int to)
701 AddRange (rangeSpecifier, (long) from, (long) to);
704 void AddRange (long range)
706 AddRange ("bytes", (long) range);
710 void AddRange (long from, long to)
712 AddRange ("bytes", from, to);
716 void AddRange (string rangeSpecifier, long range)
718 if (rangeSpecifier == null)
719 throw new ArgumentNullException ("rangeSpecifier");
720 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
721 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
723 string r = webHeaders ["Range"];
725 r = rangeSpecifier + "=";
727 string old_specifier = r.Substring (0, r.IndexOf ('='));
728 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
729 throw new InvalidOperationException ("A different range specifier is already in use");
733 string n = range.ToString (CultureInfo.InvariantCulture);
738 webHeaders.RemoveAndAdd ("Range", r);
742 void AddRange (string rangeSpecifier, long from, long to)
744 if (rangeSpecifier == null)
745 throw new ArgumentNullException ("rangeSpecifier");
746 if (!WebHeaderCollection.IsHeaderValue (rangeSpecifier))
747 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
748 if (from > to || from < 0)
749 throw new ArgumentOutOfRangeException ("from");
751 throw new ArgumentOutOfRangeException ("to");
753 string r = webHeaders ["Range"];
755 r = rangeSpecifier + "=";
759 r = String.Format ("{0}{1}-{2}", r, from, to);
760 webHeaders.RemoveAndAdd ("Range", r);
764 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
767 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
769 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
771 if (method == null || !send)
772 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
774 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
775 throw new ProtocolViolationException ("Content-Length not set");
777 string transferEncoding = TransferEncoding;
778 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
779 throw new ProtocolViolationException ("SendChunked should be true.");
783 if (getResponseCalled)
784 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
786 if (asyncWrite != null) {
787 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
788 "method while a previous call is still in progress.");
791 asyncWrite = new WebAsyncResult (this, callback, state);
792 initialMethod = method;
794 if (writeStream != null) {
795 asyncWrite.SetCompleted (true, writeStream);
796 asyncWrite.DoCallback ();
801 gotRequestStream = true;
802 WebAsyncResult result = asyncWrite;
806 servicePoint = GetServicePoint ();
807 abortHandler = servicePoint.SendRequest (this, connectionGroup);
813 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
815 if (asyncResult == null)
816 throw new ArgumentNullException ("asyncResult");
818 WebAsyncResult result = asyncResult as WebAsyncResult;
820 throw new ArgumentException ("Invalid IAsyncResult");
823 result.WaitUntilComplete ();
825 Exception e = result.Exception;
829 return result.WriteStream;
832 public override Stream GetRequestStream()
834 IAsyncResult asyncResult = asyncWrite;
835 if (asyncResult == null) {
836 asyncResult = BeginGetRequestStream (null, null);
837 asyncWrite = (WebAsyncResult) asyncResult;
840 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
842 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
845 return EndGetRequestStream (asyncResult);
848 bool CheckIfForceWrite (SimpleAsyncResult result)
850 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
852 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
855 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
856 InternalContentLength = writeStream.WriteBufferLength;
858 // This will write the POST/PUT if the write stream already has the expected
859 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
860 // contains data and it has been closed already (xamarin bug #1512).
862 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
863 return writeStream.WriteRequestAsync (result);
868 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
871 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
874 throw new ProtocolViolationException ("Method is null.");
876 string transferEncoding = TransferEncoding;
877 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
878 throw new ProtocolViolationException ("SendChunked should be true.");
880 Monitor.Enter (locker);
881 getResponseCalled = true;
882 if (asyncRead != null && !haveResponse) {
883 Monitor.Exit (locker);
884 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
885 "method while a previous call is still in progress.");
888 asyncRead = new WebAsyncResult (this, callback, state);
889 WebAsyncResult aread = asyncRead;
890 initialMethod = method;
892 SimpleAsyncResult.RunWithLock (locker, CheckIfForceWrite, inner => {
893 var synch = inner.CompletedSynchronously;
895 if (inner.GotException) {
896 aread.SetCompleted (synch, inner.Exception);
902 Exception saved = saved_exc;
903 if (webResponse != null) {
905 aread.SetCompleted (synch, webResponse);
907 aread.SetCompleted (synch, saved);
911 } else if (saved != null) {
912 aread.SetCompleted (synch, saved);
921 servicePoint = GetServicePoint ();
922 abortHandler = servicePoint.SendRequest (this, connectionGroup);
929 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
931 if (asyncResult == null)
932 throw new ArgumentNullException ("asyncResult");
934 WebAsyncResult result = asyncResult as WebAsyncResult;
936 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
938 if (!result.WaitUntilComplete (timeout, false)) {
940 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
943 if (result.GotException)
944 throw result.Exception;
946 return result.Response;
949 public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
951 transportContext = null;
952 return EndGetRequestStream (asyncResult);
955 public override WebResponse GetResponse()
957 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
958 return EndGetResponse (result);
961 internal bool FinishedReading {
962 get { return finished_reading; }
963 set { finished_reading = value; }
966 internal bool Aborted {
967 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
970 public override void Abort ()
972 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
975 if (haveResponse && finished_reading)
979 if (abortHandler != null) {
981 abortHandler (this, EventArgs.Empty);
982 } catch (Exception) {}
986 if (asyncWrite != null) {
987 WebAsyncResult r = asyncWrite;
988 if (!r.IsCompleted) {
990 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
991 r.SetCompleted (false, wexc);
998 if (asyncRead != null) {
999 WebAsyncResult r = asyncRead;
1000 if (!r.IsCompleted) {
1002 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1003 r.SetCompleted (false, wexc);
1010 if (writeStream != null) {
1012 writeStream.Close ();
1017 if (webResponse != null) {
1019 webResponse.Close ();
1025 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1026 StreamingContext streamingContext)
1028 GetObjectData (serializationInfo, streamingContext);
1031 protected override void GetObjectData (SerializationInfo serializationInfo,
1032 StreamingContext streamingContext)
1034 SerializationInfo info = serializationInfo;
1036 info.AddValue ("requestUri", requestUri, typeof (Uri));
1037 info.AddValue ("actualUri", actualUri, typeof (Uri));
1038 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1039 info.AddValue ("allowBuffering", allowBuffering);
1040 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1041 info.AddValue ("connectionGroup", connectionGroup);
1042 info.AddValue ("contentLength", contentLength);
1043 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1044 info.AddValue ("keepAlive", keepAlive);
1045 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1046 info.AddValue ("mediaType", mediaType);
1047 info.AddValue ("method", method);
1048 info.AddValue ("initialMethod", initialMethod);
1049 info.AddValue ("pipelined", pipelined);
1050 info.AddValue ("version", version, typeof (Version));
1051 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1052 info.AddValue ("sendChunked", sendChunked);
1053 info.AddValue ("timeout", timeout);
1054 info.AddValue ("redirects", redirects);
1055 info.AddValue ("host", host);
1058 void CheckRequestStarted ()
1061 throw new InvalidOperationException ("request started");
1064 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1066 if (continueDelegate != null)
1067 continueDelegate (statusCode, headers);
1070 void RewriteRedirectToGet ()
1073 webHeaders.RemoveInternal ("Transfer-Encoding");
1074 sendChunked = false;
1077 bool Redirect (WebAsyncResult result, HttpStatusCode code, WebResponse response)
1081 string uriString = null;
1083 case HttpStatusCode.Ambiguous: // 300
1084 e = new WebException ("Ambiguous redirect.");
1086 case HttpStatusCode.MovedPermanently: // 301
1087 case HttpStatusCode.Redirect: // 302
1088 if (method == "POST")
1089 RewriteRedirectToGet ();
1091 case HttpStatusCode.TemporaryRedirect: // 307
1093 case HttpStatusCode.SeeOther: //303
1094 RewriteRedirectToGet ();
1096 case HttpStatusCode.NotModified: // 304
1098 case HttpStatusCode.UseProxy: // 305
1099 e = new NotImplementedException ("Proxy support not available.");
1101 case HttpStatusCode.Unused: // 306
1103 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1107 if (method != "GET" && !InternalAllowBuffering && (writeStream.WriteBufferLength > 0 || contentLength > 0))
1108 e = new WebException ("The request requires buffering data to succeed.", null, WebExceptionStatus.ProtocolError, webResponse);
1113 if (AllowWriteStreamBuffering || method == "GET")
1116 uriString = webResponse.Headers ["Location"];
1118 if (uriString == null)
1119 throw new WebException ("No Location header found for " + (int) code,
1120 WebExceptionStatus.ProtocolError);
1122 Uri prev = actualUri;
1124 actualUri = new Uri (actualUri, uriString);
1125 } catch (Exception) {
1126 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1127 uriString, (int) code),
1128 WebExceptionStatus.ProtocolError);
1131 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1135 string GetHeaders ()
1137 bool continue100 = false;
1140 webHeaders.RemoveAndAdd ("Transfer-Encoding", "chunked");
1141 webHeaders.RemoveInternal ("Content-Length");
1142 } else if (contentLength != -1) {
1143 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1144 // We don't send any body with the NTLM Challenge request.
1145 if (haveContentLength || gotRequestStream || contentLength > 0)
1146 webHeaders.SetInternal ("Content-Length", "0");
1148 webHeaders.RemoveInternal ("Content-Length");
1150 if (contentLength > 0)
1153 if (haveContentLength || gotRequestStream || contentLength > 0)
1154 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1156 webHeaders.RemoveInternal ("Transfer-Encoding");
1158 webHeaders.RemoveInternal ("Content-Length");
1161 if (actualVersion == HttpVersion.Version11 && continue100 &&
1162 servicePoint.SendContinue) { // RFC2616 8.2.3
1163 webHeaders.RemoveAndAdd ("Expect" , "100-continue");
1164 expectContinue = true;
1166 webHeaders.RemoveInternal ("Expect");
1167 expectContinue = false;
1170 bool proxy_query = ProxyQuery;
1171 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1172 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1173 Version proto_version = servicePoint.ProtocolVersion;
1174 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1176 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1177 if (webHeaders[connectionHeader] == null
1178 || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
1179 webHeaders.RemoveAndAdd (connectionHeader, "keep-alive");
1180 } else if (!keepAlive && version == HttpVersion.Version11) {
1181 webHeaders.RemoveAndAdd (connectionHeader, "close");
1184 webHeaders.SetInternal ("Host", Host);
1185 if (cookieContainer != null) {
1186 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1187 if (cookieHeader != "")
1188 webHeaders.RemoveAndAdd ("Cookie", cookieHeader);
1190 webHeaders.RemoveInternal ("Cookie");
1193 string accept_encoding = null;
1194 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1195 accept_encoding = "gzip";
1196 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1197 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1198 if (accept_encoding != null)
1199 webHeaders.RemoveAndAdd ("Accept-Encoding", accept_encoding);
1201 if (!usedPreAuth && preAuthenticate)
1202 DoPreAuthenticate ();
1204 return webHeaders.ToString ();
1207 void DoPreAuthenticate ()
1209 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1210 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1211 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1215 webHeaders.RemoveInternal ("Proxy-Authorization");
1216 webHeaders.RemoveInternal ("Authorization");
1217 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1218 webHeaders [authHeader] = auth.Message;
1222 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1227 WebAsyncResult r = asyncWrite;
1235 msg = "Error: " + status;
1236 wex = new WebException (msg, status);
1238 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1239 wex = new WebException (msg, exc, status);
1241 r.SetCompleted (false, wex);
1246 internal byte[] GetRequestHeaders ()
1248 StringBuilder req = new StringBuilder ();
1251 query = actualUri.PathAndQuery;
1253 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1255 actualUri.PathAndQuery);
1258 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1259 actualVersion = servicePoint.ProtocolVersion;
1261 actualVersion = version;
1264 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1265 actualVersion.Major, actualVersion.Minor);
1266 req.Append (GetHeaders ());
1267 string reqstr = req.ToString ();
1268 return Encoding.UTF8.GetBytes (reqstr);
1271 internal void SetWriteStream (WebConnectionStream stream)
1276 writeStream = stream;
1277 if (bodyBuffer != null) {
1278 webHeaders.RemoveInternal ("Transfer-Encoding");
1279 contentLength = bodyBufferLength;
1280 writeStream.SendChunked = false;
1283 writeStream.SetHeadersAsync (false, result => {
1284 if (result.GotException) {
1285 SetWriteStreamError (result.Exception);
1291 SetWriteStreamInner (inner => {
1292 if (inner.GotException) {
1293 SetWriteStreamError (inner.Exception);
1297 if (asyncWrite != null) {
1298 asyncWrite.SetCompleted (inner.CompletedSynchronously, writeStream);
1299 asyncWrite.DoCallback ();
1306 void SetWriteStreamInner (SimpleAsyncCallback callback)
1308 SimpleAsyncResult.Run (result => {
1309 if (bodyBuffer != null) {
1310 // The body has been written and buffered. The request "user"
1311 // won't write it again, so we must do it.
1312 if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
1313 // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
1314 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1316 writeStream.Close ();
1318 } else if (MethodWithBuffer) {
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 (MethodWithBuffer) {
1618 if (AllowWriteStreamBuffering) {
1619 if (writeStream.WriteBufferLength > 0) {
1620 bodyBuffer = writeStream.WriteBuffer;
1621 bodyBufferLength = writeStream.WriteBufferLength;
1628 // Buffering is not allowed but we have alternative way to get same content (we
1629 // need to resent it due to NTLM Authentication).
1631 if (ResendContentFactory != null) {
1632 using (var ms = new MemoryStream ()) {
1633 ResendContentFactory (ms);
1634 bodyBuffer = ms.ToArray ();
1635 bodyBufferLength = bodyBuffer.Length;
1639 } else if (method != "PUT" && method != "POST") {
1647 writeStream.InternalClose ();
1649 webResponse.Close ();
1653 throw new WebException ("This request requires buffering " +
1654 "of data for authentication or " +
1655 "redirection to be sucessful.");
1660 if ((int) code >= 400) {
1661 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1662 (int) code, webResponse.StatusDescription);
1663 throwMe = new WebException (err, null, protoError, webResponse);
1664 webResponse.ReadAll ();
1665 } else if ((int) code == 304 && allowAutoRedirect) {
1666 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1667 (int) code, webResponse.StatusDescription);
1668 throwMe = new WebException (err, null, protoError, webResponse);
1669 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1670 throwMe = new WebException ("Max. redirections exceeded.", null,
1671 protoError, webResponse);
1672 webResponse.ReadAll ();
1677 if (throwMe == null) {
1680 if (allowAutoRedirect && c >= 300) {
1681 b = Redirect (result, code, webResponse);
1682 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1683 bodyBuffer = writeStream.WriteBuffer;
1684 bodyBufferLength = writeStream.WriteBufferLength;
1686 if (b && !unsafe_auth_blah) {
1687 auth_state.Reset ();
1688 proxy_auth_state.Reset ();
1692 if (resp != null && c >= 300 && c != 304)
1701 if (writeStream != null) {
1702 writeStream.InternalClose ();
1711 internal bool ReuseConnection {
1716 internal WebConnection StoredConnection;