Enter() private method

private Enter ( string func ) : void
func string
return void
Beispiel #1
0
        //
        // This version of an Ssl Stream is for internal HttpWebrequest use.
        // This Ssl client owns the underlined socket
        // The TlsStream will own secured read/write and disposal of the passed "networkStream" stream.
        //
        public TlsStream(string destinationHost, NetworkStream networkStream, X509CertificateCollection clientCertificates, ServicePoint servicePoint, object initiatingRequest, ExecutionContext executionContext)
            : base(networkStream, true)
        {
            // WebRequest manages the execution context manually so we have to ensure we get one for SSL client certificate demand
            _ExecutionContext = executionContext;
            if (_ExecutionContext == null)
            {
                _ExecutionContext = ExecutionContext.Capture();
            }

            //


            GlobalLog.Enter("TlsStream::TlsStream", "host=" + destinationHost + ", #certs=" + ((clientCertificates == null) ? "none" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));
            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web, this, ".ctor", "host=" + destinationHost + ", #certs=" + ((clientCertificates == null) ? "null" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));
            }

            m_ExceptionStatus = WebExceptionStatus.SecureChannelFailure;
            m_Worker          = new SslState(networkStream, initiatingRequest is HttpWebRequest, SettingsSectionInternal.Section.EncryptionPolicy);

            m_DestinationHost    = destinationHost;
            m_ClientCertificates = clientCertificates;

            RemoteCertValidationCallback certValidationCallback = servicePoint.SetupHandshakeDoneProcedure(this, initiatingRequest);

            m_Worker.SetCertValidationDelegate(certValidationCallback);

            // The Handshake is NOT done at this point
            GlobalLog.Leave("TlsStream::TlsStream (Handshake is not done)");
        }
Beispiel #2
0
        private static void GetRequestStreamCallback(object state)
        {
            GlobalLog.Enter("FileWebRequest::GetRequestStreamCallback");
            LazyAsyncResult asyncResult = (LazyAsyncResult)state;
            FileWebRequest  request     = (FileWebRequest)asyncResult.AsyncObject;

            try
            {
                if (request.m_stream == null)
                {
                    request.m_stream     = new FileWebStream(request, request.m_uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.Read);
                    request.m_fileAccess = FileAccess.Write;
                    request.m_writing    = true;
                }
            }
            catch (Exception e)
            {
                // any exceptions previously thrown must be passed to the callback
                Exception ex = new WebException(e.Message, e);
                GlobalLog.LeaveException("FileWebRequest::GetRequestStreamCallback", ex);

                // if the callback throws, correct behavior is to crash the process
                asyncResult.InvokeCallback(ex);
                return;
            }

            // if the callback throws, correct behavior is to crash the process
            asyncResult.InvokeCallback(request.m_stream);
            GlobalLog.Leave("FileWebRequest::GetRequestStreamCallback");
        }
Beispiel #3
0
        internal static byte[] EncodingRightGetBytes(string rawString)
        {
            GlobalLog.Enter("BasicClient::EncodingRightGetBytes", "[" + rawString.Length.ToString() + ":" + rawString + "]");
            //
            // in order to know if there will not be any '?' translations (which means
            // we should use the Default Encoding) we need to attempt encoding and then decoding.
            //
            GlobalLog.Print("BasicClient::EncodingRightGetBytes(): Default Encoding is:" + Encoding.Default.EncodingName);

            byte[] bytes   = Encoding.Default.GetBytes(rawString);
            string rawCopy = Encoding.Default.GetString(bytes);
            bool   canMapToCurrentCodePage = string.Compare(rawString, rawCopy, false, CultureInfo.InvariantCulture) == 0;

            GlobalLog.Print("BasicClient::EncodingRightGetBytes(): canMapToCurrentCodePage:" + canMapToCurrentCodePage.ToString());

            if (!canMapToCurrentCodePage)
            {
                throw ExceptionHelper.MethodNotSupportedException;

                /*
                 * GlobalLog.Print("BasicClient::EncodingRightGetBytes(): using:" + Encoding.UTF8.EncodingName);
                 * bytes = Encoding.UTF8.GetBytes(rawString);
                 *
                 * string blob = "=?utf-8?B?" + Convert.ToBase64String(bytes) + "?=";
                 * bytes = Encoding.ASCII.GetBytes(blob);
                 */
            }

            GlobalLog.Dump(bytes);
            GlobalLog.Leave("BasicClient::EncodingRightGetBytes", bytes.Length.ToString());

            return(bytes);
        }
        void ICloseEx.CloseEx(CloseExState closeState)
        {
            GlobalLog.Enter("FileWebResponse::Close()");
            try {
                if (!m_closed)
                {
                    m_closed = true;

                    Stream chkStream = m_stream;
                    if (chkStream != null)
                    {
                        if (chkStream is ICloseEx)
                        {
                            ((ICloseEx)chkStream).CloseEx(closeState);
                        }
                        else
                        {
                            chkStream.Close();
                        }
                        m_stream = null;
                    }
                }
            }
            finally {
                GlobalLog.Leave("FileWebResponse::Close()");
            }
        }
Beispiel #5
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));
        }
Beispiel #6
0
        private static uint Verify(SafeX509ChainHandle chainContext, ref Interop.Crypt32.CERT_CHAIN_POLICY_PARA cpp)
        {
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Enter("SecureChannel::VerifyChainPolicy", "chainContext=" + chainContext + ", options=" + String.Format("0x{0:x}", cpp.dwFlags));
            }

            var status = new Interop.Crypt32.CERT_CHAIN_POLICY_STATUS();

            status.cbSize = (uint)Marshal.SizeOf <Interop.Crypt32.CERT_CHAIN_POLICY_STATUS>();

            bool errorCode =
                Interop.Crypt32.CertVerifyCertificateChainPolicy(
                    (IntPtr)Interop.Crypt32.CertChainPolicy.CERT_CHAIN_POLICY_SSL,
                    chainContext,
                    ref cpp,
                    ref status);

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Print("SecureChannel::VerifyChainPolicy() CertVerifyCertificateChainPolicy returned: " + errorCode);
#if TRACE_VERBOSE
                GlobalLog.Print("SecureChannel::VerifyChainPolicy() error code: " + status.dwError + String.Format(" [0x{0:x8}", status.dwError) + " " + Interop.MapSecurityStatus(status.dwError) + "]");
#endif
                GlobalLog.Leave("SecureChannel::VerifyChainPolicy", status.dwError.ToString());
            }

            return(status.dwError);
        }
Beispiel #7
0
        //
        // this method runs in the context of the user Begin call .
        //
        private static void WrappedGetRequestStreamCallback(object state)
        {
            GlobalLog.Enter("FileWebRequest::GetRequestStreamCallback");
            ContextAwareResult asyncResult = (ContextAwareResult)state;
            FileWebRequest     request     = (FileWebRequest)asyncResult.AsyncObject;

            try
            {
                if (request.m_stream == null)
                {
                    request.m_stream     = new FileWebStream(request, request.m_uri.LocalPath, FileMode.Create, FileAccess.Write, FileShare.Read);
                    request.m_fileAccess = FileAccess.Write;
                    request.m_writing    = true;
                    asyncResult.InvokeCallback(request.m_stream);
                    GlobalLog.Leave("FileWebRequest::GetRequestStreamCallback");
                }
            }
            catch (Exception e)
            {
                if (asyncResult.IsCompleted || NclUtilities.IsFatal(e))
                {
                    throw;
                }

                Exception ex = new WebException(e.Message, e);
                GlobalLog.LeaveException("FileWebRequest::GetRequestStreamCallback", ex);
                asyncResult.InvokeCallback(ex);
            }
        }
Beispiel #8
0
        public override WebResponse EndGetResponse(IAsyncResult asyncResult)
        {
            GlobalLog.Enter("FileWebRequest::EndGetResponse");

            WebResponse response;

            try {
                ContextAwareResult ar = asyncResult as ContextAwareResult;
                if (asyncResult == null || ar == null)
                {
                    Exception e = asyncResult == null? new ArgumentNullException("asyncResult"): new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "asyncResult");
                    GlobalLog.LeaveException("FileWebRequest::EndGetRequestStream", e);
                    throw e;
                }


                object result = ar.InternalWaitForCompletion();
                if (result is Exception)
                {
                    throw (Exception)result;
                }
                response      = (WebResponse)result;
                m_readPending = false;
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "EndGetResponse", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::EndGetResponse");
            }
            return(response);
        }
 /// <include file='doc\filewebresponse.uex' path='docs/doc[@for="FileWebResponse.GetResponseStream"]/*' />
 public override Stream GetResponseStream()
 {
     GlobalLog.Enter("FileWebResponse::GetResponseStream()");
     CheckDisposed();
     GlobalLog.Leave("FileWebResponse::GetResponseStream()");
     return(m_stream);
 }
        /// <devdoc>
        ///    <para>Creates a new PooledStream is allowable</para>
        /// </devdoc>
        private PooledStream UserCreateRequest()
        {
            // called by user when they were not able to obtain a free object but
            // instead obtained creation mutex
            GlobalLog.Enter("ConnectionPool#" + ValidationHelper.HashString(this) + "::UserCreateRequest");

            PooledStream pooledStream = null;

            if (!ErrorOccurred)
            {
                if (Count < MaxPoolSize || 0 == MaxPoolSize)
                {
                    // If we have an odd number of total objects, reclaim any dead objects.
                    // If we did not find any objects to reclaim, create a new one.

                    //
                    if ((Count & 0x1) == 0x1 || !ReclaimEmancipatedObjects())
                    {
                        pooledStream = Create(m_CreateConnectionCallback);
                    }
                }
            }
            GlobalLog.Leave("ConnectionPool#" + ValidationHelper.HashString(this) + "::UserCreateRequest", ValidationHelper.HashString(pooledStream));
            return(pooledStream);
        }
Beispiel #11
0
        public static SafeFreeContextBufferChannelBinding QueryContextChannelBinding(SSPIInterface secModule, SafeDeleteContext securityContext, Interop.SspiCli.ContextAttribute contextAttribute)
        {
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Enter(nameof(QueryContextChannelBinding), contextAttribute.ToString());
            }

            SafeFreeContextBufferChannelBinding result;
            int errorCode = secModule.QueryContextChannelBinding(securityContext, contextAttribute, out result);

            if (errorCode != 0)
            {
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Leave(nameof(QueryContextChannelBinding), "ERROR = " + ErrorDescription(errorCode));
                }
                return(null);
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Leave(nameof(QueryContextChannelBinding), LoggingHash.HashString(result));
            }
            return(result);
        }
 //
 // SetTcpKeepAlive
 //
 // Enable/Disable the use of TCP keepalive option on ServicePoint
 // connections. This method does not affect existing ServicePoints.
 // When a ServicePoint is constructed it will inherit the current
 // settings.
 //
 // Parameters:
 //
 // enabled - if true enables the use of the TCP keepalive option
 // for ServicePoint connections.
 //
 // keepAliveTime - specifies the timeout, in milliseconds, with no
 // activity until the first keep-alive packet is sent. Ignored if
 // enabled parameter is false.
 //
 // keepAliveInterval - specifies the interval, in milliseconds, between
 // when successive keep-alive packets are sent if no acknowledgement is
 // received. Ignored if enabled parameter is false.
 //
 public static void SetTcpKeepAlive(
     bool enabled,
     int keepAliveTime,
     int keepAliveInterval)
 {
     GlobalLog.Enter(
         "ServicePointManager::SetTcpKeepAlive()" +
         " enabled: " + enabled.ToString() +
         " keepAliveTime: " + keepAliveTime.ToString() +
         " keepAliveInterval: " + keepAliveInterval.ToString()
         );
     if (enabled)
     {
         s_UseTcpKeepAlive = true;
         if (keepAliveTime <= 0)
         {
             throw new ArgumentOutOfRangeException("keepAliveTime");
         }
         if (keepAliveInterval <= 0)
         {
             throw new ArgumentOutOfRangeException("keepAliveInterval");
         }
         s_TcpKeepAliveTime     = keepAliveTime;
         s_TcpKeepAliveInterval = keepAliveInterval;
     }
     else
     {
         s_UseTcpKeepAlive      = false;
         s_TcpKeepAliveTime     = 0;
         s_TcpKeepAliveInterval = 0;
     }
     GlobalLog.Leave("ServicePointManager::SetTcpKeepAlive()");
 }
        internal HttpProxyTunnelRequest(Uri proxyUri, Uri requestUri) : base(proxyUri)
        {
            GlobalLog.Enter("HttpProxyTunnelRequest::HttpProxyTunnelRequest",
                            "proxyUri=" + proxyUri + ", requestUri=" + requestUri
                            );

            Method = "CONNECT";

            //
            // CONNECT requests cannot be pipelined
            //

            Pipelined      = false;
            m_originServer = requestUri;

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

            ConnectionGroupName = ServicePointManager.SpecialConnectGroupName + "(" + UniqueGroupId + ")";

            //
            // 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);

            GlobalLog.Leave("HttpProxyTunnelRequest::HttpProxyTunnelRequest");
        }
Beispiel #14
0
 public FileWebStream(FileWebRequest request, string path, FileMode mode, FileAccess access, FileShare sharing, int length, bool async)
     : base(path, mode, access, sharing, length, async)
 {
     GlobalLog.Enter("FileWebStream::FileWebStream");
     m_request = request;
     GlobalLog.Leave("FileWebStream::FileWebStream");
 }
Beispiel #15
0
        //
        // ScavengeIdleServicePoints -
        //
        //  Removes an Idled ServicePoint as it is detected to be
        //  expired and ready to be removed.  This is called fairly
        //  often, so we should be O(1) in the case when no service points
        //  have idled.
        //

        private static void ScavengeIdleServicePoints()
        {
            DateTime now = DateTime.Now;

            GlobalLog.Enter("ServicePointManager::ScavengeIdleServicePoints() now:" + (now.ToFileTime()).ToString());
            lock (s_StrongReferenceServicePointList) {
                while (s_StrongReferenceServicePointList.Count != 0)
                {
                    DateTime expiresAt = (DateTime)s_StrongReferenceServicePointList.GetKey(0);
                    if (ServicePoint.InternalTimedOut(now, expiresAt))
                    {
                        ServicePoint servicePoint = (ServicePoint)
                                                    s_StrongReferenceServicePointList.GetByIndex(0);
                        GlobalLog.Print("ServicePointManager::ScavengeIdleServicePoints() servicePoint#" + ValidationHelper.HashString(servicePoint) + " ExpiresAt:" + (servicePoint.ExpiresAt.ToFileTime()).ToString() + " is being removed");
                        s_StrongReferenceServicePointList.RemoveAt(0);
                    }
                    else
                    {
                        // if the first in the list isn't expired, than no one later is either
                        break;
                    }
                }
            }
            GlobalLog.Leave("ServicePointManager::ScavengeIdleServicePoints");
        }
        //
        // IDisposable
        //

        /// <include file='doc\filewebresponse.uex' path='docs/doc[@for="FileWebResponse.IDisposable.Dispose"]/*' />
        /// <internalonly/>
        void IDisposable.Dispose()
        {
            GlobalLog.Enter("FileWebResponse::Dispose");
            Dispose(true);
            GC.SuppressFinalize(this);
            GlobalLog.Leave("FileWebResponse::Dispose");
        }
Beispiel #17
0
        // methods

        /// <include file='doc\filewebrequest.uex' path='docs/doc[@for="FileWebRequest.BeginGetRequestStream"]/*' />
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");
            if (!CanGetRequestStream())
            {
                Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
                GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                throw e;
            }
            if (m_response != null)
            {
                Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                throw e;
            }
            lock (this) {
                if (m_writePending)
                {
                    Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                m_writePending = true;
            }
            m_GetRequestStreamDelegate = new AsyncGetRequestStream(InternalGetRequestStream);
            GlobalLog.Leave("FileWebRequest::BeginGetRequestStream");
            return(m_GetRequestStreamDelegate.BeginInvoke(callback, state));
        }
Beispiel #18
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");

            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                if (!CanGetRequestStream())
                {
                    Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                if (m_response != null)
                {
                    Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                lock (this) {
                    if (m_writePending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                        throw e;
                    }
                    m_writePending = true;
                }

                //we need to force the capture of the identity and context to make sure the
                //posted callback doesn't inavertently gain access to something it shouldn't.
                m_ReadAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult);
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam");
            }

            string suri;

            if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient))
            {
                suri = this.RequestUri.ToString();
            }
            else
            {
                suri = this.RequestUri.OriginalString;
            }
            FrameworkEventSource.Log.BeginGetRequestStream(this, suri);

            return(m_ReadAResult);
        }
Beispiel #19
0
        internal static SecurityPackageInfoClass[] EnumerateSecurityPackages(SSPIInterface secModule)
        {
            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Enter(nameof(EnumerateSecurityPackages));
            }

            if (secModule.SecurityPackages == null)
            {
                lock (secModule)
                {
                    if (secModule.SecurityPackages == null)
                    {
                        int moduleCount = 0;
                        SafeFreeContextBuffer arrayBaseHandle = null;
                        try
                        {
                            int errorCode = secModule.EnumerateSecurityPackages(out moduleCount, out arrayBaseHandle);
                            if (GlobalLog.IsEnabled)
                            {
                                GlobalLog.Print("SSPIWrapper::arrayBase: " + (arrayBaseHandle.DangerousGetHandle().ToString("x")));
                            }
                            if (errorCode != 0)
                            {
                                throw new Win32Exception(errorCode);
                            }

                            var securityPackages = new SecurityPackageInfoClass[moduleCount];

                            int i;
                            for (i = 0; i < moduleCount; i++)
                            {
                                securityPackages[i] = new SecurityPackageInfoClass(arrayBaseHandle, i);
                                if (SecurityEventSource.Log.IsEnabled())
                                {
                                    SecurityEventSource.Log.EnumerateSecurityPackages(securityPackages[i].Name);
                                }
                            }

                            secModule.SecurityPackages = securityPackages;
                        }
                        finally
                        {
                            if (arrayBaseHandle != null)
                            {
                                arrayBaseHandle.Dispose();
                            }
                        }
                    }
                }
            }

            if (GlobalLog.IsEnabled)
            {
                GlobalLog.Leave(nameof(EnumerateSecurityPackages));
            }
            return(secModule.SecurityPackages);
        }
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");
#if !MONO
            bool success = true;
#endif
            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                if (!CanGetRequestStream())
                {
                    Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                if (m_response != null)
                {
                    Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                lock (this) {
                    if (m_writePending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                        throw e;
                    }
                    m_writePending = true;
                }

                //we need to force the capture of the identity and context to make sure the
                //posted callback doesn't inavertently gain access to something it shouldn't.
                m_ReadAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult);
            } catch (Exception exception) {
#if !MONO
                success = false;
#endif
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception);
                }
                throw;
            } finally {
#if !MONO
                if (FrameworkEventSource.Log.IsEnabled())
                {
                    LogBeginGetRequestStream(success, synchronous: false);
                }
#endif
                GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam");
            }

            return(m_ReadAResult);
        }
Beispiel #21
0
        protected override void BuildInternal()
        {
            GlobalLog.Enter("WinHttpWebProxyBuilder#" + ValidationHelper.HashString(this) + "::BuildInternal()");

            UnsafeNclNativeMethods.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG ieProxyConfig =
                new UnsafeNclNativeMethods.WinHttp.WINHTTP_CURRENT_USER_IE_PROXY_CONFIG();

            // Make sure the native strings get freed, even if some unexpected exception occurs.
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                if (UnsafeNclNativeMethods.WinHttp.WinHttpGetIEProxyConfigForCurrentUser(ref ieProxyConfig))
                {
                    string proxy         = null;
                    string proxyByPass   = null;
                    string autoConfigUrl = null;

                    proxy         = Marshal.PtrToStringUni(ieProxyConfig.Proxy);
                    proxyByPass   = Marshal.PtrToStringUni(ieProxyConfig.ProxyBypass);
                    autoConfigUrl = Marshal.PtrToStringUni(ieProxyConfig.AutoConfigUrl);

                    // note that ieProxyConfig.Proxy will be null if "use a proxy server" flag is turned off, even if
                    // the user specified a proxy address. When we read directly from the Registry we need to check
                    // for ProxyTypeFlags.PROXY_TYPE_PROXY. WinHttp does this for us and if the flag is not set,
                    // ieProxyConfig.Proxy will be null.
                    SetProxyAndBypassList(proxy, proxyByPass);

                    SetAutoDetectSettings(ieProxyConfig.AutoDetect);

                    // similar to comment above: ieProxyConfig.AutoConfigUrl will only be set if "automatically detect
                    // settings" flag is set. We don't need to check ProxyTypeFlags.PROXY_TYPE_AUTO_PROXY_URL; WinHttp
                    // takes care of it and sets AutoConfigUrl to null if the flag is not set, regardless of the actual
                    // config script string.
                    SetAutoProxyUrl(autoConfigUrl);
                }
                else
                {
                    int errorCode = Marshal.GetLastWin32Error();

                    if (errorCode == Microsoft.Win32.NativeMethods.ERROR_NOT_ENOUGH_MEMORY)
                    {
                        throw new OutOfMemoryException();
                    }

                    // if API call fails, rely on automatic detection
                    SetAutoDetectSettings(true);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(ieProxyConfig.Proxy);
                Marshal.FreeHGlobal(ieProxyConfig.ProxyBypass);
                Marshal.FreeHGlobal(ieProxyConfig.AutoConfigUrl);
            }

            GlobalLog.Leave("WinHttpWebProxyBuilder#" + ValidationHelper.HashString(this) + "::BuildInternal()");
        }
Beispiel #22
0
 public override void Close()
 {
     GlobalLog.Enter("FileWebStream::Close");
     if (m_request != null)
     {
         m_request.UnblockReader();
     }
     base.Close();
     GlobalLog.Leave("FileWebStream::Close");
 }
        private void EnumerateSecurityPackages()
        {
            GlobalLog.Enter("EnumerateSecurityPackages");
            if (securityPackages == null)
            {
                lock (this)
                {
                    if (securityPackages == null)
                    {
                        int moduleCount = 0;
                        SafeFreeContextBuffer arrayBaseHandle = null;
                        try
                        {
                            int errorCode = SafeFreeContextBuffer.EnumeratePackages(out moduleCount, out arrayBaseHandle);

                            GlobalLog.Print("SSPIWrapper::arrayBase: " + (arrayBaseHandle.DangerousGetHandle().ToString("x")));

                            if (errorCode != 0)
                            {
                                throw new Win32Exception(errorCode);
                            }

                            SecurityPackageInfoClass[] securityPackagesList = new SecurityPackageInfoClass[moduleCount];

                            if (Logging.On)
                            {
                                Logging.PrintInfo(Logging.Web, SR.net_log_sspi_enumerating_security_packages);
                            }

                            for (int i = 0; i < moduleCount; i++)
                            {
                                securityPackagesList[i] = new SecurityPackageInfoClass(arrayBaseHandle, i);

                                if (Logging.On)
                                {
                                    Logging.PrintInfo(Logging.Web, "    " + securityPackagesList[i].Name);
                                }
                            }

                            securityPackages = securityPackagesList;
                        }
                        finally
                        {
                            if (arrayBaseHandle != null)
                            {
                                arrayBaseHandle.Dispose();
                            }
                        }
                    }
                }
            }

            GlobalLog.Leave("EnumerateSecurityPackages");
        }
        /// <devdoc>
        ///    <para>Places a new/reusable stream in the new stack of the pool</para>
        /// </devdoc>
        private void PutNew(PooledStream pooledStream)
        {
            GlobalLog.Enter("ConnectionPool#" + ValidationHelper.HashString(this) + "::PutNew", "#" + ValidationHelper.HashString(pooledStream));

            GlobalLog.Assert(null != pooledStream, "Why are we adding a null object to the pool?");
            GlobalLog.Assert(pooledStream.CanBePooled, "Non-poolable object in pool.");

            m_StackNew.Push(pooledStream);
            Semaphore.ReleaseSemaphore();
            GlobalLog.Leave("ConnectionPool#" + ValidationHelper.HashString(this) + "::PutNew");
        }
Beispiel #25
0
 internal void UnblockReader()
 {
     GlobalLog.Enter("FileWebRequest::UnblockReader");
     lock (this) {
         if (m_readerEvent != null)
         {
             m_readerEvent.Set();
         }
     }
     m_writing = false;
     GlobalLog.Leave("FileWebRequest::UnblockReader");
 }
Beispiel #26
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");
            }
        }
        /// <devdoc>
        ///    <para>Places a new/reusable stream in the new stack of the pool</para>
        /// </devdoc>
        private void PutNew(PooledStream pooledStream)
        {
            GlobalLog.Enter("ConnectionPool#" + ValidationHelper.HashString(this) + "::PutNew", "#" + ValidationHelper.HashString(pooledStream));

            GlobalLog.Assert(null != pooledStream, "Why are we adding a null object to the pool?");
            GlobalLog.Assert(pooledStream.CanBePooled, "Non-poolable object in pool.");

            m_StackNew.Push(pooledStream);
            // ensure that the semaphore's count is incremented to signal an available connection is in
            // the pool
            Semaphore.ReleaseSemaphore();
            GlobalLog.Leave("ConnectionPool#" + ValidationHelper.HashString(this) + "::PutNew");
        }
Beispiel #28
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");

            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                if (!CanGetRequestStream())
                {
                    Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                if (m_response != null)
                {
                    Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                lock (this) {
                    if (m_writePending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                        throw e;
                    }
                    m_writePending = true;
                }

                //we need to force the capture of the identity and context to make sure the
                //posted callback doesn't inavertently gain access to something it shouldn't.
                m_ReadAResult = new ContextAwareResult(true, true, true, this, state, callback);
                lock (m_ReadAResult.StartPostingAsyncOp())
                {
                    ThreadPool.UnsafeQueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult);
                    m_ReadAResult.FinishPostingAsyncOp();
                }
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam");
            }
            return(m_ReadAResult);
        }
Beispiel #29
0
 private void AsyncReceiveComplete(IAsyncResult result)
 {
     GlobalLog.Enter("TlsStream#" + ValidationHelper.HashString(this) + "::AsyncReceiveComplete");
     try {
         int bytesRead = base.EndRead(result);
         GlobalLog.Print("TlsStream#" + ValidationHelper.HashString(this) + "::AsyncReceiveComplete: received " + bytesRead + " bytes");
         GlobalLog.Dump(m_AsyncResponseBuffer, bytesRead);
         NextRecord(m_AsyncResponseBuffer, bytesRead);
     } catch (Exception exception) {
         InnerException = new IOException(SR.GetString(SR.net_io_readfailure), exception);
     }
     ((NestedSingleAsyncResult)result.AsyncState).InvokeCallback(false);
     GlobalLog.Leave("TlsStream#" + ValidationHelper.HashString(this) + "::AsyncReceiveComplete");
 }
Beispiel #30
0
 protected override void Dispose(bool disposing)
 {
     GlobalLog.Enter("FileWebStream::Close");
     try {
         if (disposing && m_request != null)
         {
             m_request.UnblockReader();
         }
     }
     finally {
         base.Dispose(disposing);
     }
     GlobalLog.Leave("FileWebStream::Close");
 }