public override WebResponse GetResponse()
        {
            IAsyncResult result;

            this.m_syncHint = true;
            try
            {
                result = this.BeginGetResponse(null, null);
                if (((this.Timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(this.Timeout, false) || !result.IsCompleted))
                {
                    if (this.m_response != null)
                    {
                        this.m_response.Close();
                    }
                    Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.Timeout), WebExceptionStatus.Timeout);
                    throw exception;
                }
            }
            catch (Exception exception2)
            {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "GetResponse", exception2);
                }
                throw;
            }
            return(this.EndGetResponse(result));
        }
Пример #2
0
        protected override void Dispose(bool disposing)
        {
            GlobalLog.Print("TlsStream::Dispose()");
            if (Interlocked.Exchange(ref m_ShutDown, 1) == 1)
            {
                return;
            }

            if (disposing)
            {
                m_DestinationHost    = null;
                m_SecureChannel      = null;
                m_ArrivingData       = null;
                m_ClientCertificates = null;

                // This might leak memory but we do clenup through garbage-collection
                if (m_Exception == null)
                {
                    m_Exception = new WebException(
                        NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.ConnectionClosed),
                        WebExceptionStatus.ConnectionClosed);
                }
            }
            //
            // only resource we need to free is the network stream, since this
            // is based on the client socket, closing the stream will cause us
            // to flush the data to the network, close the stream and (in the
            // NetoworkStream code) might close the socket as well if we own it.
            //
            base.Dispose(disposing);
        }
 private void CheckError()
 {
     if (this.m_Request.Aborted)
     {
         throw new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
     }
 }
Пример #4
0
        public override WebResponse GetResponse()
        {
            GlobalLog.Enter("FileWebRequest::GetResponse");

            m_syncHint = true;

            IAsyncResult result;

            try {
                result = BeginGetResponse(null, null);

                if ((Timeout != System.Threading.Timeout.Infinite) && !result.IsCompleted)
                {
                    if (!result.AsyncWaitHandle.WaitOne(Timeout, false) || !result.IsCompleted)
                    {
                        if (m_response != null)
                        {
                            m_response.Close();
                        }
                        Exception e = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.Timeout), WebExceptionStatus.Timeout);
                        GlobalLog.LeaveException("FileWebRequest::GetResponse", e);
                        throw e;
                    }
                }
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "GetResponse", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::GetResponse");
            }
            return(EndGetResponse(result));
        }
Пример #5
0
        private void CompletePayloadReadOperation(int bytesRead)
        {
            Contract.Requires(bytesRead >= 0);
            Contract.Assert(readState == ReadState.Payload,
                            "Chunk payload read completion must only be invoked when we're processing payload data.");

            // Getting EOF in the middle of a chunk is a failure.
            if (bytesRead == 0)
            {
                throw new WebException(NetRes.GetWebStatusString("net_requestaborted",
                                                                 WebExceptionStatus.ConnectionClosed), WebExceptionStatus.ConnectionClosed);
            }

            currentChunkBytesRead += bytesRead;
            Contract.Assert(currentChunkBytesRead <= currentChunkLength,
                            "Read more bytes than available in the current chunk.");

            int totalBytesRead = currentOperationBytesRead + bytesRead;

            if (currentChunkBytesRead == currentChunkLength)
            {
                // We're done reading this chunk.
                readState = ReadState.PayloadEnd;
            }

            currentOperationBytesRead = 0;
            CompleteUserRead(totalBytesRead);
        }
Пример #6
0
 protected Exception GenerateException(WebExceptionStatus status, Exception innerException)
 {
     return(new WebException(
                NetRes.GetWebStatusString("net_connclosed", status),
                innerException,
                status,
                null /* no response */));
 }
Пример #7
0
        private PooledStream Get(object owningObject, int result, ref bool continueLoop, ref WaitHandle[] waitHandles)
        {
            PooledStream fromPool = null;
            int          num2     = result;

            switch (num2)
            {
            case 1:
            {
                int num = Interlocked.Decrement(ref this.m_WaitCount);
                continueLoop = false;
                Exception resError = this.m_ResError;
                if (num == 0)
                {
                    this.CancelErrorCallback();
                }
                throw resError;
            }

            case 2:
                try
                {
                    continueLoop = true;
                    fromPool     = this.UserCreateRequest();
                    if (fromPool != null)
                    {
                        fromPool.PostPop(owningObject);
                        Interlocked.Decrement(ref this.m_WaitCount);
                        continueLoop = false;
                        return(fromPool);
                    }
                    if (((this.Count >= this.MaxPoolSize) && (this.MaxPoolSize != 0)) && !this.ReclaimEmancipatedObjects())
                    {
                        waitHandles = new WaitHandle[] { this.m_WaitHandles[0], this.m_WaitHandles[1] };
                    }
                    return(fromPool);
                }
                finally
                {
                    this.CreationMutex.ReleaseMutex();
                }
                break;

            default:
                if (num2 == 0x102)
                {
                    Interlocked.Decrement(ref this.m_WaitCount);
                    continueLoop = false;
                    throw new WebException(NetRes.GetWebStatusString("net_timeout", WebExceptionStatus.ConnectFailure), WebExceptionStatus.Timeout);
                }
                break;
            }
            Interlocked.Decrement(ref this.m_WaitCount);
            fromPool     = this.GetFromPool(owningObject);
            continueLoop = false;
            return(fromPool);
        }
        private static void ConnectSocketCallback(IAsyncResult asyncResult)
        {
            ConnectSocketState asyncState     = (ConnectSocketState)asyncResult.AsyncState;
            Socket             socket         = null;
            IPAddress          address        = null;
            Exception          exception      = null;
            Exception          e              = null;
            WebExceptionStatus connectFailure = WebExceptionStatus.ConnectFailure;

            try
            {
                connectFailure = asyncState.servicePoint.ConnectSocketInternal(asyncState.connectFailure, asyncState.s4, asyncState.s6, ref socket, ref address, asyncState, asyncResult, -1, out exception);
            }
            catch (SocketException exception3)
            {
                e = exception3;
            }
            catch (ObjectDisposedException exception4)
            {
                e = exception4;
            }
            switch (connectFailure)
            {
            case WebExceptionStatus.Pending:
                return;

            case WebExceptionStatus.Success:
                try
                {
                    asyncState.servicePoint.CompleteGetConnection(asyncState.s4, asyncState.s6, socket, address);
                }
                catch (SocketException exception5)
                {
                    e = exception5;
                }
                catch (ObjectDisposedException exception6)
                {
                    e = exception6;
                }
                break;

            default:
                e = new WebException(NetRes.GetWebStatusString(connectFailure), ((connectFailure == WebExceptionStatus.ProxyNameResolutionFailure) || (connectFailure == WebExceptionStatus.NameResolutionFailure)) ? asyncState.servicePoint.Host : null, exception, connectFailure, null, WebExceptionInternalStatus.ServicePointFatal);
                break;
            }
            try
            {
                asyncState.pooledStream.ConnectionCallback(asyncState.owner, e, socket, address);
            }
            catch
            {
                if ((socket == null) || !socket.CleanedUp)
                {
                    throw;
                }
            }
        }
Пример #9
0
 private void CheckAsyncResult(IAsyncResult ar)
 {
     // A null return indicates that the connection was closed underneath us.
     if (ar == null)
     {
         throw new WebException(NetRes.GetWebStatusString("net_requestaborted",
                                                          WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
     }
 }
Пример #10
0
 internal void Abort()
 {
     if (this.m_ResError == null)
     {
         this.m_ResError = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
     }
     this.ErrorEvent.Set();
     this.m_ErrorOccured = true;
     this.m_ErrorTimer   = s_CancelErrorQueue.CreateTimer(s_CancelErrorCallback, this);
 }
Пример #11
0
        public override void Abort()
        {
            GlobalLog.Enter("FileWebRequest::Abort");
            if (Logging.On)
            {
                Logging.PrintWarning(Logging.Web, NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled));
            }
            try {
                if (Interlocked.Increment(ref m_Aborted) == 1)
                {
                    LazyAsyncResult readAResult  = m_ReadAResult;
                    LazyAsyncResult writeAResult = m_WriteAResult;

                    WebException webException = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);

                    Stream requestStream = m_stream;

                    if (readAResult != null && !readAResult.IsCompleted)
                    {
                        readAResult.InvokeCallback(webException);
                    }
                    if (writeAResult != null && !writeAResult.IsCompleted)
                    {
                        writeAResult.InvokeCallback(webException);
                    }

                    if (requestStream != null)
                    {
                        if (requestStream is ICloseEx)
                        {
                            ((ICloseEx)requestStream).CloseEx(CloseExState.Abort);
                        }
                        else
                        {
                            requestStream.Close();
                        }
                    }

                    if (m_response != null)
                    {
                        ((ICloseEx)m_response).CloseEx(CloseExState.Abort);
                    }
                }
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "Abort", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::Abort");
            }
        }
 public override void Abort()
 {
     if (Logging.On)
     {
         Logging.PrintWarning(Logging.Web, NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled));
     }
     try
     {
         if (Interlocked.Increment(ref this.m_Aborted) == 1)
         {
             LazyAsyncResult readAResult  = this.m_ReadAResult;
             LazyAsyncResult writeAResult = this.m_WriteAResult;
             WebException    result       = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
             Stream          stream       = this.m_stream;
             if ((readAResult != null) && !readAResult.IsCompleted)
             {
                 readAResult.InvokeCallback(result);
             }
             if ((writeAResult != null) && !writeAResult.IsCompleted)
             {
                 writeAResult.InvokeCallback(result);
             }
             if (stream != null)
             {
                 if (stream is ICloseEx)
                 {
                     ((ICloseEx)stream).CloseEx(CloseExState.Abort);
                 }
                 else
                 {
                     stream.Close();
                 }
             }
             if (this.m_response != null)
             {
                 ((ICloseEx)this.m_response).CloseEx(CloseExState.Abort);
             }
         }
     }
     catch (Exception exception2)
     {
         if (Logging.On)
         {
             Logging.Exception(Logging.Web, this, "Abort", exception2);
         }
         throw;
     }
 }
Пример #13
0
        internal static ServicePoint FindServicePoint(Uri address, IWebProxy proxy, out ProxyChain chain, ref HttpAbortDelegate abortDelegate, ref int abortState)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }
            bool isProxyServicePoint = false;

            chain = null;
            Uri current = null;

            if ((proxy != null) && !address.IsLoopback)
            {
                IAutoWebProxy proxy2 = proxy as IAutoWebProxy;
                if (proxy2 != null)
                {
                    chain         = proxy2.GetProxies(address);
                    abortDelegate = chain.HttpAbortDelegate;
                    try
                    {
                        Thread.MemoryBarrier();
                        if (abortState != 0)
                        {
                            Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
                            throw exception;
                        }
                        chain.Enumerator.MoveNext();
                        current = chain.Enumerator.Current;
                    }
                    finally
                    {
                        abortDelegate = null;
                    }
                }
                else if (!proxy.IsBypassed(address))
                {
                    current = proxy.GetProxy(address);
                }
                if (current != null)
                {
                    address             = current;
                    isProxyServicePoint = true;
                }
            }
            return(FindServicePointHelper(address, isProxyServicePoint));
        }
        internal Socket GetConnection(PooledStream PooledStream, object owner, bool async, out IPAddress address, ref Socket abortSocket, ref Socket abortSocket6, int timeout)
        {
            Socket             socket         = null;
            Socket             socket2        = null;
            Socket             socket3        = null;
            Exception          exception      = null;
            WebExceptionStatus connectFailure = WebExceptionStatus.ConnectFailure;

            address = null;
            if (Socket.OSSupportsIPv4)
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            }
            if (Socket.OSSupportsIPv6)
            {
                socket2 = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
            }
            abortSocket  = socket;
            abortSocket6 = socket2;
            ConnectSocketState state = null;

            if (async)
            {
                state = new ConnectSocketState(this, PooledStream, owner, socket, socket2);
            }
            connectFailure = this.ConnectSocket(socket, socket2, ref socket3, ref address, state, timeout, out exception);
            if (connectFailure == WebExceptionStatus.Pending)
            {
                return(null);
            }
            if (connectFailure != WebExceptionStatus.Success)
            {
                throw new WebException(NetRes.GetWebStatusString(connectFailure), ((connectFailure == WebExceptionStatus.ProxyNameResolutionFailure) || (connectFailure == WebExceptionStatus.NameResolutionFailure)) ? this.Host : null, exception, connectFailure, null, WebExceptionInternalStatus.ServicePointFatal);
            }
            if (socket3 == null)
            {
                throw new IOException(SR.GetString("net_io_transportfailure"));
            }
            this.CompleteGetConnection(socket, socket2, socket3, address);
            return(socket3);
        }
        /// <summary>
        ///    <para>Retrieves the pooled stream out of the pool, does this by using the result
        ///    of a WaitAny as input, and then based on whether it has a mutex, event, semaphore,
        ///     or timeout decides what action to take</para>
        /// </summary>
        private PooledStream Get(object owningObject, int result, ref bool continueLoop, ref WaitHandle [] waitHandles)
        {
            PooledStream pooledStream = null;

            GlobalLog.Enter("ConnectionPool#" + ValidationHelper.HashString(this) + "::Get", result.ToString());


            // From the WaitAny docs: "If more than one object became signaled during
            // the call, this is the array index of the signaled object with the
            // smallest index value of all the signaled objects."  This is important
            // so that the free object signal will be returned before a creation
            // signal.

            switch (result)
            {
            case WaitTimeout:
                Interlocked.Decrement(ref m_WaitCount);
                continueLoop = false;
                GlobalLog.Leave("ConnectionPool#" + ValidationHelper.HashString(this) + "::Get", "throw Timeout WebException");
                throw new WebException(NetRes.GetWebStatusString("net_timeout", WebExceptionStatus.ConnectFailure), WebExceptionStatus.Timeout);


            case ErrorHandleIndex:
                // Throw the error that PoolCreateRequest stashed.
                int newWaitCount = Interlocked.Decrement(ref m_WaitCount);
                continueLoop = false;
                Exception exceptionToThrow = m_ResError;
                if (newWaitCount == 0)
                {
                    CancelErrorCallback();
                }
                throw exceptionToThrow;

            case CreationHandleIndex:
                try {
                    continueLoop = true;
                    pooledStream = UserCreateRequest();

                    if (null != pooledStream)
                    {
                        pooledStream.PostPop(owningObject);
                        Interlocked.Decrement(ref m_WaitCount);
                        continueLoop = false;
                    }
                    else
                    {
                        // If we were not able to create an object, check to see if
                        // we reached MaxPoolSize.  If so, we will no longer wait on
                        // the CreationHandle, but instead wait for a free object or
                        // the timeout.

                        // BUG - if we receive the CreationHandle midway into the wait
                        // period and re-wait, we will be waiting on the full period
                        if (Count >= MaxPoolSize && 0 != MaxPoolSize)
                        {
                            if (!ReclaimEmancipatedObjects())
                            {
                                // modify handle array not to wait on creation mutex anymore
                                waitHandles    = new WaitHandle[2];
                                waitHandles[0] = m_WaitHandles[0];
                                waitHandles[1] = m_WaitHandles[1];
                            }
                        }
                    }
                }
                finally {
                    CreationMutex.ReleaseMutex();
                }
                break;

            default:
                //
                //    guaranteed available inventory
                //
                Interlocked.Decrement(ref m_WaitCount);
                pooledStream = GetFromPool(owningObject);
                continueLoop = false;
                break;
            }
            GlobalLog.Leave("ConnectionPool#" + ValidationHelper.HashString(this) + "::Get", ValidationHelper.HashString(pooledStream));
            return(pooledStream);
        }
        // If abortState becomes non-zero, the attempt to find a service point has been aborted.
        internal static ServicePoint FindServicePoint(Uri address, IWebProxy proxy, out ProxyChain chain, ref HttpAbortDelegate abortDelegate, ref int abortState)
        {
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }
            GlobalLog.Enter("ServicePointManager::FindServicePoint() address:" + address.ToString());

            bool isProxyServicePoint = false;

            chain = null;

            //
            // find proxy info, and then switch on proxy
            //
            Uri proxyAddress = null;

            if (proxy != null && !address.IsLoopback)
            {
                IAutoWebProxy autoProxy = proxy as IAutoWebProxy;
                if (autoProxy != null)
                {
                    chain = autoProxy.GetProxies(address);

                    // Set up our ability to abort this MoveNext call.  Note that the current implementations of ProxyChain will only
                    // take time on the first call, so this is the only place we do this.  If a new ProxyChain takes time in later
                    // calls, this logic should be copied to other places MoveNext is called.
                    GlobalLog.Assert(abortDelegate == null, "ServicePointManager::FindServicePoint()|AbortDelegate already set.");
                    abortDelegate = chain.HttpAbortDelegate;
                    try
                    {
                        Thread.MemoryBarrier();
                        if (abortState != 0)
                        {
                            Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
                            GlobalLog.LeaveException("ServicePointManager::FindServicePoint() Request aborted before proxy lookup.", exception);
                            throw exception;
                        }

                        if (!chain.Enumerator.MoveNext())
                        {
                            GlobalLog.Assert("ServicePointManager::FindServicePoint()|GetProxies() returned zero proxies.");

/*
 *                          Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.RequestProhibitedByProxy), WebExceptionStatus.RequestProhibitedByProxy);
 *                          GlobalLog.LeaveException("ServicePointManager::FindServicePoint() Proxy prevented request.", exception);
 *                          throw exception;
 */
                        }
                        proxyAddress = chain.Enumerator.Current;
                    }
                    finally
                    {
                        abortDelegate = null;
                    }
                }
                else if (!proxy.IsBypassed(address))
                {
                    // use proxy support
                    // rework address
                    proxyAddress = proxy.GetProxy(address);
                }

                // null means DIRECT
                if (proxyAddress != null)
                {
                    address             = proxyAddress;
                    isProxyServicePoint = true;
                }
            }

            ServicePoint servicePoint = FindServicePointHelper(address, isProxyServicePoint);

            GlobalLog.Leave("ServicePointManager::FindServicePoint() servicePoint#" + ValidationHelper.HashString(servicePoint));
            return(servicePoint);
        }
        // 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);
        }
Пример #18
0
        /// <devdoc>
        ///    <para>
        ///       Used by the ServicePoint to find a free or new Connection
        ///       for use in making Requests, this is done with the cavet,
        ///       that once a Connection is "locked" it can only be used
        ///       by a specific request.
        ///
        ///     NOTE: For Whidbey: try to integrate this code into FindConnection()
        ///    </para>
        /// </devdoc>
        private Connection FindConnectionAuthenticationGroup(HttpWebRequest request, string connName)
        {
            Connection leastBusyConnection = null;

            GlobalLog.Print("ConnectionGroup::FindConnectionAuthenticationGroup [" + connName + "] m_ConnectionList.Count:" + m_ConnectionList.Count.ToString());

            //
            // First try and find a free Connection (i.e. one not busy with Authentication handshake)
            //   or try to find a Request that has already locked a specific Connection,
            //   if a matching Connection is found, then we're done
            //
            lock (m_ConnectionList) {
                Connection matchingConnection;
                matchingConnection = FindMatchingConnection(request, connName, out leastBusyConnection);
                if (matchingConnection != null)
                {
                    return(matchingConnection);
                }

                if (AuthenticationRequestQueue.Count == 0)
                {
                    if (leastBusyConnection != null)
                    {
                        if (request.LockConnection)
                        {
                            GlobalLog.Print("Assigning New Locked Request#" + request.GetHashCode().ToString());
                            leastBusyConnection.LockedRequest = request;
                        }
                        return(leastBusyConnection);
                    }
                }
                else if (leastBusyConnection != null)
                {
                    AsyncWaitHandle.Set();
                }
                AuthenticationRequestQueue.Enqueue(request);
            }

            //
            // If all the Connections are busy, then we queue ourselves and need to wait.   As soon as
            //   one of the Connections are free, we grab the lock, and see if we find ourselves
            //   at the head of the queue.  If not, we loop backaround.
            //   Care is taken to examine the request when we wakeup, in case the request is aborted.
            //
            while (true)
            {
                GlobalLog.Print("waiting");
                request.AbortDelegate = m_AbortDelegate;
                AsyncWaitHandle.WaitOne();
                GlobalLog.Print("wait up");
                lock (m_ConnectionList) {
                    if (m_Abort)
                    {
                        PruneAbortedRequests();
                    }
                    if (request.Aborted)
                    {
                        throw new WebException(
                                  NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled),
                                  WebExceptionStatus.RequestCanceled);
                    }

                    FindMatchingConnection(request, connName, out leastBusyConnection);
                    if (AuthenticationRequestQueue.Peek() == request)
                    {
                        GlobalLog.Print("dequeue");
                        AuthenticationRequestQueue.Dequeue();
                        if (leastBusyConnection != null)
                        {
                            if (request.LockConnection)
                            {
                                leastBusyConnection.LockedRequest = request;
                            }
                            return(leastBusyConnection);
                        }
                        AuthenticationRequestQueue.Enqueue(request);
                    }
                    if (leastBusyConnection == null)
                    {
                        AsyncWaitHandle.Reset();
                    }
                }
            }
        }
Пример #19
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);
        }