The Labs \ Source Viewer \ SSCLI \ System.Net \ ConnectSocketState

  1. //------------------------------------------------------------------------------
  2. // <copyright file="ServicePoint.cs" company="Microsoft">
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. // </copyright>
  14. //------------------------------------------------------------------------------
  15. namespace System.Net
  16. {
  17.     using System.Net.Sockets;
  18.     using System.Net.NetworkInformation;
  19.     using System.Collections;
  20.     using System.IO;
  21.     using System.Threading;
  22.     using System.Security.Permissions;
  23.     using System.Security.Cryptography.X509Certificates;
  24.     using System.ComponentModel;
  25.     using System.Runtime.InteropServices;
  26.     using System.Net.Security;
  27.     using System.Globalization;
  28.    
  29.     public delegate IPEndPoint BindIPEndPoint(ServicePoint servicePoint, IPEndPoint remoteEndPoint, int retryCount);
  30.    
  31.    
  32.     // ServicePoints are never created directly but always handed out by the
  33.     // ServicePointManager. The ServicePointManager and the ServicePoints must be in
  34.     // the same name space so that the ServicePointManager can call the
  35.     // internal constructor
  36.    
  37.     /// <devdoc>
  38.     /// <para>Provides connection management for other classes.</para>
  39.     /// </devdoc>
  40.     public class ServicePoint
  41.     {
  42.        
  43.         internal const int LoopbackConnectionLimit = Int32.MaxValue;
  44.        
  45.         private int m_ConnectionLeaseTimeout;
  46.         private TimerThread.Queue m_ConnectionLeaseTimerQueue;
  47.         private bool m_ProxyServicePoint;
  48.         private bool m_UserChangedLimit;
  49.         private bool m_UseNagleAlgorithm;
  50.         private TriState m_HostLoopbackGuess;
  51.         private int m_ReceiveBufferSize;
  52.         private bool m_Expect100Continue;
  53.         private bool m_Understands100Continue;
  54.         private HttpBehaviour m_HttpBehaviour;
  55.         private string m_LookupString;
  56.         private int m_ConnectionLimit;
  57.         private Hashtable m_ConnectionGroupList;
  58.         private Uri m_Address;
  59.         private string m_Host;
  60.         private int m_Port;
  61.         private TimerThread.Queue m_IdlingQueue;
  62.         private TimerThread.Timer m_ExpiringTimer;
  63.         private DateTime m_IdleSince;
  64.         private string m_ConnectionName;
  65.         private int m_CurrentConnections;
  66.         private bool m_HostMode;
  67.         private BindIPEndPoint m_BindIPEndPointDelegate = null;
  68.        
  69.         private static readonly AsyncCallback m_ConnectCallbackDelegate = new AsyncCallback(ConnectSocketCallback);
  70.        
  71.        
  72.         internal string LookupString {
  73.             get { return m_LookupString; }
  74.         }
  75.        
  76.         internal string Hostname {
  77.             get { return m_HostName; }
  78.         }
  79.        
  80.         public BindIPEndPoint BindIPEndPointDelegate {
  81.             get { return m_BindIPEndPointDelegate; }
  82.             set {
  83.                 ExceptionHelper.InfrastructurePermission.Demand();
  84.                 m_BindIPEndPointDelegate = value;
  85.             }
  86.         }
  87.        
  88.         //
  89.         // constructors
  90.         //
  91.         internal ServicePoint(Uri address, TimerThread.Queue defaultIdlingQueue, int defaultConnectionLimit, string lookupString, bool userChangedLimit, bool proxyServicePoint)
  92.         {
  93.             GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::.ctor(" + lookupString + ")");
  94.             m_ProxyServicePoint = proxyServicePoint;
  95.             m_Address = address;
  96.             m_ConnectionName = address.Scheme;
  97.             m_Host = address.DnsSafeHost;
  98.             m_Port = address.Port;
  99.             m_IdlingQueue = defaultIdlingQueue;
  100.             m_ConnectionLimit = defaultConnectionLimit;
  101.             m_HostLoopbackGuess = TriState.Unspecified;
  102.             m_LookupString = lookupString;
  103.             m_UserChangedLimit = userChangedLimit;
  104.             m_UseNagleAlgorithm = ServicePointManager.UseNagleAlgorithm;
  105.             m_Expect100Continue = ServicePointManager.Expect100Continue;
  106.             m_ConnectionGroupList = new Hashtable(10);
  107.             m_ConnectionLeaseTimeout = System.Threading.Timeout.Infinite;
  108.             m_ReceiveBufferSize = -1;
  109.            
  110.             // it would be safer to make sure the server is 1.1
  111.             // but assume it is at the beginning, and update it later
  112.             m_Understands100Continue = true;
  113.             m_HttpBehaviour = HttpBehaviour.Unknown;
  114.            
  115.             // upon creation, the service point should be idle, by default
  116.             m_IdleSince = DateTime.Now;
  117.             m_ExpiringTimer = m_IdlingQueue.CreateTimer(ServicePointManager.IdleServicePointTimeoutDelegate, this);
  118.         }
  119.        
  120.        
  121.        
  122.         internal ServicePoint(string host, int port, TimerThread.Queue defaultIdlingQueue, int defaultConnectionLimit, string lookupString, bool userChangedLimit, bool proxyServicePoint)
  123.         {
  124.             GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::.ctor(" + lookupString + ")");
  125.             m_ProxyServicePoint = proxyServicePoint;
  126.             m_ConnectionName = "ByHost:" + host + ":" + port.ToString(CultureInfo.InvariantCulture);
  127.             m_IdlingQueue = defaultIdlingQueue;
  128.             m_ConnectionLimit = defaultConnectionLimit;
  129.             m_HostLoopbackGuess = TriState.Unspecified;
  130.             m_LookupString = lookupString;
  131.             m_UserChangedLimit = userChangedLimit;
  132.             m_ConnectionGroupList = new Hashtable(10);
  133.             m_ConnectionLeaseTimeout = System.Threading.Timeout.Infinite;
  134.             m_ReceiveBufferSize = -1;
  135.             m_Host = host;
  136.             m_Port = port;
  137.             m_HostMode = true;
  138.            
  139.             // upon creation, the service point should be idle, by default
  140.             m_IdleSince = DateTime.Now;
  141.             m_ExpiringTimer = m_IdlingQueue.CreateTimer(ServicePointManager.IdleServicePointTimeoutDelegate, this);
  142.         }
  143.        
  144.        
  145.        
  146.         // methods
  147.        
  148. /*++
  149.             FindConnectionGroup      -
  150.             Searches for the a Group object that actually holds the connections
  151.               that we want to peak at.
  152.             Input:
  153.                     request                - Request that's being submitted.
  154.                     connName                - Connection Name if needed
  155.             Returns:
  156.                     ConnectionGroup
  157.         --*/       
  158.        
  159.         private ConnectionGroup FindConnectionGroup(string connName, bool dontCreate)
  160.         {
  161.             string lookupStr = ConnectionGroup.MakeQueryStr(connName);
  162.            
  163.             GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() lookupStr:[" + ValidationHelper.ToString(connName) + "]");
  164.            
  165.             ConnectionGroup entry = m_ConnectionGroupList[lookupStr] as ConnectionGroup;
  166.            
  167.             if (entry == null && !dontCreate) {
  168.                 entry = new ConnectionGroup(this, connName);
  169.                 GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() adding ConnectionGroup lookupStr:[" + lookupStr + "]");
  170.                
  171.                 m_ConnectionGroupList[lookupStr] = entry;
  172.             }
  173.             else {
  174.                 GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() using existing ConnectionGroup");
  175.             }
  176.             GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::FindConnectionGroup() returning ConnectionGroup:" + ValidationHelper.ToString(entry) + (entry != null ? " ConnLimit:" + entry.ConnectionLimit.ToString() : ""));
  177.             return entry;
  178.         }
  179.        
  180.        
  181.         /// <devdoc>
  182.         /// <para>
  183.         /// Tempory for getting a new Connection for FTP client, for the time being
  184.         /// </para>
  185.         /// </devdoc>
  186.         internal Socket GetConnection(PooledStream PooledStream, object owner, bool async, out IPAddress address, ref Socket abortSocket, ref Socket abortSocket6, int timeout)
  187.         {
  188.             Socket socket = null;
  189.             Socket socket6 = null;
  190.             Socket finalSocket = null;
  191.             Exception innerException = null;
  192.             WebExceptionStatus ws = WebExceptionStatus.ConnectFailure;
  193.             address = null;
  194.            
  195.             //
  196.             // if we will not create a tunnel through a proxy then create
  197.             // and connect the socket we will use for the connection
  198.             //
  199.            
  200.             //
  201.             // IPv6 Support: If IPv6 is enabled, then we create a second socket that ServicePoint
  202.             // will use if it wants to connect via IPv6.
  203.             //
  204.             socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  205.            
  206.             if (Socket.OSSupportsIPv6) {
  207.                 socket6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
  208.             }
  209.            
  210.             abortSocket = socket;
  211.             abortSocket6 = socket6;
  212.            
  213.             //
  214.            
  215.             ConnectSocketState state = null;
  216.            
  217.             if (async) {
  218.                 state = new ConnectSocketState(this, PooledStream, owner, socket, socket6);
  219.             }
  220.            
  221.             ws = ConnectSocket(socket, socket6, ref finalSocket, ref address, state, timeout, out innerException);
  222.            
  223.             if (ws == WebExceptionStatus.Pending) {
  224.                 return null;
  225.             }
  226.            
  227.             if (ws != WebExceptionStatus.Success) {
  228.                     /* no response */                throw new WebException(NetRes.GetWebStatusString(ws), ws == WebExceptionStatus.ProxyNameResolutionFailure || ws == WebExceptionStatus.NameResolutionFailure ? Host : null, innerException, ws, null, WebExceptionInternalStatus.ServicePointFatal);
  229.             }
  230.            
  231.             //
  232.             // There should be no means for socket to be null at this
  233.             // point, but the damage is greater if we just carry on
  234.             // without ensuring that it's good.
  235.             //
  236.             if (finalSocket == null) {
  237.                 throw new IOException(SR.GetString(SR.net_io_transportfailure));
  238.             }
  239.            
  240.             CompleteGetConnection(socket, socket6, finalSocket, address);
  241.             return finalSocket;
  242.         }
  243.        
  244.         /// <devdoc>
  245.         /// <para>
  246.         /// Complete the GetConnection(...) call, the function was divided for async completion
  247.         /// </para>
  248.         /// </devdoc>
  249.         private void CompleteGetConnection(Socket socket, Socket socket6, Socket finalSocket, IPAddress address)
  250.         {
  251.             //
  252.             // Decide which socket to retain
  253.             //
  254.             if (finalSocket.AddressFamily == AddressFamily.InterNetwork) {
  255.                 if (socket6 != null) {
  256.                     socket6.Close();
  257.                     socket6 = null;
  258.                 }
  259.             }
  260.             else {
  261.                 socket.Close();
  262.                 socket = null;
  263.             }
  264.            
  265.             // make this configurable from the user:
  266.             if (!UseNagleAlgorithm) {
  267.                 finalSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);
  268.             }
  269.             if (ReceiveBufferSize != -1) {
  270.                 finalSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, ReceiveBufferSize);
  271.             }
  272.             //return CreateConnection(NetworkStream stream, IPAddress address);
  273.             //return new NetworkStream(finalSocket, true);
  274.         }
  275.        
  276.        
  277. /*++
  278.             SubmitRequest      - Submit a request for sending.
  279.             The service point submit handler. This is called when a request needs
  280.             to be submitted to the network. This routine is asynchronous; the caller
  281.             passes in an HttpSubmitDelegate that is invoked when the caller
  282.             can use the underlying network. The delegate is invoked with the
  283.             stream that it can write to.
  284.             In this version, we use HttpWebRequest. In the future we use IRequest
  285.             Input:
  286.                     Request                - Request that's being submitted.
  287.                     SubmitDelegate          - Delegate to be invoked.
  288.             Returns:
  289.                     Nothing.
  290.         --*/       
  291.        
  292.         internal virtual void SubmitRequest(HttpWebRequest request)
  293.         {
  294.             SubmitRequest(request, null);
  295.         }
  296.        
  297.         // userReqeustThread says whether we can post IO from this thread or not.
  298.         internal void SubmitRequest(HttpWebRequest request, string connName)
  299.         {
  300.             //
  301.             // We attempt to locate a free connection sitting on our list
  302.             // avoiding multiple loops of the same the list.
  303.             // We do this, by enumerating the list of the connections,
  304.             // looking for Free items, and the least busy item
  305.             //
  306.             Connection connToUse;
  307.             ConnectionGroup connGroup;
  308.             lock (this) {
  309.                 GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::SubmitRequest() Finding ConnectionGroup:[" + connName + "]");
  310.                 connGroup = FindConnectionGroup(connName, false);
  311.                 GlobalLog.Assert(connGroup != null, "ServicePoint#{0}::SubmitRequest()|connGroup == null", ValidationHelper.HashString(this));
  312.             }
  313.            
  314.             do {
  315.                 connToUse = connGroup.FindConnection(request, connName);
  316.                 // The request could be already aborted
  317.                 if (connToUse == null)
  318.                     return;
  319.                
  320.                 GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::SubmitRequest() Using Connection#" + ValidationHelper.HashString(connToUse));
  321.                 // finally sumbit delegate
  322.                 if (connToUse.SubmitRequest(request)) {
  323.                     break;
  324.                 }
  325.             }
  326.             while (true);
  327.         }
  328.        
  329.         // properties
  330.        
  331.         /// <devdoc>
  332.         /// <para>
  333.         /// Gets and sets timeout for when connections should be recycled.
  334.         /// </para>
  335.         /// </devdoc>
  336.         public int ConnectionLeaseTimeout {
  337.             get { return m_ConnectionLeaseTimeout; }
  338.             set {
  339.                 if (!ValidationHelper.ValidateRange(value, Timeout.Infinite, Int32.MaxValue)) {
  340.                     throw new ArgumentOutOfRangeException("value");
  341.                 }
  342.                 if (value != m_ConnectionLeaseTimeout) {
  343.                     m_ConnectionLeaseTimeout = value;
  344.                     m_ConnectionLeaseTimerQueue = null;
  345.                 }
  346.             }
  347.         }
  348.        
  349.         /// <summary>
  350.         /// <para>Returns a timer queue that can be used internally to create timers of
  351.         /// ConnectionLeaseTimeout duration.</para>
  352.         /// </summary>
  353.         internal TimerThread.Queue ConnectionLeaseTimerQueue {
  354.             get {
  355.                 TimerThread.Queue queue = m_ConnectionLeaseTimerQueue;
  356.                 if (queue == null) {
  357.                     queue = TimerThread.GetOrCreateQueue(ConnectionLeaseTimeout);
  358.                     m_ConnectionLeaseTimerQueue = queue;
  359.                 }
  360.                 return m_ConnectionLeaseTimerQueue;
  361.             }
  362.         }
  363.        
  364.         // Only the scheme and hostport, for example http://www.microsoft.com
  365.         /// <devdoc>
  366.         /// <para>
  367.         /// Gets the Uniform Resource Identifier of the <see cref='System.Net.ServicePoint'/>.
  368.         /// </para>
  369.         /// </devdoc>
  370.         public Uri Address {
  371.             get {
  372.                 if (m_HostMode) {
  373.                     throw new NotSupportedException(SR.GetString(SR.net_servicePointAddressNotSupportedInHostMode));
  374.                 }
  375.                
  376.                 // Don't let low-trust apps discover the proxy information.
  377.                 if (m_ProxyServicePoint) {
  378.                     ExceptionHelper.WebPermissionUnrestricted.Demand();
  379.                 }
  380.                
  381.                 return m_Address;
  382.             }
  383.         }
  384.        
  385.         internal Uri InternalAddress {
  386.             get {
  387.                 GlobalLog.Assert(!m_HostMode, "ServicePoint#{0}::InternalAddress|Can't be used in Host Mode.", ValidationHelper.HashString(this));
  388.                 return m_Address;
  389.             }
  390.         }
  391.        
  392.         internal string Host {
  393.             get {
  394.                 if (m_HostMode) {
  395.                     return m_Host;
  396.                 }
  397.                 return m_Address.Host;
  398.             }
  399.         }
  400.        
  401.         internal int Port {
  402.             get { return m_Port; }
  403.         }
  404.        
  405.        
  406.         //
  407.         // Gets or sets the maximum idle time allowed for connections of this ServicePoint and then for ServicePoint itself
  408.         // Default value coming in ctor is ServicePointManager.s_MaxServicePointIdleTime which 100 sec
  409.         //
  410.         public int MaxIdleTime {
  411.             get { return m_IdlingQueue.Duration; }
  412.             set {
  413.                 if (!ValidationHelper.ValidateRange(value, Timeout.Infinite, Int32.MaxValue)) {
  414.                     throw new ArgumentOutOfRangeException("value");
  415.                 }
  416.                
  417.                 // Already set?
  418.                 if (value == m_IdlingQueue.Duration)
  419.                     return;
  420.                
  421.                 lock (this) {
  422.                     // Make sure we can cancel the existing one. If not, we already idled out.
  423.                     if (m_ExpiringTimer == null || m_ExpiringTimer.Cancel()) {
  424.                         m_IdlingQueue = TimerThread.GetOrCreateQueue(value);
  425.                         if (m_ExpiringTimer != null) {
  426.                             // Need to create a one-off timer for the remaining period.
  427.                             double elapsedDouble = (DateTime.Now - m_IdleSince).TotalMilliseconds;
  428.                             int elapsed = elapsedDouble >= (double)Int32.MaxValue ? Int32.MaxValue : (int)elapsedDouble;
  429.                             int timeLeft = value == Timeout.Infinite ? Timeout.Infinite : elapsed >= value ? 0 : value - elapsed;
  430.                             m_ExpiringTimer = TimerThread.CreateQueue(timeLeft).CreateTimer(ServicePointManager.IdleServicePointTimeoutDelegate, this);
  431.                         }
  432.                     }
  433.                 }
  434.             }
  435.         }
  436.        
  437.         /// <devdoc>
  438.         /// <para>
  439.         /// Gets or sets the Nagling algorithm on the connections that are created to this <see cref='System.Net.ServicePoint'/>.
  440.         /// Changing this value does not affect existing connections but only to new ones that are created from that moment on.
  441.         /// </para>
  442.         /// </devdoc>
  443.         public bool UseNagleAlgorithm {
  444.             get { return m_UseNagleAlgorithm; }
  445.             set { m_UseNagleAlgorithm = value; }
  446.         }
  447.        
  448.         /// <devdoc>
  449.         /// <para>
  450.         /// Gets and sets the socket's receive buffer size.
  451.         /// </para>
  452.         /// </devdoc>
  453.         public int ReceiveBufferSize {
  454.             get { return m_ReceiveBufferSize; }
  455.             set {
  456.                 if (!ValidationHelper.ValidateRange(value, -1, Int32.MaxValue)) {
  457.                     throw new ArgumentOutOfRangeException("value");
  458.                 }
  459.                 m_ReceiveBufferSize = value;
  460.             }
  461.         }
  462.        
  463.        
  464.        
  465.         /// <devdoc>
  466.         /// <para>
  467.         /// Gets or sets indication whether 100-continue behaviour is desired when using this <see cref='System.Net.ServicePoint'/>.
  468.         /// Changing this value does not affect existing connections but only to new ones that are created from that moment on.
  469.         /// </para>
  470.         /// </devdoc>
  471.         public bool Expect100Continue {
  472.             get { return m_Expect100Continue; }
  473.             set { m_Expect100Continue = value; }
  474.         }
  475.        
  476.         /// <devdoc>
  477.         /// <para>
  478.         /// Gets the date/time that the <see cref='System.Net.ServicePoint'/> went idle.
  479.         /// </para>
  480.         /// </devdoc>
  481.         public DateTime IdleSince {
  482.             get { return m_IdleSince; }
  483.         }
  484.        
  485.         // HTTP Server Version
  486.         /// <devdoc>
  487.         /// <para>
  488.         /// The version of the protocol being used on this <see cref='System.Net.ServicePoint'/>.
  489.         /// </para>
  490.         /// </devdoc>
  491.         public virtual Version ProtocolVersion {
  492.             get { return (m_HttpBehaviour > HttpBehaviour.HTTP10 || m_HttpBehaviour == HttpBehaviour.Unknown) ? HttpVersion.Version11 : HttpVersion.Version10; }
  493.         }
  494.        
  495.         // Contains set accessor for Version property. Version is a read-only
  496.         // property at the API
  497.         internal HttpBehaviour HttpBehaviour {
  498.             get { return m_HttpBehaviour; }
  499.             set {
  500.                 m_HttpBehaviour = value;
  501.                 //
  502.                 // if version is greater than HTTP/1.1, and server undesrtood
  503.                 // 100 Continue so far, keep expecting it.
  504.                 //
  505.                 m_Understands100Continue = m_Understands100Continue && (m_HttpBehaviour > HttpBehaviour.HTTP10 || m_HttpBehaviour == HttpBehaviour.Unknown);
  506.             }
  507.         }
  508.        
  509.         /// <devdoc>
  510.         /// <para>
  511.         /// Gets the connection name established by the <see cref='System.Net.WebRequest'/> that created the connection.
  512.         /// </para>
  513.         /// </devdoc>
  514.         public string ConnectionName {
  515.             get { return m_ConnectionName; }
  516.         }
  517.        
  518. /*
  519.         /// <devdoc>
  520.         ///    Gets the connection mode in use by the <see cref='System.Net.ServicePoint'/>. One of the <see cref='System.Net.ConnectionModes'/>
  521.         ///    values.
  522.         /// </devdoc>
  523.         internal ConnectionModes ConnectionMode {
  524.             get {
  525.                 return m_HttpBehaviour>=HttpBehaviour.HTTP11 ? ConnectionModes.Pipeline : ConnectionModes.Persistent;
  526.             }
  527.         }
  528.         */       
  529.        
  530.         /// <devdoc>
  531.         /// Removes the specified Connection group from the ServicePoint, destroys safe and unsafe groups, but not internal.
  532.         /// </devdoc>
  533.        
  534.         public bool CloseConnectionGroup(string connectionGroupName)
  535.         {
  536.             GlobalLog.Enter("ServicePoint#" + ValidationHelper.HashString(this) + "::CloseConnectionGroup() lookupStr:[" + connectionGroupName + "]");
  537.             if (ReleaseConnectionGroup(HttpWebRequest.GenerateConnectionGroup(connectionGroupName, false, false).ToString()) || ReleaseConnectionGroup(HttpWebRequest.GenerateConnectionGroup(connectionGroupName, true, false).ToString()) || ConnectionPoolManager.RemoveConnectionPool(this, connectionGroupName)) {
  538.                
  539.                 GlobalLog.Leave("ServicePoint#" + ValidationHelper.HashString(this) + "::CloseConnectionGroup()", "true");
  540.                 return true;
  541.             }
  542.             GlobalLog.Leave("ServicePoint#" + ValidationHelper.HashString(this) + "::CloseConnectionGroup()", "false");
  543.             return false;
  544.         }
  545.        
  546.        
  547.         /// <devdoc>
  548.         /// <para>
  549.         /// Gets or sets the maximum number of connections allowed on this <see cref='System.Net.ServicePoint'/>.
  550.         /// </para>
  551.         /// </devdoc>
  552.         public int ConnectionLimit {
  553.             get {
  554.                 // If there hasn't been a DNS resolution yet, make a guess based on the host name. It might change
  555.                 // when DNS is finally done, but that's ok. It can change anyway based on other factors like redirects.
  556.                 if (!m_UserChangedLimit && m_IPAddressInfoList == null && m_HostLoopbackGuess == TriState.Unspecified) {
  557.                     // This can only happen the first time through, and before any ConnectionGroups are made.
  558.                     lock (this) {
  559.                         if (!m_UserChangedLimit && m_IPAddressInfoList == null && m_HostLoopbackGuess == TriState.Unspecified) {
  560.                             // First check if it's just an IP address anyway.
  561.                             IPAddress addr = null;
  562.                             if (IPAddress.TryParse(m_Host, out addr)) {
  563.                                 m_HostLoopbackGuess = IsAddressListLoopback(new IPAddress[] {addr}) ? TriState.True : TriState.False;
  564.                             }
  565.                             else {
  566.                                 m_HostLoopbackGuess = NclUtilities.GuessWhetherHostIsLoopback(m_Host) ? TriState.True : TriState.False;
  567.                             }
  568.                         }
  569.                     }
  570.                 }
  571.                
  572.                 return m_UserChangedLimit || (m_IPAddressInfoList == null ? m_HostLoopbackGuess != TriState.True : !m_IPAddressesAreLoopback) ? m_ConnectionLimit : LoopbackConnectionLimit;
  573.             }
  574.            
  575.             set {
  576.                 if (value <= 0) {
  577.                     throw new ArgumentOutOfRangeException("value");
  578.                 }
  579.                
  580.                 if (!m_UserChangedLimit || m_ConnectionLimit != value) {
  581.                     lock (this) {
  582.                         if (!m_UserChangedLimit || m_ConnectionLimit != value) {
  583.                             m_ConnectionLimit = value;
  584.                             m_UserChangedLimit = true;
  585.                            
  586.                             // Don't want to call ResolveConnectionLimit() or ConnectionLimit before setting m_UserChangedLimit
  587.                             // in order to avoid the 'guess' logic in ConnectionLimit.
  588.                             ResolveConnectionLimit();
  589.                         }
  590.                     }
  591.                 }
  592.             }
  593.         }
  594.        
  595.         // Must be called under lock.
  596.         private void ResolveConnectionLimit()
  597.         {
  598.             int limit = ConnectionLimit;
  599.             foreach (ConnectionGroup cg in m_ConnectionGroupList.Values) {
  600.                 cg.ConnectionLimit = limit;
  601.             }
  602.         }
  603.        
  604.         /// <devdoc>
  605.         /// <para>
  606.         /// Gets the current number of connections associated with this
  607.         /// <see cref='System.Net.ServicePoint'/>.
  608.         /// </para>
  609.         /// </devdoc>
  610.         public int CurrentConnections {
  611.             get {
  612.                 int connections = 0;
  613.                 lock (this) {
  614.                     foreach (ConnectionGroup group in m_ConnectionGroupList.Values) {
  615.                         connections += group.CurrentConnections;
  616.                     }
  617.                 }
  618.                 return connections;
  619.             }
  620.         }
  621.        
  622.        
  623.        
  624.         /// <devdoc>
  625.         /// <para>
  626.         /// Indicates that the <see cref='System.Net.ServicePoint'/> supports pipelined connections.
  627.         /// </para>
  628.         /// </devdoc>
  629.         public bool SupportsPipelining {
  630.             get { return (m_HttpBehaviour > HttpBehaviour.HTTP10 || m_HttpBehaviour == HttpBehaviour.Unknown); }
  631.         }
  632.        
  633.        
  634.         //
  635.         // Internal Properties
  636.         //
  637.        
  638.         internal bool Understands100Continue {
  639.             get { return m_Understands100Continue; }
  640.             set { m_Understands100Continue = value; }
  641.         }
  642.        
  643.         //
  644.         // InternalProxyServicePoint
  645.         //
  646.         // Indicates if we are using this service point to represent
  647.         // a proxy connection, if so we may have to use special
  648.         // semantics when creating connections
  649.         //
  650.        
  651.         internal bool InternalProxyServicePoint {
  652.             get { return m_ProxyServicePoint; }
  653.         }
  654.        
  655.         //
  656.         // IncrementConnection
  657.         //
  658.         // call to indicate that we now are starting a new
  659.         // connection within this service point
  660.         //
  661.        
  662.         internal void IncrementConnection()
  663.         {
  664.             GlobalLog.Enter("ServicePoint#" + ValidationHelper.HashString(this) + "::IncrementConnection()", m_CurrentConnections.ToString());
  665.             // we need these to be atomic operations
  666.             lock (this) {
  667.                 m_CurrentConnections++;
  668.                 if (m_CurrentConnections == 1) {
  669.                     GlobalLog.Assert(m_ExpiringTimer != null, "ServicePoint#{0}::IncrementConnection|First connection active, but ServicePoint wasn't idle.", ValidationHelper.HashString(this));
  670.                    
  671.                     m_ExpiringTimer.Cancel();
  672.                     m_ExpiringTimer = null;
  673.                 }
  674.             }
  675.             GlobalLog.Leave("ServicePoint#" + ValidationHelper.HashString(this) + "::IncrementConnection()", m_CurrentConnections.ToString());
  676.         }
  677.        
  678.         //
  679.         // DecrementConnection
  680.         //
  681.         // call to indicate that we now are removing
  682.         // a connection within this connection group
  683.         //
  684.        
  685.         internal void DecrementConnection()
  686.         {
  687.             // The timer thread is allowed to call this. (It doesn't call user code and doesn't block.)
  688.             GlobalLog.ThreadContract(ThreadKinds.Unknown, ThreadKinds.SafeSources | ThreadKinds.Timer, "ServicePoint#" + ValidationHelper.HashString(this) + "::DecrementConnection");
  689.             GlobalLog.Enter("ServicePoint#" + ValidationHelper.HashString(this) + "::DecrementConnection()", m_CurrentConnections.ToString());
  690.            
  691.             // we need these to be atomic operations
  692.             lock (this) {
  693.                 m_CurrentConnections--;
  694.                 if (m_CurrentConnections == 0) {
  695.                     GlobalLog.Assert(m_ExpiringTimer == null, "ServicePoint#{0}::DecrementConnection|Expiring timer set on non-idle ServicePoint.", ValidationHelper.HashString(this));
  696.                     m_IdleSince = DateTime.Now;
  697.                     m_ExpiringTimer = m_IdlingQueue.CreateTimer(ServicePointManager.IdleServicePointTimeoutDelegate, this);
  698.                 }
  699.                 else if (m_CurrentConnections < 0) {
  700.                     m_CurrentConnections = 0;
  701.                 }
  702.             }
  703.             GlobalLog.Leave("ServicePoint#" + ValidationHelper.HashString(this) + "::DecrementConnection()", m_CurrentConnections.ToString());
  704.         }
  705.        
  706.        
  707. /*
  708.         //                                   
  709.         internal bool UserDefinedLimit {
  710.             get {
  711.                 return m_UserChangedLimit;
  712.             }
  713.         }
  714.         */       
  715.        
  716.        
  717.        
  718.         /// <devdoc>
  719.         /// <para>
  720.         /// Sets connections in this group to not be KeepAlive.
  721.         /// This is called to force cleanup of the ConnectionGroup by the
  722.         /// NTLM and Negotiate authentication modules.
  723.         /// </para>
  724.         /// </devdoc>
  725.         internal bool ReleaseConnectionGroup(string connName)
  726.         {
  727.             //
  728.             // look up the ConnectionGroup based on the name
  729.             //
  730.             lock (this) {
  731.                
  732.                 ConnectionGroup connectionGroup = FindConnectionGroup(connName, true);
  733.                 //
  734.                 // force all connections on the ConnectionGroup to not be KeepAlive
  735.                 //
  736.                 if (connectionGroup == null) {
  737.                     return false;
  738.                 }
  739.                
  740.                 connectionGroup.DisableKeepAliveOnConnections();
  741.                 //
  742.                 // remove ConnectionGroup from our Hashtable
  743.                 //
  744.                 m_ConnectionGroupList.Remove(connName);
  745.             }
  746.            
  747.             return true;
  748.         }
  749.        
  750.         /// <devdoc>
  751.         /// <para>
  752.         /// - Sets all connections in all connections groups to not be KeepAlive.
  753.         /// - Causes all connections to be closed, if they are not active
  754.         /// - Removes all references to all connection groups and their connections
  755.         /// does essentially a "ReleaseConnectionGroup" of each group in this ServicePoint
  756.         /// </para>
  757.         /// </devdoc>
  758.         internal void ReleaseAllConnectionGroups()
  759.         {
  760.             // The timer thread is allowed to call this. (It doesn't call user code and doesn't block.)
  761.             GlobalLog.ThreadContract(ThreadKinds.Unknown, ThreadKinds.SafeSources | ThreadKinds.Timer, "ServicePoint#" + ValidationHelper.HashString(this) + "::ReleaseAllConnectionGroups");
  762.            
  763.             // To avoid deadlock (can't lock a ServicePoint followed by a Connection), copy out all the
  764.             // connection groups in a lock, then release them all outside of it.
  765.             ArrayList cgs = new ArrayList(m_ConnectionGroupList.Count);
  766.             lock (this) {
  767.                 foreach (ConnectionGroup cg in m_ConnectionGroupList.Values) {
  768.                     cgs.Add(cg);
  769.                 }
  770.                 m_ConnectionGroupList.Clear();
  771.             }
  772.             foreach (ConnectionGroup cg in cgs) {
  773.                 cg.DisableKeepAliveOnConnections();
  774.             }
  775.         }
  776.        
  777.        
  778.         /// <summary>
  779.         /// <para>Internal class, used to store state for async Connect</para>
  780.         /// </summary>
  781.         private class ConnectSocketState
  782.         {
  783.             internal ConnectSocketState(ServicePoint servicePoint, PooledStream pooledStream, object owner, Socket s4, Socket s6)
  784.             {
  785.                 this.servicePoint = servicePoint;
  786.                 this.pooledStream = pooledStream;
  787.                 this.owner = owner;
  788.                 this.s4 = s4;
  789.                 this.s6 = s6;
  790.             }
  791.             internal ServicePoint servicePoint;
  792.             internal Socket s4;
  793.             internal Socket s6;
  794.             internal object owner;
  795.             internal IPAddress[] addresses;
  796.             internal int currentIndex;
  797.             internal int i;
  798.             internal int unsuccessfulAttempts;
  799.             internal bool connectFailure;
  800.             internal PooledStream pooledStream;
  801.         }
  802.        
  803.        
  804.         /// <summary>
  805.         /// <para>Proviates an async callback that is called when Connect completes [part of ConnectSocket(...)]</para>
  806.         /// </summary>
  807.         private static void ConnectSocketCallback(IAsyncResult asyncResult)
  808.         {
  809.             ConnectSocketState state = (ConnectSocketState)asyncResult.AsyncState;
  810.             Socket socket = null;
  811.             IPAddress address = null;
  812.             Exception innerException = null;
  813.             Exception exception = null;
  814.             WebExceptionStatus ws = WebExceptionStatus.ConnectFailure;
  815.            
  816.            
  817.             try {
  818.                 ws = state.servicePoint.ConnectSocketInternal(state.connectFailure, state.s4, state.s6, ref socket, ref address, state, asyncResult, Timeout.Infinite, out innerException);
  819.             }
  820.             catch (SocketException socketException) {
  821.                 exception = socketException;
  822.             }
  823.             catch (ObjectDisposedException socketException) {
  824.                 exception = socketException;
  825.             }
  826.            
  827.             if (ws == WebExceptionStatus.Pending) {
  828.                 return;
  829.             }
  830.            
  831.             if (ws == WebExceptionStatus.Success) {
  832.                 try {
  833.                     state.servicePoint.CompleteGetConnection(state.s4, state.s6, socket, address);
  834.                 }
  835.                 catch (SocketException socketException) {
  836.                     exception = socketException;
  837.                 }
  838.                 catch (ObjectDisposedException socketException) {
  839.                     exception = socketException;
  840.                 }
  841.                
  842.             }
  843.             else {
  844.                     /* no response */                exception = new WebException(NetRes.GetWebStatusString(ws), ws == WebExceptionStatus.ProxyNameResolutionFailure || ws == WebExceptionStatus.NameResolutionFailure ? state.servicePoint.Host : null, innerException, ws, null, WebExceptionInternalStatus.ServicePointFatal);
  845.             }
  846.             try {
  847.                 state.pooledStream.ConnectionCallback(state.owner, exception, socket, address);
  848.             }
  849.             catch {
  850.                 if (socket != null && socket.CleanedUp)
  851.                     return;
  852.                 // The connection was aborted and requests dispatched
  853.                 throw;
  854.             }
  855.            
  856.         }
  857.        
  858.         private void BindUsingDelegate(Socket socket, IPEndPoint remoteIPEndPoint)
  859.         {
  860.             IPEndPoint clonedRemoteIPEndPoint = new IPEndPoint(remoteIPEndPoint.Address, remoteIPEndPoint.Port);
  861.            
  862.             int retryCount;
  863.             for (retryCount = 0; retryCount < int.MaxValue; retryCount++) {
  864.                 IPEndPoint localIPEndPoint = BindIPEndPointDelegate(this, clonedRemoteIPEndPoint, retryCount);
  865.                 if (localIPEndPoint == null)
  866.                     break;
  867.                
  868.                 try {
  869.                     socket.InternalBind(localIPEndPoint);
  870.                 }
  871.                 catch {
  872.                     continue;
  873.                 }
  874.                 break;
  875.             }
  876.             if (retryCount == int.MaxValue)
  877.                 throw new OverflowException("Reached maximum number of BindIPEndPointDelegate retries");
  878.         }
  879.        
  880.         /// <summary>
  881.         /// <para>This is the real logic for doing the Connect with IPv4 and IPv6 addresses, see ConnectSocket for details</para>
  882.         /// </summary>
  883.         private WebExceptionStatus ConnectSocketInternal(bool connectFailure, Socket s4, Socket s6, ref Socket socket, ref IPAddress address, ConnectSocketState state, IAsyncResult asyncResult, int timeout, out Exception exception)
  884.         {
  885.             IPEndPoint remoteIPEndPoint;
  886.             exception = null;
  887.             bool timedOut = false;
  888.            
  889.             //
  890.             // so, here we are: we have the EndPoint we need to connect to, all we
  891.             // need to do is call into winsock and try to connect to this HTTP server.
  892.             //
  893.             // this is how we do it:
  894.             // we'll keep trying to Connect() until either:
  895.             // (1) Connect() succeeds (on which we increment the number of connections opened) or
  896.             // (2) we can't get any new address for this host.
  897.             //
  898.             // (1) is pretty easy, here's how we do (2):
  899.             // If the hostinformation is every marked as failed, we will automatically refresh it
  900.             // the next time it is read.
  901.             // If we fail the first time using the DNS information and the DNS information is recent,
  902.             // which mean's it either hasn't been tried or it failed, we will mark the
  903.             // hostinformation as failed, and quit. Otherwise we'll refresh the DNS information and
  904.             // try one more time. If we fail the second time, then we'll mark the DNS information
  905.             // as failed and quit.
  906.             IPAddress[] addresses = null;
  907.             for (int unsuccessfulAttempts = 0; unsuccessfulAttempts < 2; unsuccessfulAttempts++) {
  908.                
  909.                 int currentIndex;
  910.                 int i = 0;
  911.                
  912.                 // Use asyncResult to make sure it is only called at initiation time.
  913.                 if (asyncResult == null) {
  914.                     // the second time, determine if the list was recent.
  915.                     GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::ConnectSocketInternal() calling GetIPAddressInfoList() timeout:" + timeout.ToString());
  916.                    
  917.                     addresses = GetIPAddressInfoList(out currentIndex, addresses, timeout, out timedOut);
  918.                    
  919.                     //the addresses were recent, or we couldn't resolve the addresses.
  920.                     if (addresses == null || addresses.Length == 0 || timedOut)
  921.                         break;
  922.                 }
  923.                 else {
  924.                     GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::ConnectSocketInternal() resuming previous state");
  925.                    
  926.                     addresses = state.addresses;
  927.                     currentIndex = state.currentIndex;
  928.                     i = state.i;
  929.                     unsuccessfulAttempts = state.unsuccessfulAttempts;
  930.                 }
  931.                
  932.                 //otherwise, try all of the addresses in the list.
  933.                 for (; i < addresses.Length; i++) {
  934.                     IPAddress ipAddressInfo = addresses[currentIndex];
  935.                     try {
  936.                         remoteIPEndPoint = new IPEndPoint(ipAddressInfo, m_Port);
  937.                         Socket attemptSocket;
  938.                         if (remoteIPEndPoint.Address.AddressFamily == AddressFamily.InterNetwork) {
  939.                             attemptSocket = s4;
  940.                         }
  941.                         else {
  942.                             attemptSocket = s6;
  943.                         }
  944.                        
  945.                         if (state != null) {
  946.                             if (asyncResult != null) {
  947.                                 IAsyncResult asyncResultCopy = asyncResult;
  948.                                 asyncResult = null;
  949.                                 attemptSocket.EndConnect(asyncResultCopy);
  950.                             }
  951.                             else {
  952.                                 GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::ConnectSocketInternal() calling BeginConnect() to:" + remoteIPEndPoint.ToString());
  953.                                
  954.                                 // save off our state and do our async call
  955.                                 state.addresses = addresses;
  956.                                 state.currentIndex = currentIndex;
  957.                                 state.i = i;
  958.                                 state.unsuccessfulAttempts = unsuccessfulAttempts;
  959.                                 state.connectFailure = connectFailure;
  960.                                
  961.                                 if (BindIPEndPointDelegate != null && !attemptSocket.IsBound) {
  962.                                     BindUsingDelegate(attemptSocket, remoteIPEndPoint);
  963.                                 }
  964.                                
  965.                                 attemptSocket.UnsafeBeginConnect(remoteIPEndPoint, m_ConnectCallbackDelegate, state);
  966.                                 return WebExceptionStatus.Pending;
  967.                             }
  968.                         }
  969.                         else {
  970.                             if (BindIPEndPointDelegate != null && !attemptSocket.IsBound) {
  971.                                 BindUsingDelegate(attemptSocket, remoteIPEndPoint);
  972.                             }
  973.                            
  974.                             attemptSocket.InternalConnect(remoteIPEndPoint);
  975.                         }
  976.                         socket = attemptSocket;
  977.                         address = ipAddressInfo;
  978.                         exception = null;
  979.                         UpdateCurrentIndex(addresses, currentIndex);
  980.                         return WebExceptionStatus.Success;
  981.                     }
  982.                     catch (ObjectDisposedException) {
  983.                         // This can happen if the request has been aborted and the attemptSocket got closed.
  984.                         return WebExceptionStatus.RequestCanceled;
  985.                     }
  986.                     catch (Exception e) {
  987.                         if (NclUtilities.IsFatal(e))
  988.                             throw;
  989.                        
  990.                         exception = e;
  991.                         connectFailure = true;
  992.                     }
  993.                     currentIndex++;
  994.                     if (currentIndex >= addresses.Length) {
  995.                         currentIndex = 0;
  996.                     }
  997.                 }
  998.             }
  999.            
  1000.             Failed(addresses);
  1001.            
  1002.             return connectFailure ? WebExceptionStatus.ConnectFailure : timedOut ? WebExceptionStatus.Timeout : InternalProxyServicePoint ? WebExceptionStatus.ProxyNameResolutionFailure : WebExceptionStatus.NameResolutionFailure;
  1003.         }
  1004.        
  1005. /*
  1006.         //                         
  1007.         private WebExceptionStatus ConnectSocket(Socket s4, Socket s6, ref Socket socket, int timeout, out Exception exception) {
  1008.             IPAddress address = null;
  1009.             return ConnectSocket(s4, s6, ref socket, ref address, null, timeout, out exception);
  1010.         }
  1011.         */       
  1012.        
  1013.         /// <summary>
  1014.         /// <para>private implimentation of ConnectSocket(...)</para>
  1015.         /// </summary>
  1016.         private WebExceptionStatus ConnectSocket(Socket s4, Socket s6, ref Socket socket, ref IPAddress address, ConnectSocketState state, int timeout, out Exception exception)
  1017.         {
  1018.             //
  1019.             // we need this for the call to connect()
  1020.             //
  1021.             return ConnectSocketInternal(false, s4, s6, ref socket, ref address, state, null, timeout, out exception);
  1022.         }
  1023.        
  1024.         [System.Diagnostics.Conditional("DEBUG")]
  1025.         internal void Debug(int requestHash)
  1026.         {
  1027.             foreach (ConnectionGroup connectGroup in m_ConnectionGroupList.Values) {
  1028.                 if (connectGroup != null) {
  1029.                     try {
  1030.                         connectGroup.Debug(requestHash);
  1031.                     }
  1032.                     catch {
  1033.                     }
  1034.                 }
  1035.             }
  1036.         }
  1037.        
  1038.        
  1039.         //
  1040.         // Previously: class IPHostInformation
  1041.         //
  1042.        
  1043.         private string m_HostName = String.Empty;
  1044.         private IPAddress[] m_IPAddressInfoList;
  1045.         private int m_CurrentAddressInfoIndex;
  1046.         private bool m_ConnectedSinceDns = false;
  1047.         private bool m_AddressListFailed = false;
  1048.         private DateTime m_LastDnsResolve;
  1049.         private bool m_IPAddressesAreLoopback;
  1050.        
  1051.         private void Failed(IPAddress[] addresses)
  1052.         {
  1053.             if (addresses == m_IPAddressInfoList) {
  1054.                 lock (this) {
  1055.                     if (addresses == m_IPAddressInfoList) {
  1056.                         m_AddressListFailed = true;
  1057.                     }
  1058.                 }
  1059.             }
  1060.         }
  1061.        
  1062.        
  1063.         //if dns round robin is enabled, we don't want to update the index
  1064.         //because other connections may have skipped to the next address.
  1065.         //we need a better mechanism to handle dead connections
  1066.         private void UpdateCurrentIndex(IPAddress[] addresses, int currentIndex)
  1067.         {
  1068.             if (addresses == m_IPAddressInfoList && (m_CurrentAddressInfoIndex != currentIndex || !m_ConnectedSinceDns)) {
  1069.                 lock (this) {
  1070.                     if (addresses == m_IPAddressInfoList) {
  1071.                         if (!ServicePointManager.EnableDnsRoundRobin) {
  1072.                             m_CurrentAddressInfoIndex = currentIndex;
  1073.                         }
  1074.                         m_ConnectedSinceDns = true;
  1075.                     }
  1076.                 }
  1077.             }
  1078.         }
  1079.        
  1080.        
  1081.         private bool HasTimedOut {
  1082.             get {
  1083.                 int dnsRefreshTimeout = ServicePointManager.DnsRefreshTimeout;
  1084.                 return dnsRefreshTimeout != Timeout.Infinite && (m_LastDnsResolve + new TimeSpan(0, 0, 0, 0, dnsRefreshTimeout)) < DateTime.UtcNow;
  1085.             }
  1086.         }
  1087.        
  1088.        
  1089.         // If addresses is specified, we determine if the addresslist is recent
  1090.         // If the answer is yes, we return null. Whether its recent is determined by whether
  1091.         // or not the current hostinformation has ever been marked as succeeded or failed (meaning
  1092.         // even tried). If it isn't recent, we'll refresh the addresslist.
  1093.        
  1094.         private IPAddress[] GetIPAddressInfoList(out int currentIndex, IPAddress[] addresses, int timeout, out bool timedOut)
  1095.         {
  1096.             IPHostEntry ipHostEntry = null;
  1097.             currentIndex = 0;
  1098.             bool needDnsResolution = false;
  1099.             bool dnsResolutionFailed = false;
  1100.             timedOut = false;
  1101.            
  1102.             // Phase 1: Decide if we need to do a DNS resolution
  1103.             lock (this) {
  1104.                
  1105.                 // return null if the current hostinformation has never been marked as succeeded or failed
  1106.                 // (the hostinformation hasn't been used) and it hasn't changed.
  1107.                
  1108.                 if (addresses != null && !m_ConnectedSinceDns && !m_AddressListFailed && addresses == m_IPAddressInfoList)
  1109.                     return null;
  1110.                
  1111.                 // refresh the list if its already failed, or if the addresslist isn't recent
  1112.                 if (m_IPAddressInfoList == null || m_AddressListFailed || addresses == m_IPAddressInfoList || HasTimedOut) {
  1113.                     m_CurrentAddressInfoIndex = 0;
  1114.                     m_ConnectedSinceDns = false;
  1115.                     m_AddressListFailed = false;
  1116.                     m_LastDnsResolve = DateTime.UtcNow;
  1117.                    
  1118.                     needDnsResolution = true;
  1119.                 }
  1120.             }
  1121.            
  1122.             // Phase 2: If we have to do a DNS resolution now, then do it now
  1123.             if (needDnsResolution) {
  1124.                 try {
  1125.                     GlobalLog.Print("IPHostInformation#" + ValidationHelper.HashString(this) + "::GetIPAddressInfoList() calling Dns.InternalResolveFast() for:" + m_Host + " timeout:" + (uint)timeout);
  1126.                     ipHostEntry = Dns.InternalResolveFast(m_Host, timeout, out timedOut);
  1127.                     GlobalLog.Print("IPHostInformation#" + ValidationHelper.HashString(this) + "::GetIPAddressInfoList() Dns.InternalResolveFast() returns:" + ValidationHelper.ToString(ipHostEntry) + " timedOut:" + timedOut);
  1128.                     if (timedOut) {
  1129.                         dnsResolutionFailed = true;
  1130.                     }
  1131.                 }
  1132.                 catch (Exception exception) {
  1133.                     if (NclUtilities.IsFatal(exception))
  1134.                         throw;
  1135.                     dnsResolutionFailed = true;
  1136.                     GlobalLog.Print("IPHostInformation#" + ValidationHelper.HashString(this) + "::GetIPAddressInfoList() Dns.InternalResolveFast() failed with exception:\r\n" + exception.ToString());
  1137.                 }
  1138.             }
  1139.            
  1140.             // Phase 3: If we did a DNS resolution, then deal with the results safely under a lock
  1141.             lock (this) {
  1142.                 if (needDnsResolution) {
  1143.                    
  1144.                     m_IPAddressInfoList = null;
  1145.                    
  1146.                     if (!dnsResolutionFailed) {
  1147.                         if (ipHostEntry != null && ipHostEntry.AddressList != null && ipHostEntry.AddressList.Length > 0) {
  1148.                             SetAddressList(ipHostEntry);
  1149.                         }
  1150.                         else {
  1151.                             GlobalLog.Print("IPHostInformation#" + ValidationHelper.HashString(this) + "::GetIPAddressInfoList() Dns.InternalResolveFast() failed with null");
  1152.                         }
  1153.                     }
  1154.                     else {
  1155.                         GlobalLog.Print("IPHostInformation#" + ValidationHelper.HashString(this) + "::GetIPAddressInfoList() Dns.InternalResolveFast() had thrown an exception");
  1156.                     }
  1157.                 }
  1158.                
  1159.                 if (m_IPAddressInfoList != null && m_IPAddressInfoList.Length > 0) {
  1160.                     GlobalLog.Print("IPHostInformation#" + ValidationHelper.HashString(this) + "::GetIPAddressInfoList() m_IPAddressInfoList = " + m_IPAddressInfoList);
  1161.                     currentIndex = m_CurrentAddressInfoIndex;
  1162.                    
  1163.                     //auto increment index for next connect request if round robin is enabled
  1164.                     if (ServicePointManager.EnableDnsRoundRobin) {
  1165.                         m_CurrentAddressInfoIndex++;
  1166.                         if (m_CurrentAddressInfoIndex >= m_IPAddressInfoList.Length) {
  1167.                             m_CurrentAddressInfoIndex = 0;
  1168.                         }
  1169.                     }
  1170.                     return m_IPAddressInfoList;
  1171.                 }
  1172.             }
  1173.             GlobalLog.Print("IPHostInformation#" + ValidationHelper.HashString(this) + "::GetIPAddressInfoList() GetIPAddressInfoList returning null");
  1174.             return null;
  1175.         }
  1176.        
  1177.         //
  1178.         // Called under lock(this)
  1179.         //
  1180.         private void SetAddressList(IPHostEntry ipHostEntry)
  1181.         {
  1182.             GlobalLog.Print("IPHostInformation#" + ValidationHelper.HashString(this) + "::SetAddressList(" + ipHostEntry.HostName + ")");
  1183.             //
  1184.             // Create an array of IPAddress of the appropriate size, then
  1185.             // get a list of our local addresses. Walk through the input
  1186.             // address list. Copy each address in the address list into
  1187.             // our array, and if the address is a loopback address, mark it as
  1188.             // such.
  1189.             //
  1190.             // Only update the member with successfull final result.
  1191.             // In case of an exception m_IPAddressInfoList will stay as null
  1192.             //
  1193.             bool wasLoopback = m_IPAddressesAreLoopback;
  1194.             bool wasNull = m_IPAddressInfoList == null;
  1195.            
  1196.             m_IPAddressesAreLoopback = IsAddressListLoopback(ipHostEntry.AddressList);
  1197.             m_IPAddressInfoList = ipHostEntry.AddressList;
  1198.             m_HostName = ipHostEntry.HostName;
  1199.            
  1200.             if (wasNull || wasLoopback != m_IPAddressesAreLoopback) {
  1201.                 ResolveConnectionLimit();
  1202.             }
  1203.         }
  1204.        
  1205.         private static bool IsAddressListLoopback(IPAddress[] addressList)
  1206.         {
  1207.             GlobalLog.Print("IPHostInformation::CheckAddressList(" + addressList.Length + ")");
  1208.            
  1209.             //
  1210.             // Walk through each member of the input list, copying it into our temp array.
  1211.             //
  1212.            
  1213.             int i;
  1214.             int k;
  1215.             IPAddress[] localAddresses = null;
  1216.             try {
  1217.                 localAddresses = NclUtilities.LocalAddresses;
  1218.             }
  1219.             catch (Exception exception) {
  1220.                 if (NclUtilities.IsFatal(exception))
  1221.                     throw;
  1222.                
  1223.                 if (Logging.On) {
  1224.                     Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_retrieving_localhost_exception, exception));
  1225.                     Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_resolved_servicepoint_may_not_be_remote_server));
  1226.                 }
  1227.             }
  1228.            
  1229.             for (i = 0; i < addressList.Length; i++) {
  1230.                 // First, check to see if the current address is a loopback address.
  1231.                 if (IPAddress.IsLoopback(addressList[i])) {
  1232.                     continue;
  1233.                 }
  1234.                
  1235.                 if (localAddresses != null) {
  1236.                     // See if the current IP address is a local address, and if
  1237.                     // so mark it as such.
  1238.                     for (k = 0; k < localAddresses.Length; k++) {
  1239.                         //
  1240.                         // IPv6 Changes: Use .Equals for this check !
  1241.                         //
  1242.                         if (addressList[i].Equals(localAddresses[k])) {
  1243.                             break;
  1244.                         }
  1245.                     }
  1246.                     if (k < localAddresses.Length) {
  1247.                         continue;
  1248.                     }
  1249.                 }
  1250.                
  1251.                 break;
  1252.             }
  1253.            
  1254.             return i == addressList.Length;
  1255.         }
  1256.     }
  1257. }

Developer Fusion