ServicePointManager.cs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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. private static HybridDictionary servicePoints = new HybridDictionary ();
  57. // Static properties
  58. private static ICertificatePolicy policy = new DefaultCertificatePolicy ();
  59. private static int defaultConnectionLimit = DefaultPersistentConnectionLimit;
  60. private static int maxServicePointIdleTime = 900000; // 15 minutes
  61. private static int maxServicePoints = 0;
  62. private static bool _checkCRL = false;
  63. private static SecurityProtocolType _securityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
  64. #if NET_1_1
  65. #if TARGET_JVM
  66. static bool expectContinue = false;
  67. #else
  68. static bool expectContinue = true;
  69. #endif
  70. static bool useNagle;
  71. #endif
  72. // Fields
  73. public const int DefaultNonPersistentConnectionLimit = 4;
  74. public const int DefaultPersistentConnectionLimit = 2;
  75. const string configKey = "system.net/connectionManagement";
  76. static ConnectionManagementData manager;
  77. static ServicePointManager ()
  78. {
  79. #if NET_2_0 && CONFIGURATION_DEP
  80. object cfg = ConfigurationManager.GetSection (configKey);
  81. ConnectionManagementSection s = cfg as ConnectionManagementSection;
  82. if (s != null) {
  83. manager = new ConnectionManagementData (null);
  84. foreach (ConnectionManagementElement e in s.ConnectionManagement)
  85. manager.Add (e.Address, e.MaxConnection);
  86. return;
  87. }
  88. #endif
  89. manager = (ConnectionManagementData) ConfigurationSettings.GetConfig (configKey);
  90. }
  91. // Constructors
  92. private ServicePointManager ()
  93. {
  94. }
  95. // Properties
  96. #if NET_2_0
  97. [Obsolete ("Use ServerCertificateValidationCallback instead",
  98. false)]
  99. #endif
  100. public static ICertificatePolicy CertificatePolicy {
  101. get { return policy; }
  102. set { policy = value; }
  103. }
  104. #if NET_1_0
  105. // we need it for SslClientStream
  106. internal
  107. #else
  108. [MonoTODO("CRL checks not implemented")]
  109. public
  110. #endif
  111. static bool CheckCertificateRevocationList {
  112. get { return _checkCRL; }
  113. set { _checkCRL = false; } // TODO - don't yet accept true
  114. }
  115. public static int DefaultConnectionLimit {
  116. get { return defaultConnectionLimit; }
  117. set {
  118. if (value <= 0)
  119. throw new ArgumentOutOfRangeException ("value");
  120. defaultConnectionLimit = value;
  121. }
  122. }
  123. #if NET_2_0
  124. static Exception GetMustImplement ()
  125. {
  126. return new NotImplementedException ();
  127. }
  128. [MonoTODO]
  129. public static int DnsRefreshTimeout
  130. {
  131. get {
  132. throw GetMustImplement ();
  133. }
  134. set {
  135. throw GetMustImplement ();
  136. }
  137. }
  138. [MonoTODO]
  139. public static bool EnableDnsRoundRobin
  140. {
  141. get {
  142. throw GetMustImplement ();
  143. }
  144. set {
  145. throw GetMustImplement ();
  146. }
  147. }
  148. #endif
  149. public static int MaxServicePointIdleTime {
  150. get {
  151. return maxServicePointIdleTime;
  152. }
  153. set {
  154. if (value < -2 || value > Int32.MaxValue)
  155. throw new ArgumentOutOfRangeException ("value");
  156. maxServicePointIdleTime = value;
  157. }
  158. }
  159. public static int MaxServicePoints {
  160. get {
  161. return maxServicePoints;
  162. }
  163. set {
  164. if (value < 0)
  165. throw new ArgumentException ("value");
  166. maxServicePoints = value;
  167. RecycleServicePoints ();
  168. }
  169. }
  170. #if NET_1_0
  171. // we need it for SslClientStream
  172. internal
  173. #else
  174. public
  175. #endif
  176. static SecurityProtocolType SecurityProtocol {
  177. get { return _securityProtocol; }
  178. set { _securityProtocol = value; }
  179. }
  180. #if NET_2_0 && SECURITY_DEP
  181. [MonoTODO]
  182. public static RemoteCertificateValidationCallback ServerCertificateValidationCallback
  183. {
  184. get {
  185. throw GetMustImplement ();
  186. }
  187. set {
  188. throw GetMustImplement ();
  189. }
  190. }
  191. #endif
  192. #if NET_1_1
  193. public static bool Expect100Continue {
  194. get { return expectContinue; }
  195. set { expectContinue = value; }
  196. }
  197. public static bool UseNagleAlgorithm {
  198. get { return useNagle; }
  199. set { useNagle = value; }
  200. }
  201. #endif
  202. // Methods
  203. public static ServicePoint FindServicePoint (Uri address)
  204. {
  205. return FindServicePoint (address, GlobalProxySelection.Select);
  206. }
  207. public static ServicePoint FindServicePoint (string uriString, IWebProxy proxy)
  208. {
  209. return FindServicePoint (new Uri(uriString), proxy);
  210. }
  211. public static ServicePoint FindServicePoint (Uri address, IWebProxy proxy)
  212. {
  213. if (address == null)
  214. throw new ArgumentNullException ("address");
  215. RecycleServicePoints ();
  216. bool usesProxy = false;
  217. bool useConnect = false;
  218. if (proxy != null && !proxy.IsBypassed(address)) {
  219. usesProxy = true;
  220. bool isSecure = address.Scheme == "https";
  221. address = proxy.GetProxy (address);
  222. if (address.Scheme != "http" && !isSecure)
  223. throw new NotSupportedException ("Proxy scheme not supported.");
  224. if (isSecure && address.Scheme == "http")
  225. useConnect = true;
  226. }
  227. address = new Uri (address.Scheme + "://" + address.Authority);
  228. ServicePoint sp = null;
  229. lock (servicePoints) {
  230. int key = address.GetHashCode () + (int) ((useConnect) ? 1 : 0);
  231. sp = servicePoints [key] as ServicePoint;
  232. if (sp != null)
  233. return sp;
  234. if (maxServicePoints > 0 && servicePoints.Count >= maxServicePoints)
  235. throw new InvalidOperationException ("maximum number of service points reached");
  236. string addr = address.ToString ();
  237. int limit = (int) manager.GetMaxConnections (addr);
  238. sp = new ServicePoint (address, limit, maxServicePointIdleTime);
  239. #if NET_1_1
  240. sp.Expect100Continue = expectContinue;
  241. sp.UseNagleAlgorithm = useNagle;
  242. #endif
  243. sp.UsesProxy = usesProxy;
  244. sp.UseConnect = useConnect;
  245. servicePoints.Add (key, sp);
  246. }
  247. return sp;
  248. }
  249. // Internal Methods
  250. internal static void RecycleServicePoints ()
  251. {
  252. ArrayList toRemove = new ArrayList ();
  253. lock (servicePoints) {
  254. IDictionaryEnumerator e = servicePoints.GetEnumerator ();
  255. while (e.MoveNext ()) {
  256. ServicePoint sp = (ServicePoint) e.Value;
  257. if (sp.AvailableForRecycling) {
  258. toRemove.Add (e.Key);
  259. }
  260. }
  261. for (int i = 0; i < toRemove.Count; i++)
  262. servicePoints.Remove (toRemove [i]);
  263. if (maxServicePoints == 0 || servicePoints.Count <= maxServicePoints)
  264. return;
  265. // get rid of the ones with the longest idle time
  266. SortedList list = new SortedList (servicePoints.Count);
  267. e = servicePoints.GetEnumerator ();
  268. while (e.MoveNext ()) {
  269. ServicePoint sp = (ServicePoint) e.Value;
  270. if (sp.CurrentConnections == 0) {
  271. while (list.ContainsKey (sp.IdleSince))
  272. sp.IdleSince = sp.IdleSince.AddMilliseconds (1);
  273. list.Add (sp.IdleSince, sp.Address);
  274. }
  275. }
  276. for (int i = 0; i < list.Count && servicePoints.Count > maxServicePoints; i++)
  277. servicePoints.Remove (list.GetByIndex (i));
  278. }
  279. }
  280. }
  281. }