Inheritance: NativeObjectSecurity
Esempio n. 1
0
        // Note: configuration based on stackoverflow answer: http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c
        public BankAccountMutex(double money)
        {
            // get application GUID as defined in AssemblyInfo.cs
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

            // unique id for global mutex - Global prefix means it is global to the machine
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            // Need a place to store a return value in Mutex() constructor call
            bool createdNew;

            // set up security for multi-user usage
            // work also on localized systems (don't use just "Everyone")
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);

            mutex = new Mutex(false, mutexId, out createdNew, securitySettings);

            LogConsole("Setting initial amount of money: " + money);

            if (money < 0)
            {
                LogConsole("The entered money quantity cannot be negative. Money: " + money);
                throw new ArgumentException(GetMessageWithTreadId("The entered money quantity cannot be negative. Money: " + money));
            }

            this.bankMoney = money;
        }
Esempio n. 2
0
        public unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity)
        {
            if(null != name && System.IO.Path.MAX_PATH < name.Length)
            { 
                throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong",name));
            } 
            Contract.EndContractBlock(); 
            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
#if !FEATURE_PAL && FEATURE_MACL 
            // For ACL's, get the security descriptor from the MutexSecurity.
            if (mutexSecurity != null) {

                secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); 
                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);
 
                byte[] sd = mutexSecurity.GetSecurityDescriptorBinaryForm(); 
                byte* pSecDescriptor = stackalloc byte[sd.Length];
                Buffer.memcpy(sd, 0, pSecDescriptor, 0, sd.Length); 
                secAttrs.pSecurityDescriptor = pSecDescriptor;
            }
#endif
 

            RuntimeHelpers.CleanupCode cleanupCode = new RuntimeHelpers.CleanupCode(MutexCleanupCode); 
            MutexCleanupInfo cleanupInfo = new MutexCleanupInfo(null, false); 
            MutexTryCodeHelper tryCodeHelper = new MutexTryCodeHelper(initiallyOwned, cleanupInfo, name, secAttrs, this);
            RuntimeHelpers.TryCode tryCode = new RuntimeHelpers.TryCode(tryCodeHelper.MutexTryCode); 
            RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(
                tryCode,
                cleanupCode,
                cleanupInfo); 
                createdNew = tryCodeHelper.m_newMutex;
 
        } 
Esempio n. 3
0
        public unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity)
        {
            if (name == string.Empty)
            {
                // Empty name is treated as an unnamed mutex. Set to null, and we will check for null from now on.
                name = null;
            }
#if !PLATFORM_UNIX
            if (name != null && System.IO.Path.MaxPath < name.Length)
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", Path.MaxPath), "name");
            }
#endif
            Contract.EndContractBlock();
            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
#if FEATURE_MACL
            // For ACL's, get the security descriptor from the MutexSecurity.
            if (mutexSecurity != null) {

                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);

                byte[] sd = mutexSecurity.GetSecurityDescriptorBinaryForm();
                byte* pSecDescriptor = stackalloc byte[sd.Length];
                Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length);
                secAttrs.pSecurityDescriptor = pSecDescriptor;
            }
#endif

            CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
        }
Esempio n. 4
0
        public unsafe Mutex(bool initiallyOwned, String name, out bool createdNew, MutexSecurity mutexSecurity)
        {
            if (name != null)
            {
#if PLATFORM_UNIX
                throw new PlatformNotSupportedException(Environment.GetResourceString("PlatformNotSupported_NamedSynchronizationPrimitives"));
#else
                if (System.IO.Path.MaxPath < name.Length)
                {
                    throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", name));
                }
#endif
            }
            Contract.EndContractBlock();
            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
#if FEATURE_MACL
            // For ACL's, get the security descriptor from the MutexSecurity.
            if (mutexSecurity != null) {

                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);

                byte[] sd = mutexSecurity.GetSecurityDescriptorBinaryForm();
                byte* pSecDescriptor = stackalloc byte[sd.Length];
                Buffer.Memcpy(pSecDescriptor, 0, sd, 0, sd.Length);
                secAttrs.pSecurityDescriptor = pSecDescriptor;
            }
#endif

            CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
        }
Esempio n. 5
0
 public static bool ObtainMutex(string settingsFolder)
 {
     SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
     MutexSecurity security = new MutexSecurity();
     bool useDefaultSecurity = false;
     bool createdNew;
     try {
         security.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));
         security.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));
         security.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));
     }
     catch (Exception ex) {
         if (ex is ArgumentOutOfRangeException || ex is NotImplementedException) {
             // Workaround for Mono
             useDefaultSecurity = true;
         }
         else {
             throw;
         }
     }
     string name = @"Global\ChanThreadWatch_" + General.Calculate64BitMD5(Encoding.UTF8.GetBytes(
         settingsFolder.ToUpperInvariant())).ToString("X16");
     Mutex mutex = !useDefaultSecurity ?
         new Mutex(false, name, out createdNew, security) :
         new Mutex(false, name);
     try {
         if (!mutex.WaitOne(0, false)) {
             return false;
         }
     }
     catch (AbandonedMutexException) { }
     ReleaseMutex();
     _mutex = mutex;
     return true;
 }
Esempio n. 6
0
        public static Mutex GrabMutex(string name)
        {
            var mutexName = "kalixLuceneSegmentMutex_" + name;
            try
            {
                return Mutex.OpenExisting(mutexName);
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                var worldSid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                var security = new MutexSecurity();
                var rule = new MutexAccessRule(worldSid, MutexRights.FullControl, AccessControlType.Allow);
                security.AddAccessRule(rule);
                var mutexIsNew = false;
                return new Mutex(false, mutexName, out mutexIsNew, security);
            }
            catch (UnauthorizedAccessException)
            {
                var m = Mutex.OpenExisting(mutexName, MutexRights.ReadPermissions | MutexRights.ChangePermissions);
                var security = m.GetAccessControl();
                var user = Environment.UserDomainName + "\\" + Environment.UserName;
                var rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow);
                security.AddAccessRule(rule);
                m.SetAccessControl(security);

                return Mutex.OpenExisting(mutexName);
            }
        }
        public static void SetAccessControl (this Mutex mutex, MutexSecurity mutexSecurity)
        {
            if (mutex == null)
                throw new ArgumentNullException (nameof (mutex));

            mutex.SetAccessControl (mutexSecurity);
        }
Esempio n. 8
0
        protected override void OnStartup(StartupEventArgs e)
        {
            // store mutex result
            bool createdNew;

            // allow multiple users to run it, but only one per user
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);

            // create mutex
            _instanceMutex = new Mutex(true, @"Global\MercurialForge_Mastery", out createdNew, securitySettings);

            // check if conflict
            if (!createdNew)
            {
                MessageBox.Show("Instance of Mastery is already running");
                _instanceMutex = null;
                Application.Current.Shutdown();
                return;
            }

            base.OnStartup(e);
            MainWindow window = new MainWindow();
            MainWindowViewModel viewModel = new MainWindowViewModel(window);
            window.DataContext = viewModel;
            window.Show();
        }
Esempio n. 9
0
        /// <summary>
        /// Tries to aquire a mutex with the name <see cref="MutexName"/>. Call this at the end of your constructors.
        /// </summary>
        /// <exception cref="UnauthorizedAccessException">Another process is already holding the mutex.</exception>
        protected void AquireMutex()
        {
            if (MachineWide)
            {
                var mutexSecurity = new MutexSecurity();
                mutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow));
                bool createdNew;
                _mutex = new Mutex(false, @"Global\" + MutexName, out createdNew, mutexSecurity);
            }
            _mutex = new Mutex(false, MutexName);

            try
            {
                switch (WaitHandle.WaitAny(new[] {_mutex, Handler.CancellationToken.WaitHandle},
                    millisecondsTimeout: (Handler.Verbosity == Verbosity.Batch) ? 30000 : 1000, exitContext: false))
                {
                    case 0:
                        return;
                    case 1:
                        throw new OperationCanceledException();
                    default:
                    case WaitHandle.WaitTimeout:
                        throw new UnauthorizedAccessException("Another process is already holding the mutex " + MutexName + ".");
                }
            }
            catch (AbandonedMutexException ex)
            {
                // Abandoned mutexes also get owned, but indicate something may have gone wrong elsewhere
                Log.Warn(ex.Message);
            }
        }
Esempio n. 10
0
        public UIMutex(string mutexName)
        {
            pGlobalMutexName = mutexName;

            // Create a string representing the current user.
            string userName = Environment.UserDomainName + "\\" + Environment.UserName;

            // Create a security object that grants no access.
            MutexSecurity mutexSecurity = new MutexSecurity();

            // Add a rule that grants the current user the right
            // to enter or release the mutex.
            MutexAccessRule mutexAccessRule = new MutexAccessRule(userName, MutexRights.FullControl, AccessControlType.Allow);
            mutexSecurity.AddAccessRule(mutexAccessRule);

            bool createdNew = false;
            pMutex = new Mutex(false, pGlobalMutexName, out createdNew, mutexSecurity);

            if (createdNew)
            {
                // loggingSystem.LogVerbose("New Mutex created {0}", pGlobalMutexName);
            }
            else
            {
                //loggingSystem.LogVerbose("Existing Mutex opened {0}", globalMutextName);
            }

        }
        public InterProcessMutexLock(String mutexName)
        {
            try
            {
                _mutexName = mutexName;

                try
                {
                    _currentMutex = Mutex.OpenExisting(_mutexName);
                }
                catch (WaitHandleCannotBeOpenedException)
                {
                    // grant everyone access to the mutex
                    var security = new MutexSecurity();
                    var everyoneIdentity = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    var rule = new MutexAccessRule(everyoneIdentity, MutexRights.FullControl, AccessControlType.Allow);
                    security.AddAccessRule(rule);

                    // make sure to not initially own it, because if you do it also acquires the lock
                    // we want to explicitly attempt to acquire the lock ourselves so we know how many times
                    // this object acquired and released the lock
                    _currentMutex = new Mutex(false, mutexName, out _created, security);
                }

                AquireMutex();
            }
            catch(Exception ex)
            {
                var exceptionString = String.Format("Exception in InterProcessMutexLock, mutex name {0}", mutexName);
                Log.Error(this, exceptionString, ex);
                throw ExceptionUtil.Rethrow(ex, exceptionString);
            }
        }
Esempio n. 12
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(true);

            string title = "KeyMagic";

            bool beta = Properties.Settings.Default.BetaRelease;

            if (beta) title += " (beta)";

            string mutexName = "\u1000\u1001";

            // http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567
            using (var mutex = new Mutex(false, mutexName))
            {
                // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
                // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);

                //edited by acidzombie24
                var hasHandle = false;
                try
                {
                    try
                    {
                        // note, you may want to time out here instead of waiting forever
                        //edited by acidzombie24
                        //mutex.WaitOne(Timeout.Infinite, false);
                        hasHandle = mutex.WaitOne(100, false);
                        if (hasHandle == false) //another instance exist
                        {
                            IntPtr pWnd = NativeMethods.FindWindow(null, title);
                            if (pWnd != IntPtr.Zero)
                            {
                                NativeMethods.ShowWindow(pWnd, 0x05);
                            }
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        // Log the fact the mutex was abandoned in another process, it will still get aquired
                    }

                    frmMain f = new frmMain();
                    Application.Run();
                }
                finally
                {
                    //edit by acidzombie24, added if statemnet
                    if (hasHandle)
                        mutex.ReleaseMutex();
                }
            }
        }
Esempio n. 13
0
 public unsafe Mutex(bool initiallyOwned, string name, out bool createdNew, MutexSecurity mutexSecurity)
 {
     if ((name != null) && (260 < name.Length))
     {
         throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", new object[] { name }));
     }
     Win32Native.SECURITY_ATTRIBUTES secAttrs = null;
     if (mutexSecurity != null)
     {
         secAttrs = new Win32Native.SECURITY_ATTRIBUTES {
             nLength = Marshal.SizeOf(secAttrs)
         };
         byte[] securityDescriptorBinaryForm = mutexSecurity.GetSecurityDescriptorBinaryForm();
         byte* pDest = stackalloc byte[1 * securityDescriptorBinaryForm.Length];
         Buffer.memcpy(securityDescriptorBinaryForm, 0, pDest, 0, securityDescriptorBinaryForm.Length);
         secAttrs.pSecurityDescriptor = pDest;
     }
     SafeWaitHandle mutexHandle = null;
     bool newMutex = false;
     RuntimeHelpers.CleanupCode backoutCode = new RuntimeHelpers.CleanupCode(this.MutexCleanupCode);
     MutexCleanupInfo cleanupInfo = new MutexCleanupInfo(mutexHandle, false);
     RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(delegate (object userData) {
         RuntimeHelpers.PrepareConstrainedRegions();
         try
         {
         }
         finally
         {
             if (initiallyOwned)
             {
                 cleanupInfo.inCriticalRegion = true;
                 Thread.BeginThreadAffinity();
                 Thread.BeginCriticalRegion();
             }
         }
         int errorCode = 0;
         RuntimeHelpers.PrepareConstrainedRegions();
         try
         {
         }
         finally
         {
             errorCode = CreateMutexHandle(initiallyOwned, name, secAttrs, out mutexHandle);
         }
         if (mutexHandle.IsInvalid)
         {
             mutexHandle.SetHandleAsInvalid();
             if (((name != null) && (name.Length != 0)) && (6 == errorCode))
             {
                 throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", new object[] { name }));
             }
             __Error.WinIOError(errorCode, name);
         }
         newMutex = errorCode != 0xb7;
         this.SetHandleInternal(mutexHandle);
         this.hasThreadAffinity = true;
     }, backoutCode, cleanupInfo);
     createdNew = newMutex;
 }
Esempio n. 14
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public static void SetAccessControl(this Mutex mutex, MutexSecurity mutexSecurity)
        {
            if (mutexSecurity == null)
                throw new ArgumentNullException("mutexSecurity");
            Contract.EndContractBlock();

            mutexSecurity.Persist(mutex.GetSafeWaitHandle());
        }
Esempio n. 15
0
 public static Mutex CreateMutexWithFullControlRights(String name, out Boolean createdNew)
 {
     SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
     MutexSecurity mutexSecurity = new MutexSecurity();
     MutexAccessRule rule = new MutexAccessRule(securityIdentifier, MutexRights.FullControl, AccessControlType.Allow);
     mutexSecurity.AddAccessRule(rule);
     return new Mutex(false, name, out createdNew, mutexSecurity);
 }
 public InterProcessLock(string name, TimeSpan timeout)
 {
     bool created;
     var security = new MutexSecurity();
     security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
     this.Mutex = new Mutex(false, name, out created, security);
     this.IsAcquired = this.Mutex.WaitOne(timeout);
 }
Esempio n. 17
0
        /// <summary>
        /// Create the mutex instance used to singal that one or more listeners are active.
        /// </summary>
        /// <param name="mutexName">The shared mutex name.</param>
        protected static Mutex CreateMutex(String mutexName)
        {
            var securitySettings = new MutexSecurity();
            var createdNew = false;

            securitySettings.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow));

            return new Mutex(false, mutexName, out createdNew, securitySettings);
        }
 internal static void EnterMutexWithoutGlobal(string mutexName, ref Mutex mutex)
 {
     bool flag;
     MutexSecurity mutexSecurity = new MutexSecurity();
     SecurityIdentifier identity = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
     mutexSecurity.AddAccessRule(new MutexAccessRule(identity, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
     Mutex mutexIn = new Mutex(false, mutexName, out flag, mutexSecurity);
     SafeWaitForMutex(mutexIn, ref mutex);
 }
Esempio n. 19
0
        public static MutexSecurity MutexSecurity()
            {
            SecurityIdentifier user = GetEveryoneSID();
            MutexSecurity result = new MutexSecurity();

            MutexAccessRule rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify | MutexRights.Delete, AccessControlType.Allow);
            result.AddAccessRule(rule);

            return result;
            }
Esempio n. 20
0
 private static MutexSecurity CreateFullAccessMutexSecurity ()
 {
     // full permissions for all authorized users
     var mutexSecurity = new MutexSecurity();
     mutexSecurity.AddAccessRule(new MutexAccessRule(
         WellKnownSidType.CreatorOwnerSid.ToIdentifier(), MutexRights.FullControl, AccessControlType.Allow));
     mutexSecurity.AddAccessRule(new MutexAccessRule(
         WellKnownSidType.AuthenticatedUserSid.ToIdentifier(), MutexRights.FullControl, AccessControlType.Allow));
     return mutexSecurity;
 }
Esempio n. 21
0
 // Methods
 public MutexHelper(string mutexName)
 {
     bool flag;
     this.pGlobalMutexName = mutexName;
     string identity = Environment.UserDomainName + @"\" + Environment.UserName;
     MutexSecurity mutexSecurity = new MutexSecurity();
     MutexAccessRule rule = new MutexAccessRule(identity, MutexRights.FullControl, AccessControlType.Allow);
     mutexSecurity.AddAccessRule(rule);
     this.pMutex = new Mutex(false, this.pGlobalMutexName, out flag, mutexSecurity);
 }
        private void InitMutex(Guid appGuid)
        {
            var mutexId = string.Format("Global\\{{{0}}}", appGuid);
            _mutex = new Mutex(false, mutexId);

            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            _mutex.SetAccessControl(securitySettings);
        }
 internal static unsafe void AcquireReservedMutex(ref bool bHandleObtained)
 {
     SafeWaitHandle handle = null;
     bHandleObtained = false;
     if (Environment.IsW2k3)
     {
         if (s_ReservedMutex == null)
         {
             Win32Native.SECURITY_ATTRIBUTES security_attributes;
             MutexSecurity security = new MutexSecurity();
             SecurityIdentifier identity = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
             security.AddAccessRule(new MutexAccessRule(identity, MutexRights.FullControl, AccessControlType.Allow));
             security_attributes = new Win32Native.SECURITY_ATTRIBUTES {
                 nLength = Marshal.SizeOf(security_attributes)
             };
             byte[] securityDescriptorBinaryForm = security.GetSecurityDescriptorBinaryForm();
             byte* pDest = stackalloc byte[(IntPtr) securityDescriptorBinaryForm.Length];
             Buffer.memcpy(securityDescriptorBinaryForm, 0, pDest, 0, securityDescriptorBinaryForm.Length);
             security_attributes.pSecurityDescriptor = pDest;
             RuntimeHelpers.PrepareConstrainedRegions();
             try
             {
             }
             finally
             {
                 handle = Win32Native.CreateMutex(security_attributes, false, @"Global\CLR_RESERVED_MUTEX_NAME");
                 handle.SetAsReservedMutex();
             }
             int errorCode = Marshal.GetLastWin32Error();
             if (handle.IsInvalid)
             {
                 handle.SetHandleAsInvalid();
                 __Error.WinIOError(errorCode, @"Global\CLR_RESERVED_MUTEX_NAME");
             }
             Mutex mutex = new Mutex(handle);
             Interlocked.CompareExchange<Mutex>(ref s_ReservedMutex, mutex, null);
         }
         RuntimeHelpers.PrepareConstrainedRegions();
         try
         {
         }
         finally
         {
             try
             {
                 s_ReservedMutex.WaitOne();
                 bHandleObtained = true;
             }
             catch (AbandonedMutexException)
             {
                 bHandleObtained = true;
             }
         }
     }
 }
Esempio n. 24
0
        private static Mutex CreateSharableMutex(string name)
        {
            // Creates a mutex sharable by more than one process
            var mutexSecurity = new MutexSecurity();
            mutexSecurity.AddAccessRule(new MutexAccessRule("Everyone", MutexRights.FullControl, AccessControlType.Allow));

            // The constructor will either create new mutex or open
            // an existing one, in a thread-safe manner
            bool createdNew;
            return new Mutex(false, name, out createdNew, mutexSecurity);
        }
Esempio n. 25
0
        private void InitMutex()
        {
            var appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value;
            var mutexId = string.Format("Global\\{{{0}}}", appGuid);
            _mutex = new Mutex(false, mutexId);

            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            _mutex.SetAccessControl(securitySettings);
        }
Esempio n. 26
0
 private static Mutex BuildMutex(string name)
 {
     name = name.Replace(":", "_");
     name = name.Replace("/", "_");
     name = name.Replace("\\", "_");
     string mutexId = string.Format("Global\\{0}", name);
     var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
     var securitySettings = new MutexSecurity();
     securitySettings.AddAccessRule(allowEveryoneRule);
     bool createdNew;
     var mutex = new Mutex(false, mutexId, out createdNew, securitySettings);
     return mutex;
 }
Esempio n. 27
0
        /// <summary>
        /// Creates a global mutex and allows everyone access to it.
        /// </summary>
        /// <param name="name">The name of the mutex to create in the Global namespace.</param>
        public GlobalMutex(string name)
        {
            // Allow full control of the mutex for everyone so that other users will be able to
            // create the same mutex and synchronise on it, if required.
            var allowEveryoneRule = new MutexAccessRule(
                new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                MutexRights.FullControl,
                AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);

            bool createdNew;
            // Use the Global prefix to make it a system-wide object
            mutex = new Mutex(false, @"Global\" + name, out createdNew, securitySettings);
        }
        private void InitWaitHandle() {
            string mutexId = String.Format("Global\\{{{0}}}", _key);

            try {
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);

                bool wasCreated = false;
                _waitHandle = new Mutex(false, mutexId, out wasCreated, securitySettings);
            } catch (Exception) {
                // We fallback to AutoResetEvent because Mutex isn't supported in medium trust.
                _waitHandle = _namedLocks.GetOrAdd(_key, key => new AutoResetEvent(true));
            }
        }
Esempio n. 29
0
        static void Main()
        {
            bool createdNew;
            var mutexSecurity = new MutexSecurity();
            mutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow));
            using (var setupMutex = new Mutex(false, @"Global\JosipMedved_HamCheck", out createdNew, mutexSecurity)) {

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Medo.Configuration.Settings.Read("CultureName", "en-US"));

                Medo.Application.UnhandledCatch.ThreadException += new EventHandler<ThreadExceptionEventArgs>(UnhandledCatch_ThreadException);
                Medo.Application.UnhandledCatch.Attach();

                Medo.Configuration.Settings.NoRegistryWrites = Settings.NoRegistryWrites;
                Medo.Windows.Forms.State.NoRegistryWrites = Settings.NoRegistryWrites;
                Medo.Diagnostics.ErrorReport.DisableAutomaticSaveToTemp = Settings.NoRegistryWrites;

                if (!((Environment.OSVersion.Version.Build < 7000) || (App.IsRunningOnMono))) {
                    var appId = Assembly.GetExecutingAssembly().Location;
                    if (appId.Length > 127) { appId = @"JosipMedved_HamCheck\" + appId.Substring(appId.Length - 127 - 20); }
                    NativeMethods.SetCurrentProcessExplicitAppUserModelID(appId);
                }

                var mainForm = new MainForm();

                //single instance
                Medo.Application.SingleInstance.NewInstanceDetected += delegate (object sender, Medo.Application.NewInstanceEventArgs e) {
                    mainForm.Show();
                    mainForm.Activate();
                };
                if (Medo.Application.SingleInstance.IsOtherInstanceRunning) {
                    var currProcess = Process.GetCurrentProcess();
                    foreach (var iProcess in Process.GetProcessesByName(currProcess.ProcessName)) {
                        try {
                            if (iProcess.Id != currProcess.Id) {
                                NativeMethods.AllowSetForegroundWindow(iProcess.Id);
                                break;
                            }
                        } catch (Win32Exception) { }
                    }
                }
                Medo.Application.SingleInstance.Attach();

                Application.Run(mainForm);
            }
        }
        public static void RunSingleProcessOnly(bool silent = false)
        {
            string        app_name = ProgramRoutines.GetAppName();
            bool          createdNew;
            MutexSecurity mutexSecurity = new System.Security.AccessControl.MutexSecurity();

            mutexSecurity.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
            for (int i = 0; i < 2; i++)
            {
                try
                {
                    GLOBAL_SINGLE_PROCESS_MUTEX = new Mutex(false, @"Global\CLIVERSOFT_" + app_name + @"_SINGLE_PROCESS", out createdNew, mutexSecurity);
                    break;
                }
                catch (Exception e)
                {//An “access denied” while creating a new Mutex can happen in the following situation:
                 //a.Process A running as an administrator creates a named mutex.
                 //b.Process B running as a normal user attempts to access the mutex which fails with “access denied” since only Administrators can access the mutex.
                    if (i == 0)
                    {
                        Thread.Sleep(1000);//wait for some time while contending, if the other instance of the program is still in progress of shutting down.
                        continue;
                    }
                    if (!silent)
                    {
                        LogMessage.Exit(e);
                    }
                    else
                    {
                        Environment.Exit(0);
                    }
                }
            }
            if (GLOBAL_SINGLE_PROCESS_MUTEX.WaitOne(1000, false))//wait for some time while contending, if the other instance of the program is still in progress of shutting down.
            {
                return;
            }
            if (!silent)
            {
                LogMessage.Exit2(app_name + " is already running, so this instance will exit.");
            }
            else
            {
                Environment.Exit(0);
            }
        }
Esempio n. 31
0
        public static bool TryGetMutex()
        {
            //source: http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c

            // get application GUID as defined in AssemblyInfo.cs
            //string appGuid = "SjUpdater\\v" +Assembly.GetExecutingAssembly().GetName().Version.Major;
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

            // unique id for global mutex - Global prefix means it is global to the machine
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            mutex = new Mutex(false, mutexId);

            // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
            // edited by 'Marc' to work also on localized systems (don't use just "Everyone")
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            mutex.SetAccessControl(securitySettings);

            // edited by acidzombie24
            try
            {
                try
                {
                    // note, you may want to time out here instead of waiting forever
                    // edited by acidzombie24
                    // mutex.WaitOne(Timeout.Infinite, false);
                    hasHandle = mutex.WaitOne(5000, false);
                    if (hasHandle == false)
                        throw new TimeoutException("Timeout waiting for exclusive access");
                }
                catch (AbandonedMutexException)
                {
                    // Log the fact the mutex was abandoned in another process, it will still get aquired
                    hasHandle = true;
                }

                return true;
            }
            catch
            {
                return false;
            }
        }