Represents a queue of timers, which all have the same duration.

 internal ServicePoint(Uri address, TimerThread.Queue defaultIdlingQueue, int defaultConnectionLimit, string lookupString, bool userChangedLimit, bool proxyServicePoint)
 {
     this.m_HostName = string.Empty;
     this.m_ProxyServicePoint = proxyServicePoint;
     this.m_Address = address;
     this.m_ConnectionName = address.Scheme;
     this.m_Host = address.DnsSafeHost;
     this.m_Port = address.Port;
     this.m_IdlingQueue = defaultIdlingQueue;
     this.m_ConnectionLimit = defaultConnectionLimit;
     this.m_HostLoopbackGuess = TriState.Unspecified;
     this.m_LookupString = lookupString;
     this.m_UserChangedLimit = userChangedLimit;
     this.m_UseNagleAlgorithm = ServicePointManager.UseNagleAlgorithm;
     this.m_Expect100Continue = ServicePointManager.Expect100Continue;
     this.m_ConnectionGroupList = new Hashtable(10);
     this.m_ConnectionLeaseTimeout = -1;
     this.m_ReceiveBufferSize = -1;
     this.m_UseTcpKeepAlive = ServicePointManager.s_UseTcpKeepAlive;
     this.m_TcpKeepAliveTime = ServicePointManager.s_TcpKeepAliveTime;
     this.m_TcpKeepAliveInterval = ServicePointManager.s_TcpKeepAliveInterval;
     this.m_Understands100Continue = true;
     this.m_HttpBehaviour = System.Net.HttpBehaviour.Unknown;
     this.m_IdleSince = DateTime.Now;
     this.m_ExpiringTimer = this.m_IdlingQueue.CreateTimer(ServicePointManager.IdleServicePointTimeoutDelegate, this);
 }
 internal ServicePoint(Uri address, TimerThread.Queue defaultIdlingQueue, int defaultConnectionLimit, string lookupString, bool userChangedLimit, bool proxyServicePoint)
 {
     this.m_HostName          = string.Empty;
     this.m_ProxyServicePoint = proxyServicePoint;
     this.m_Address           = address;
     this.m_ConnectionName    = address.Scheme;
     this.m_Host                   = address.DnsSafeHost;
     this.m_Port                   = address.Port;
     this.m_IdlingQueue            = defaultIdlingQueue;
     this.m_ConnectionLimit        = defaultConnectionLimit;
     this.m_HostLoopbackGuess      = TriState.Unspecified;
     this.m_LookupString           = lookupString;
     this.m_UserChangedLimit       = userChangedLimit;
     this.m_UseNagleAlgorithm      = ServicePointManager.UseNagleAlgorithm;
     this.m_Expect100Continue      = ServicePointManager.Expect100Continue;
     this.m_ConnectionGroupList    = new Hashtable(10);
     this.m_ConnectionLeaseTimeout = -1;
     this.m_ReceiveBufferSize      = -1;
     this.m_UseTcpKeepAlive        = ServicePointManager.s_UseTcpKeepAlive;
     this.m_TcpKeepAliveTime       = ServicePointManager.s_TcpKeepAliveTime;
     this.m_TcpKeepAliveInterval   = ServicePointManager.s_TcpKeepAliveInterval;
     this.m_Understands100Continue = true;
     this.m_HttpBehaviour          = System.Net.HttpBehaviour.Unknown;
     this.m_IdleSince              = DateTime.Now;
     this.m_ExpiringTimer          = this.m_IdlingQueue.CreateTimer(ServicePointManager.IdleServicePointTimeoutDelegate, this);
 }
示例#3
0
 internal ConnectionPool(System.Net.ServicePoint servicePoint, int maxPoolSize, int minPoolSize, int idleTimeout, CreateConnectionDelegate createConnectionCallback)
 {
     this.m_CreateConnectionCallback = createConnectionCallback;
     this.m_MaxPoolSize  = maxPoolSize;
     this.m_MinPoolSize  = minPoolSize;
     this.m_ServicePoint = servicePoint;
     this.Initialize();
     if (idleTimeout > 0)
     {
         this.m_CleanupQueue = TimerThread.GetOrCreateQueue((idleTimeout == 1) ? 1 : (idleTimeout / 2));
         this.m_CleanupQueue.CreateTimer(s_CleanupCallback, this);
     }
 }
 internal ConnectionPool(System.Net.ServicePoint servicePoint, int maxPoolSize, int minPoolSize, int idleTimeout, CreateConnectionDelegate createConnectionCallback)
 {
     this.m_CreateConnectionCallback = createConnectionCallback;
     this.m_MaxPoolSize = maxPoolSize;
     this.m_MinPoolSize = minPoolSize;
     this.m_ServicePoint = servicePoint;
     this.Initialize();
     if (idleTimeout > 0)
     {
         this.m_CleanupQueue = TimerThread.GetOrCreateQueue((idleTimeout == 1) ? 1 : (idleTimeout / 2));
         this.m_CleanupQueue.CreateTimer(s_CleanupCallback, this);
     }
 }
        /// <summary>
        ///    <para>Constructor - binds pool with a servicePoint and sets up a cleanup Timer to nuke Idle Connections</para>
        /// </summary>
        internal ConnectionPool(ServicePoint servicePoint, int maxPoolSize, int minPoolSize, int idleTimeout, CreateConnectionDelegate createConnectionCallback) : base()
        {
            m_State = State.Initializing;

            m_CreateConnectionCallback = createConnectionCallback;
            m_MaxPoolSize  = maxPoolSize;
            m_MinPoolSize  = minPoolSize;
            m_ServicePoint = servicePoint;

            Initialize();

            if (idleTimeout > 0)
            {
                m_CleanupQueue = TimerThread.GetOrCreateQueue(idleTimeout / 2);
                m_CleanupQueue.CreateTimer(s_CleanupCallback, this);
            }
        }
示例#6
0
        /// <summary>
        ///    <para>Constructor - binds pool with a servicePoint and sets up a cleanup Timer to remove Idle Connections</para>
        /// </summary>
        internal ConnectionPool(ServicePoint servicePoint, int maxPoolSize, int minPoolSize, int idleTimeout, CreateConnectionDelegate createConnectionCallback) : base()
        {
            m_State = State.Initializing;

            m_CreateConnectionCallback = createConnectionCallback;
            m_MaxPoolSize  = maxPoolSize;
            m_MinPoolSize  = minPoolSize;
            m_ServicePoint = servicePoint;

            Initialize();

            if (idleTimeout > 0)
            {
                // special case: if the timeout value is 1 then the timer thread should have a duration
                // of 1 to avoid having the timer callback run constantly
                m_CleanupQueue = TimerThread.GetOrCreateQueue(idleTimeout == 1 ? 1 : (idleTimeout / 2));
                m_CleanupQueue.CreateTimer(s_CleanupCallback, this);
            }
        }
 internal ServicePoint(string host, int port, TimerThread.Queue defaultIdlingQueue, int defaultConnectionLimit, string lookupString, bool userChangedLimit, bool proxyServicePoint)
 {
     this.m_HostName               = string.Empty;
     this.m_ProxyServicePoint      = proxyServicePoint;
     this.m_ConnectionName         = "ByHost:" + host + ":" + port.ToString(CultureInfo.InvariantCulture);
     this.m_IdlingQueue            = defaultIdlingQueue;
     this.m_ConnectionLimit        = defaultConnectionLimit;
     this.m_HostLoopbackGuess      = TriState.Unspecified;
     this.m_LookupString           = lookupString;
     this.m_UserChangedLimit       = userChangedLimit;
     this.m_ConnectionGroupList    = new Hashtable(10);
     this.m_ConnectionLeaseTimeout = -1;
     this.m_ReceiveBufferSize      = -1;
     this.m_Host          = host;
     this.m_Port          = port;
     this.m_HostMode      = true;
     this.m_IdleSince     = DateTime.Now;
     this.m_ExpiringTimer = this.m_IdlingQueue.CreateTimer(ServicePointManager.IdleServicePointTimeoutDelegate, this);
 }
示例#8
0
        internal HttpWebRequest(Uri uri, ServicePoint servicePoint) {
            if(Logging.On)Logging.Enter(Logging.Web, this, "HttpWebRequest", uri);

            CheckConnectPermission(uri, false);

            m_StartTimestamp = NetworkingPerfCounters.GetTimestamp();
            NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.HttpWebRequestCreated);

            // OOPS, This ctor can also be called with FTP scheme but then it should only allowed if going through the proxy
            // Something to think about...
            //if ((object)uri.Scheme != (object)Uri.UriSchemeHttp && (object)uri.Scheme != (object)Uri.UriSchemeHttps)
                //throw new ArgumentOutOfRangeException("uri");

            GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + "::.ctor(" + uri.ToString() + ")");
            //
            // internal constructor, HttpWebRequest cannot be created directly
            // but only through WebRequest.Create() method
            // set defaults
            //
            _HttpRequestHeaders         = new WebHeaderCollection(WebHeaderCollectionType.HttpWebRequest);
            _Proxy                      = WebRequest.InternalDefaultWebProxy;
            _HttpWriteMode              = HttpWriteMode.Unknown;
            _MaximumAllowedRedirections = 50;
            _Timeout                    = WebRequest.DefaultTimeout;
            _TimerQueue                 = WebRequest.DefaultTimerQueue;
            _ReadWriteTimeout           = DefaultReadWriteTimeout;
            _MaximumResponseHeadersLength = DefaultMaximumResponseHeadersLength;
            _ContentLength              = -1;
            _originalContentLength      = -1;
            _OriginVerb                 = KnownHttpVerb.Get;
            _OriginUri                  = uri;
            _Uri                        = _OriginUri;
            _ServicePoint               = servicePoint;
            _RequestIsAsync             = TriState.Unspecified;
            m_ContinueTimeout          = DefaultContinueTimeout;
            m_ContinueTimerQueue        = s_ContinueTimerQueue;

            SetupCacheProtocol(_OriginUri);

#if HTTP_HEADER_EXTENSIONS_SUPPORTED
            _NextExtension      = 10;
#endif // HTTP_HEADER_EXTENSIONS_SUPPORTED

            if(Logging.On)Logging.Exit(Logging.Web, this, "HttpWebRequest", null);
        }
        internal ServicePoint(string host, int port, TimerThread.Queue defaultIdlingQueue, int defaultConnectionLimit, string lookupString, bool userChangedLimit, bool proxyServicePoint) {
            GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::.ctor(" + lookupString+")");
            if (Logging.On) Logging.Enter(Logging.Web, this, "ServicePoint", host + ":" + port);
            
            m_ProxyServicePoint     = proxyServicePoint;
            m_ConnectionName        = "ByHost:"+host+":"+port.ToString(CultureInfo.InvariantCulture);
            m_IdlingQueue           = defaultIdlingQueue;
            m_ConnectionLimit       = defaultConnectionLimit;
            m_HostLoopbackGuess     = TriState.Unspecified;
            m_LookupString          = lookupString;
            m_UserChangedLimit      = userChangedLimit;
            m_ConnectionGroupList   = new Hashtable(10);
            m_ConnectionLeaseTimeout = System.Threading.Timeout.Infinite;
            m_ReceiveBufferSize     = -1;
            m_Host = host;
            m_Port = port;
            m_HostMode = true;

            // upon creation, the service point should be idle, by default
            m_IdleSince             = DateTime.Now;
            m_ExpiringTimer         = m_IdlingQueue.CreateTimer(ServicePointManager.IdleServicePointTimeoutDelegate, this);
            m_IdleConnectionGroupTimeoutDelegate = new TimerThread.Callback(IdleConnectionGroupTimeoutCallback);
        }
        //
        // constructors
        //
        internal ServicePoint(Uri address, TimerThread.Queue defaultIdlingQueue, int defaultConnectionLimit, string lookupString, bool userChangedLimit, bool proxyServicePoint) {
            GlobalLog.Print("ServicePoint#" + ValidationHelper.HashString(this) + "::.ctor(" + lookupString+")");
            if (Logging.On) Logging.Enter(Logging.Web, this, "ServicePoint", address.DnsSafeHost + ":" + address.Port);

            m_ProxyServicePoint     = proxyServicePoint;
            m_Address               = address;
            m_ConnectionName        = address.Scheme;
            m_Host                  = address.DnsSafeHost;
            m_Port                  = address.Port;
            m_IdlingQueue           = defaultIdlingQueue;
            m_ConnectionLimit       = defaultConnectionLimit;
            m_HostLoopbackGuess     = TriState.Unspecified;
            m_LookupString          = lookupString;
            m_UserChangedLimit      = userChangedLimit;
            m_UseNagleAlgorithm     = ServicePointManager.UseNagleAlgorithm;
            m_Expect100Continue     = ServicePointManager.Expect100Continue;
            m_ConnectionGroupList   = new Hashtable(10);
            m_ConnectionLeaseTimeout = System.Threading.Timeout.Infinite;
            m_ReceiveBufferSize     = -1;
            m_UseTcpKeepAlive       = ServicePointManager.s_UseTcpKeepAlive;
            m_TcpKeepAliveTime      = ServicePointManager.s_TcpKeepAliveTime;
            m_TcpKeepAliveInterval  = ServicePointManager.s_TcpKeepAliveInterval;

            // it would be safer to make sure the server is 1.1
            // but assume it is at the beginning, and update it later
            m_Understands100Continue = true;
            m_HttpBehaviour         = HttpBehaviour.Unknown;

            // upon creation, the service point should be idle, by default
            m_IdleSince             = DateTime.Now;
            m_ExpiringTimer         = m_IdlingQueue.CreateTimer(ServicePointManager.IdleServicePointTimeoutDelegate, this);
            m_IdleConnectionGroupTimeoutDelegate = new TimerThread.Callback(IdleConnectionGroupTimeoutCallback);
        }
示例#11
0
        //
        // PERF:
        // removed some double initializations.
        // perf went from:
        // clocks per instruction CPI: 9,098.72 to 1,301.14
        // %app exclusive time: 2.92 to 0.43
        //
        /// <devdoc>
        ///    <para>
        ///       Basic Constructor for HTTP Protocol Class, Initializes to basic header state.
        ///    </para>
        /// </devdoc>
        internal HttpWebRequest(Uri uri, ServicePoint servicePoint)
        {
            if(Logging.On)Logging.Enter(Logging.Web, this, "HttpWebRequest", uri);

            (new WebPermission(NetworkAccess.Connect, uri)).Demand();

            // OOPS, This ctor can also be called with FTP scheme but then it should only allowed if going through the proxy
            // Something to think about...
            //if ((object)uri.Scheme != (object)Uri.UriSchemeHttp && (object)uri.Scheme != (object)Uri.UriSchemeHttps)
                //throw new ArgumentOutOfRangeException("uri");

            GlobalLog.Print("HttpWebRequest#" + ValidationHelper.HashString(this) + "::.ctor(" + uri.ToString() + ")");
            //
            // internal constructor, HttpWebRequest cannot be created directly
            // but only through WebRequest.Create() method
            // set defaults
            //
            _HttpRequestHeaders         = new WebHeaderCollection(WebHeaderCollectionType.HttpWebRequest);
            _Proxy                      = WebRequest.InternalDefaultWebProxy;
            _HttpWriteMode              = HttpWriteMode.Unknown;
            _MaximumAllowedRedirections = 50;
            _Timeout                    = WebRequest.DefaultTimeout;
            _TimerQueue                 = WebRequest.DefaultTimerQueue;
            _ReadWriteTimeout           = DefaultReadWriteTimeout;
            _MaximumResponseHeadersLength = DefaultMaximumResponseHeadersLength;
            _ContentLength              = -1;
            _OriginVerb                 = KnownHttpVerb.Get;
            _OriginUri                  = uri;
            _Uri                        = _OriginUri;
            _ServicePoint               = servicePoint;
            _RequestIsAsync             = TriState.Unspecified;

            SetupCacheProtocol(_OriginUri);

            if(Logging.On)Logging.Exit(Logging.Web, this, "HttpWebRequest", null);
        }
        /// <devdoc>
        ///     <para>
        ///         Downloads and compiles the script from a given Uri.
        ///         This code can be called by config for a downloaded control, we need to assert.
        ///         This code is called holding the lock.
        ///     </para>
        /// </devdoc>
        private AutoWebProxyState DownloadAndCompile(Uri location, out AutoWebProxyScriptWrapper newScriptInstance, ref int syncStatus)
        {
            GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() location:" + ValidationHelper.ToString(location));
            AutoWebProxyState newState = AutoWebProxyState.DownloadFailure;
            WebResponse response = null;
            TimerThread.Timer timer = null;
            newScriptInstance = null;

            // Can't assert this in declarative form (DCR?). This Assert() is needed to be able to create the request to download the proxy script.
            ExceptionHelper.WebPermissionUnrestricted.Assert();
            try {
                // here we have a reentrance issue due to config load.
                WebRequest request = WebRequest.Create(location);
                request.Timeout = Timeout.Infinite;
                request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
                request.ConnectionGroupName = "__WebProxyScript";
                
                // We have an opportunity here, if caching is disabled AppDomain-wide, to override it with a
                // custom, trivial cache-provider to get a similar semantic.
                //
                // We also want to have a backup caching key in the case when IE has locked an expired script response
                //
                if (request.CacheProtocol != null)
                {
                    GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Using backup caching.");
                    request.CacheProtocol = new RequestCacheProtocol(backupCache, request.CacheProtocol.Validator);
                }

                HttpWebRequest httpWebRequest = request as HttpWebRequest;
                if (httpWebRequest!=null)
                {
                    httpWebRequest.Accept = "*/*";
                    httpWebRequest.UserAgent = this.GetType().FullName + "/" + Environment.Version;
                    httpWebRequest.KeepAlive = false;
                    httpWebRequest.Pipelined = false;
                    httpWebRequest.InternalConnectionGroup = true;
                }
                else
                {
                    FtpWebRequest ftpWebRequest = request as FtpWebRequest;
                    if (ftpWebRequest!=null)
                    {
                        ftpWebRequest.KeepAlive = false;
                    }
                }

                // Use no proxy, default cache - initiate the download.
                request.Proxy = null;
                request.Credentials = webProxy.Credentials;

                // Set this up with the abortable lock to abort this too.
                LockRequest(request, ref syncStatus);
                if (syncStatus != SyncStatus.RequestOwner)
                {
                    throw new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
                }

                // Use our own timeout timer so that it can encompass the whole request, not just the headers.
                if (s_TimerQueue == null)
                {
                    s_TimerQueue = TimerThread.GetOrCreateQueue(SettingsSectionInternal.Section.DownloadTimeout);
                }
                timer = s_TimerQueue.CreateTimer(s_TimerCallback, request);
                response = request.GetResponse();

                // Check Last Modified.
                DateTime lastModified = DateTime.MinValue;
                HttpWebResponse httpResponse = response as HttpWebResponse;
                if (httpResponse != null)
                {
                    lastModified = httpResponse.LastModified;
                }
                else
                {
                    FtpWebResponse ftpResponse = response as FtpWebResponse;
                    if (ftpResponse != null)
                    {
                        lastModified = ftpResponse.LastModified;
                    }
                }
                GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() lastModified:" + lastModified.ToString() + " (script):" + (scriptInstance == null ? "(null)" : scriptInstance.LastModified.ToString()));
                if (scriptInstance != null && lastModified != DateTime.MinValue && scriptInstance.LastModified == lastModified)
                {
                    newScriptInstance = scriptInstance;
                    newState = AutoWebProxyState.CompilationSuccess;
                }
                else
                {
                    string scriptBody = null;
                    byte[] scriptBuffer = null;
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        SingleItemRequestCache.ReadOnlyStream ros = responseStream as SingleItemRequestCache.ReadOnlyStream;
                        if (ros != null)
                        {
                            scriptBuffer = ros.Buffer;
                        }
                        if (scriptInstance != null && scriptBuffer != null && scriptBuffer == scriptInstance.Buffer)
                        {
                            scriptInstance.LastModified = lastModified;
                            newScriptInstance = scriptInstance;
                            newState = AutoWebProxyState.CompilationSuccess;
                            GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Buffer matched - reusing engine.");
                        }
                        else
                        {
                            using (StreamReader streamReader = new StreamReader(responseStream))
                            {
                                scriptBody = streamReader.ReadToEnd();
                            }
                        }
                    }

                    WebResponse tempResponse = response;
                    response = null;
                    tempResponse.Close();
                    timer.Cancel();
                    timer = null;

                    if (newState != AutoWebProxyState.CompilationSuccess)
                    {
                        newState = AutoWebProxyState.DownloadSuccess;

                        GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() IsFromCache:" + tempResponse.IsFromCache.ToString() + " scriptInstance:" + ValidationHelper.HashString(scriptInstance));
                        if (scriptInstance != null && scriptBody == scriptInstance.ScriptBody)
                        {
                            GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Script matched - using existing engine.");
                            scriptInstance.LastModified = lastModified;
                            if (scriptBuffer != null)
                            {
                                scriptInstance.Buffer = scriptBuffer;
                            }
                            newScriptInstance = scriptInstance;
                            newState = AutoWebProxyState.CompilationSuccess;
                        }
                        else
                        {
                            GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Creating AutoWebProxyScriptWrapper.");
                            newScriptInstance = new AutoWebProxyScriptWrapper();
                            newScriptInstance.LastModified = lastModified;
                            newState = newScriptInstance.Compile(location, scriptBody, scriptBuffer);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (NclUtilities.IsFatal(exception)) throw;
                if(Logging.On)Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_script_download_compile_error, exception));
                GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Download() threw:" + ValidationHelper.ToString(exception));
            }
            finally
            {
                if (timer != null)
                {
                    timer.Cancel();
                }

                //                                                                                 
                try
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                finally
                {
                    WebPermission.RevertAssert();
                }
            }
            if (newState!=AutoWebProxyState.CompilationSuccess) {
                newScriptInstance = null;
            }
            GlobalLog.Print("AutoWebProxyScriptEngine#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() retuning newState:" + ValidationHelper.ToString(newState));
            return newState;
        }
示例#13
0
        /// <summary>
        ///    <para>Constructor - binds pool with a servicePoint and sets up a cleanup Timer to remove Idle Connections</para>
        /// </summary>
        internal ConnectionPool(ServicePoint servicePoint, int maxPoolSize, int minPoolSize, int idleTimeout, CreateConnectionDelegate createConnectionCallback) : base() {
            m_State                = State.Initializing;

            m_CreateConnectionCallback = createConnectionCallback;
            m_MaxPoolSize = maxPoolSize;
            m_MinPoolSize = minPoolSize;
            m_ServicePoint = servicePoint;

            Initialize();

            if (idleTimeout > 0) {
                // special case: if the timeout value is 1 then the timer thread should have a duration
                // of 1 to avoid having the timer callback run constantly
                m_CleanupQueue = TimerThread.GetOrCreateQueue(idleTimeout == 1 ? 1 : (idleTimeout / 2));
                m_CleanupQueue.CreateTimer(s_CleanupCallback, this);
            }
        }
示例#14
0
        private BaseWebProxyFinder.AutoWebProxyState DownloadAndCompile(Uri location)
        {
            BaseWebProxyFinder.AutoWebProxyState downloadFailure = BaseWebProxyFinder.AutoWebProxyState.DownloadFailure;
            WebResponse response = null;

            TimerThread.Timer         timer          = null;
            AutoWebProxyScriptWrapper scriptInstance = null;

            ExceptionHelper.WebPermissionUnrestricted.Assert();
            try
            {
                lock (this.lockObject)
                {
                    if (this.aborted)
                    {
                        throw new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
                    }
                    this.request = WebRequest.Create(location);
                }
                this.request.Timeout             = -1;
                this.request.CachePolicy         = new RequestCachePolicy(RequestCacheLevel.Default);
                this.request.ConnectionGroupName = "__WebProxyScript";
                if (this.request.CacheProtocol != null)
                {
                    this.request.CacheProtocol = new RequestCacheProtocol(this.backupCache, this.request.CacheProtocol.Validator);
                }
                HttpWebRequest request = this.request as HttpWebRequest;
                if (request != null)
                {
                    request.Accept    = "*/*";
                    request.UserAgent = base.GetType().FullName + "/" + Environment.Version;
                    request.KeepAlive = false;
                    request.Pipelined = false;
                    request.InternalConnectionGroup = true;
                }
                else
                {
                    FtpWebRequest request2 = this.request as FtpWebRequest;
                    if (request2 != null)
                    {
                        request2.KeepAlive = false;
                    }
                }
                this.request.Proxy       = null;
                this.request.Credentials = base.Engine.Credentials;
                if (timerQueue == null)
                {
                    timerQueue = TimerThread.GetOrCreateQueue(SettingsSectionInternal.Section.DownloadTimeout);
                }
                timer    = timerQueue.CreateTimer(timerCallback, this.request);
                response = this.request.GetResponse();
                DateTime        minValue  = DateTime.MinValue;
                HttpWebResponse response2 = response as HttpWebResponse;
                if (response2 != null)
                {
                    minValue = response2.LastModified;
                }
                else
                {
                    FtpWebResponse response3 = response as FtpWebResponse;
                    if (response3 != null)
                    {
                        minValue = response3.LastModified;
                    }
                }
                if (((this.scriptInstance != null) && (minValue != DateTime.MinValue)) && (this.scriptInstance.LastModified == minValue))
                {
                    scriptInstance  = this.scriptInstance;
                    downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                }
                else
                {
                    string scriptBody = null;
                    byte[] buffer     = null;
                    using (Stream stream = response.GetResponseStream())
                    {
                        SingleItemRequestCache.ReadOnlyStream stream2 = stream as SingleItemRequestCache.ReadOnlyStream;
                        if (stream2 != null)
                        {
                            buffer = stream2.Buffer;
                        }
                        if (((this.scriptInstance != null) && (buffer != null)) && (buffer == this.scriptInstance.Buffer))
                        {
                            this.scriptInstance.LastModified = minValue;
                            scriptInstance  = this.scriptInstance;
                            downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                        }
                        else
                        {
                            using (StreamReader reader = new StreamReader(stream))
                            {
                                scriptBody = reader.ReadToEnd();
                            }
                        }
                    }
                    WebResponse response4 = response;
                    response = null;
                    response4.Close();
                    timer.Cancel();
                    timer = null;
                    if (downloadFailure != BaseWebProxyFinder.AutoWebProxyState.Completed)
                    {
                        if ((this.scriptInstance != null) && (scriptBody == this.scriptInstance.ScriptBody))
                        {
                            this.scriptInstance.LastModified = minValue;
                            if (buffer != null)
                            {
                                this.scriptInstance.Buffer = buffer;
                            }
                            scriptInstance  = this.scriptInstance;
                            downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                        }
                        else
                        {
                            scriptInstance = new AutoWebProxyScriptWrapper {
                                LastModified = minValue
                            };
                            if (scriptInstance.Compile(location, scriptBody, buffer))
                            {
                                downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                            }
                            else
                            {
                                downloadFailure = BaseWebProxyFinder.AutoWebProxyState.CompilationFailure;
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (Logging.On)
                {
                    Logging.PrintWarning(Logging.Web, SR.GetString("net_log_proxy_script_download_compile_error", new object[] { exception }));
                }
            }
            finally
            {
                if (timer != null)
                {
                    timer.Cancel();
                }
                try
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                finally
                {
                    CodeAccessPermission.RevertAssert();
                    this.request = null;
                }
            }
            if ((downloadFailure == BaseWebProxyFinder.AutoWebProxyState.Completed) && (this.scriptInstance != scriptInstance))
            {
                if (this.scriptInstance != null)
                {
                    this.scriptInstance.Close();
                }
                this.scriptInstance = scriptInstance;
            }
            return(downloadFailure);
        }
示例#15
0
        internal HttpWebRequest(Uri proxyUri, Uri requestUri, HttpWebRequest orginalRequest) : this(proxyUri, null) {

            GlobalLog.Enter("HttpWebRequest::HttpWebRequest",
                            "proxyUri="+proxyUri+", requestUri="+requestUri
                            );

            _OriginVerb = KnownHttpVerb.Parse("CONNECT");

            //
            // CONNECT requests cannot be pipelined
            //

            Pipelined = false;

            //
            // each CONNECT request has a unique connection group name to avoid
            // non-CONNECT requests being made over the same connection
            //

            _OriginUri = requestUri;

            IsTunnelRequest = true;

            _ConnectionGroupName = ServicePointManager.SpecialConnectGroupName + "(" + UniqueGroupId + ")";
            m_InternalConnectionGroup = true;

            //
            // the CONNECT request must respond to a 407 as if it were a 401.
            // So we set up the server authentication state as if for a proxy
            //
            ServerAuthenticationState = new AuthenticationState(true);

            // CONNECT request is not suitable for caching
            CacheProtocol = null;

            m_ContinueTimeout = DefaultContinueTimeout;
            m_ContinueTimerQueue = s_ContinueTimerQueue;

            GlobalLog.Leave("HttpWebRequest::HttpWebRequest");
        }
        /// <summary>
        ///    <para>Constructor - binds pool with a servicePoint and sets up a cleanup Timer to nuke Idle Connections</para>
        /// </summary>
        internal ConnectionPool(ServicePoint servicePoint, int maxPoolSize, int minPoolSize, int idleTimeout, CreateConnectionDelegate createConnectionCallback) : base() {
            m_State                = State.Initializing;

            m_CreateConnectionCallback = createConnectionCallback;
            m_MaxPoolSize = maxPoolSize;
            m_MinPoolSize = minPoolSize;
            m_ServicePoint = servicePoint;

            Initialize();

            if (idleTimeout > 0) {
                m_CleanupQueue = TimerThread.GetOrCreateQueue(idleTimeout / 2);
                m_CleanupQueue.CreateTimer(s_CleanupCallback, this);
            }
        }
示例#17
0
        /*private*/ protected HttpWebRequest(SerializationInfo serializationInfo, StreamingContext streamingContext):base(serializationInfo, streamingContext) {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            ExceptionHelper.WebPermissionUnrestricted.Demand();
            if(Logging.On)Logging.Enter(Logging.Web, this, "HttpWebRequest", serializationInfo);

            _HttpRequestHeaders         = (WebHeaderCollection)serializationInfo.GetValue("_HttpRequestHeaders", typeof(WebHeaderCollection));
            _Proxy                      = (IWebProxy)serializationInfo.GetValue("_Proxy", typeof(IWebProxy));
            KeepAlive                   = serializationInfo.GetBoolean("_KeepAlive");
            Pipelined                   = serializationInfo.GetBoolean("_Pipelined");
            AllowAutoRedirect           = serializationInfo.GetBoolean("_AllowAutoRedirect");
            if (!serializationInfo.GetBoolean("_AllowWriteStreamBuffering"))
            {
                _Booleans &= ~Booleans.AllowWriteStreamBuffering;
            }
            HttpWriteMode               = (HttpWriteMode)serializationInfo.GetInt32("_HttpWriteMode");
            _MaximumAllowedRedirections = serializationInfo.GetInt32("_MaximumAllowedRedirections");
            _AutoRedirects              = serializationInfo.GetInt32("_AutoRedirects");
            _Timeout                    = serializationInfo.GetInt32("_Timeout");
            m_ContinueTimeout           = DefaultContinueTimeout; // This ctor is deprecated. Just set the default value.
            m_ContinueTimerQueue        = s_ContinueTimerQueue;
            try {
                _ReadWriteTimeout       = serializationInfo.GetInt32("_ReadWriteTimeout");
            }
            catch {
                _ReadWriteTimeout       = DefaultReadWriteTimeout;
            }
            try {
                _MaximumResponseHeadersLength = serializationInfo.GetInt32("_MaximumResponseHeadersLength");
            }
            catch {
                _MaximumResponseHeadersLength = DefaultMaximumResponseHeadersLength;
            }
            _ContentLength              = serializationInfo.GetInt64("_ContentLength");
            _MediaType                  = serializationInfo.GetString("_MediaType");
            _OriginVerb                 = KnownHttpVerb.Parse(serializationInfo.GetString("_OriginVerb"));
            _ConnectionGroupName        = serializationInfo.GetString("_ConnectionGroupName");
            ProtocolVersion             = (Version)serializationInfo.GetValue("_Version", typeof(Version));
            _OriginUri                  = (Uri)serializationInfo.GetValue("_OriginUri", typeof(Uri));
#if HTTP_HEADER_EXTENSIONS_SUPPORTED
            _NextExtension              = serializationInfo.GetInt32("_NextExtension");
#endif // HTTP_HEADER_EXTENSIONS_SUPPORTED

            SetupCacheProtocol(_OriginUri);
            if(Logging.On)Logging.Exit(Logging.Web, this, "HttpWebRequest", null);
#if DEBUG
            }
#endif
        }
        // Downloads and compiles the script from a given Uri.
        // This code can be called by config for a downloaded control, we need to assert.
        // This code is called holding the lock.
        private AutoWebProxyState DownloadAndCompile(Uri location)
        {
            GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() location:" + ValidationHelper.ToString(location));
            AutoWebProxyState newState = AutoWebProxyState.DownloadFailure;
            WebResponse       response = null;

            TimerThread.Timer         timer             = null;
            AutoWebProxyScriptWrapper newScriptInstance = null;

            // Can't assert this in declarative form (DCR?). This Assert() is needed to be able to create the request to download the proxy script.
            ExceptionHelper.WebPermissionUnrestricted.Assert();
            try
            {
                lock (lockObject)
                {
                    if (aborted)
                    {
                        throw new WebException(NetRes.GetWebStatusString("net_requestaborted",
                                                                         WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
                    }

                    request = WebRequest.Create(location);
                }

                request.Timeout             = Timeout.Infinite;
                request.CachePolicy         = new RequestCachePolicy(RequestCacheLevel.Default);
                request.ConnectionGroupName = "__WebProxyScript";

                // We have an opportunity here, if caching is disabled AppDomain-wide, to override it with a
                // custom, trivial cache-provider to get a similar semantic.
                //
                // We also want to have a backup caching key in the case when IE has locked an expired script response
                //
                if (request.CacheProtocol != null)
                {
                    GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Using backup caching.");
                    request.CacheProtocol = new RequestCacheProtocol(backupCache, request.CacheProtocol.Validator);
                }

                HttpWebRequest httpWebRequest = request as HttpWebRequest;
                if (httpWebRequest != null)
                {
                    httpWebRequest.Accept    = "*/*";
                    httpWebRequest.UserAgent = this.GetType().FullName + "/" + Environment.Version;
                    httpWebRequest.KeepAlive = false;
                    httpWebRequest.Pipelined = false;
                    httpWebRequest.InternalConnectionGroup = true;
                }
                else
                {
                    FtpWebRequest ftpWebRequest = request as FtpWebRequest;
                    if (ftpWebRequest != null)
                    {
                        ftpWebRequest.KeepAlive = false;
                    }
                }

                // Use no proxy, default cache - initiate the download.
                request.Proxy       = null;
                request.Credentials = Engine.Credentials;

                // Use our own timeout timer so that it can encompass the whole request, not just the headers.
                if (timerQueue == null)
                {
                    timerQueue = TimerThread.GetOrCreateQueue(SettingsSectionInternal.Section.DownloadTimeout);
                }
                timer    = timerQueue.CreateTimer(timerCallback, request);
                response = request.GetResponse();

                // Check Last Modified.
                DateTime        lastModified = DateTime.MinValue;
                HttpWebResponse httpResponse = response as HttpWebResponse;
                if (httpResponse != null)
                {
                    lastModified = httpResponse.LastModified;
                }
                else
                {
                    FtpWebResponse ftpResponse = response as FtpWebResponse;
                    if (ftpResponse != null)
                    {
                        lastModified = ftpResponse.LastModified;
                    }
                }
                GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() lastModified:" + lastModified.ToString() + " (script):" + (scriptInstance == null ? "(null)" : scriptInstance.LastModified.ToString()));
                if (scriptInstance != null && lastModified != DateTime.MinValue && scriptInstance.LastModified == lastModified)
                {
                    newScriptInstance = scriptInstance;
                    newState          = AutoWebProxyState.Completed;
                }
                else
                {
                    string scriptBody   = null;
                    byte[] scriptBuffer = null;
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        SingleItemRequestCache.ReadOnlyStream ros = responseStream as SingleItemRequestCache.ReadOnlyStream;
                        if (ros != null)
                        {
                            scriptBuffer = ros.Buffer;
                        }
                        if (scriptInstance != null && scriptBuffer != null && scriptBuffer == scriptInstance.Buffer)
                        {
                            scriptInstance.LastModified = lastModified;
                            newScriptInstance           = scriptInstance;
                            newState = AutoWebProxyState.Completed;
                            GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Buffer matched - reusing Engine.");
                        }
                        else
                        {
                            using (StreamReader streamReader = new StreamReader(responseStream))
                            {
                                scriptBody = streamReader.ReadToEnd();
                            }
                        }
                    }

                    WebResponse tempResponse = response;
                    response = null;
                    tempResponse.Close();
                    timer.Cancel();
                    timer = null;

                    if (newState != AutoWebProxyState.Completed)
                    {
                        GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() IsFromCache:" + tempResponse.IsFromCache.ToString() + " scriptInstance:" + ValidationHelper.HashString(scriptInstance));
                        if (scriptInstance != null && scriptBody == scriptInstance.ScriptBody)
                        {
                            GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Script matched - using existing Engine.");
                            scriptInstance.LastModified = lastModified;
                            if (scriptBuffer != null)
                            {
                                scriptInstance.Buffer = scriptBuffer;
                            }
                            newScriptInstance = scriptInstance;
                            newState          = AutoWebProxyState.Completed;
                        }
                        else
                        {
                            GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Creating AutoWebProxyScriptWrapper.");
                            newScriptInstance = new AutoWebProxyScriptWrapper();
                            newScriptInstance.LastModified = lastModified;

                            if (newScriptInstance.Compile(location, scriptBody, scriptBuffer))
                            {
                                newState = AutoWebProxyState.Completed;
                            }
                            else
                            {
                                newState = AutoWebProxyState.CompilationFailure;
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (Logging.On)
                {
                    Logging.PrintWarning(Logging.Web, SR.GetString(SR.net_log_proxy_script_download_compile_error, exception));
                }
                GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() Download() threw:" + ValidationHelper.ToString(exception));
            }
            finally
            {
                if (timer != null)
                {
                    timer.Cancel();
                }

                //
                try
                {
                    if (response != null)
                    {
                        response.Close();
                    }
                }
                finally
                {
                    WebPermission.RevertAssert();

                    // The request is not needed anymore. Set it to null, so if Abort() gets called,
                    // after this point, it will result in a no-op.
                    request = null;
                }
            }

            if ((newState == AutoWebProxyState.Completed) && (scriptInstance != newScriptInstance))
            {
                if (scriptInstance != null)
                {
                    scriptInstance.Close();
                }

                scriptInstance = newScriptInstance;
            }

            GlobalLog.Print("NetWebProxyFinder#" + ValidationHelper.HashString(this) + "::DownloadAndCompile() retuning newState:" + ValidationHelper.ToString(newState));
            return(newState);
        }
 internal ServicePoint(string host, int port, TimerThread.Queue defaultIdlingQueue, int defaultConnectionLimit, string lookupString, bool userChangedLimit, bool proxyServicePoint)
 {
     this.m_HostName = string.Empty;
     this.m_ProxyServicePoint = proxyServicePoint;
     this.m_ConnectionName = "ByHost:" + host + ":" + port.ToString(CultureInfo.InvariantCulture);
     this.m_IdlingQueue = defaultIdlingQueue;
     this.m_ConnectionLimit = defaultConnectionLimit;
     this.m_HostLoopbackGuess = TriState.Unspecified;
     this.m_LookupString = lookupString;
     this.m_UserChangedLimit = userChangedLimit;
     this.m_ConnectionGroupList = new Hashtable(10);
     this.m_ConnectionLeaseTimeout = -1;
     this.m_ReceiveBufferSize = -1;
     this.m_Host = host;
     this.m_Port = port;
     this.m_HostMode = true;
     this.m_IdleSince = DateTime.Now;
     this.m_ExpiringTimer = this.m_IdlingQueue.CreateTimer(ServicePointManager.IdleServicePointTimeoutDelegate, this);
 }
 private BaseWebProxyFinder.AutoWebProxyState DownloadAndCompile(Uri location)
 {
     BaseWebProxyFinder.AutoWebProxyState downloadFailure = BaseWebProxyFinder.AutoWebProxyState.DownloadFailure;
     WebResponse response = null;
     TimerThread.Timer timer = null;
     AutoWebProxyScriptWrapper scriptInstance = null;
     ExceptionHelper.WebPermissionUnrestricted.Assert();
     try
     {
         lock (this.lockObject)
         {
             if (this.aborted)
             {
                 throw new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
             }
             this.request = WebRequest.Create(location);
         }
         this.request.Timeout = -1;
         this.request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default);
         this.request.ConnectionGroupName = "__WebProxyScript";
         if (this.request.CacheProtocol != null)
         {
             this.request.CacheProtocol = new RequestCacheProtocol(this.backupCache, this.request.CacheProtocol.Validator);
         }
         HttpWebRequest request = this.request as HttpWebRequest;
         if (request != null)
         {
             request.Accept = "*/*";
             request.UserAgent = base.GetType().FullName + "/" + Environment.Version;
             request.KeepAlive = false;
             request.Pipelined = false;
             request.InternalConnectionGroup = true;
         }
         else
         {
             FtpWebRequest request2 = this.request as FtpWebRequest;
             if (request2 != null)
             {
                 request2.KeepAlive = false;
             }
         }
         this.request.Proxy = null;
         this.request.Credentials = base.Engine.Credentials;
         if (timerQueue == null)
         {
             timerQueue = TimerThread.GetOrCreateQueue(SettingsSectionInternal.Section.DownloadTimeout);
         }
         timer = timerQueue.CreateTimer(timerCallback, this.request);
         response = this.request.GetResponse();
         DateTime minValue = DateTime.MinValue;
         HttpWebResponse response2 = response as HttpWebResponse;
         if (response2 != null)
         {
             minValue = response2.LastModified;
         }
         else
         {
             FtpWebResponse response3 = response as FtpWebResponse;
             if (response3 != null)
             {
                 minValue = response3.LastModified;
             }
         }
         if (((this.scriptInstance != null) && (minValue != DateTime.MinValue)) && (this.scriptInstance.LastModified == minValue))
         {
             scriptInstance = this.scriptInstance;
             downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
         }
         else
         {
             string scriptBody = null;
             byte[] buffer = null;
             using (Stream stream = response.GetResponseStream())
             {
                 SingleItemRequestCache.ReadOnlyStream stream2 = stream as SingleItemRequestCache.ReadOnlyStream;
                 if (stream2 != null)
                 {
                     buffer = stream2.Buffer;
                 }
                 if (((this.scriptInstance != null) && (buffer != null)) && (buffer == this.scriptInstance.Buffer))
                 {
                     this.scriptInstance.LastModified = minValue;
                     scriptInstance = this.scriptInstance;
                     downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                 }
                 else
                 {
                     using (StreamReader reader = new StreamReader(stream))
                     {
                         scriptBody = reader.ReadToEnd();
                     }
                 }
             }
             WebResponse response4 = response;
             response = null;
             response4.Close();
             timer.Cancel();
             timer = null;
             if (downloadFailure != BaseWebProxyFinder.AutoWebProxyState.Completed)
             {
                 if ((this.scriptInstance != null) && (scriptBody == this.scriptInstance.ScriptBody))
                 {
                     this.scriptInstance.LastModified = minValue;
                     if (buffer != null)
                     {
                         this.scriptInstance.Buffer = buffer;
                     }
                     scriptInstance = this.scriptInstance;
                     downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                 }
                 else
                 {
                     scriptInstance = new AutoWebProxyScriptWrapper {
                         LastModified = minValue
                     };
                     if (scriptInstance.Compile(location, scriptBody, buffer))
                     {
                         downloadFailure = BaseWebProxyFinder.AutoWebProxyState.Completed;
                     }
                     else
                     {
                         downloadFailure = BaseWebProxyFinder.AutoWebProxyState.CompilationFailure;
                     }
                 }
             }
         }
     }
     catch (Exception exception)
     {
         if (Logging.On)
         {
             Logging.PrintWarning(Logging.Web, SR.GetString("net_log_proxy_script_download_compile_error", new object[] { exception }));
         }
     }
     finally
     {
         if (timer != null)
         {
             timer.Cancel();
         }
         try
         {
             if (response != null)
             {
                 response.Close();
             }
         }
         finally
         {
             CodeAccessPermission.RevertAssert();
             this.request = null;
         }
     }
     if ((downloadFailure == BaseWebProxyFinder.AutoWebProxyState.Completed) && (this.scriptInstance != scriptInstance))
     {
         if (this.scriptInstance != null)
         {
             this.scriptInstance.Close();
         }
         this.scriptInstance = scriptInstance;
     }
     return downloadFailure;
 }