public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface SecModule, string package, CredentialUse intent)
        {
            GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): using " + package);
            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web,
                                  "AcquireDefaultCredential(" +
                                  "package = " + package + ", " +
                                  "intent  = " + intent + ")");
            }


            SafeFreeCredentials outCredential = null;
            int errorCode = SecModule.AcquireDefaultCredential(package, intent, out outCredential);

            if (errorCode != 0)
            {
#if TRAVE
                GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): error " + SecureChannel.MapSecurityStatus((uint)errorCode));
#endif
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_operation_failed_with_error, "AcquireDefaultCredential()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
                }
                throw new Win32Exception(errorCode);
            }
            return(outCredential);
        }
Example #2
0
        public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.Secur32.CredentialUse intent, ref Interop.Secur32.AuthIdentity authdata)
        {
            GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#2(): using " + package);

            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web,
                                  "AcquireCredentialsHandle(" +
                                  "package  = " + package + ", " +
                                  "intent   = " + intent + ", " +
                                  "authdata = " + authdata + ")");
            }

            SafeFreeCredentials credentialsHandle = null;
            int errorCode = secModule.AcquireCredentialsHandle(package,
                                                               intent,
                                                               ref authdata,
                                                               out credentialsHandle
                                                               );

            if (errorCode != 0)
            {
#if TRACE_VERBOSE
                GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#2(): error " + Interop.MapSecurityStatus((uint)errorCode));
#endif
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
                }

                throw new Win32Exception(errorCode);
            }
            return(credentialsHandle);
        }
Example #3
0
        public static SafeFreeCredentials AcquireCredentialsHandle(SSPIInterface secModule, string package, Interop.Secur32.CredentialUse intent, ref SafeSspiAuthDataHandle authdata)
        {
            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web,
                                  "AcquireCredentialsHandle(" +
                                  "package  = " + package + ", " +
                                  "intent   = " + intent + ", " +
                                  "authdata = " + authdata + ")");
            }

            SafeFreeCredentials credentialsHandle = null;
            int errorCode = secModule.AcquireCredentialsHandle(package, intent, ref authdata, out credentialsHandle);

            if (errorCode != 0)
            {
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
                }

                throw new Win32Exception(errorCode);
            }

            return(credentialsHandle);
        }
Example #4
0
        private int GetProxies(Uri destination, Uri scriptLocation, out string proxyListString)
        {
            int errorCode = 0;

            proxyListString = null;

            UnsafeNclNativeMethods.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions =
                new UnsafeNclNativeMethods.WinHttp.WINHTTP_AUTOPROXY_OPTIONS();

            // Always try to download the PAC file without authentication. If we turn auth. on, the WinHttp
            // service will create a new session for every request (performance/memory implications).
            // Therefore we only turn auto-logon on if it is really needed.
            autoProxyOptions.AutoLogonIfChallenged = false;

            if (scriptLocation == null)
            {
                // Use auto-discovery to find the script location.
                autoProxyOptions.Flags           = UnsafeNclNativeMethods.WinHttp.AutoProxyFlags.AutoDetect;
                autoProxyOptions.AutoConfigUrl   = null;
                autoProxyOptions.AutoDetectFlags = UnsafeNclNativeMethods.WinHttp.AutoDetectType.Dhcp |
                                                   UnsafeNclNativeMethods.WinHttp.AutoDetectType.DnsA;
            }
            else
            {
                // Use the provided script location for the PAC file.
                autoProxyOptions.Flags           = UnsafeNclNativeMethods.WinHttp.AutoProxyFlags.AutoProxyConfigUrl;
                autoProxyOptions.AutoConfigUrl   = scriptLocation.ToString();
                autoProxyOptions.AutoDetectFlags = UnsafeNclNativeMethods.WinHttp.AutoDetectType.None;
            }

            if (!WinHttpGetProxyForUrl(destination.ToString(), ref autoProxyOptions, out proxyListString))
            {
                errorCode = GetLastWin32Error();

                // If the PAC file can't be downloaded because auth. was required, we check if the
                // credentials are set; if so, then we try again using auto-logon.
                // Note that by default webProxy.Credentials will be null. The user needs to set
                // <defaultProxy useDefaultCredentials="true"> in the config file, in order for
                // webProxy.Credentials to be set to DefaultNetworkCredentials.
                if ((errorCode == (int)UnsafeNclNativeMethods.WinHttp.ErrorCodes.LoginFailure) &&
                    (Engine.Credentials != null))
                {
                    // Now we need to try again, this time by enabling auto-logon.
                    autoProxyOptions.AutoLogonIfChallenged = true;

                    if (!WinHttpGetProxyForUrl(destination.ToString(), ref autoProxyOptions,
                                               out proxyListString))
                    {
                        errorCode = GetLastWin32Error();
                    }
                }

                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_proxy_winhttp_getproxy_failed, destination, errorCode));
                }
            }

            return(errorCode);
        }
 private static void CreateInstance()
 {
     instance = new NetworkingPerfCounters();
     if ((instance.Enabled && !ThreadPool.QueueUserWorkItem(new WaitCallback(instance.Initialize))) && Logging.On)
     {
         Logging.PrintError(Logging.Web, SR.GetString("net_perfcounter_cant_queue_workitem"));
     }
 }
Example #6
0
        private static WindowsInstallationType GetWindowsInstallType()
        {
            WindowsInstallationType unknown;

            try
            {
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Windows NT\CurrentVersion"))
                {
                    string str = key.GetValue("InstallationType") as string;
                    if (string.IsNullOrEmpty(str))
                    {
                        if (Logging.On)
                        {
                            Logging.PrintWarning(Logging.Web, SR.GetString("net_empty_osinstalltype", new object[] { @"Software\Microsoft\Windows NT\CurrentVersion\InstallationType" }));
                        }
                        return(WindowsInstallationType.Unknown);
                    }
                    if (string.Compare(str, "Client", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return(WindowsInstallationType.Client);
                    }
                    if (string.Compare(str, "Server", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return(WindowsInstallationType.Server);
                    }
                    if (string.Compare(str, "Server Core", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return(WindowsInstallationType.ServerCore);
                    }
                    if (string.Compare(str, "Embedded", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        return(WindowsInstallationType.Embedded);
                    }
                    if (Logging.On)
                    {
                        Logging.PrintError(Logging.Web, SR.GetString("net_unknown_osinstalltype", new object[] { str }));
                    }
                    unknown = WindowsInstallationType.Unknown;
                }
            }
            catch (UnauthorizedAccessException exception)
            {
                if (Logging.On)
                {
                    Logging.PrintWarning(Logging.Web, SR.GetString("net_cant_determine_osinstalltype", new object[] { @"Software\Microsoft\Windows NT\CurrentVersion", exception.Message }));
                }
                unknown = WindowsInstallationType.Unknown;
            }
            catch (SecurityException exception2)
            {
                if (Logging.On)
                {
                    Logging.PrintWarning(Logging.Web, SR.GetString("net_cant_determine_osinstalltype", new object[] { @"Software\Microsoft\Windows NT\CurrentVersion", exception2.Message }));
                }
                unknown = WindowsInstallationType.Unknown;
            }
            return(unknown);
        }
        private static FormatException CreateInvalidProxyStringException(string originalProxyString)
        {
            string message = SR.GetString(SR.net_proxy_invalid_url_format, originalProxyString);

            if (Logging.On)
            {
                Logging.PrintError(Logging.Web, message);
            }
            return(new FormatException(message));
        }
Example #8
0
        private static FormatException CreateInvalidProxyStringException(string originalProxyString)
        {
            string msg = SR.GetString("net_proxy_invalid_url_format", new object[] { originalProxyString });

            if (Logging.On)
            {
                Logging.PrintError(Logging.Web, msg);
            }
            return(new FormatException(msg));
        }
 private static void CreateInstance()
 {
     instance = new NetworkingPerfCounters();
     if (instance.Enabled)
     {
         // as recommended by the perf. counter team: initialize perf. counters in background thread
         // since initialization may take a long time. Therefore we should not block.
         if (!ThreadPool.QueueUserWorkItem(instance.Initialize))
         {
             if (Logging.On)
             {
                 Logging.PrintError(Logging.Web, SR.GetString(SR.net_perfcounter_cant_queue_workitem));
             }
         }
     }
 }
 private static string computeSecret(HttpDigestChallenge challenge, string username, string password)
 {
     if ((challenge.Algorithm == null) || (string.Compare(challenge.Algorithm, "md5", StringComparison.OrdinalIgnoreCase) == 0))
     {
         return(username + ":" + challenge.Realm + ":" + password);
     }
     if (string.Compare(challenge.Algorithm, "md5-sess", StringComparison.OrdinalIgnoreCase) == 0)
     {
         return(hashString(username + ":" + challenge.Realm + ":" + password, challenge.MD5provider) + ":" + challenge.Nonce + ":" + challenge.ClientNonce);
     }
     if (Logging.On)
     {
         Logging.PrintError(Logging.Web, SR.GetString("net_log_digest_hash_algorithm_not_supported", new object[] { challenge.Algorithm }));
     }
     return(null);
 }
Example #11
0
 internal bool Fire()
 {
     if (this.m_TimerState == TimerState.Ready)
     {
         int tickCount = Environment.TickCount;
         if (TimerThread.IsTickBetween(base.StartTime, base.Expiration, tickCount))
         {
             return(false);
         }
         bool flag = false;
         lock (this.m_QueueLock)
         {
             if (this.m_TimerState == TimerState.Ready)
             {
                 this.m_TimerState = TimerState.Fired;
                 this.Next.Prev    = this.Prev;
                 this.Prev.Next    = this.Next;
                 this.Next         = null;
                 this.Prev         = null;
                 flag = this.m_Callback != null;
             }
         }
         if (flag)
         {
             try
             {
                 TimerThread.Callback callback = this.m_Callback;
                 object context = this.m_Context;
                 this.m_Callback = null;
                 this.m_Context  = null;
                 callback(this, tickCount, context);
             }
             catch (Exception exception)
             {
                 if (NclUtilities.IsFatal(exception))
                 {
                     throw;
                 }
                 if (Logging.On)
                 {
                     Logging.PrintError(Logging.Web, "TimerThreadTimer#" + base.StartTime.ToString(NumberFormatInfo.InvariantInfo) + "::Fire() - " + SR.GetString("net_log_exception_in_callback", new object[] { exception }));
                 }
             }
         }
     }
     return(true);
 }
        private static bool IsAddressListLoopback(IPAddress[] addressList)
        {
            IPAddress[] localAddresses = null;
            try
            {
                localAddresses = NclUtilities.LocalAddresses;
            }
            catch (Exception exception)
            {
                if (NclUtilities.IsFatal(exception))
                {
                    throw;
                }
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, SR.GetString("net_log_retrieving_localhost_exception", new object[] { exception }));
                    Logging.PrintWarning(Logging.Web, SR.GetString("net_log_resolved_servicepoint_may_not_be_remote_server"));
                }
            }
            int index = 0;

            while (index < addressList.Length)
            {
                if (!IPAddress.IsLoopback(addressList[index]))
                {
                    if (localAddresses == null)
                    {
                        break;
                    }
                    int num2 = 0;
                    while (num2 < localAddresses.Length)
                    {
                        if (addressList[index].Equals(localAddresses[num2]))
                        {
                            break;
                        }
                        num2++;
                    }
                    if (num2 >= localAddresses.Length)
                    {
                        break;
                    }
                }
                index++;
            }
            return(index == addressList.Length);
        }
        public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface SecModule, string package, CredentialUse intent)
        {
            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web, string.Concat(new object[] { "AcquireDefaultCredential(package = ", package, ", intent  = ", intent, ")" }));
            }
            SafeFreeCredentials outCredential = null;
            int error = SecModule.AcquireDefaultCredential(package, intent, out outCredential);

            if (error == 0)
            {
                return(outCredential);
            }
            if (Logging.On)
            {
                Logging.PrintError(Logging.Web, SR.GetString("net_log_operation_failed_with_error", new object[] { "AcquireDefaultCredential()", string.Format(CultureInfo.CurrentCulture, "0X{0:X}", new object[] { error }) }));
            }
            throw new Win32Exception(error);
        }
        //
        // Parses out a string from IE and turns it into a URI
        //
        private static Uri ParseProxyUri(string proxyString)
        {
            Debug.Assert(!string.IsNullOrEmpty(proxyString));

            if (proxyString.IndexOf("://") == -1)
            {
                proxyString = "http://" + proxyString;
            }

            try {
                return(new Uri(proxyString));
            }
            catch (UriFormatException e) {
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, e.Message);
                }
                throw CreateInvalidProxyStringException(proxyString);
            }
        }
Example #15
0
        private static Uri ParseProxyUri(string proxyString)
        {
            Uri uri;

            if (proxyString.IndexOf("://") == -1)
            {
                proxyString = "http://" + proxyString;
            }
            try
            {
                uri = new Uri(proxyString);
            }
            catch (UriFormatException exception)
            {
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, exception.Message);
                }
                throw CreateInvalidProxyStringException(proxyString);
            }
            return(uri);
        }
Example #16
0
        private int GetProxies(Uri destination, Uri scriptLocation, out string proxyListString)
        {
            int num = 0;

            proxyListString = null;
            UnsafeNclNativeMethods.WinHttp.WINHTTP_AUTOPROXY_OPTIONS autoProxyOptions = new UnsafeNclNativeMethods.WinHttp.WINHTTP_AUTOPROXY_OPTIONS {
                AutoLogonIfChallenged = false
            };
            if (scriptLocation == null)
            {
                autoProxyOptions.Flags           = UnsafeNclNativeMethods.WinHttp.AutoProxyFlags.AutoDetect;
                autoProxyOptions.AutoConfigUrl   = null;
                autoProxyOptions.AutoDetectFlags = UnsafeNclNativeMethods.WinHttp.AutoDetectType.DnsA | UnsafeNclNativeMethods.WinHttp.AutoDetectType.Dhcp;
            }
            else
            {
                autoProxyOptions.Flags           = UnsafeNclNativeMethods.WinHttp.AutoProxyFlags.AutoProxyConfigUrl;
                autoProxyOptions.AutoConfigUrl   = scriptLocation.ToString();
                autoProxyOptions.AutoDetectFlags = UnsafeNclNativeMethods.WinHttp.AutoDetectType.None;
            }
            if (!this.WinHttpGetProxyForUrl(destination.ToString(), ref autoProxyOptions, out proxyListString))
            {
                num = GetLastWin32Error();
                if ((num == 0x2eef) && (base.Engine.Credentials != null))
                {
                    autoProxyOptions.AutoLogonIfChallenged = true;
                    if (!this.WinHttpGetProxyForUrl(destination.ToString(), ref autoProxyOptions, out proxyListString))
                    {
                        num = GetLastWin32Error();
                    }
                }
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, SR.GetString("net_log_proxy_winhttp_getproxy_failed", new object[] { destination, num }));
                }
            }
            return(num);
        }
Example #17
0
        public WinHttpWebProxyFinder(AutoWebProxyScriptEngine engine)
            : base(engine)
        {
            // Don't specify a user agent and dont' specify proxy settings. This is the same behavior WinHttp
            // uses when downloading the PAC file.
            session = UnsafeNclNativeMethods.WinHttp.WinHttpOpen(null,
                                                                 UnsafeNclNativeMethods.WinHttp.AccessType.NoProxy, null, null, 0);

            // Don't throw on error, just log the error information. This is consistent with how auto-proxy
            // works: we never throw on error (discovery, download, execution errors).
            if (session == null || session.IsInvalid)
            {
                int errorCode = GetLastWin32Error();
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_proxy_winhttp_cant_open_session, errorCode));
                }
            }
            else
            {
                // The default download-timeout is 1 min.
                // WinHTTP will use the sum of all four timeouts provided in WinHttpSetTimeouts as the
                // actual timeout. Setting a value to 0 means "infinite".
                // Since we don't provide the ability to specify finegrained timeouts like WinHttp does,
                // we simply apply the configured timeout to all four WinHttp timeouts.
                int timeout = SettingsSectionInternal.Section.DownloadTimeout;

                if (!UnsafeNclNativeMethods.WinHttp.WinHttpSetTimeouts(session, timeout, timeout, timeout, timeout))
                {
                    // We weren't able to set the timeouts. Just log and continue.
                    int errorCode = GetLastWin32Error();
                    if (Logging.On)
                    {
                        Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_proxy_winhttp_timeout_error, errorCode));
                    }
                }
            }
        }
Example #18
0
        private SafeFreeCredentials AcquireCredentialsHandle(string package, bool isServer, Interop.Secur32.SecureCredential scc)
        {
            GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): using " + package);

            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web,
                                  "AcquireCredentialsHandle(" +
                                  "package = " + package + ", " +
                                  "IsInBoundCred  = " + isServer + ", " +
                                  "scc     = " + scc + ")");
            }

            SafeFreeCredentials outCredential = null;
            int errorCode = AcquireCredentialsHandle(
                package,
                isServer,
                ref scc,
                out outCredential
                );

            if (errorCode != 0)
            {
#if TRACE_VERBOSE
                GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): error " + Interop.MapSecurityStatus((uint)errorCode));
#endif
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, "AcquireCredentialsHandle()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
                }
                throw new Win32Exception(errorCode);
            }

#if TRACE_VERBOSE
            GlobalLog.Print("SSPIWrapper::AcquireCredentialsHandle#3(): cred handle = " + outCredential.ToString());
#endif
            return(outCredential);
        }
Example #19
0
 public WinHttpWebProxyFinder(AutoWebProxyScriptEngine engine) : base(engine)
 {
     this.session = UnsafeNclNativeMethods.WinHttp.WinHttpOpen(null, UnsafeNclNativeMethods.WinHttp.AccessType.NoProxy, null, null, 0);
     if ((this.session == null) || this.session.IsInvalid)
     {
         int num = GetLastWin32Error();
         if (Logging.On)
         {
             Logging.PrintError(Logging.Web, SR.GetString("net_log_proxy_winhttp_cant_open_session", new object[] { num }));
         }
     }
     else
     {
         int downloadTimeout = SettingsSectionInternal.Section.DownloadTimeout;
         if (!UnsafeNclNativeMethods.WinHttp.WinHttpSetTimeouts(this.session, downloadTimeout, downloadTimeout, downloadTimeout, downloadTimeout))
         {
             int num3 = GetLastWin32Error();
             if (Logging.On)
             {
                 Logging.PrintError(Logging.Web, SR.GetString("net_log_proxy_winhttp_timeout_error", new object[] { num3 }));
             }
         }
     }
 }
Example #20
0
        //
        // Security: We temporarily reset thread token to open the cert store under process account.
        //
        internal override X509Store EnsureStoreOpened(bool isMachineStore)
        {
            X509Store store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx;

            if (store == null)
            {
                lock (s_syncObject)
                {
                    store = isMachineStore ? s_myMachineCertStoreEx : s_myCertStoreEx;
                    if (store == null)
                    {
                        // NOTE: that if this call fails we won't keep track and the next time we enter we will try to open the store again.
                        StoreLocation storeLocation = isMachineStore ? StoreLocation.LocalMachine : StoreLocation.CurrentUser;
                        store = new X509Store(StoreName.My, storeLocation);
                        try
                        {
                            // For app-compat We want to ensure the store is opened under the **process** account.
                            try
                            {
                                WindowsIdentity.RunImpersonated(SafeAccessTokenHandle.InvalidHandle, () =>
                                {
                                    store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
                                    GlobalLog.Print("SecureChannel::EnsureStoreOpened() storeLocation:" + storeLocation + " returned store:" + store.GetHashCode().ToString("x"));
                                });
                            }
                            catch
                            {
                                throw;
                            }

                            if (isMachineStore)
                            {
                                s_myMachineCertStoreEx = store;
                            }
                            else
                            {
                                s_myCertStoreEx = store;
                            }

                            return(store);
                        }
                        catch (Exception exception)
                        {
                            if (exception is CryptographicException || exception is SecurityException)
                            {
                                GlobalLog.Assert("SecureChannel::EnsureStoreOpened()", "Failed to open cert store, location:" + storeLocation + " exception:" + exception);
                                return(null);
                            }

                            if (Logging.On)
                            {
                                Logging.PrintError(Logging.Web, SR.Format(SR.net_log_open_store_failed, storeLocation, exception));
                            }

                            throw;
                        }
                    }
                }
            }
            return(store);
        }
        private static unsafe int EncryptDecryptHelper(OP op, SSPIInterface SecModule, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
        {
            SecurityBufferDescriptor inputOutput = new SecurityBufferDescriptor(input.Length);

            SecurityBufferStruct[] structArray = new SecurityBufferStruct[input.Length];
            fixed(SecurityBufferStruct *structRef = structArray)
            {
                int num6;

                inputOutput.UnmanagedPointer = (void *)structRef;
                GCHandle[] handleArray = new GCHandle[input.Length];
                byte[][]   bufferArray = new byte[input.Length][];
                try
                {
                    int num2;
                    for (int i = 0; i < input.Length; i++)
                    {
                        SecurityBuffer buffer = input[i];
                        structArray[i].count = buffer.size;
                        structArray[i].type  = buffer.type;
                        if ((buffer.token == null) || (buffer.token.Length == 0))
                        {
                            structArray[i].token = IntPtr.Zero;
                        }
                        else
                        {
                            handleArray[i]       = GCHandle.Alloc(buffer.token, GCHandleType.Pinned);
                            structArray[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(buffer.token, buffer.offset);
                            bufferArray[i]       = buffer.token;
                        }
                    }
                    switch (op)
                    {
                    case OP.Encrypt:
                        num2 = SecModule.EncryptMessage(context, inputOutput, sequenceNumber);
                        break;

                    case OP.Decrypt:
                        num2 = SecModule.DecryptMessage(context, inputOutput, sequenceNumber);
                        break;

                    case OP.MakeSignature:
                        num2 = SecModule.MakeSignature(context, inputOutput, sequenceNumber);
                        break;

                    case OP.VerifySignature:
                        num2 = SecModule.VerifySignature(context, inputOutput, sequenceNumber);
                        break;

                    default:
                        throw ExceptionHelper.MethodNotImplementedException;
                    }
                    for (int j = 0; j < input.Length; j++)
                    {
                        SecurityBuffer buffer2 = input[j];
                        buffer2.size = structArray[j].count;
                        buffer2.type = structArray[j].type;
                        if (buffer2.size == 0)
                        {
                            buffer2.offset = 0;
                            buffer2.token  = null;
                        }
                        else
                        {
                            int index = 0;
                            while (index < input.Length)
                            {
                                if (bufferArray[index] != null)
                                {
                                    byte *numPtr = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(bufferArray[index], 0);
                                    if ((((void *)structArray[j].token) >= numPtr) && ((((void *)structArray[j].token) + buffer2.size) <= (numPtr + bufferArray[index].Length)))
                                    {
                                        buffer2.offset = (int)((long)((((void *)structArray[j].token) - numPtr) / 1));
                                        buffer2.token  = bufferArray[index];
                                        break;
                                    }
                                }
                                index++;
                            }
                            if (index >= input.Length)
                            {
                                buffer2.size   = 0;
                                buffer2.offset = 0;
                                buffer2.token  = null;
                            }
                        }
                    }
                    if ((num2 != 0) && Logging.On)
                    {
                        if (num2 == 0x90321)
                        {
                            Logging.PrintError(Logging.Web, SR.GetString("net_log_operation_returned_something", new object[] { op, "SEC_I_RENEGOTIATE" }));
                        }
                        else
                        {
                            Logging.PrintError(Logging.Web, SR.GetString("net_log_operation_failed_with_error", new object[] { op, string.Format(CultureInfo.CurrentCulture, "0X{0:X}", new object[] { num2 }) }));
                        }
                    }
                    num6 = num2;
                }
                finally
                {
                    for (int k = 0; k < handleArray.Length; k++)
                    {
                        if (handleArray[k].IsAllocated)
                        {
                            handleArray[k].Free();
                        }
                    }
                }
                return(num6);
            }
        }
Example #22
0
        /// <summary>
        /// <para>Thread for the timer.  Swallows all exceptions except ThreadAbort.  If no activity occurs for a while,
        /// the thread will shut down.</para>
        /// </summary>
        private static void ThreadProc()
        {
#if DEBUG
            GlobalLog.SetThreadSource(ThreadKinds.Timer);
            using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async)) {
#endif
            GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Start");

            // t_IsTimerThread = true; -- Not used anywhere.

            // Set this thread as a background thread.  On AppDomain/Process shutdown, the thread will just be killed.
            Thread.CurrentThread.IsBackground = true;

            // Keep a permanent lock on s_Queues.  This lets for example Shutdown() know when this thread isn't running.
            lock (s_Queues) {
                // If shutdown was recently called, abort here.
                if (Interlocked.CompareExchange(ref s_ThreadState, (int)TimerThreadState.Running, (int)TimerThreadState.Running) !=
                    (int)TimerThreadState.Running)
                {
                    return;
                }

                bool running = true;
                while (running)
                {
                    try {
                        s_ThreadReadyEvent.Reset();

                        while (true)
                        {
                            // Copy all the new queues to the real queues.  Since only this thread modifies the real queues, it doesn't have to lock it.
                            if (s_NewQueues.Count > 0)
                            {
                                lock (s_NewQueues) {
                                    for (LinkedListNode <WeakReference> node = s_NewQueues.First; node != null; node = s_NewQueues.First)
                                    {
                                        s_NewQueues.Remove(node);
                                        s_Queues.AddLast(node);
                                    }
                                }
                            }

                            int  now          = Environment.TickCount;
                            int  nextTick     = 0;
                            bool haveNextTick = false;
                            for (LinkedListNode <WeakReference> node = s_Queues.First; node != null; /* node = node.Next must be done in the body */)
                            {
                                TimerQueue queue = (TimerQueue)node.Value.Target;
                                if (queue == null)
                                {
                                    LinkedListNode <WeakReference> next = node.Next;
                                    s_Queues.Remove(node);
                                    node = next;
                                    continue;
                                }

                                // Fire() will always return values that should be interpreted as later than 'now' (that is, even if 'now' is
                                // returned, it is 0x100000000 milliseconds in the future).  There's also a chance that Fire() will return a value
                                // intended as > 0x100000000 milliseconds from 'now'.  Either case will just cause an extra scan through the timers.
                                int nextTickInstance;
                                if (queue.Fire(out nextTickInstance) && (!haveNextTick || IsTickBetween(now, nextTick, nextTickInstance)))
                                {
                                    nextTick     = nextTickInstance;
                                    haveNextTick = true;
                                }

                                node = node.Next;
                            }

                            // Figure out how long to wait, taking into account how long the loop took.
                            // Add 15 ms to compensate for poor TickCount resolution (want to guarantee a firing).
                            int newNow       = Environment.TickCount;
                            int waitDuration = haveNextTick ?
                                               (int)(IsTickBetween(now, nextTick, newNow) ?
                                                     Math.Min(unchecked ((uint)(nextTick - newNow)), (uint)(Int32.MaxValue - c_TickCountResolution)) + c_TickCountResolution :
                                                     0) :
                                               c_ThreadIdleTimeoutMilliseconds;

                            GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Waiting for " + waitDuration + "ms");
                            int waitResult = WaitHandle.WaitAny(s_ThreadEvents, waitDuration, false);

                            // 0 is s_ThreadShutdownEvent - die.
                            if (waitResult == 0)
                            {
                                GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Awoke, cause: Shutdown");
                                running = false;
                                break;
                            }

                            GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Awoke, cause: " + (waitResult == WaitHandle.WaitTimeout ? "Timeout" : "Prod"));

                            // If we timed out with nothing to do, shut down.
                            if (waitResult == WaitHandle.WaitTimeout && !haveNextTick)
                            {
                                Interlocked.CompareExchange(ref s_ThreadState, (int)TimerThreadState.Idle, (int)TimerThreadState.Running);
                                // There could have been one more prod between the wait and the exchange.  Check, and abort if necessary.
                                if (s_ThreadReadyEvent.WaitOne(0, false))
                                {
                                    if (Interlocked.CompareExchange(ref s_ThreadState, (int)TimerThreadState.Running, (int)TimerThreadState.Idle) ==
                                        (int)TimerThreadState.Idle)
                                    {
                                        continue;
                                    }
                                }

                                running = false;
                                break;
                            }
                        }
                    }
                    catch (Exception exception) {
                        if (NclUtilities.IsFatal(exception))
                        {
                            throw;
                        }

                        if (Logging.On)
                        {
                            Logging.PrintError(Logging.Web, "TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString(NumberFormatInfo.InvariantInfo) + "::ThreadProc() - Exception:" + exception.ToString());
                        }
                        GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() exception: " + exception);

                        // The only options are to continue processing and likely enter an error-loop,
                        // shut down timers for this AppDomain, or shut down the AppDomain.  Go with shutting
                        // down the AppDomain in debug, and going into a loop in retail, but try to make the
                        // loop somewhat slow.  Note that in retail, this can only be triggered by OutOfMemory or StackOverflow,
                        // or an thrown within TimerThread - the rest are caught in Fire().
#if !DEBUG
                        Thread.Sleep(1000);
#else
                        throw;
#endif
                    }
                }
            }

            GlobalLog.Print("TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString() + "::ThreadProc() Stop");
#if DEBUG
        }
#endif
        }
Example #23
0
            /// <summary>
            /// <para>Fires the timer if it is still active and has expired.  Returns
            /// true if it can be deleted, or false if it is still timing.</para>
            /// </summary>
            internal bool Fire()
            {
                GlobalLog.Assert(m_TimerState != TimerState.Sentinel, "TimerThread#{0}::Fire()|TimerQueue tried to Fire a Sentinel.", Thread.CurrentThread.ManagedThreadId.ToString());

                if (m_TimerState != TimerState.Ready)
                {
                    return(true);
                }

                // Must get the current tick count within this method so it is guaranteed not to be before
                // StartTime, which is set in the constructor.
                int nowMilliseconds = Environment.TickCount;

                if (IsTickBetween(StartTime, Expiration, nowMilliseconds))
                {
                    GlobalLog.Print("TimerThreadTimer#" + StartTime + "::Fire() Not firing (" + StartTime + " <= " + nowMilliseconds + " < " + Expiration + ")");
                    return(false);
                }

                bool needCallback = false;

                lock (m_QueueLock)
                {
                    if (m_TimerState == TimerState.Ready)
                    {
                        GlobalLog.Print("TimerThreadTimer#" + StartTime + "::Fire() Firing (" + StartTime + " <= " + nowMilliseconds + " >= " + Expiration + ")");
                        m_TimerState = TimerState.Fired;

                        // Remove it from the list.
                        Next.Prev = Prev;
                        Prev.Next = Next;

                        // Doesn't need to be in the lock but is easier to have here.
                        Next         = null;
                        Prev         = null;
                        needCallback = m_Callback != null;
                    }
                }

                if (needCallback)
                {
                    try {
                        Callback callback = m_Callback;
                        object   context  = m_Context;
                        m_Callback = null;
                        m_Context  = null;
                        callback(this, nowMilliseconds, context);
                    }
                    catch (Exception exception) {
                        if (NclUtilities.IsFatal(exception))
                        {
                            throw;
                        }

                        if (Logging.On)
                        {
                            Logging.PrintError(Logging.Web, "TimerThreadTimer#" + StartTime.ToString(NumberFormatInfo.InvariantInfo) + "::Fire() - " + SR.GetString(SR.net_log_exception_in_callback, exception));
                        }
                        GlobalLog.Print("TimerThreadTimer#" + StartTime + "::Fire() exception in callback: " + exception);

                        // This thread is not allowed to go into user code, so we should never get an exception here.
                        // So, in debug, throw it up, killing the AppDomain.  In release, we'll just ignore it.
#if DEBUG
                        throw;
#endif
                    }
                }

                return(true);
            }
        internal static HttpDigestChallenge Interpret(string challenge, int startingPoint, HttpWebRequest httpWebRequest)
        {
            int    num2;
            string str2;
            HttpDigestChallenge challenge2 = new HttpDigestChallenge();

            challenge2.SetFromRequest(httpWebRequest);
            startingPoint = (startingPoint == -1) ? 0 : (startingPoint + DigestClient.SignatureSize);
            int startIndex = startingPoint;

Label_001F:
            num2 = startIndex;
            int num3 = AuthenticationManager.SplitNoQuotes(challenge, ref num2);

            if (num2 >= 0)
            {
                if (string.Compare(challenge.Substring(startIndex, num2 - startIndex), "charset", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    if (num3 < 0)
                    {
                        str2 = unquote(challenge.Substring(num2 + 1));
                    }
                    else
                    {
                        str2 = unquote(challenge.Substring(num2 + 1, (num3 - num2) - 1));
                    }
                    if (string.Compare(str2, "utf-8", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        challenge2.UTF8Charset = true;
                        goto Label_009E;
                    }
                }
                if (num3 >= 0)
                {
                    startIndex = ++num3;
                    goto Label_001F;
                }
            }
Label_009E:
            startIndex = startingPoint;
Label_00A0:
            num2 = startIndex;
            num3 = AuthenticationManager.SplitNoQuotes(challenge, ref num2);
            if (num2 >= 0)
            {
                string name = challenge.Substring(startIndex, num2 - startIndex);
                if (num3 < 0)
                {
                    str2 = unquote(challenge.Substring(num2 + 1));
                }
                else
                {
                    str2 = unquote(challenge.Substring(num2 + 1, (num3 - num2) - 1));
                }
                if (challenge2.UTF8Charset)
                {
                    bool flag2 = true;
                    for (int i = 0; i < str2.Length; i++)
                    {
                        if (str2[i] > '\x007f')
                        {
                            flag2 = false;
                            break;
                        }
                    }
                    if (!flag2)
                    {
                        byte[] bytes = new byte[str2.Length];
                        for (int j = 0; j < str2.Length; j++)
                        {
                            bytes[j] = (byte)str2[j];
                        }
                        str2 = Encoding.UTF8.GetString(bytes);
                    }
                }
                bool flag = challenge2.defineAttribute(name, str2);
                if ((num3 >= 0) && flag)
                {
                    startIndex = ++num3;
                    goto Label_00A0;
                }
            }
            if (challenge2.Nonce != null)
            {
                return(challenge2);
            }
            if (Logging.On)
            {
                Logging.PrintError(Logging.Web, SR.GetString("net_log_digest_requires_nonce"));
            }
            return(null);
        }
Example #25
0
        private Authorization DoAuthenticate(string challenge, WebRequest webRequest, ICredentials credentials, bool preAuthenticate)
        {
            HttpDigestChallenge challenge2;

            if (credentials == null)
            {
                return(null);
            }
            HttpWebRequest    httpWebRequest = webRequest as HttpWebRequest;
            NetworkCredential credential     = credentials.GetCredential(httpWebRequest.ChallengedUri, Signature);

            if (credential is SystemNetworkCredential)
            {
                if (WDigestAvailable)
                {
                    return(this.XPDoAuthenticate(challenge, httpWebRequest, credentials, preAuthenticate));
                }
                return(null);
            }
            if (!preAuthenticate)
            {
                int startingPoint = AuthenticationManager.FindSubstringNotInQuotes(challenge, Signature);
                if (startingPoint < 0)
                {
                    return(null);
                }
                challenge2 = HttpDigest.Interpret(challenge, startingPoint, httpWebRequest);
            }
            else
            {
                challenge2 = challengeCache.Lookup(httpWebRequest.ChallengedUri.AbsoluteUri) as HttpDigestChallenge;
            }
            if (challenge2 == null)
            {
                return(null);
            }
            if (!CheckQOP(challenge2))
            {
                if (Logging.On)
                {
                    Logging.PrintError(Logging.Web, SR.GetString("net_log_digest_qop_not_supported", new object[] { challenge2.QualityOfProtection }));
                }
                return(null);
            }
            if (preAuthenticate)
            {
                challenge2 = challenge2.CopyAndIncrementNonce();
                challenge2.SetFromRequest(httpWebRequest);
            }
            if (credential == null)
            {
                return(null);
            }
            ICredentialPolicy credentialPolicy = AuthenticationManager.CredentialPolicy;

            if ((credentialPolicy != null) && !credentialPolicy.ShouldSendCredential(httpWebRequest.ChallengedUri, httpWebRequest, credential, this))
            {
                return(null);
            }
            string         computeSpn     = httpWebRequest.CurrentAuthenticationState.GetComputeSpn(httpWebRequest);
            ChannelBinding channelBinding = null;

            if (httpWebRequest.CurrentAuthenticationState.TransportContext != null)
            {
                channelBinding = httpWebRequest.CurrentAuthenticationState.TransportContext.GetChannelBinding(ChannelBindingKind.Endpoint);
            }
            Authorization authorization = HttpDigest.Authenticate(challenge2, credential, computeSpn, channelBinding);

            if ((!preAuthenticate && webRequest.PreAuthenticate) && (authorization != null))
            {
                string[] strArray = (challenge2.Domain == null) ? new string[] { httpWebRequest.ChallengedUri.GetParts(UriComponents.SchemeAndServer, UriFormat.UriEscaped) } : challenge2.Domain.Split(singleSpaceArray);
                authorization.ProtectionRealm = (challenge2.Domain == null) ? null : strArray;
                for (int i = 0; i < strArray.Length; i++)
                {
                    challengeCache.Add(strArray[i], challenge2);
                }
            }
            return(authorization);
        }
        public static SafeFreeCredentials AcquireDefaultCredential(SSPIInterface SecModule, string package, CredentialUse intent)
        {
            SafeFreeCredentials outCredential = null;
            string currentIdentityKey         = null;
            bool   isIdentityCached;

            if (s_DefaultCredentialsHandleCacheEnabled)
            {
                currentIdentityKey = string.Format("{0}_{1}_{2}", package, intent.ToString(), WindowsIdentity.GetCurrent().Name);
                isIdentityCached   = s_DefaultCredentialsHandleCache.Value.TryGetValue(currentIdentityKey, out outCredential);
            }
            else
            {
                isIdentityCached = false;
            }

            GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): using " + package);
            if (Logging.On)
            {
                if (currentIdentityKey == null)
                {
                    // We aren't using the cache but it's still useful to log the current identity for diagnostics.
                    currentIdentityKey = string.Format("{0}_{1}_{2}", package, intent.ToString(), WindowsIdentity.GetCurrent().Name);
                }

                Logging.PrintInfo(Logging.Web,
                                  "AcquireDefaultCredential(" +
                                  "package = " + package + ", " +
                                  "intent = " + intent + ", " +
                                  "identity = " + currentIdentityKey + ", " +
                                  "cached = " + isIdentityCached + ")");
            }

            if (!isIdentityCached)
            {
                int errorCode = SecModule.AcquireDefaultCredential(package, intent, out outCredential);

                if (errorCode != 0)
                {
#if TRAVE
                    GlobalLog.Print("SSPIWrapper::AcquireDefaultCredential(): error " + SecureChannel.MapSecurityStatus((uint)errorCode));
#endif
                    if (Logging.On)
                    {
                        Logging.PrintError(Logging.Web, SR.GetString(SR.net_log_operation_failed_with_error, "AcquireDefaultCredential()", String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
                    }
                    throw new Win32Exception(errorCode);
                }

                if (s_DefaultCredentialsHandleCacheEnabled &&
                    s_DefaultCredentialsHandleCache.Value.Count < s_DefaultCredentialsHandleCacheSize)
                {
                    try {
                        s_DefaultCredentialsHandleCache.Value.TryAdd(currentIdentityKey, outCredential);
                    }
                    catch (OverflowException) {
                        // Unlikely to be thrown since it requires Int32.MaxValue items to already be in the cache.
                        // But we don't want to throw a new exception. So, we'll ignore this error and accept that
                        // the handle won't be cached.
                    }
                }
            }

            return(outCredential);
        }
Example #27
0
        private unsafe SecurityStatus EncryptDecryptHelper(OP op, SafeDeleteContext context, SecurityBuffer[] input, uint sequenceNumber)
        {
            Interop.Secur32.SecurityBufferDescriptor sdcInOut = new Interop.Secur32.SecurityBufferDescriptor(input.Length);
            var unmanagedBuffer = new Interop.Secur32.SecurityBufferStruct[input.Length];

            fixed(Interop.Secur32.SecurityBufferStruct *unmanagedBufferPtr = unmanagedBuffer)
            {
                sdcInOut.UnmanagedPointer = unmanagedBufferPtr;
                GCHandle[] pinnedBuffers = new GCHandle[input.Length];
                byte[][]   buffers       = new byte[input.Length][];
                try
                {
                    for (int i = 0; i < input.Length; i++)
                    {
                        SecurityBuffer iBuffer = input[i];
                        unmanagedBuffer[i].count = iBuffer.size;
                        unmanagedBuffer[i].type  = iBuffer.type;
                        if (iBuffer.token == null || iBuffer.token.Length == 0)
                        {
                            unmanagedBuffer[i].token = IntPtr.Zero;
                        }
                        else
                        {
                            pinnedBuffers[i]         = GCHandle.Alloc(iBuffer.token, GCHandleType.Pinned);
                            unmanagedBuffer[i].token = Marshal.UnsafeAddrOfPinnedArrayElement(iBuffer.token, iBuffer.offset);
                            buffers[i] = iBuffer.token;
                        }
                    }

                    // The result is written in the input Buffer passed as type=BufferType.Data.
                    int errorCode;
                    switch (op)
                    {
                    case OP.Encrypt:
                        errorCode = EncryptMessage(context, sdcInOut, sequenceNumber);
                        break;

                    case OP.Decrypt:
                        errorCode = DecryptMessage(context, sdcInOut, sequenceNumber);
                        break;

                    default: throw NotImplemented.ByDesignWithMessage(SR.net_MethodNotImplementedException);
                    }

                    // Marshalling back returned sizes / data.
                    for (int i = 0; i < input.Length; i++)
                    {
                        SecurityBuffer iBuffer = input[i];
                        iBuffer.size = unmanagedBuffer[i].count;
                        iBuffer.type = unmanagedBuffer[i].type;

                        if (iBuffer.size == 0)
                        {
                            iBuffer.offset = 0;
                            iBuffer.token  = null;
                        }
                        else
                        {
                            checked
                            {
                                // Find the buffer this is inside of.  Usually they all point inside buffer 0.
                                int j;
                                for (j = 0; j < input.Length; j++)
                                {
                                    if (buffers[j] == null)
                                    {
                                        continue;
                                    }

                                    byte *bufferAddress = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(buffers[j], 0);
                                    if ((byte *)unmanagedBuffer[i].token >= bufferAddress &&
                                        (byte *)unmanagedBuffer[i].token + iBuffer.size <= bufferAddress + buffers[j].Length)
                                    {
                                        iBuffer.offset = (int)((byte *)unmanagedBuffer[i].token - bufferAddress);
                                        iBuffer.token  = buffers[j];
                                        break;
                                    }
                                }

                                if (j >= input.Length)
                                {
                                    GlobalLog.Assert("SSPIWrapper::EncryptDecryptHelper", "Output buffer out of range.");
                                    iBuffer.size   = 0;
                                    iBuffer.offset = 0;
                                    iBuffer.token  = null;
                                }
                            }
                        }

                        // Backup validate the new sizes.
                        GlobalLog.Assert(iBuffer.offset >= 0 && iBuffer.offset <= (iBuffer.token == null ? 0 : iBuffer.token.Length), "SSPIWrapper::EncryptDecryptHelper|'offset' out of range.  [{0}]", iBuffer.offset);
                        GlobalLog.Assert(iBuffer.size >= 0 && iBuffer.size <= (iBuffer.token == null ? 0 : iBuffer.token.Length - iBuffer.offset), "SSPIWrapper::EncryptDecryptHelper|'size' out of range.  [{0}]", iBuffer.size);
                    }

                    if (errorCode != 0 && Logging.On)
                    {
                        if (errorCode == 0x90321)
                        {
                            Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_returned_something, op, "SEC_I_RENEGOTIATE"));
                        }
                        else
                        {
                            Logging.PrintError(Logging.Web, SR.Format(SR.net_log_operation_failed_with_error, op, String.Format(CultureInfo.CurrentCulture, "0X{0:X}", errorCode)));
                        }
                    }
                    return(MapToSecurityStatus((Interop.SecurityStatus)errorCode));
                }
                finally
                {
                    for (int i = 0; i < pinnedBuffers.Length; ++i)
                    {
                        if (pinnedBuffers[i].IsAllocated)
                        {
                            pinnedBuffers[i].Free();
                        }
                    }
                }
            }
        }
 private void Initialize(object state)
 {
     if (Logging.On)
     {
         Logging.PrintInfo(Logging.Web, SR.GetString("net_perfcounter_initialization_started"));
     }
     new PerformanceCounterPermission(PermissionState.Unrestricted).Assert();
     try
     {
         if (!PerformanceCounterCategory.Exists(".NET CLR Networking 4.0.0.0"))
         {
             if (Logging.On)
             {
                 Logging.PrintError(Logging.Web, SR.GetString("net_perfcounter_nocategory", new object[] { ".NET CLR Networking 4.0.0.0" }));
             }
         }
         else
         {
             string instanceName = GetInstanceName();
             this.counters = new CounterPair[counterNames.Length];
             for (int i = 0; i < counterNames.Length; i++)
             {
                 this.counters[i] = CreateCounterPair(counterNames[i], instanceName);
             }
             AppDomain.CurrentDomain.DomainUnload       += new EventHandler(this.UnloadEventHandler);
             AppDomain.CurrentDomain.ProcessExit        += new EventHandler(this.ExitEventHandler);
             AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(this.ExceptionEventHandler);
             this.initSuccessful = true;
         }
     }
     catch (Win32Exception exception)
     {
         if (Logging.On)
         {
             Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Initialize", exception);
         }
         this.Cleanup();
     }
     catch (InvalidOperationException exception2)
     {
         if (Logging.On)
         {
             Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Initialize", exception2);
         }
         this.Cleanup();
     }
     finally
     {
         CodeAccessPermission.RevertAssert();
         this.initDone = true;
         if (Logging.On)
         {
             if (this.initSuccessful)
             {
                 Logging.PrintInfo(Logging.Web, SR.GetString("net_perfcounter_initialized_success"));
             }
             else
             {
                 Logging.PrintInfo(Logging.Web, SR.GetString("net_perfcounter_initialized_error"));
             }
         }
     }
 }
Example #29
0
        private static void ThreadProc()
        {
            Thread.CurrentThread.IsBackground = true;
            lock (s_Queues)
            {
                if (Interlocked.CompareExchange(ref s_ThreadState, 1, 1) == 1)
                {
                    bool flag = true;
                    while (flag)
                    {
                        try
                        {
                            s_ThreadReadyEvent.Reset();
Label_0043:
                            if (s_NewQueues.Count > 0)
                            {
                                lock (s_NewQueues)
                                {
                                    for (LinkedListNode <WeakReference> node = s_NewQueues.First; node != null; node = s_NewQueues.First)
                                    {
                                        s_NewQueues.Remove(node);
                                        s_Queues.AddLast(node);
                                    }
                                }
                            }
                            int  tickCount = Environment.TickCount;
                            int  end       = 0;
                            bool flag3     = false;
                            LinkedListNode <WeakReference> first = s_Queues.First;
                            while (first != null)
                            {
                                TimerQueue target = (TimerQueue)first.Value.Target;
                                if (target == null)
                                {
                                    LinkedListNode <WeakReference> next = first.Next;
                                    s_Queues.Remove(first);
                                    first = next;
                                }
                                else
                                {
                                    int num3;
                                    if (target.Fire(out num3) && (!flag3 || IsTickBetween(tickCount, end, num3)))
                                    {
                                        end   = num3;
                                        flag3 = true;
                                    }
                                    first = first.Next;
                                }
                            }
                            int comparand           = Environment.TickCount;
                            int millisecondsTimeout = flag3 ? (IsTickBetween(tickCount, end, comparand) ? (((int)Math.Min((uint)(end - comparand), 0x7ffffff0)) + 15) : 0) : 0x7530;
                            int num6 = WaitHandle.WaitAny(s_ThreadEvents, millisecondsTimeout, false);
                            if (num6 == 0)
                            {
                                flag = false;
                            }
                            else
                            {
                                if ((num6 != 0x102) || flag3)
                                {
                                    goto Label_0043;
                                }
                                Interlocked.CompareExchange(ref s_ThreadState, 0, 1);
                                if (s_ThreadReadyEvent.WaitOne(0, false) && (Interlocked.CompareExchange(ref s_ThreadState, 1, 0) == 0))
                                {
                                    goto Label_0043;
                                }
                                flag = false;
                            }
                            continue;
                        }
                        catch (Exception exception)
                        {
                            if (NclUtilities.IsFatal(exception))
                            {
                                throw;
                            }
                            if (Logging.On)
                            {
                                Logging.PrintError(Logging.Web, "TimerThread#" + Thread.CurrentThread.ManagedThreadId.ToString(NumberFormatInfo.InvariantInfo) + "::ThreadProc() - Exception:" + exception.ToString());
                            }
                            Thread.Sleep(0x3e8);
                            continue;
                        }
                    }
                }
            }
        }
        private void Initialize(object state)
        {
            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web, SR.GetString(SR.net_perfcounter_initialization_started));
            }

            PerformanceCounterPermission perfCounterPermission = new PerformanceCounterPermission(PermissionState.Unrestricted);

            perfCounterPermission.Assert();
            try
            {
                if (!PerformanceCounterCategory.Exists(categoryName))
                {
                    // if the perf. counter category doesn't exist, just log this information and exit.
                    if (Logging.On)
                    {
                        Logging.PrintError(Logging.Web, SR.GetString(SR.net_perfcounter_nocategory, categoryName));
                    }
                    return;
                }

                string instanceName = GetInstanceName();

                Debug.Assert(counterNames.Length == Enum.GetValues(typeof(NetworkingPerfCounterName)).Length,
                             "The number of NetworkingPerfCounterName items must match the number of CounterNames");

                // create the counters, this will check for the right permissions (false)
                // means the counter is not readonly (it's read/write) and cache them while
                // we're under the Assert(), which will be reverted in the finally below.
                counters = new CounterPair[counterNames.Length];
                for (int i = 0; i < counterNames.Length; i++)
                {
                    counters[i] = CreateCounterPair(counterNames[i], instanceName);
                }

                AppDomain.CurrentDomain.DomainUnload       += new EventHandler(UnloadEventHandler);
                AppDomain.CurrentDomain.ProcessExit        += new EventHandler(ExitEventHandler);
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionEventHandler);

                initSuccessful = true;
            }
            catch (Win32Exception e)
            {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Initialize", e);
                }
                Cleanup();
                return;
            }
            catch (InvalidOperationException e)
            {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Initialize", e);
                }
                Cleanup();
                return;
            }
            finally
            {
                PerformanceCounterPermission.RevertAssert();

                initDone = true;

                if (Logging.On)
                {
                    if (initSuccessful)
                    {
                        Logging.PrintInfo(Logging.Web, SR.GetString(SR.net_perfcounter_initialized_success));
                    }
                    else
                    {
                        Logging.PrintInfo(Logging.Web, SR.GetString(SR.net_perfcounter_initialized_error));
                    }
                }
            }
        }