ServicePointManager.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. //
  2. // System.Net.ServicePointManager
  3. //
  4. // Author:
  5. // Lawrence Pit ([email protected])
  6. //
  7. //
  8. // Permission is hereby granted, free of charge, to any person obtaining
  9. // a copy of this software and associated documentation files (the
  10. // "Software"), to deal in the Software without restriction, including
  11. // without limitation the rights to use, copy, modify, merge, publish,
  12. // distribute, sublicense, and/or sell copies of the Software, and to
  13. // permit persons to whom the Software is furnished to do so, subject to
  14. // the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be
  17. // included in all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  20. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  21. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  22. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  23. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  24. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  25. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  26. //
  27. using System;
  28. using System.Collections;
  29. using System.Collections.Specialized;
  30. using System.Configuration;
  31. using System.Net.Configuration;
  32. using System.Security.Cryptography.X509Certificates;
  33. #if NET_2_0
  34. using System.Net.Security;
  35. #endif
  36. //
  37. // notes:
  38. // A service point manager manages service points (duh!).
  39. // A service point maintains a list of connections (per scheme + authority).
  40. // According to HttpWebRequest.ConnectionGroupName each connection group
  41. // creates additional connections. therefor, a service point has a hashtable
  42. // of connection groups where each value is a list of connections.
  43. //
  44. // when we need to make an HttpWebRequest, we need to do the following:
  45. // 1. find service point, given Uri and Proxy
  46. // 2. find connection group, given service point and group name
  47. // 3. find free connection in connection group, or create one (if ok due to limits)
  48. // 4. lease connection
  49. // 5. execute request
  50. // 6. when finished, return connection
  51. //
  52. namespace System.Net
  53. {
  54. public class ServicePointManager
  55. {
  56. class SPKey {
  57. Uri uri; // schema/host/port
  58. bool use_connect;
  59. public SPKey (Uri uri, bool use_connect) {
  60. this.uri = uri;
  61. this.use_connect = use_connect;
  62. }
  63. public Uri Uri {
  64. get { return uri; }
  65. }
  66. public bool UseConnect {
  67. get { return use_connect; }
  68. }
  69. public override int GetHashCode () {
  70. return uri.GetHashCode () + ((use_connect) ? 1 : 0);
  71. }
  72. public override bool Equals (object obj) {
  73. SPKey other = obj as SPKey;
  74. if (obj == null) {
  75. return false;
  76. }
  77. return (uri.Equals (other.uri) && other.use_connect == use_connect);
  78. }
  79. }
  80. private static HybridDictionary servicePoints = new HybridDictionary ();
  81. // Static properties
  82. private static ICertificatePolicy policy = new DefaultCertificatePolicy ();
  83. private static int defaultConnectionLimit = DefaultPersistentConnectionLimit;
  84. private static int maxServicePointIdleTime = 900000; // 15 minutes
  85. private static int maxServicePoints = 0;
  86. private static bool _checkCRL = false;
  87. private static SecurityProtocolType _securityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
  88. #if NET_1_1
  89. #if TARGET_JVM
  90. static bool expectContinue = false;
  91. #else
  92. static bool expectContinue = true;
  93. #endif
  94. static bool useNagle;
  95. #endif
  96. #if NET_2_0
  97. static RemoteCertificateValidationCallback server_cert_cb;
  98. #endif
  99. // Fields
  100. public const int DefaultNonPersistentConnectionLimit = 4;
  101. public const int DefaultPersistentConnectionLimit = 2;
  102. #if !MONOTOUCH
  103. const string configKey = "system.net/connectionManagement";
  104. static ConnectionManagementData manager;
  105. #endif
  106. static ServicePointManager ()
  107. {
  108. #if !MONOTOUCH
  109. #if NET_2_0 && CONFIGURATION_DEP
  110. object cfg = ConfigurationManager.GetSection (configKey);
  111. ConnectionManagementSection s = cfg as ConnectionManagementSection;
  112. if (s != null) {
  113. manager = new ConnectionManagementData (null);
  114. foreach (ConnectionManagementElement e in s.ConnectionManagement)
  115. manager.Add (e.Address, e.MaxConnection);
  116. defaultConnectionLimit = (int) manager.GetMaxConnections ("*");
  117. return;
  118. }
  119. #endif
  120. manager = (ConnectionManagementData) ConfigurationSettings.GetConfig (configKey);
  121. if (manager != null) {
  122. defaultConnectionLimit = (int) manager.GetMaxConnections ("*");
  123. }
  124. #endif
  125. }
  126. // Constructors
  127. private ServicePointManager ()
  128. {
  129. }
  130. // Properties
  131. #if NET_2_0
  132. [Obsolete ("Use ServerCertificateValidationCallback instead",
  133. false)]
  134. #endif
  135. public static ICertificatePolicy CertificatePolicy {
  136. get { return policy; }
  137. set { policy = value; }
  138. }
  139. #if NET_1_0
  140. // we need it for SslClientStream
  141. internal
  142. #else
  143. [MonoTODO("CRL checks not implemented")]
  144. public
  145. #endif
  146. static bool CheckCertificateRevocationList {
  147. get { return _checkCRL; }
  148. set { _checkCRL = false; } // TODO - don't yet accept true
  149. }
  150. public static int DefaultConnectionLimit {
  151. get { return defaultConnectionLimit; }
  152. set {
  153. if (value <= 0)
  154. throw new ArgumentOutOfRangeException ("value");
  155. defaultConnectionLimit = value;
  156. }
  157. }
  158. #if NET_2_0
  159. static Exception GetMustImplement ()
  160. {
  161. return new NotImplementedException ();
  162. }
  163. [MonoTODO]
  164. public static int DnsRefreshTimeout
  165. {
  166. get {
  167. throw GetMustImplement ();
  168. }
  169. set {
  170. throw GetMustImplement ();
  171. }
  172. }
  173. [MonoTODO]
  174. public static bool EnableDnsRoundRobin
  175. {
  176. get {
  177. throw GetMustImplement ();
  178. }
  179. set {
  180. throw GetMustImplement ();
  181. }
  182. }
  183. #endif
  184. public static int MaxServicePointIdleTime {
  185. get {
  186. return maxServicePointIdleTime;
  187. }
  188. set {
  189. if (value < -2 || value > Int32.MaxValue)
  190. throw new ArgumentOutOfRangeException ("value");
  191. maxServicePointIdleTime = value;
  192. }
  193. }
  194. public static int MaxServicePoints {
  195. get {
  196. return maxServicePoints;
  197. }
  198. set {
  199. if (value < 0)
  200. throw new ArgumentException ("value");
  201. maxServicePoints = value;
  202. RecycleServicePoints ();
  203. }
  204. }
  205. #if NET_1_0
  206. // we need it for SslClientStream
  207. internal
  208. #else
  209. public
  210. #endif
  211. static SecurityProtocolType SecurityProtocol {
  212. get { return _securityProtocol; }
  213. set { _securityProtocol = value; }
  214. }
  215. #if NET_2_0
  216. public static RemoteCertificateValidationCallback ServerCertificateValidationCallback
  217. {
  218. get {
  219. return server_cert_cb;
  220. }
  221. set {
  222. server_cert_cb = value;
  223. }
  224. }
  225. #endif
  226. #if NET_1_1
  227. public static bool Expect100Continue {
  228. get { return expectContinue; }
  229. set { expectContinue = value; }
  230. }
  231. public static bool UseNagleAlgorithm {
  232. get { return useNagle; }
  233. set { useNagle = value; }
  234. }
  235. #endif
  236. // Methods
  237. public static ServicePoint FindServicePoint (Uri address)
  238. {
  239. return FindServicePoint (address, GlobalProxySelection.Select);
  240. }
  241. public static ServicePoint FindServicePoint (string uriString, IWebProxy proxy)
  242. {
  243. return FindServicePoint (new Uri(uriString), proxy);
  244. }
  245. public static ServicePoint FindServicePoint (Uri address, IWebProxy proxy)
  246. {
  247. if (address == null)
  248. throw new ArgumentNullException ("address");
  249. RecycleServicePoints ();
  250. bool usesProxy = false;
  251. bool useConnect = false;
  252. if (proxy != null && !proxy.IsBypassed(address)) {
  253. usesProxy = true;
  254. bool isSecure = address.Scheme == "https";
  255. address = proxy.GetProxy (address);
  256. if (address.Scheme != "http" && !isSecure)
  257. throw new NotSupportedException ("Proxy scheme not supported.");
  258. if (isSecure && address.Scheme == "http")
  259. useConnect = true;
  260. }
  261. address = new Uri (address.Scheme + "://" + address.Authority);
  262. ServicePoint sp = null;
  263. lock (servicePoints) {
  264. SPKey key = new SPKey (address, useConnect);
  265. sp = servicePoints [key] as ServicePoint;
  266. if (sp != null)
  267. return sp;
  268. if (maxServicePoints > 0 && servicePoints.Count >= maxServicePoints)
  269. throw new InvalidOperationException ("maximum number of service points reached");
  270. string addr = address.ToString ();
  271. #if MONOTOUCH
  272. int limit = defaultConnectionLimit;
  273. #else
  274. int limit = (int) manager.GetMaxConnections (addr);
  275. #endif
  276. sp = new ServicePoint (address, limit, maxServicePointIdleTime);
  277. #if NET_1_1
  278. sp.Expect100Continue = expectContinue;
  279. sp.UseNagleAlgorithm = useNagle;
  280. #endif
  281. sp.UsesProxy = usesProxy;
  282. sp.UseConnect = useConnect;
  283. servicePoints.Add (key, sp);
  284. }
  285. return sp;
  286. }
  287. // Internal Methods
  288. internal static void RecycleServicePoints ()
  289. {
  290. ArrayList toRemove = new ArrayList ();
  291. lock (servicePoints) {
  292. IDictionaryEnumerator e = servicePoints.GetEnumerator ();
  293. while (e.MoveNext ()) {
  294. ServicePoint sp = (ServicePoint) e.Value;
  295. if (sp.AvailableForRecycling) {
  296. toRemove.Add (e.Key);
  297. }
  298. }
  299. for (int i = 0; i < toRemove.Count; i++)
  300. servicePoints.Remove (toRemove [i]);
  301. if (maxServicePoints == 0 || servicePoints.Count <= maxServicePoints)
  302. return;
  303. // get rid of the ones with the longest idle time
  304. SortedList list = new SortedList (servicePoints.Count);
  305. e = servicePoints.GetEnumerator ();
  306. while (e.MoveNext ()) {
  307. ServicePoint sp = (ServicePoint) e.Value;
  308. if (sp.CurrentConnections == 0) {
  309. while (list.ContainsKey (sp.IdleSince))
  310. sp.IdleSince = sp.IdleSince.AddMilliseconds (1);
  311. list.Add (sp.IdleSince, sp.Address);
  312. }
  313. }
  314. for (int i = 0; i < list.Count && servicePoints.Count > maxServicePoints; i++)
  315. servicePoints.Remove (list.GetByIndex (i));
  316. }
  317. }
  318. }
  319. }