Inheritance: NativeObjectSecurity
コード例 #1
0
ファイル: Installer.cs プロジェクト: ericschultz/coapp
        public Installer(string filename)
        {
            try {
                MsiFilename = filename;
                Task.Factory.StartNew(() => {
                    // was coapp just installed by the bootstrapper?
                    if (((AppDomain.CurrentDomain.GetData("COAPP_INSTALLED") as string) ?? "false").IsTrue()) {
                        // we'd better make sure that the most recent version of the service is running.
                        EngineServiceManager.InstallAndStartService();
                    }
                    InstallTask = LoadPackageDetails();
                });

                bool wasCreated;
                var ewhSec = new EventWaitHandleSecurity();
                ewhSec.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow));
                _ping = new EventWaitHandle(false, EventResetMode.ManualReset, "BootstrapperPing", out wasCreated, ewhSec);

                // if we got this far, CoApp must be running.
                try {
                    Application.ResourceAssembly = Assembly.GetExecutingAssembly();
                } catch {
                }

                _window = new InstallerMainWindow(this);
                _window.ShowDialog();

                if (Application.Current != null) {
                    Application.Current.Shutdown(0);
                }
                ExitQuick();
            } catch (Exception e) {
                DoError(InstallerFailureState.FailedToGetPackageDetails, e);
            }
        }
コード例 #2
0
ファイル: EventWaitHandle.cs プロジェクト: nicolas-raoul/mono
		public EventWaitHandle (bool initialState, EventResetMode mode,
					string name, out bool createdNew,
					EventWaitHandleSecurity eventSecurity)
		{
			bool manual = IsManualReset (mode);
			Handle = NativeEventCalls.CreateEvent_internal (manual, initialState, name, out createdNew);
		}
コード例 #3
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            String fileName = GetFileNameFromStartup(e);

            bool bCreated = false;
            EventWaitHandleSecurity security = new EventWaitHandleSecurity();
            String identity = WindowsIdentity.GetCurrent().Name;
            security.AddAccessRule(new EventWaitHandleAccessRule(identity, EventWaitHandleRights.FullControl, AccessControlType.Allow));
            this.nextInstanceStarted = new EventWaitHandle(false, EventResetMode.AutoReset, CommonStrings.PRODUCT_VERSION_SHORT, out bCreated, security);

            if (bCreated)
            {
                ThreadPool.RegisterWaitForSingleObject(this.nextInstanceStarted, new WaitOrTimerCallback(DispatchNextInstanceStarted), this, -1, false);

                if (!StringUtils.IsEmpty(fileName) && System.IO.File.Exists(fileName))
                {
                    DispatchShellOpen(fileName);
                }
            }
            else
            {
                if (!StringUtils.IsEmpty(fileName) && System.IO.File.Exists(fileName))
                {
                    PutFileNameToClipboard(fileName);
                }

                this.nextInstanceStarted.Set();
                Dispatcher.InvokeShutdown();
            }
        }
コード例 #4
0
        public static void SetAccessControl (this EventWaitHandle handle, EventWaitHandleSecurity eventSecurity)
        {
            if (handle == null)
                throw new ArgumentNullException (nameof (handle));

            handle.SetAccessControl (eventSecurity);
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: KebinuChiousu/MangaCrawler
        private static bool OnlyOneCopy()
        {
            bool isnew;
            s_setup_mutex = new Mutex(true, SETUP_MUTEX_NAME, out isnew);

            RestoreEvent = null;
            try
            {
#if RELEASE
                RestoreEvent = AutoResetEvent.OpenExisting(EVENT_NAME);
                RestoreEvent.Set();
                return false;
            }
            catch (WaitHandleCannotBeOpenedException)
            {
#endif
                string user = Environment.UserDomainName + "\\" + Environment.UserName;
                EventWaitHandleSecurity evh_sec = new EventWaitHandleSecurity();

                EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule(user,
                    EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify,
                    AccessControlType.Allow);
                evh_sec.AddAccessRule(rule);

                bool was_created;
                RestoreEvent = new EventWaitHandle(false, EventResetMode.AutoReset, 
                    EVENT_NAME, out was_created, evh_sec);
            }
            catch (Exception)
            {
            }

            return true;
        }
コード例 #6
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public static void SetAccessControl(this EventWaitHandle handle, EventWaitHandleSecurity eventSecurity)
        {
            if (eventSecurity == null)
                throw new ArgumentNullException("eventSecurity");
            Contract.EndContractBlock();

            eventSecurity.Persist(handle.GetSafeWaitHandle());
        }
コード例 #7
0
ファイル: Installer.cs プロジェクト: virmitio/coapp
        public Installer(string filename)
        {
            try {
                MsiFilename = filename;
                // was coapp just installed by the bootstrapper?
                var tsk = Task.Factory.StartNew(() => {
                    if (((AppDomain.CurrentDomain.GetData("COAPP_INSTALLED") as string) ?? "false").IsTrue()) {
                        // we'd better make sure that the most recent version of the service is running.
                        EngineServiceManager.InstallAndStartService();

                    }
                    bool wasCreated;
                    var ewhSec = new EventWaitHandleSecurity();
                    ewhSec.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow));
                    _ping = new EventWaitHandle(false, EventResetMode.ManualReset, "BootstrapperPing", out wasCreated, ewhSec);
                });

                // force the explorer process to pick up changes to the environment.
                EnvironmentUtility.BroadcastChange();

                var ts2= tsk.Continue(() => {
                    // gets the package data for the likely suspects.
                    _packageManager.AddSessionFeed(Path.GetDirectoryName(Path.GetFullPath(MsiFilename))).Continue(() => {
                        _packageManager.GetPackageFromFile(Path.GetFullPath(MsiFilename)).Continue(pkg =>
                            Task.WaitAll(new[] { pkg.InstalledNewest, pkg.AvailableNewestUpdate, pkg.AvailableNewestUpgrade }
                                .Select(each => each != null ? _packageManager.GetPackage(each.CanonicalName, true)
                                .Continue(() => { _packageManager.GetPackageDetails(each.CanonicalName); })
                                : "".AsResultTask())
                            .UnionSingleItem(_packageManager.GetPackageDetails(pkg).Continue(() => { PrimaryPackage = pkg; }))
                            .ToArray()));
                    });
                });

                tsk.ContinueOnFail(error => {
                    DoError(InstallerFailureState.FailedToGetPackageFromFile, error);
                    ExitQuick();
                });

                try {
                    Application.ResourceAssembly = Assembly.GetExecutingAssembly();
                }
                catch {
                }

                ts2.Wait();

                _window = new InstallerMainWindow(this);
                _window.ShowDialog();

                if (Application.Current != null) {
                    Application.Current.Shutdown(0);
                }
                ExitQuick();
            }
            catch (Exception e) {
                DoError(InstallerFailureState.FailedToGetPackageDetails, e);
            }
        }
コード例 #8
0
ファイル: Util.cs プロジェクト: SwerveRobotics/tools
        public static EventWaitHandleSecurity EventSecurity()
            {
            SecurityIdentifier user = GetEveryoneSID();
            EventWaitHandleSecurity result = new EventWaitHandleSecurity();

            EventWaitHandleAccessRule  rule = new EventWaitHandleAccessRule(user, EventWaitHandleRights.FullControl, AccessControlType.Allow);
            result.AddAccessRule(rule);

            return result;
            }
コード例 #9
0
ファイル: Signals.cs プロジェクト: virmitio/coapp
        static Signals()
        {
            bool wasCreated;
            var ewhSec = new EventWaitHandleSecurity();
            ewhSec.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow));

            AvailableEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\CoAppAvailable", out wasCreated, ewhSec);
            StartingupEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\CoAppStartingUp", out wasCreated, ewhSec);
            ShuttingdownEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\CoAppShuttingDown", out wasCreated, ewhSec);
            ShuttingdownRequestedEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\CoAppShutdownRequested", out wasCreated, ewhSec);
            InstalledEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\CoAppInstalledPackage", out wasCreated, ewhSec);
            RemovedEvent = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\CoAppRemovedPackage", out wasCreated, ewhSec);
        }
コード例 #10
0
        public static bool Create(string name, EventResetMode mode, out EventWaitHandle signal)
        {
            var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            var rule = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize |
            EventWaitHandleRights.Modify, AccessControlType.Allow);
            var security = new EventWaitHandleSecurity();
            security.AddAccessRule(rule);

            bool created;
            signal = new EventWaitHandle(false, mode, @"Global\" + name, out created, security);

            return created;
        }
コード例 #11
0
ファイル: SysWaiter.cs プロジェクト: thomb1/SeleniumBasic
        static SysWaiter() {
            string user = Environment.UserDomainName + "\\" + Environment.UserName;
            var rule = new EventWaitHandleAccessRule(user,
                                                     EventWaitHandleRights.FullControl,
                                                     AccessControlType.Allow);
            var security = new EventWaitHandleSecurity();
            security.AddAccessRule(rule);

            bool createdNew;
            _signal_interrupt = new EventWaitHandle(false,
                                                    EventResetMode.ManualReset,
                                                    @"Global\InterruptKey",
                                                    out createdNew,
                                                    security);

            HotKeyGlobal.DefineHotKey(MOD_NONE, VK_ESCAPE, ProcInterrupt);
        }
コード例 #12
0
        public unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity)
        {
            bool flag;
            if ((name != null) && (260 < name.Length))
            {
                throw new ArgumentException(Environment.GetResourceString("Argument_WaitHandleNameTooLong", new object[] { name }));
            }
            Win32Native.SECURITY_ATTRIBUTES structure = null;
            if (eventSecurity != null)
            {
                structure = new Win32Native.SECURITY_ATTRIBUTES {
                    nLength = Marshal.SizeOf(structure)
                };
                byte[] securityDescriptorBinaryForm = eventSecurity.GetSecurityDescriptorBinaryForm();
                byte* pDest = stackalloc byte[1 * securityDescriptorBinaryForm.Length];
                Buffer.memcpy(securityDescriptorBinaryForm, 0, pDest, 0, securityDescriptorBinaryForm.Length);
                structure.pSecurityDescriptor = pDest;
            }
            SafeWaitHandle handle = null;
            switch (mode)
            {
                case EventResetMode.AutoReset:
                    flag = false;
                    break;

                case EventResetMode.ManualReset:
                    flag = true;
                    break;

                default:
                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag", new object[] { name }));
            }
            handle = Win32Native.CreateEvent(structure, flag, initialState, name);
            int errorCode = Marshal.GetLastWin32Error();
            if (handle.IsInvalid)
            {
                handle.SetHandleAsInvalid();
                if (((name != null) && (name.Length != 0)) && (6 == errorCode))
                {
                    throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle", new object[] { name }));
                }
                __Error.WinIOError(errorCode, name);
            }
            createdNew = errorCode != 0xb7;
            base.SetHandleInternal(handle);
        }
コード例 #13
0
ファイル: Utils.cs プロジェクト: jbatonnet/flowtomator
        public static EventWaitHandle GetOrCreateEvent(string name)
        {
            EventWaitHandle eventWaitHandle = null;

            if (!EventWaitHandle.TryOpenExisting(@"Global\" + name, out eventWaitHandle))
            {
                SecurityIdentifier users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
                EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow);
                EventWaitHandleSecurity security = new EventWaitHandleSecurity();
                security.AddAccessRule(rule);

                bool created;
                eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, @"Global\" + name, out created, security);
            }

            return eventWaitHandle;
        }
コード例 #14
0
        public bool Flush(int timeout)
        {
            // Special case for timeout = 0; just send the request and immediately return.
            if (timeout == 0)
            {
                FlushImpl();
                return true;
            }

            // Create the wait handle with appropriate permissions.
            bool fCreatedNew;
            EventWaitHandleSecurity security = new EventWaitHandleSecurity();
            security.SetAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.ServiceSid, null), EventWaitHandleRights.Modify, AccessControlType.Allow));

            using (EventWaitHandle waitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, TRACE_FLUSH_EVENT_NAME, out fCreatedNew, security))
            {
                // Request the trace service to flush data, and wait for the service to signal completion.
                FlushImpl();
                return waitHandle.WaitOne(timeout);
            }
        }
コード例 #15
0
ファイル: UpdateService.cs プロジェクト: Shad0wSt3p/CySCA2015
        private bool SetupUpdateEvent()
        {
            bool createdNew;

            //Setup Security, all authenticated users can open and signal
            EventWaitHandleSecurity ewhs = new EventWaitHandleSecurity();
            SecurityIdentifier wellKnownAuthUsers = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
            EventWaitHandleAccessRule ewhar = new EventWaitHandleAccessRule(wellKnownAuthUsers,EventWaitHandleRights.Modify|EventWaitHandleRights.Synchronize,AccessControlType.Allow);
            ewhs.AddAccessRule(ewhar);
                    
            //Create the update named event
            try
            {
                mRunUpdateEvent = new EventWaitHandle(false, EventResetMode.ManualReset, TRIGGER_EVENT_NAME, out createdNew, ewhs);
            }
            catch (Exception e)
            {
                System.Diagnostics.EventLog.WriteEntry(this.ServiceName, "Software Update Service threw an exception when trying to create the update trigger event. Detail="+e.ToString());
                return false;
            }

            return true;            
        }
コード例 #16
0
        private void ConfigureDropListener()
        {
            var sid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
            var accessRule = new EventWaitHandleAccessRule(sid, EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, AccessControlType.Allow);

            var security = new EventWaitHandleSecurity();
            security.AddAccessRule(accessRule);

            bool newlyCreated = false;
            var waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, "ExtensionsForOneDrive_DataAvailableEvent", out newlyCreated, security);

            if (!newlyCreated)
            {
                throw new InvalidOperationException("Configuration Changed event already exists.");
            }

            _changeListenerTask = Task.Factory.StartNew(() =>
            {
                while (waitHandle.WaitOne())
                {
                    GetPublicLinkAndStore();
                }
            });
        }
コード例 #17
0
ファイル: EventWaitHandle.cs プロジェクト: nicolas-raoul/mono
		public void SetAccessControl (EventWaitHandleSecurity eventSecurity)
		{
			if (null == eventSecurity)
				throw new ArgumentNullException ("eventSecurity");
				
			eventSecurity.PersistModifications (SafeWaitHandle);

		}
コード例 #18
0
ファイル: Monitor.cs プロジェクト: roomaroo/coapp.powershell
        public static void Start() {
            if (_listenTask == null) {
                lock (typeof (Monitor)) {
                    _cancellationTokenSource = new CancellationTokenSource();

                    bool wasCreated;
                    var ewhSec = new EventWaitHandleSecurity();
                    ewhSec.AddAccessRule(
                        new EventWaitHandleAccessRule(
                            new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    var sessionAckEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_BUFFER_READY", out wasCreated, ewhSec);
                    var sessionReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "DBWIN_DATA_READY", out wasCreated, ewhSec);
                    var globalAckEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Global\\DBWIN_BUFFER_READY", out wasCreated, ewhSec);
                    var globalReadyEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Global\\DBWIN_DATA_READY", out wasCreated, ewhSec);

                    var sd = new SECURITY_DESCRIPTOR();
                    var sa = new SECURITY_ATTRIBUTES();

                    // Initialize the security descriptor.
                    if (!Advapi32.InitializeSecurityDescriptor(ref sd, 1)) {
                        throw new ApplicationException(
                            string.Format("{0}. Last Win32 Error was {1}", "Failed to initializes the security descriptor.", Marshal.GetLastWin32Error()));
                    }

                    // Set information in a discretionary access control list
                    if (!Advapi32.SetSecurityDescriptorDacl(ref sd, true, IntPtr.Zero, false)) {
                        throw new ApplicationException(
                            string.Format("{0}. Last Win32 Error was {1}", "Failed to initializes the security descriptor", Marshal.GetLastWin32Error()));
                    }

                    // Create the event for slot 'DBWIN_BUFFER_READY'
                    sa.nLength = Marshal.SizeOf(sa);
                    sa.lpSecurityDescriptor = Marshal.AllocHGlobal(Marshal.SizeOf(sd));
                    Marshal.StructureToPtr(sd, sa.lpSecurityDescriptor, false);

                    // Get a handle to the readable shared memory at slot 'DBWIN_BUFFER'.
                    var sessionSharedFileHandle = Kernel32.CreateFileMapping(new IntPtr(-1), ref sa, PageProtection.ReadWrite, 0, 4096, "DBWIN_BUFFER");
                    if (sessionSharedFileHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a file mapping to slot 'DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    // Create a view for this file mapping so we can access it
                    var sessionSharedMemoryHandle = Kernel32.MapViewOfFile(sessionSharedFileHandle, /*SECTION_MAP_READ*/ 0x0004, 0, 0, 4096);
                    if (sessionSharedMemoryHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a mapping view for slot 'DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    // Get a handle to the readable shared memory at slot 'DBWIN_BUFFER'.
                    var globalSharedFileHandle = Kernel32.CreateFileMapping(new IntPtr(-1), ref sa, PageProtection.ReadWrite, 0, 4096, "Global\\DBWIN_BUFFER");
                    if (globalSharedFileHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a file mapping to slot 'Global\\DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    // Create a view for this file mapping so we can access it
                    var globalSharedMemoryHandle = Kernel32.MapViewOfFile(globalSharedFileHandle, /*SECTION_MAP_READ*/ 0x0004, 0, 0, 4096);
                    if (globalSharedMemoryHandle == IntPtr.Zero) {
                        throw new ApplicationException(
                            string.Format(
                                "{0}. Last Win32 Error was {1}", "Failed to create a mapping view for slot 'Global\\DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                    }

                    var queue = new Queue<Tuple<int, DateTime, string>>();
                    var dataAvailable = new ManualResetEvent(true);

                    _listenTask = Task.Factory.StartNew(
                        () => {
                            // Everything after the first DWORD is our debugging text
                            IntPtr sessionStringPointer;
                            IntPtr globalStringPointer;

                            if (Environment.Is64BitProcess) {
                                sessionStringPointer = new IntPtr(sessionSharedMemoryHandle.ToInt64() + Marshal.SizeOf(typeof (int)));
                                globalStringPointer = new IntPtr(globalSharedMemoryHandle.ToInt64() + Marshal.SizeOf(typeof (int)));
                            } else {
                                sessionStringPointer = new IntPtr(sessionSharedMemoryHandle.ToInt32() + Marshal.SizeOf(typeof (int)));
                                globalStringPointer = new IntPtr(globalSharedMemoryHandle.ToInt32() + Marshal.SizeOf(typeof (int)));
                            }

                            while (!_cancellationTokenSource.IsCancellationRequested) {
                                sessionAckEvent.Set();
                                globalAckEvent.Set();

                                try {
                                    var i = WaitHandle.WaitAny(new[] {
                                        sessionReadyEvent, globalReadyEvent, _cancellationTokenSource.Token.WaitHandle
                                    });
                                    var now = DateTime.Now;
                                    if (i == 0) {
                                        lock (queue) {
                                            queue.Enqueue(new Tuple<int, DateTime, string>(Marshal.ReadInt32(sessionSharedMemoryHandle), now, Marshal.PtrToStringAnsi(sessionStringPointer)));
                                            dataAvailable.Set();
                                        }
                                    }

                                    if (i == 1) {
                                        lock (queue) {
                                            queue.Enqueue(new Tuple<int, DateTime, string>(Marshal.ReadInt32(globalSharedMemoryHandle), now, Marshal.PtrToStringAnsi(globalStringPointer)));
                                            dataAvailable.Set();
                                        }
                                    }
                                } catch {
                                    // it's over. 
                                    _cancellationTokenSource.Cancel();
                                }
                            }
                            _listenTask = null;

                            // cleanup after stopping.
                            globalAckEvent.Reset();
                            globalAckEvent.Dispose();
                            globalAckEvent = null;

                            sessionAckEvent.Reset();
                            sessionAckEvent.Dispose();
                            sessionAckEvent = null;

                            globalReadyEvent.Reset();
                            globalReadyEvent.Dispose();
                            globalReadyEvent = null;

                            sessionReadyEvent.Reset();
                            sessionReadyEvent.Dispose();
                            sessionReadyEvent = null;

                            // Close SharedFile
                            if (sessionSharedFileHandle != IntPtr.Zero) {
                                if (!Kernel32.CloseHandle(sessionSharedFileHandle)) {
                                    throw new ApplicationException(
                                        string.Format("{0}. Last Win32 Error was {1}", "Failed to close handle for 'SharedFile'", Marshal.GetLastWin32Error()));
                                }
                                sessionSharedFileHandle = IntPtr.Zero;
                            }

                            // Unmap SharedMem
                            if (sessionSharedMemoryHandle != IntPtr.Zero) {
                                if (!Kernel32.UnmapViewOfFile(sessionSharedMemoryHandle)) {
                                    throw new ApplicationException(
                                        string.Format(
                                            "{0}. Last Win32 Error was {1}", "Failed to unmap view for slot 'DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                                }
                                sessionSharedMemoryHandle = IntPtr.Zero;
                            }

                            // Close SharedFile
                            if (globalSharedFileHandle != IntPtr.Zero) {
                                if (!Kernel32.CloseHandle(globalSharedFileHandle)) {
                                    throw new ApplicationException(
                                        string.Format("{0}. Last Win32 Error was {1}", "Failed to close handle for 'SharedFile'", Marshal.GetLastWin32Error()));
                                }
                                globalSharedFileHandle = IntPtr.Zero;
                            }

                            // Unmap SharedMem
                            if (globalSharedMemoryHandle != IntPtr.Zero) {
                                if (!Kernel32.UnmapViewOfFile(globalSharedMemoryHandle)) {
                                    throw new ApplicationException(
                                        string.Format(
                                            "{0}. Last Win32 Error was {1}", "Failed to unmap view for slot 'Global\\DBWIN_BUFFER'", Marshal.GetLastWin32Error()));
                                }
                                globalSharedMemoryHandle = IntPtr.Zero;
                            }
                        }, _cancellationTokenSource.Token);

                    Task.Factory.StartNew(() => {
                        // handle events on seperate task to minimize the work that is done blocking the handles
                        Tuple<int, DateTime, string> item = null;

                        while (WaitHandle.WaitAny(new[] {
                            dataAvailable, _cancellationTokenSource.Token.WaitHandle
                        }) == 0) {
                            lock (queue) {
                                if (queue.Count > 0) {
                                    item = queue.Dequeue();
                                }
                                if (queue.Count == 0) {
                                    dataAvailable.Reset();
                                }
                            }

                            if (item == null || OnOutputDebugString == null) {
                                continue;
                            }

                            try {
                                OnOutputDebugString(new OutputDebugStringEventArgs(item.Item1, item.Item2, item.Item3));
                            } catch {
                                // if it's taken, good, if not--well too bad!
                            }
                        }
                    }, _cancellationTokenSource.Token);
                }
            }
        }
コード例 #19
0
ファイル: EventWaitHandle.cs プロジェクト: robert-j/mono-fork
		public void SetAccessControl (EventWaitHandleSecurity eventSecurity)
		{
			throw new NotImplementedException ();
		}
コード例 #20
0
ファイル: EventWaitHandle.cs プロジェクト: nlhepler/mono
		public EventWaitHandle (bool initialState, EventResetMode mode,
		                        string name, out bool createdNew,
		                        EventWaitHandleSecurity eventSecurity)
		{
			throw new NotSupportedException ();
		}
コード例 #21
0
 public void SetAccessControl(EventWaitHandleSecurity eventSecurity)
 {
     if (eventSecurity == null)
     {
         throw new ArgumentNullException("eventSecurity");
     }
     eventSecurity.Persist(base.safeWaitHandle);
 }
コード例 #22
0
ファイル: MemoryManager.cs プロジェクト: Sam13/opencover
            internal ManagedCommunicationBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable<string> servicePrincpal)
            {
                Namespace = @namespace;
                Key = key;

                EventWaitHandleSecurity open = null;
                MemoryMappedFileSecurity transparent = null;

                var service = servicePrincpal.FirstOrDefault();
                var currentIdentity = WindowsIdentity.GetCurrent();
                if (service != null && currentIdentity != null)
                {
                    open = new EventWaitHandleSecurity();
                    open.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow));
                    open.AddAccessRule(new EventWaitHandleAccessRule(service, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    transparent = new MemoryMappedFileSecurity();
                    transparent.AddAccessRule(new AccessRule<MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    transparent.AddAccessRule(new AccessRule<MemoryMappedFileRights>(service, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
                }

                _memoryMappedFile = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Communication_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    transparent,
                    HandleInheritability.Inheritable);

                StreamAccessorComms = _memoryMappedFile.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);

                bool createdNew;

                ProfilerRequestsInformation = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendData_Event_", bufferId),
                    out createdNew,
                    open);

                InformationReadyForProfiler = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveData_Event_", bufferId),
                    out createdNew,
                    open);

                InformationReadByProfiler = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ChunkData_Event_", bufferId),
                    out createdNew,
                    open);

                DataCommunication = new byte[bufferSize];
                PinnedDataCommunication = GCHandle.Alloc(DataCommunication, GCHandleType.Pinned);
            }
コード例 #23
0
ファイル: MemoryManager.cs プロジェクト: Sam13/opencover
            internal ManagedMemoryBlock(string @namespace, string key, int bufferSize, int bufferId, IEnumerable<string> servicePrincpal)
            {
                Namespace = @namespace;
                Key = key;

                EventWaitHandleSecurity open = null;
                MemoryMappedFileSecurity transparent = null;

                var service = servicePrincpal.FirstOrDefault();
                var currentIdentity = WindowsIdentity.GetCurrent();
                if (service != null && currentIdentity != null)
                {
                    open = new EventWaitHandleSecurity();
                    open.AddAccessRule(new EventWaitHandleAccessRule(currentIdentity.Name, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    // The event handles need more than just EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize to work
                    open.AddAccessRule(new EventWaitHandleAccessRule(service, EventWaitHandleRights.FullControl, AccessControlType.Allow));

                    transparent = new MemoryMappedFileSecurity();
                    transparent.AddAccessRule(new AccessRule<MemoryMappedFileRights>(currentIdentity.Name, MemoryMappedFileRights.FullControl, AccessControlType.Allow));
                    transparent.AddAccessRule(new AccessRule<MemoryMappedFileRights>(service, MemoryMappedFileRights.ReadWrite, AccessControlType.Allow));
                }

                bool createdNew;

                ProfilerHasResults = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_SendResults_Event_", bufferId),
                    out createdNew,
                    open);

                ResultsHaveBeenReceived = new EventWaitHandle(
                    false,
                    EventResetMode.ManualReset,
                    MakeName(@"\OpenCover_Profiler_Communication_ReceiveResults_Event_", bufferId),
                    out createdNew,
                    open);

                _mmfResults = MemoryMappedFile.CreateNew(
                    MakeName(@"\OpenCover_Profiler_Results_MemoryMapFile_", bufferId),
                    bufferSize,
                    MemoryMappedFileAccess.ReadWrite,
                    MemoryMappedFileOptions.None,
                    transparent,
                    HandleInheritability.Inheritable);

                StreamAccessorResults = _mmfResults.CreateViewStream(0, bufferSize, MemoryMappedFileAccess.ReadWrite);
                StreamAccessorResults.Write(BitConverter.GetBytes(0), 0, 4);
                BufferSize = bufferSize;
            }
コード例 #24
0
        [System.Security.SecuritySafeCritical]  // auto-generated
        public void SetAccessControl(EventWaitHandleSecurity eventSecurity)
        {
            if (eventSecurity == null)
                throw new ArgumentNullException("eventSecurity");
            Contract.EndContractBlock();

            eventSecurity.Persist(safeWaitHandle);
        }
コード例 #25
0
        public unsafe EventWaitHandle(bool initialState, EventResetMode mode, string name, out bool createdNew, EventWaitHandleSecurity eventSecurity)
        {
            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_MACL
            // For ACL's, get the security descriptor from the EventWaitHandleSecurity.
            if (eventSecurity != null) {
                secAttrs = new Win32Native.SECURITY_ATTRIBUTES();
                secAttrs.nLength = (int)Marshal.SizeOf(secAttrs);

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

            SafeWaitHandle _handle = null;
            Boolean isManualReset;
            switch(mode)
            {
                case EventResetMode.ManualReset:
                    isManualReset = true;
                    break;
                case EventResetMode.AutoReset:
                    isManualReset = false;
                    break;

                default:
                    throw new ArgumentException(Environment.GetResourceString("Argument_InvalidFlag",name));
            };

            _handle = Win32Native.CreateEvent(secAttrs, isManualReset, initialState, name);
            int errorCode = Marshal.GetLastWin32Error();

            if (_handle.IsInvalid)
            {

                _handle.SetHandleAsInvalid();
                if(null != name && 0 != name.Length && Win32Native.ERROR_INVALID_HANDLE == errorCode)
                    throw new WaitHandleCannotBeOpenedException(Environment.GetResourceString("Threading.WaitHandleCannotBeOpenedException_InvalidHandle",name));

                __Error.WinIOError(errorCode, name);
            }
            createdNew = errorCode != Win32Native.ERROR_ALREADY_EXISTS;
            SetHandleInternal(_handle);
        }
コード例 #26
0
 public static void SetAccessControl(EventWaitHandle handle, EventWaitHandleSecurity eventSecurity)
 {
     handle.SetAccessControl(eventSecurity);
 }
コード例 #27
0
        private EventWaitHandle CreateGlobalEventWaitHandle(string name)
        {
            var users = new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null);
            var rule = new EventWaitHandleAccessRule(users, EventWaitHandleRights.Synchronize |
                EventWaitHandleRights.Modify, AccessControlType.Allow);
            var security = new EventWaitHandleSecurity();
            security.AddAccessRule(rule);

            bool createdNew;
            return new EventWaitHandle(false, EventResetMode.AutoReset, name, out createdNew, security);
        }
コード例 #28
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);
 }
コード例 #29
0
    public TvServiceThread()
    {
      // set working dir from application.exe
      string applicationPath = Application.ExecutablePath;
      applicationPath = System.IO.Path.GetFullPath(applicationPath);
      applicationPath = System.IO.Path.GetDirectoryName(applicationPath);
      System.IO.Directory.SetCurrentDirectory(applicationPath);

      _powerEventHandlers = new List<PowerEventHandler>();
      GlobalServiceProvider.Instance.Add<IPowerEventHandler>(this);
      AddPowerEventHandler(OnPowerEventHandler);
      try
      {
        Log.Debug("Setting up EventWaitHandle with name: {0}", RemoteControl.InitializedEventName);

        EventWaitHandleAccessRule rule =
          new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                                        EventWaitHandleRights.FullControl, AccessControlType.Allow);
        EventWaitHandleSecurity sec = new EventWaitHandleSecurity();
        sec.AddAccessRule(rule);
        bool eventCreated;
        _InitializedEvent = new EventWaitHandle(false, EventResetMode.ManualReset, RemoteControl.InitializedEventName,
                                                out eventCreated, sec);
        if (!eventCreated)
        {
          Log.Info("{0} was not created", RemoteControl.InitializedEventName);
        }
      }
      catch (Exception ex)
      {
        Log.Write(ex);
      }
      // setup the remoting channels
      try
      {
        string remotingFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
        // process the remoting configuration file
        RemotingConfiguration.Configure(remotingFile, false);
      }
      catch (Exception ex)
      {
        Log.Write(ex);
      }
    }
コード例 #30
0
ファイル: SignalViewModel.cs プロジェクト: Jeremiahf/wix3
        private static EventWaitHandle CreateEvent(string name, bool auto)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentNullException("name");
            }

            // Allow everyone to signal the event from medium or higher integrity levels.
            EventWaitHandleSecurity security = new EventWaitHandleSecurity();
            SignalViewModel.SetSecurity(security);

            // Create the event without signaling.
            EventResetMode mode = auto ? EventResetMode.AutoReset : EventResetMode.ManualReset;
            bool created = false;
            EventWaitHandle evt = new EventWaitHandle(false, EventResetMode.AutoReset, name, out created, security);

            return evt;
        }