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 #if MONO_SECURITY_ALIAS
36 extern alias MonoSecurity;
37 using MonoSecurity::Mono.Security.Interface;
39 using Mono.Security.Interface;
44 using System.Collections;
45 using System.Configuration;
46 using System.Globalization;
49 using System.Net.Cache;
50 using System.Net.Sockets;
51 using System.Net.Security;
52 using System.Runtime.Remoting.Messaging;
53 using System.Runtime.Serialization;
54 using System.Security.Cryptography.X509Certificates;
56 using System.Threading;
57 using Mono.Net.Security;
62 public class HttpWebRequest : WebRequest, ISerializable {
66 bool allowAutoRedirect = true;
67 bool allowBuffering = true;
68 X509CertificateCollection certificates;
69 string connectionGroup;
70 bool haveContentLength;
71 long contentLength = -1;
72 HttpContinueDelegate continueDelegate;
73 CookieContainer cookieContainer;
74 ICredentials credentials;
78 WebHeaderCollection webHeaders;
79 bool keepAlive = true;
80 int maxAutoRedirect = 50;
81 string mediaType = String.Empty;
82 string method = "GET";
83 string initialMethod = "GET";
84 bool pipelined = true;
87 Version version = HttpVersion.Version11;
89 Version actualVersion;
92 ServicePoint servicePoint;
95 WebConnectionStream writeStream;
96 HttpWebResponse webResponse;
97 WebAsyncResult asyncWrite;
98 WebAsyncResult asyncRead;
99 EventHandler abortHandler;
101 bool gotRequestStream;
105 int bodyBufferLength;
106 bool getResponseCalled;
108 object locker = new object ();
109 bool finished_reading;
110 internal WebConnection WebConnection;
111 DecompressionMethods auto_decomp;
112 int maxResponseHeadersLength;
113 static int defaultMaxResponseHeadersLength;
114 int readWriteTimeout = 300000; // ms
115 IMonoTlsProvider tlsProvider;
117 MonoTlsSettings tlsSettings;
119 ServerCertValidationCallback certValidationCallback;
126 AuthorizationState auth_state, proxy_auth_state;
130 internal Action<Stream> ResendContentFactory;
133 static HttpWebRequest ()
135 defaultMaxResponseHeadersLength = 64 * 1024;
137 NetConfig config = ConfigurationSettings.GetConfig ("system.net/settings") as NetConfig;
138 if (config != null) {
139 int x = config.MaxResponseHeadersLength;
143 defaultMaxResponseHeadersLength = x;
153 HttpWebRequest (Uri uri)
155 this.requestUri = uri;
156 this.actualUri = uri;
157 this.proxy = InternalDefaultWebProxy;
158 this.webHeaders = new WebHeaderCollection (WebHeaderCollectionType.HttpWebRequest);
160 ResetAuthorization ();
164 internal HttpWebRequest (Uri uri, IMonoTlsProvider tlsProvider, MonoTlsSettings settings = null)
167 this.tlsProvider = tlsProvider;
168 this.tlsSettings = settings;
172 [Obsolete ("Serialization is obsoleted for this type", false)]
173 protected HttpWebRequest (SerializationInfo serializationInfo, StreamingContext streamingContext)
175 SerializationInfo info = serializationInfo;
177 requestUri = (Uri) info.GetValue ("requestUri", typeof (Uri));
178 actualUri = (Uri) info.GetValue ("actualUri", typeof (Uri));
179 allowAutoRedirect = info.GetBoolean ("allowAutoRedirect");
180 allowBuffering = info.GetBoolean ("allowBuffering");
181 certificates = (X509CertificateCollection) info.GetValue ("certificates", typeof (X509CertificateCollection));
182 connectionGroup = info.GetString ("connectionGroup");
183 contentLength = info.GetInt64 ("contentLength");
184 webHeaders = (WebHeaderCollection) info.GetValue ("webHeaders", typeof (WebHeaderCollection));
185 keepAlive = info.GetBoolean ("keepAlive");
186 maxAutoRedirect = info.GetInt32 ("maxAutoRedirect");
187 mediaType = info.GetString ("mediaType");
188 method = info.GetString ("method");
189 initialMethod = info.GetString ("initialMethod");
190 pipelined = info.GetBoolean ("pipelined");
191 version = (Version) info.GetValue ("version", typeof (Version));
192 proxy = (IWebProxy) info.GetValue ("proxy", typeof (IWebProxy));
193 sendChunked = info.GetBoolean ("sendChunked");
194 timeout = info.GetInt32 ("timeout");
195 redirects = info.GetInt32 ("redirects");
196 host = info.GetString ("host");
197 ResetAuthorization ();
200 void ResetAuthorization ()
202 auth_state = new AuthorizationState (this, false);
203 proxy_auth_state = new AuthorizationState (this, true);
208 void SetSpecialHeaders(string HeaderName, string value) {
209 value = WebHeaderCollection.CheckBadChars(value, true);
210 webHeaders.RemoveInternal(HeaderName);
211 if (value.Length != 0) {
212 webHeaders.AddInternal(HeaderName, value);
216 public string Accept {
217 get { return webHeaders ["Accept"]; }
219 CheckRequestStarted ();
220 SetSpecialHeaders ("Accept", value);
225 get { return actualUri; }
226 internal set { actualUri = value; } // Used by Ftp+proxy
229 public bool AllowAutoRedirect {
230 get { return allowAutoRedirect; }
231 set { this.allowAutoRedirect = value; }
234 public bool AllowWriteStreamBuffering {
235 get { return allowBuffering; }
236 set { allowBuffering = value; }
239 public virtual bool AllowReadStreamBuffering {
240 get { return false; }
243 throw new InvalidOperationException ();
247 static Exception GetMustImplement ()
249 return new NotImplementedException ();
252 public DecompressionMethods AutomaticDecompression
258 CheckRequestStarted ();
263 internal bool InternalAllowBuffering {
265 return allowBuffering && MethodWithBuffer;
269 bool MethodWithBuffer {
271 return method != "HEAD" && method != "GET" &&
272 method != "MKCOL" && method != "CONNECT" &&
277 internal IMonoTlsProvider TlsProvider {
278 get { return tlsProvider; }
282 internal MonoTlsSettings TlsSettings {
283 get { return tlsSettings; }
287 public X509CertificateCollection ClientCertificates {
289 if (certificates == null)
290 certificates = new X509CertificateCollection ();
295 throw new ArgumentNullException ("value");
296 certificates = value;
300 public string Connection {
301 get { return webHeaders ["Connection"]; }
303 CheckRequestStarted ();
305 if (string.IsNullOrEmpty (value)) {
306 webHeaders.RemoveInternal ("Connection");
310 string val = value.ToLowerInvariant ();
311 if (val.Contains ("keep-alive") || val.Contains ("close"))
312 throw new ArgumentException ("Keep-Alive and Close may not be set with this property");
315 value = value + ", Keep-Alive";
317 webHeaders.CheckUpdate ("Connection", value);
321 public override string ConnectionGroupName {
322 get { return connectionGroup; }
323 set { connectionGroup = value; }
326 public override long ContentLength {
327 get { return contentLength; }
329 CheckRequestStarted ();
331 throw new ArgumentOutOfRangeException ("value", "Content-Length must be >= 0");
333 contentLength = value;
334 haveContentLength = true;
338 internal long InternalContentLength {
339 set { contentLength = value; }
342 internal bool ThrowOnError { get; set; }
344 public override string ContentType {
345 get { return webHeaders ["Content-Type"]; }
347 SetSpecialHeaders ("Content-Type", value);
351 public HttpContinueDelegate ContinueDelegate {
352 get { return continueDelegate; }
353 set { continueDelegate = value; }
357 public CookieContainer CookieContainer {
358 get { return cookieContainer; }
359 set { cookieContainer = value; }
362 public override ICredentials Credentials {
363 get { return credentials; }
364 set { credentials = value; }
366 public DateTime Date {
368 string date = webHeaders ["Date"];
370 return DateTime.MinValue;
371 return DateTime.ParseExact (date, "r", CultureInfo.InvariantCulture).ToLocalTime ();
374 SetDateHeaderHelper ("Date", value);
378 void SetDateHeaderHelper(string headerName, DateTime dateTime) {
379 if (dateTime == DateTime.MinValue)
380 SetSpecialHeaders(headerName, null); // remove header
382 SetSpecialHeaders(headerName, HttpProtocolUtils.date2string(dateTime));
387 public static new RequestCachePolicy DefaultCachePolicy
390 throw GetMustImplement ();
393 throw GetMustImplement ();
399 public static int DefaultMaximumErrorResponseLength
402 throw GetMustImplement ();
405 throw GetMustImplement ();
409 public string Expect {
410 get { return webHeaders ["Expect"]; }
412 CheckRequestStarted ();
415 val = val.Trim ().ToLower ();
417 if (val == null || val.Length == 0) {
418 webHeaders.RemoveInternal ("Expect");
422 if (val == "100-continue")
423 throw new ArgumentException ("100-Continue cannot be set with this property.",
426 webHeaders.CheckUpdate ("Expect", value);
431 public bool HaveResponse {
432 get { return haveResponse; }
435 public override WebHeaderCollection Headers {
436 get { return webHeaders; }
438 CheckRequestStarted ();
440 WebHeaderCollection webHeaders = value;
441 WebHeaderCollection newWebHeaders = new WebHeaderCollection(WebHeaderCollectionType.HttpWebRequest);
443 // Copy And Validate -
444 // Handle the case where their object tries to change
445 // name, value pairs after they call set, so therefore,
446 // we need to clone their headers.
449 foreach (String headerName in webHeaders.AllKeys ) {
450 newWebHeaders.Add(headerName,webHeaders[headerName]);
453 this.webHeaders = newWebHeaders;
461 return actualUri.Authority;
466 throw new ArgumentNullException ("value");
468 if (!CheckValidHost (actualUri.Scheme, value))
469 throw new ArgumentException ("Invalid host: " + value);
475 static bool CheckValidHost (string scheme, string val)
483 int idx = val.IndexOf ('/');
488 if (IPAddress.TryParse (val, out ipaddr))
491 string u = scheme + "://" + val + "/";
492 return Uri.IsWellFormedUriString (u, UriKind.Absolute);
495 public DateTime IfModifiedSince {
497 string str = webHeaders ["If-Modified-Since"];
501 return MonoHttpDate.Parse (str);
502 } catch (Exception) {
507 CheckRequestStarted ();
509 webHeaders.SetInternal ("If-Modified-Since",
510 value.ToUniversalTime ().ToString ("r", null));
511 // TODO: check last param when using different locale
515 public bool KeepAlive {
524 public int MaximumAutomaticRedirections {
525 get { return maxAutoRedirect; }
528 throw new ArgumentException ("Must be > 0", "value");
530 maxAutoRedirect = value;
534 [MonoTODO ("Use this")]
535 public int MaximumResponseHeadersLength {
536 get { return maxResponseHeadersLength; }
537 set { maxResponseHeadersLength = value; }
540 [MonoTODO ("Use this")]
541 public static int DefaultMaximumResponseHeadersLength {
542 get { return defaultMaxResponseHeadersLength; }
543 set { defaultMaxResponseHeadersLength = value; }
546 public int ReadWriteTimeout {
547 get { return readWriteTimeout; }
550 throw new InvalidOperationException ("The request has already been sent.");
553 throw new ArgumentOutOfRangeException ("value", "Must be >= -1");
555 readWriteTimeout = value;
560 public int ContinueTimeout {
561 get { throw new NotImplementedException (); }
562 set { throw new NotImplementedException (); }
565 public string MediaType {
566 get { return mediaType; }
572 public override string Method {
573 get { return this.method; }
575 if (value == null || value.Trim () == "")
576 throw new ArgumentException ("not a valid method");
578 method = value.ToUpperInvariant ();
579 if (method != "HEAD" && method != "GET" && method != "POST" && method != "PUT" &&
580 method != "DELETE" && method != "CONNECT" && method != "TRACE" &&
587 public bool Pipelined {
588 get { return pipelined; }
589 set { pipelined = value; }
592 public override bool PreAuthenticate {
593 get { return preAuthenticate; }
594 set { preAuthenticate = value; }
597 public Version ProtocolVersion {
598 get { return version; }
600 if (value != HttpVersion.Version10 && value != HttpVersion.Version11)
601 throw new ArgumentException ("value");
603 force_version = true;
608 public override IWebProxy Proxy {
609 get { return proxy; }
611 CheckRequestStarted ();
613 servicePoint = null; // we may need a new one
618 public string Referer {
619 get { return webHeaders ["Referer"]; }
621 CheckRequestStarted ();
622 if (value == null || value.Trim().Length == 0) {
623 webHeaders.RemoveInternal ("Referer");
626 webHeaders.SetInternal ("Referer", value);
630 public override Uri RequestUri {
631 get { return requestUri; }
634 public bool SendChunked {
635 get { return sendChunked; }
637 CheckRequestStarted ();
642 public ServicePoint ServicePoint {
643 get { return GetServicePoint (); }
646 internal ServicePoint ServicePointNoLock {
647 get { return servicePoint; }
649 public virtual bool SupportsCookieContainer {
651 // The managed implementation supports the cookie container
652 // it is only Silverlight that returns false here
656 public override int Timeout {
657 get { return timeout; }
660 throw new ArgumentOutOfRangeException ("value");
666 public string TransferEncoding {
667 get { return webHeaders ["Transfer-Encoding"]; }
669 CheckRequestStarted ();
672 val = val.Trim ().ToLower ();
674 if (val == null || val.Length == 0) {
675 webHeaders.RemoveInternal ("Transfer-Encoding");
679 if (val == "chunked")
680 throw new ArgumentException ("Chunked encoding must be set with the SendChunked property");
683 throw new ArgumentException ("SendChunked must be True", "value");
685 webHeaders.CheckUpdate ("Transfer-Encoding", value);
689 public override bool UseDefaultCredentials
691 get { return CredentialCache.DefaultCredentials == Credentials; }
692 set { Credentials = value ? CredentialCache.DefaultCredentials : null; }
695 public string UserAgent {
696 get { return webHeaders ["User-Agent"]; }
697 set { webHeaders.SetInternal ("User-Agent", value); }
700 bool unsafe_auth_blah;
701 public bool UnsafeAuthenticatedConnectionSharing
703 get { return unsafe_auth_blah; }
704 set { unsafe_auth_blah = value; }
707 internal bool GotRequestStream {
708 get { return gotRequestStream; }
711 internal bool ExpectContinue {
712 get { return expectContinue; }
713 set { expectContinue = value; }
716 internal Uri AuthUri {
717 get { return actualUri; }
720 internal bool ProxyQuery {
721 get { return servicePoint.UsesProxy && !servicePoint.UseConnect; }
724 internal ServerCertValidationCallback ServerCertValidationCallback {
725 get { return certValidationCallback; }
728 public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
730 if (certValidationCallback == null)
732 return certValidationCallback.ValidationCallback;
737 certValidationCallback = null;
739 certValidationCallback = new ServerCertValidationCallback (value);
745 internal ServicePoint GetServicePoint ()
748 if (hostChanged || servicePoint == null) {
749 servicePoint = ServicePointManager.FindServicePoint (actualUri, proxy);
757 public void AddRange (int range)
759 AddRange ("bytes", (long) range);
762 public void AddRange (int from, int to)
764 AddRange ("bytes", (long) from, (long) to);
767 public void AddRange (string rangeSpecifier, int range)
769 AddRange (rangeSpecifier, (long) range);
772 public void AddRange (string rangeSpecifier, int from, int to)
774 AddRange (rangeSpecifier, (long) from, (long) to);
777 void AddRange (long range)
779 AddRange ("bytes", (long) range);
783 void AddRange (long from, long to)
785 AddRange ("bytes", from, to);
789 void AddRange (string rangeSpecifier, long range)
791 if (rangeSpecifier == null)
792 throw new ArgumentNullException ("rangeSpecifier");
793 if (!WebHeaderCollection.IsValidToken (rangeSpecifier))
794 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
796 string r = webHeaders ["Range"];
798 r = rangeSpecifier + "=";
800 string old_specifier = r.Substring (0, r.IndexOf ('='));
801 if (String.Compare (old_specifier, rangeSpecifier, StringComparison.OrdinalIgnoreCase) != 0)
802 throw new InvalidOperationException ("A different range specifier is already in use");
806 string n = range.ToString (CultureInfo.InvariantCulture);
811 webHeaders.ChangeInternal ("Range", r);
815 void AddRange (string rangeSpecifier, long from, long to)
817 if (rangeSpecifier == null)
818 throw new ArgumentNullException ("rangeSpecifier");
819 if (!WebHeaderCollection.IsValidToken (rangeSpecifier))
820 throw new ArgumentException ("Invalid range specifier", "rangeSpecifier");
821 if (from > to || from < 0)
822 throw new ArgumentOutOfRangeException ("from");
824 throw new ArgumentOutOfRangeException ("to");
826 string r = webHeaders ["Range"];
828 r = rangeSpecifier + "=";
832 r = String.Format ("{0}{1}-{2}", r, from, to);
833 webHeaders.ChangeInternal ("Range", r);
837 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state)
840 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
842 bool send = !(method == "GET" || method == "CONNECT" || method == "HEAD" ||
844 if (method == null || !send)
845 throw new ProtocolViolationException ("Cannot send data when method is: " + method);
847 if (contentLength == -1 && !sendChunked && !allowBuffering && KeepAlive)
848 throw new ProtocolViolationException ("Content-Length not set");
850 string transferEncoding = TransferEncoding;
851 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
852 throw new ProtocolViolationException ("SendChunked should be true.");
856 if (getResponseCalled)
857 throw new InvalidOperationException ("The operation cannot be performed once the request has been submitted.");
859 if (asyncWrite != null) {
860 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
861 "method while a previous call is still in progress.");
864 asyncWrite = new WebAsyncResult (this, callback, state);
865 initialMethod = method;
867 if (writeStream != null) {
868 asyncWrite.SetCompleted (true, writeStream);
869 asyncWrite.DoCallback ();
874 gotRequestStream = true;
875 WebAsyncResult result = asyncWrite;
879 servicePoint = GetServicePoint ();
880 abortHandler = servicePoint.SendRequest (this, connectionGroup);
886 public override Stream EndGetRequestStream (IAsyncResult asyncResult)
888 if (asyncResult == null)
889 throw new ArgumentNullException ("asyncResult");
891 WebAsyncResult result = asyncResult as WebAsyncResult;
893 throw new ArgumentException ("Invalid IAsyncResult");
896 result.WaitUntilComplete ();
898 Exception e = result.Exception;
902 return result.WriteStream;
905 public override Stream GetRequestStream()
907 IAsyncResult asyncResult = asyncWrite;
908 if (asyncResult == null) {
909 asyncResult = BeginGetRequestStream (null, null);
910 asyncWrite = (WebAsyncResult) asyncResult;
913 if (!asyncResult.IsCompleted && !asyncResult.AsyncWaitHandle.WaitOne (timeout, false)) {
915 throw new WebException ("The request timed out", WebExceptionStatus.Timeout);
918 return EndGetRequestStream (asyncResult);
921 bool CheckIfForceWrite (SimpleAsyncResult result)
923 if (writeStream == null || writeStream.RequestWritten || !InternalAllowBuffering)
925 if (contentLength < 0 && writeStream.CanWrite == true && writeStream.WriteBufferLength < 0)
928 if (contentLength < 0 && writeStream.WriteBufferLength >= 0)
929 InternalContentLength = writeStream.WriteBufferLength;
931 // This will write the POST/PUT if the write stream already has the expected
932 // amount of bytes in it (ContentLength) (bug #77753) or if the write stream
933 // contains data and it has been closed already (xamarin bug #1512).
935 if (writeStream.WriteBufferLength == contentLength || (contentLength == -1 && writeStream.CanWrite == false))
936 return writeStream.WriteRequestAsync (result);
941 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state)
944 throw new WebException ("The request was canceled.", WebExceptionStatus.RequestCanceled);
947 throw new ProtocolViolationException ("Method is null.");
949 string transferEncoding = TransferEncoding;
950 if (!sendChunked && transferEncoding != null && transferEncoding.Trim () != "")
951 throw new ProtocolViolationException ("SendChunked should be true.");
953 Monitor.Enter (locker);
954 getResponseCalled = true;
955 if (asyncRead != null && !haveResponse) {
956 Monitor.Exit (locker);
957 throw new InvalidOperationException ("Cannot re-call start of asynchronous " +
958 "method while a previous call is still in progress.");
961 asyncRead = new WebAsyncResult (this, callback, state);
962 WebAsyncResult aread = asyncRead;
963 initialMethod = method;
965 SimpleAsyncResult.RunWithLock (locker, CheckIfForceWrite, inner => {
966 var synch = inner.CompletedSynchronouslyPeek;
968 if (inner.GotException) {
969 aread.SetCompleted (synch, inner.Exception);
975 Exception saved = saved_exc;
976 if (webResponse != null) {
978 aread.SetCompleted (synch, webResponse);
980 aread.SetCompleted (synch, saved);
984 } else if (saved != null) {
985 aread.SetCompleted (synch, saved);
997 servicePoint = GetServicePoint ();
998 abortHandler = servicePoint.SendRequest (this, connectionGroup);
999 } catch (Exception ex) {
1000 aread.SetCompleted (synch, ex);
1001 aread.DoCallback ();
1008 public override WebResponse EndGetResponse (IAsyncResult asyncResult)
1010 if (asyncResult == null)
1011 throw new ArgumentNullException ("asyncResult");
1013 WebAsyncResult result = asyncResult as WebAsyncResult;
1015 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
1017 if (!result.WaitUntilComplete (timeout, false)) {
1019 throw new WebException("The request timed out", WebExceptionStatus.Timeout);
1022 if (result.GotException)
1023 throw result.Exception;
1025 return result.Response;
1028 public Stream EndGetRequestStream (IAsyncResult asyncResult, out TransportContext transportContext)
1030 transportContext = null;
1031 return EndGetRequestStream (asyncResult);
1034 public override WebResponse GetResponse()
1036 WebAsyncResult result = (WebAsyncResult) BeginGetResponse (null, null);
1037 return EndGetResponse (result);
1040 internal bool FinishedReading {
1041 get { return finished_reading; }
1042 set { finished_reading = value; }
1045 internal bool Aborted {
1046 get { return Interlocked.CompareExchange (ref aborted, 0, 0) == 1; }
1049 public override void Abort ()
1051 if (Interlocked.CompareExchange (ref aborted, 1, 0) == 1)
1054 if (haveResponse && finished_reading)
1057 haveResponse = true;
1058 if (abortHandler != null) {
1060 abortHandler (this, EventArgs.Empty);
1061 } catch (Exception) {}
1062 abortHandler = null;
1065 if (asyncWrite != null) {
1066 WebAsyncResult r = asyncWrite;
1067 if (!r.IsCompleted) {
1069 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1070 r.SetCompleted (false, wexc);
1077 if (asyncRead != null) {
1078 WebAsyncResult r = asyncRead;
1079 if (!r.IsCompleted) {
1081 WebException wexc = new WebException ("Aborted.", WebExceptionStatus.RequestCanceled);
1082 r.SetCompleted (false, wexc);
1089 if (writeStream != null) {
1091 writeStream.Close ();
1096 if (webResponse != null) {
1098 webResponse.Close ();
1104 void ISerializable.GetObjectData (SerializationInfo serializationInfo,
1105 StreamingContext streamingContext)
1107 GetObjectData (serializationInfo, streamingContext);
1110 protected override void GetObjectData (SerializationInfo serializationInfo,
1111 StreamingContext streamingContext)
1113 SerializationInfo info = serializationInfo;
1115 info.AddValue ("requestUri", requestUri, typeof (Uri));
1116 info.AddValue ("actualUri", actualUri, typeof (Uri));
1117 info.AddValue ("allowAutoRedirect", allowAutoRedirect);
1118 info.AddValue ("allowBuffering", allowBuffering);
1119 info.AddValue ("certificates", certificates, typeof (X509CertificateCollection));
1120 info.AddValue ("connectionGroup", connectionGroup);
1121 info.AddValue ("contentLength", contentLength);
1122 info.AddValue ("webHeaders", webHeaders, typeof (WebHeaderCollection));
1123 info.AddValue ("keepAlive", keepAlive);
1124 info.AddValue ("maxAutoRedirect", maxAutoRedirect);
1125 info.AddValue ("mediaType", mediaType);
1126 info.AddValue ("method", method);
1127 info.AddValue ("initialMethod", initialMethod);
1128 info.AddValue ("pipelined", pipelined);
1129 info.AddValue ("version", version, typeof (Version));
1130 info.AddValue ("proxy", proxy, typeof (IWebProxy));
1131 info.AddValue ("sendChunked", sendChunked);
1132 info.AddValue ("timeout", timeout);
1133 info.AddValue ("redirects", redirects);
1134 info.AddValue ("host", host);
1137 void CheckRequestStarted ()
1140 throw new InvalidOperationException ("request started");
1143 internal void DoContinueDelegate (int statusCode, WebHeaderCollection headers)
1145 if (continueDelegate != null)
1146 continueDelegate (statusCode, headers);
1149 void RewriteRedirectToGet ()
1152 webHeaders.RemoveInternal ("Transfer-Encoding");
1153 sendChunked = false;
1156 bool Redirect (WebAsyncResult result, HttpStatusCode code, WebResponse response)
1160 string uriString = null;
1162 case HttpStatusCode.Ambiguous: // 300
1163 e = new WebException ("Ambiguous redirect.");
1165 case HttpStatusCode.MovedPermanently: // 301
1166 case HttpStatusCode.Redirect: // 302
1167 if (method == "POST")
1168 RewriteRedirectToGet ();
1170 case HttpStatusCode.TemporaryRedirect: // 307
1172 case HttpStatusCode.SeeOther: //303
1173 RewriteRedirectToGet ();
1175 case HttpStatusCode.NotModified: // 304
1177 case HttpStatusCode.UseProxy: // 305
1178 e = new NotImplementedException ("Proxy support not available.");
1180 case HttpStatusCode.Unused: // 306
1182 e = new ProtocolViolationException ("Invalid status code: " + (int) code);
1186 if (method != "GET" && !InternalAllowBuffering && (writeStream.WriteBufferLength > 0 || contentLength > 0))
1187 e = new WebException ("The request requires buffering data to succeed.", null, WebExceptionStatus.ProtocolError, webResponse);
1192 if (AllowWriteStreamBuffering || method == "GET")
1195 uriString = webResponse.Headers ["Location"];
1197 if (uriString == null)
1198 throw new WebException ("No Location header found for " + (int) code,
1199 WebExceptionStatus.ProtocolError);
1201 Uri prev = actualUri;
1203 actualUri = new Uri (actualUri, uriString);
1204 } catch (Exception) {
1205 throw new WebException (String.Format ("Invalid URL ({0}) for {1}",
1206 uriString, (int) code),
1207 WebExceptionStatus.ProtocolError);
1210 hostChanged = (actualUri.Scheme != prev.Scheme || Host != prev.Authority);
1214 string GetHeaders ()
1216 bool continue100 = false;
1219 webHeaders.ChangeInternal ("Transfer-Encoding", "chunked");
1220 webHeaders.RemoveInternal ("Content-Length");
1221 } else if (contentLength != -1) {
1222 if (auth_state.NtlmAuthState == NtlmAuthState.Challenge || proxy_auth_state.NtlmAuthState == NtlmAuthState.Challenge) {
1223 // We don't send any body with the NTLM Challenge request.
1224 if (haveContentLength || gotRequestStream || contentLength > 0)
1225 webHeaders.SetInternal ("Content-Length", "0");
1227 webHeaders.RemoveInternal ("Content-Length");
1229 if (contentLength > 0)
1232 if (haveContentLength || gotRequestStream || contentLength > 0)
1233 webHeaders.SetInternal ("Content-Length", contentLength.ToString ());
1235 webHeaders.RemoveInternal ("Transfer-Encoding");
1237 webHeaders.RemoveInternal ("Content-Length");
1240 if (actualVersion == HttpVersion.Version11 && continue100 &&
1241 servicePoint.SendContinue) { // RFC2616 8.2.3
1242 webHeaders.ChangeInternal ("Expect" , "100-continue");
1243 expectContinue = true;
1245 webHeaders.RemoveInternal ("Expect");
1246 expectContinue = false;
1249 bool proxy_query = ProxyQuery;
1250 string connectionHeader = (proxy_query) ? "Proxy-Connection" : "Connection";
1251 webHeaders.RemoveInternal ((!proxy_query) ? "Proxy-Connection" : "Connection");
1252 Version proto_version = servicePoint.ProtocolVersion;
1253 bool spoint10 = (proto_version == null || proto_version == HttpVersion.Version10);
1255 if (keepAlive && (version == HttpVersion.Version10 || spoint10)) {
1256 if (webHeaders[connectionHeader] == null
1257 || webHeaders[connectionHeader].IndexOf ("keep-alive", StringComparison.OrdinalIgnoreCase) == -1)
1258 webHeaders.ChangeInternal (connectionHeader, "keep-alive");
1259 } else if (!keepAlive && version == HttpVersion.Version11) {
1260 webHeaders.ChangeInternal (connectionHeader, "close");
1263 webHeaders.SetInternal ("Host", Host);
1264 if (cookieContainer != null) {
1265 string cookieHeader = cookieContainer.GetCookieHeader (actualUri);
1266 if (cookieHeader != "")
1267 webHeaders.ChangeInternal ("Cookie", cookieHeader);
1269 webHeaders.RemoveInternal ("Cookie");
1272 string accept_encoding = null;
1273 if ((auto_decomp & DecompressionMethods.GZip) != 0)
1274 accept_encoding = "gzip";
1275 if ((auto_decomp & DecompressionMethods.Deflate) != 0)
1276 accept_encoding = accept_encoding != null ? "gzip, deflate" : "deflate";
1277 if (accept_encoding != null)
1278 webHeaders.ChangeInternal ("Accept-Encoding", accept_encoding);
1280 if (!usedPreAuth && preAuthenticate)
1281 DoPreAuthenticate ();
1283 return webHeaders.ToString ();
1286 void DoPreAuthenticate ()
1288 bool isProxy = (proxy != null && !proxy.IsBypassed (actualUri));
1289 ICredentials creds = (!isProxy || credentials != null) ? credentials : proxy.Credentials;
1290 Authorization auth = AuthenticationManager.PreAuthenticate (this, creds);
1294 webHeaders.RemoveInternal ("Proxy-Authorization");
1295 webHeaders.RemoveInternal ("Authorization");
1296 string authHeader = (isProxy && credentials == null) ? "Proxy-Authorization" : "Authorization";
1297 webHeaders [authHeader] = auth.Message;
1301 internal void SetWriteStreamError (WebExceptionStatus status, Exception exc)
1306 WebAsyncResult r = asyncWrite;
1314 msg = "Error: " + status;
1315 wex = new WebException (msg, status);
1317 msg = String.Format ("Error: {0} ({1})", status, exc.Message);
1318 wex = new WebException (msg, status, WebExceptionInternalStatus.RequestFatal, exc);
1320 r.SetCompleted (false, wex);
1325 internal byte[] GetRequestHeaders ()
1327 StringBuilder req = new StringBuilder ();
1330 query = actualUri.PathAndQuery;
1332 query = String.Format ("{0}://{1}{2}", actualUri.Scheme,
1334 actualUri.PathAndQuery);
1337 if (!force_version && servicePoint.ProtocolVersion != null && servicePoint.ProtocolVersion < version) {
1338 actualVersion = servicePoint.ProtocolVersion;
1340 actualVersion = version;
1343 req.AppendFormat ("{0} {1} HTTP/{2}.{3}\r\n", method, query,
1344 actualVersion.Major, actualVersion.Minor);
1345 req.Append (GetHeaders ());
1346 string reqstr = req.ToString ();
1347 return Encoding.UTF8.GetBytes (reqstr);
1350 internal void SetWriteStream (WebConnectionStream stream)
1355 writeStream = stream;
1356 if (bodyBuffer != null) {
1357 webHeaders.RemoveInternal ("Transfer-Encoding");
1358 contentLength = bodyBufferLength;
1359 writeStream.SendChunked = false;
1362 writeStream.SetHeadersAsync (false, result => {
1363 if (result.GotException) {
1364 SetWriteStreamError (result.Exception);
1370 SetWriteStreamInner (inner => {
1371 if (inner.GotException) {
1372 SetWriteStreamError (inner.Exception);
1376 if (asyncWrite != null) {
1377 asyncWrite.SetCompleted (inner.CompletedSynchronouslyPeek, writeStream);
1378 asyncWrite.DoCallback ();
1385 void SetWriteStreamInner (SimpleAsyncCallback callback)
1387 SimpleAsyncResult.Run (result => {
1388 if (bodyBuffer != null) {
1389 // The body has been written and buffered. The request "user"
1390 // won't write it again, so we must do it.
1391 if (auth_state.NtlmAuthState != NtlmAuthState.Challenge && proxy_auth_state.NtlmAuthState != NtlmAuthState.Challenge) {
1392 // FIXME: this is a blocking call on the thread pool that could lead to thread pool exhaustion
1393 writeStream.Write (bodyBuffer, 0, bodyBufferLength);
1395 writeStream.Close ();
1397 } else if (MethodWithBuffer) {
1398 if (getResponseCalled && !writeStream.RequestWritten)
1399 return writeStream.WriteRequestAsync (result);
1406 void SetWriteStreamError (Exception exc)
1408 WebException wexc = exc as WebException;
1410 SetWriteStreamError (wexc.Status, wexc);
1412 SetWriteStreamError (WebExceptionStatus.SendFailure, exc);
1415 internal void SetResponseError (WebExceptionStatus status, Exception e, string where)
1420 string msg = String.Format ("Error getting response stream ({0}): {1}", where, status);
1421 WebAsyncResult r = asyncRead;
1426 if (e is WebException) {
1427 wexc = (WebException) e;
1429 wexc = new WebException (msg, e, status, null);
1432 if (!r.IsCompleted) {
1433 r.SetCompleted (false, wexc);
1435 } else if (r == asyncWrite) {
1438 haveResponse = true;
1442 haveResponse = true;
1448 void CheckSendError (WebConnectionData data)
1450 // Got here, but no one called GetResponse
1451 int status = data.StatusCode;
1452 if (status < 400 || status == 401 || status == 407)
1455 if (writeStream != null && asyncRead == null && !writeStream.CompleteRequestWritten) {
1456 // The request has not been completely sent and we got here!
1457 // We should probably just close and cause an error in any case,
1458 saved_exc = new WebException (data.StatusDescription, null, WebExceptionStatus.ProtocolError, webResponse);
1459 if (allowBuffering || sendChunked || writeStream.totalWritten >= contentLength) {
1460 webResponse.ReadAll ();
1462 writeStream.IgnoreIOErrors = true;
1467 bool HandleNtlmAuth (WebAsyncResult r)
1469 bool isProxy = webResponse.StatusCode == HttpStatusCode.ProxyAuthenticationRequired;
1470 if ((isProxy ? proxy_auth_state.NtlmAuthState : auth_state.NtlmAuthState) == NtlmAuthState.None)
1473 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1475 WebConnection cnc = wce.Connection;
1476 cnc.PriorityRequest = this;
1477 ICredentials creds = (!isProxy || proxy == null) ? credentials : proxy.Credentials;
1478 if (creds != null) {
1479 cnc.NtlmCredential = creds.GetCredential (requestUri, "NTLM");
1480 cnc.UnsafeAuthenticatedConnectionSharing = unsafe_auth_blah;
1484 finished_reading = false;
1485 haveResponse = false;
1486 webResponse.ReadAll ();
1491 internal void SetResponseData (WebConnectionData data)
1495 if (data.stream != null)
1496 data.stream.Close ();
1500 WebException wexc = null;
1502 webResponse = new HttpWebResponse (actualUri, method, data, cookieContainer);
1503 } catch (Exception e) {
1504 wexc = new WebException (e.Message, e, WebExceptionStatus.ProtocolError, null);
1505 if (data.stream != null)
1506 data.stream.Close ();
1509 if (wexc == null && (method == "POST" || method == "PUT")) {
1510 CheckSendError (data);
1511 if (saved_exc != null)
1512 wexc = (WebException) saved_exc;
1515 WebAsyncResult r = asyncRead;
1517 bool forced = false;
1518 if (r == null && webResponse != null) {
1519 // This is a forced completion (302, 204)...
1521 r = new WebAsyncResult (null, null);
1522 r.SetCompleted (false, webResponse);
1527 haveResponse = true;
1529 r.SetCompleted (false, wexc);
1534 bool isProxy = ProxyQuery && proxy != null && !proxy.IsBypassed (actualUri);
1538 redirected = CheckFinalStatus (r);
1540 if ((isProxy ? proxy_auth_state.IsNtlmAuthenticated : auth_state.IsNtlmAuthenticated) &&
1541 webResponse != null && (int)webResponse.StatusCode < 400) {
1542 WebConnectionStream wce = webResponse.GetResponseStream () as WebConnectionStream;
1544 WebConnection cnc = wce.Connection;
1545 cnc.NtlmAuthenticated = true;
1549 // clear internal buffer so that it does not
1550 // hold possible big buffer (bug #397627)
1551 if (writeStream != null)
1552 writeStream.KillBuffer ();
1554 haveResponse = true;
1555 r.SetCompleted (false, webResponse);
1559 sendChunked = false;
1560 webHeaders.RemoveInternal ("Transfer-Encoding");
1563 if (webResponse != null) {
1564 if (HandleNtlmAuth (r))
1566 webResponse.Close ();
1568 finished_reading = false;
1569 haveResponse = false;
1572 servicePoint = GetServicePoint ();
1573 abortHandler = servicePoint.SendRequest (this, connectionGroup);
1575 } catch (WebException wexc2) {
1578 haveResponse = true;
1580 r.SetCompleted (false, wexc2);
1583 } catch (Exception ex) {
1584 wexc = new WebException (ex.Message, ex, WebExceptionStatus.ProtocolError, null);
1587 haveResponse = true;
1589 r.SetCompleted (false, wexc);
1597 struct AuthorizationState
1599 readonly HttpWebRequest request;
1600 readonly bool isProxy;
1602 NtlmAuthState ntlm_auth_state;
1604 public bool IsCompleted {
1605 get { return isCompleted; }
1608 public NtlmAuthState NtlmAuthState {
1609 get { return ntlm_auth_state; }
1612 public bool IsNtlmAuthenticated {
1613 get { return isCompleted && ntlm_auth_state != NtlmAuthState.None; }
1616 public AuthorizationState (HttpWebRequest request, bool isProxy)
1618 this.request = request;
1619 this.isProxy = isProxy;
1620 isCompleted = false;
1621 ntlm_auth_state = NtlmAuthState.None;
1624 public bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1626 isCompleted = false;
1627 if (code == HttpStatusCode.Unauthorized && request.credentials == null)
1630 // FIXME: This should never happen!
1631 if (isProxy != (code == HttpStatusCode.ProxyAuthenticationRequired))
1634 if (isProxy && (request.proxy == null || request.proxy.Credentials == null))
1637 string [] authHeaders = response.Headers.GetValues (isProxy ? "Proxy-Authenticate" : "WWW-Authenticate");
1638 if (authHeaders == null || authHeaders.Length == 0)
1641 ICredentials creds = (!isProxy) ? request.credentials : request.proxy.Credentials;
1642 Authorization auth = null;
1643 foreach (string authHeader in authHeaders) {
1644 auth = AuthenticationManager.Authenticate (authHeader, request, creds);
1650 request.webHeaders [isProxy ? "Proxy-Authorization" : "Authorization"] = auth.Message;
1651 isCompleted = auth.Complete;
1652 bool is_ntlm = (auth.ModuleAuthenticationType == "NTLM");
1654 ntlm_auth_state = (NtlmAuthState)((int) ntlm_auth_state + 1);
1658 public void Reset ()
1660 isCompleted = false;
1661 ntlm_auth_state = NtlmAuthState.None;
1662 request.webHeaders.RemoveInternal (isProxy ? "Proxy-Authorization" : "Authorization");
1665 public override string ToString ()
1667 return string.Format ("{0}AuthState [{1}:{2}]", isProxy ? "Proxy" : "", isCompleted, ntlm_auth_state);
1671 bool CheckAuthorization (WebResponse response, HttpStatusCode code)
1673 bool isProxy = code == HttpStatusCode.ProxyAuthenticationRequired;
1674 return isProxy ? proxy_auth_state.CheckAuthorization (response, code) : auth_state.CheckAuthorization (response, code);
1677 // Returns true if redirected
1678 bool CheckFinalStatus (WebAsyncResult result)
1680 if (result.GotException) {
1682 throw result.Exception;
1685 Exception throwMe = result.Exception;
1687 HttpWebResponse resp = result.Response;
1688 WebExceptionStatus protoError = WebExceptionStatus.ProtocolError;
1689 HttpStatusCode code = 0;
1690 if (throwMe == null && webResponse != null) {
1691 code = webResponse.StatusCode;
1692 if ((!auth_state.IsCompleted && code == HttpStatusCode.Unauthorized && credentials != null) ||
1693 (ProxyQuery && !proxy_auth_state.IsCompleted && code == HttpStatusCode.ProxyAuthenticationRequired)) {
1694 if (!usedPreAuth && CheckAuthorization (webResponse, code)) {
1695 // Keep the written body, so it can be rewritten in the retry
1696 if (MethodWithBuffer) {
1697 if (AllowWriteStreamBuffering) {
1698 if (writeStream.WriteBufferLength > 0) {
1699 bodyBuffer = writeStream.WriteBuffer;
1700 bodyBufferLength = writeStream.WriteBufferLength;
1707 // Buffering is not allowed but we have alternative way to get same content (we
1708 // need to resent it due to NTLM Authentication).
1710 if (ResendContentFactory != null) {
1711 using (var ms = new MemoryStream ()) {
1712 ResendContentFactory (ms);
1713 bodyBuffer = ms.ToArray ();
1714 bodyBufferLength = bodyBuffer.Length;
1718 } else if (method != "PUT" && method != "POST") {
1726 writeStream.InternalClose ();
1728 webResponse.Close ();
1732 throw new WebException ("This request requires buffering " +
1733 "of data for authentication or " +
1734 "redirection to be sucessful.");
1739 if ((int) code >= 400) {
1740 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1741 (int) code, webResponse.StatusDescription);
1742 throwMe = new WebException (err, null, protoError, webResponse);
1743 webResponse.ReadAll ();
1744 } else if ((int) code == 304 && allowAutoRedirect) {
1745 string err = String.Format ("The remote server returned an error: ({0}) {1}.",
1746 (int) code, webResponse.StatusDescription);
1747 throwMe = new WebException (err, null, protoError, webResponse);
1748 } else if ((int) code >= 300 && allowAutoRedirect && redirects >= maxAutoRedirect) {
1749 throwMe = new WebException ("Max. redirections exceeded.", null,
1750 protoError, webResponse);
1751 webResponse.ReadAll ();
1756 if (throwMe == null) {
1759 if (allowAutoRedirect && c >= 300) {
1760 b = Redirect (result, code, webResponse);
1761 if (InternalAllowBuffering && writeStream.WriteBufferLength > 0) {
1762 bodyBuffer = writeStream.WriteBuffer;
1763 bodyBufferLength = writeStream.WriteBufferLength;
1765 if (b && !unsafe_auth_blah) {
1766 auth_state.Reset ();
1767 proxy_auth_state.Reset ();
1771 if (resp != null && c >= 300 && c != 304)
1780 if (writeStream != null) {
1781 writeStream.InternalClose ();
1790 internal bool ReuseConnection {
1795 internal WebConnection StoredConnection;
1797 #region referencesource
1798 internal static StringBuilder GenerateConnectionGroup(string connectionGroupName, bool unsafeConnectionGroup, bool isInternalGroup)
1800 StringBuilder connectionLine = new StringBuilder(connectionGroupName);
1802 connectionLine.Append(unsafeConnectionGroup ? "U>" : "S>");
1804 if (isInternalGroup)
1806 connectionLine.Append("I>");
1809 return connectionLine;