private void InitMutex()
 {
     string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
     string mutexId = string.Format("Global\\{{{0}}}", appGuid);
     this.mutex = new Mutex(false, mutexId);
     MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
     MutexSecurity securitySettings = new MutexSecurity();
     securitySettings.AddAccessRule(allowEveryoneRule);
     this.mutex.SetAccessControl(securitySettings);
 }
Ejemplo n.º 2
0
        private static Mutex CreateMutex(string name)
        {
            try
            {
                // Open the mutex.
                return(Mutex.OpenExisting(name));
            }
            catch (WaitHandleCannotBeOpenedException)
            {
                // The named mutex does not exist.
                MutexSecurity mSec = new MutexSecurity();

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

                bool mutexWasCreated;
                return(new Mutex(false, name, out mutexWasCreated, mSec));
            }
            catch (UnauthorizedAccessException)
            {
                // The named mutex exists, but the user does not have the security access required to use it.
                try
                {
                    var mutex = Mutex.OpenExisting(name, MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                    // Get the current ACL. This requires MutexRights.ReadPermissions.
                    MutexSecurity mSec = mutex.GetAccessControl();

                    // Now grant the user the correct rights.
                    MutexAccessRule rule = new MutexAccessRule(
                        new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                        MutexRights.FullControl, AccessControlType.Allow);
                    mSec.AddAccessRule(rule);

                    // Update the ACL. This requires MutexRights.ChangePermissions.
                    mutex.SetAccessControl(mSec);

                    return(Mutex.OpenExisting(name));
                }
                catch (UnauthorizedAccessException)
                {
                    return(new Mutex(false, name));
                }
            }
        }
Ejemplo n.º 3
0
    /// <summary>
    /// Tries to acquire a mutex with the name <see cref="MutexName"/>. Call this at the end of your constructors.
    /// </summary>
    /// <exception cref="TimeoutException">Another process is already holding the mutex.</exception>
    protected void AcquireMutex()
    {
#if NETFRAMEWORK
        if (MachineWide)
        {
            var mutexSecurity = new MutexSecurity();
            mutexSecurity.AddAccessRule(new(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow));
            _mutex = new(false, @"Global\" + MutexName, out _, mutexSecurity);
        }
        else
#endif
        {
            _mutex = new(false, MutexName);
        }

        _mutex.WaitOne(Handler.CancellationToken, millisecondsTimeout: 2000);
    }
Ejemplo n.º 4
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MemoryNaturalKeyRepository"/> class.
        /// </summary>
        public MemoryNaturalKeyRepository()
        {
            var securitySettings = new MutexSecurity();

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

            var mutexCreated = false;

            this.mutex = new Mutex(false, @"Global\MemoryNaturalKeyRepository3Mutex", out mutexCreated, securitySettings);
            this.file  = MemoryMappedFile.CreateOrOpen("MemoryNaturalKeyRepository3", 1 * 1024 * 1024 /* 1MB */);

            Serializer.RegisterConverters(new[] { new DateTimeConverter() });
        }
Ejemplo n.º 5
0
        internal 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_WINDOWS
            if (name != null && System.IO.Path.MaxPath < name.Length)
            {
                throw new ArgumentException(SR.Format(SR.Argument_WaitHandleNameTooLong, Path.MaxPath), nameof(name));
            }
#endif // PLATFORM_WINDOWS
            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;

            CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
        }
Ejemplo n.º 6
0
        internal 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);
        }
Ejemplo n.º 7
0
        public void Mutex_TryOpenExisting()
        {
            string        name             = GetRandomName();
            MutexSecurity expectedSecurity = GetMutexSecurity(WellKnownSidType.BuiltinUsersSid, MutexRights.FullControl, AccessControlType.Allow);

            using Mutex mutexNew = CreateAndVerifyMutex(initiallyOwned: true, name, expectedSecurity, expectedCreatedNew: true);

            Assert.True(MutexAcl.TryOpenExisting(name, MutexRights.FullControl, out Mutex mutexExisting));
            Assert.NotNull(mutexExisting);

            VerifyHandles(mutexNew, mutexExisting);
            MutexSecurity actualSecurity = mutexExisting.GetAccessControl();

            VerifyMutexSecurity(expectedSecurity, actualSecurity);

            mutexExisting.Dispose();
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Create a global shared mutex.
        /// </summary>
        /// <param name="mutexName">The mutex name.</param>
        /// <returns>Instance of Mutex.</returns>
        public static Mutex CreateSharedMutex(string mutexName)
        {
            try
            {
                MutexSecurity mutexSecurity = new MutexSecurity();

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

                bool createdNew;

                return(new Mutex(false, mutexName, out createdNew, mutexSecurity));
            }
            catch
            {
                return(null);
            }
        }
Ejemplo n.º 9
0
        private void InitMutex(string?mutexName)
        {
            if (string.IsNullOrEmpty(mutexName))
            {
                mutexName = Assembly.GetExecutingAssembly().GetName().Name ??= nameof(Luna);
            }

            Guid uniqueId = new Guid(mutexName);

            Mutex = new Mutex(false, string.Format("{0}_{1}", mutexName, uniqueId.ToString()));

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

            securitySettings.AddAccessRule(allowEveryoneRule);
            Mutex.SetAccessControl(securitySettings);
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            using (var 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);

                // edited by acidzombie24
                var hasHandle = false;
                try
                {
                    try
                    {
                        hasHandle = mutex.WaitOne(2000, false);
                        if (hasHandle == false)
                        {
                            MessageBox.Show("osu!StreamCompanion is already running.", "Error");
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        hasHandle = true;
                    }
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    AppDomain.CurrentDomain.UnhandledException +=
                        new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
                    _initializer = new Initializer();
                    _initializer.Start();
                    Application.Run(_initializer);
                }
                finally
                {
                    if (hasHandle)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
        /// <summary>
        /// Initializes a new instance of the InterProcessWaitHandle class
        /// </summary>
        /// <param name="name">the name of the underlaying mutex</param>
        public InterProcessWaitHandle(string name)
        {
            var ctl = new MutexSecurity();
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);

            ctl.AddAccessRule(allowEveryoneRule);
            innerMux = MutexAcl.Create(false, name, out bool isNew, ctl);
            if (!isNew)
            {
                LogEnvironment.LogDebugEvent("opened existing mutex...", LogSeverity.Report);
                //currentlyOwned.Value = false;
            }
            else
            {
                //currentlyOwned = false;
            }
        }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
0
        private static Mutex CreateMutex(string name)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            // Allow Everyone to signal the mutex from medium or higher integrity levels.
            MutexSecurity security = new MutexSecurity();
            SignalViewModel.SetSecurity(security);

            // Create the mutex without taking ownership.
            bool created = false;
            Mutex mtx = new Mutex(false, name, out created, security);

            return mtx;
        }
Ejemplo n.º 14
0
        private void InitializeMutex([NotNull] string serviceName)
        {
            string mutexId = string.Format("Global\\{{{0}}}",
                                           serviceName);

            m_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);
            m_Mutex.SetAccessControl(securitySettings);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Construct instance of InterProcessMutexLock with given name and acquire lock
        /// </summary>
        /// <param name="mutexName">Mutex name. Created if doesn't exist, otherwise attempts to open existing mutex</param>
        /// <exception cref="ArgumentException">Mutex must be given a name</exception>
        /// <exception cref="FailedToCreateOrAcquireMutexException">Failed to create or acquire mutex</exception>
        /// <exception cref="FailedToReaquireMutexException">Thrown when failing to re-acquire an abandoned mutex</exception>
        public InterProcessMutexLock(string mutexName)
        {
            if (string.IsNullOrEmpty(mutexName))
            {
                throw new ArgumentException("Mutex must be given a name", "mutexName");
            }

            try
            {
                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 (IOException ex)
            {
                throw new FailedToCreateOrAcquireMutexException(string.Format("Failed to create or acquire mutext: {0}", mutexName), ex);
            }
            catch (UnauthorizedAccessException ex)
            {
                throw new FailedToCreateOrAcquireMutexException(string.Format("Failed to create or acquire mutext: {0}", mutexName), ex);
            }
            catch (IdentityNotMappedException ex)
            {
                throw new FailedToCreateOrAcquireMutexException(string.Format("Failed to create or acquire mutext: {0}", mutexName), ex);
            }
            catch (WaitHandleCannotBeOpenedException ex)
            {
                throw new FailedToCreateOrAcquireMutexException(string.Format("Failed to create or acquire mutext: {0}", mutexName), ex);
            }
        }
Ejemplo n.º 16
0
        public bool Create()
        {
            m_Mutex = new Mutex(false, Log.MutexName, out bool createdNew);

            if (!createdNew)
            {
                return(false);
            }

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

            securitySettings.AddAccessRule(allowEveryoneRule);
            m_Mutex.SetAccessControl(securitySettings);
            GC.KeepAlive(m_Mutex);

            return(true);
        }
Ejemplo n.º 17
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), nameof(name));
            }
#endif
            Contract.EndContractBlock();
            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;

            CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
        }
Ejemplo n.º 18
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), nameof(name));
            }
#endif
            Contract.EndContractBlock();
            Win32Native.SECURITY_ATTRIBUTES secAttrs = null;

            CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, secAttrs);
        }
Ejemplo n.º 19
0
Archivo: App.cs Proyecto: medo64/DmmLog
        private 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_DmmLog", out createdNew, mutexSecurity)) {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

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

                Drivers.Initialize();

                Application.Run(new MainForm());
            }
        }
Ejemplo n.º 20
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", (object)name));
     }
     Win32Native.SECURITY_ATTRIBUTES securityAttributes = (Win32Native.SECURITY_ATTRIBUTES)null;
     if (mutexSecurity != null)
     {
         securityAttributes         = new Win32Native.SECURITY_ATTRIBUTES();
         securityAttributes.nLength = Marshal.SizeOf <Win32Native.SECURITY_ATTRIBUTES>(securityAttributes);
         byte[] descriptorBinaryForm = mutexSecurity.GetSecurityDescriptorBinaryForm();
         byte * pDest = stackalloc byte[descriptorBinaryForm.Length];
         Buffer.Memcpy(pDest, 0, descriptorBinaryForm, 0, descriptorBinaryForm.Length);
         securityAttributes.pSecurityDescriptor = pDest;
     }
     this.CreateMutexWithGuaranteedCleanup(initiallyOwned, name, out createdNew, securityAttributes);
 }
Ejemplo n.º 21
0
        static void Main()
        {
            MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
            MutexSecurity   securitySettings  = new MutexSecurity();

            securitySettings.AddAccessRule(allowEveryoneRule);
            using (Mutex mutex = new Mutex(false, string.Format("Global\\{{{0}}}",
                                                                "Synchrocade Updater")))
            {
                ThreadingAclExtensions.SetAccessControl(mutex, securitySettings);
                bool hasHandle = false;
                try
                {
                    try
                    {
                        hasHandle = mutex.WaitOne(TimeSpan.Zero, false);
                        if (!hasHandle)
                        {
                            MessageBox.Show(MainWindowResources.ALREADY_RUNNING, MainWindowResources.ALREADY_RUNNING_ERROR, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }
                    }
                    catch (AbandonedMutexException)
                    {
                        hasHandle = true;
                    }
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new PatcherMainWindow());
                }
                catch (Exception ex)
                {
                    Handler handler = new Handler(new WinformsErrorDisplay());
                    handler.Handle(ex);
                }
                finally
                {
                    if (hasHandle)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// bassed on http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567
        /// </summary>
        /// <returns></returns>
        public bool CheckInstance()
        {
            // 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;

            // 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 = new Mutex(false, mutexId, out createdNew, securitySettings);

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

            return(hasMutexHandle);
        }
Ejemplo n.º 23
0
        static void Main(string[] args)
        {
            // Get the application GUID defined in AssemblyInfo.cs
            string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();

            // id for global mutex (global to machine)
            string mutexId = string.Format("Global\\{{{0}}}", guid);

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

            securitySettings.AddAccessRule(allowEveryoneRule);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            using (Mutex mutex = new Mutex(false, mutexId, out _, securitySettings)) {
                bool hasHandle = false;
                try {
                    try {
                        hasHandle = mutex.WaitOne(250, false); // Timeout after 250ms.
                        if (!hasHandle)                        // Application is already running.
                        //  MessageBox.Show("The application is already running.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        {
                            SendMessage("bringtofront");

                            Environment.Exit(0);
                            return;
                        }
                    } catch (AbandonedMutexException) {
                        hasHandle = true; // The mutex was abandoned in another process, it will still get acquired.
                    }

                    // Start application normally.
                    Application.Run(new FormMain());
                } finally {
                    if (hasHandle)
                    {
                        mutex.ReleaseMutex();
                    }
                }
            }
        }
Ejemplo n.º 24
0
            public static bool Create(string procMtxName, string title)
            {
                try
                {
                    MutexSecurity security = new MutexSecurity();

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

                    bool createdNew;
                    ProcMtx = new Mutex(false, @"Global\Global_" + procMtxName, out createdNew, security);

                    if (ProcMtx.WaitOne(0))
                    {
                        return(true);
                    }

                    ProcMtx.Close();
                    ProcMtx = null;
                }
                catch (Exception e)
                {
                    MessageBox.Show("" + e, title + " / Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

                CloseProcMtx();

                MessageBox.Show(
                    "Already started on the other logon session !",
                    title + " / Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                    );

                return(false);
            }
Ejemplo n.º 25
0
        public static Mutex Create(string Name, out bool mutexWasCreated)
        {
            //Always use global scop
            string name = @"Global\" + Name;

            MutexSecurity sec = new MutexSecurity();

            MutexAccessRule secRule = new MutexAccessRule(
                new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                MutexRights.FullControl, AccessControlType.Allow);

            sec.AddAccessRule(secRule);

            bool  mutexWasCreatedOut;
            Mutex m = new Mutex(false, name, out mutexWasCreatedOut, sec);

            mutexWasCreated = mutexWasCreatedOut;
            return(m);
        }
Ejemplo n.º 26
0
        public DXHookD3D9SharedMem(CaptureInterface ssInterface)
            : base(ssInterface)
        {
            var security = new MutexSecurity();

            security.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow));
            bool created;

            sharedMemMutexes = new[]
            {
                new Mutex(false, "Global\\DXHookD3D9Shared0", out created, security),
                new Mutex(false, "Global\\DXHookD3D9Shared1", out created, security)
            };
            var ewsecurity = new EventWaitHandleSecurity();

            ewsecurity.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow));
            captureWaitHandle   = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\DXHookD3D9Capture", out created, ewsecurity);
            hookReadyWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\DXHookD3D9CaptureReady", out created, ewsecurity);
        }
Ejemplo n.º 27
0
        private void InitMutex(string _CustomID)
        {
#if MUTEX_ENABLED
            //( (GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes( typeof( GuidAttribute ), false ).GetValue( 0 ) ).Value;
            string appGuid = HEVIO.AssemblyGuidCurrent();
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);
            if (HEVText.Validate(_CustomID))
            {
                mutexId = _CustomID;
            }
            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);
#endif
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Creates a mutex that is sharable by more than one process.
        /// </summary>
        /// <param name="mutexNamePrefix">The prefix to use for the name of the mutex.</param>
        /// <returns>A <see cref="Mutex"/> object which is sharable by multiple processes.</returns>
        protected Mutex CreateSharableMutex(string mutexNamePrefix)
        {
            if (!PlatformDetector.SupportsSharableMutex)
            {
                return(new Mutex());
            }

            // Creates a mutex sharable by more than one process
            var mutexSecurity = new MutexSecurity();
            var everyoneSid   = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

            mutexSecurity.AddAccessRule(new MutexAccessRule(everyoneSid, 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, GetMutexName(mutexNamePrefix), out createdNew, mutexSecurity));
        }
Ejemplo n.º 29
0
    public static void Main()
    {
        // Create a string representing the current user.
        string user = Environment.UserDomainName + "\\" +
                      Environment.UserName;

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

        // Add a rule that grants the current user the
        // right to enter or release the mutex and read the
        // permissions on the mutex.
        MutexAccessRule rule = new MutexAccessRule(user,
                                                   MutexRights.Synchronize | MutexRights.Modify
                                                   | MutexRights.ReadPermissions,
                                                   AccessControlType.Allow);

        mSec.AddAccessRule(rule);

        // Add a rule that denies the current user the
        // right to change permissions on the mutex.
        rule = new MutexAccessRule(user,
                                   MutexRights.ChangePermissions,
                                   AccessControlType.Deny);
        mSec.AddAccessRule(rule);

        // Display the rules in the security object.
        ShowSecurity(mSec);

        // Create a rule that grants the current user
        // the right to read permissions on the mutex, and
        // take ownership of the mutex. Use this rule to
        // remove the right to read permissions from the
        // Allow rule for the current user. The inclusion
        // of the right to take ownership has no effect.
        rule = new MutexAccessRule(user,
                                   MutexRights.TakeOwnership |
                                   MutexRights.ReadPermissions,
                                   AccessControlType.Allow);
        mSec.RemoveAccessRule(rule);

        ShowSecurity(mSec);
    }
Ejemplo n.º 30
0
        private void InitMutex()
        {
            string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
            string mutexId = string.Format("Global\\{{{0}}}", appGuid);

            mutex = new Mutex(false, mutexId);

            try
            {
                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings  = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);
                mutex.SetAccessControl(securitySettings);
            }
            catch (PlatformNotSupportedException)
            {
                System.Diagnostics.Trace.WriteLine("Unable to set mutex security");
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        ///
        /// </summary>
        public static ApplicationRunning getUserTypeRurnningthisApplication()
        {
            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);
            bool   createdNew;
            // 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);
            createdNew = true;

            try
            {
                Mutex mutex = new Mutex(true, mutexId, out createdNew, securitySettings);
            }
            catch (Exception e)
            {
                createdNew = false;
            }

            if (!createdNew)
            {
                //long sameUserRunning = 0;
                long wdwIntPtr = ApplicationInstanceChecker.getSameNameProcess(true);

                if (wdwIntPtr > 0)
                {
                    ApplicationInstanceChecker.activateProcessMainWindow((long)wdwIntPtr);
                    // TODO ..
                    //MessageBox.Show("Same user running...");
                    return(ApplicationRunning.SameUserRunning);
                }
                // TODO ..
                //MessageBox.Show("Diff user running...");
                return(ApplicationRunning.DifferentUserRunning);
            }

            return(ApplicationRunning.NoUserRunning);
        }
Ejemplo n.º 32
0
        public SingletonAppGuard(Assembly assembly, int timeout)
        {
            try
            {
                assembly ??= Assembly.GetCallingAssembly();
                AppInfo appInfo = new AppInfo(assembly);
                // Global prefix means it is global to the machine.
                string mutexId = $"Global\\{appInfo.AppGuid}";
                _mutex = new Mutex(false, mutexId);

                SecurityIdentifier worldSid      = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                MutexAccessRule    allowAll      = new MutexAccessRule(worldSid, MutexRights.FullControl, AccessControlType.Allow);
                MutexSecurity      mutexSecurity = new MutexSecurity();
                mutexSecurity.AddAccessRule(allowAll);
                _mutex.SetAccessControl(mutexSecurity);
                _hasHandle = timeout < 0
                                                                ? _mutex.WaitOne(TimeSpanHelper.INFINITE, false)
                                                                : _mutex.WaitOne(timeout, false);
                if (!_hasHandle)
                {
                    throw new TimeoutException();
                }
            }
            catch (AbandonedMutexException)
            {
                _hasHandle = true;
            }
            catch
            {
                if (_mutex != null)
                {
                    if (_hasHandle)
                    {
                        _mutex.ReleaseMutex();
                    }
                    _mutex.Close();
                    ObjectHelper.Dispose(ref _mutex);
                }

                throw;
            }
        }
Ejemplo n.º 33
0
    // Mutex code from http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c
    public static void PreloadUnmanagedLibraries(string hash, string tempBasePath, IEnumerable<string> libs, Dictionary<string, string> checksums)
    {
        var mutexId = string.Format("Global\\Costura{0}", hash);

        using (var 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);

            var hasHandle = false;
            try
            {
                try
                {
                    hasHandle = mutex.WaitOne(60000, false);
                    if (hasHandle == false)
                        throw new TimeoutException("Timeout waiting for exclusive access");
                }
                catch (AbandonedMutexException)
                {
                    hasHandle = true;
                }

                var bittyness = IntPtr.Size == 8 ? "64" : "32";
                CreateDirectory(Path.Combine(tempBasePath, bittyness));
                InternalPreloadUnmanagedLibraries(tempBasePath, libs, checksums);
            }
            finally
            {
                if (hasHandle)
                    mutex.ReleaseMutex();
            }
        }
    }
 public static void SetAccessControl(this Mutex mutex, MutexSecurity mutexSecurity);
Ejemplo n.º 35
0
        static void ThreadFunc()
        {
            bool bCreated = false;
            var user = "******";
            var rule = new MutexAccessRule(user, MutexRights.FullControl, AccessControlType.Allow );
            var mSecurity = new MutexSecurity();
            mSecurity.AddAccessRule(rule);
            
            Mutex m = new Mutex(true, Program.mutex_name, out bCreated, mSecurity);
            if (!bCreated)
            {
                Console.WriteLine("Waiting... {0}", Thread.CurrentThread.ManagedThreadId);
                m.WaitOne();
                Console.WriteLine("Acquired Mutex! {0}", Thread.CurrentThread.ManagedThreadId);
            }

            System.Threading.Thread.Sleep(5 * 1000);

            m.ReleaseMutex();

            m.Close();

        }