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); } }
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; }
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(); } }
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); } }
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; }
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); }
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; }
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); }
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; }
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; }
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(); } }); }
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); } }
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); }
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; }
public void Open(bool isReconnecting) { if (!this.closed) { this.listenerEndPoint = this.HandleServiceStart(isReconnecting); if (string.IsNullOrEmpty(this.listenerEndPoint)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("Sharing_EmptyListenerEndpoint", new object[] { this.serviceName }))); } if (!this.closed) { this.LookupListenerSid(); EventWaitHandle handle = null; bool flag = false; lock (this.ThisLock) { try { bool flag2; this.CreateControlProxy(); EventWaitHandleSecurity eventSecurity = new EventWaitHandleSecurity(); eventSecurity.AddAccessRule(new EventWaitHandleAccessRule(this.listenerUniqueSid, EventWaitHandleRights.Modify, AccessControlType.Allow)); handle = new EventWaitHandle(false, EventResetMode.ManualReset, @"Global\" + this.securityEventName, out flag2, eventSecurity); if (!flag2) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SharedManagerBase", new object[] { this.serviceName, System.ServiceModel.SR.GetString("SharedManagerServiceSecurityFailed") }))); } this.Register(); if (!handle.WaitOne(0, false)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(System.ServiceModel.SR.GetString("SharedManagerBase", new object[] { this.serviceName, System.ServiceModel.SR.GetString("SharedManagerServiceSecurityFailed") }))); } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, 0xa0005, System.ServiceModel.SR.GetString("TraceCodePortSharingListening")); } this.opened = true; flag = true; } finally { if (handle != null) { handle.Close(); } if (!flag) { this.Cleanup(true, TimeSpan.Zero); this.closed = true; } } } } } }
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); }
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); }
/************************************************************************ * Constructor * * *********************************************************************/ private Logger () { m_NoClients = 0; m_levellist = new Dictionary<string, ErrorLevel> (); /* Make sure LogCtl can write to the event log using "LogCtl" as the event source * ------------------------------------------------------------------------------ * Vista makes this difficult, and we need to add some messy code to deal with this. * Throw an exception if we can't set up the event source */ EnsureEventSourceExists (); try { using (RegistryKey logkey = Registry.LocalMachine.OpenSubKey ("SOFTWARE\\SWI\\LogCtl", false)) { m_Filename = logkey.GetValue ("LogFile").ToString (); using (RegistryKey rk = logkey.OpenSubKey ("LogLevel")) { foreach (string s in rk.GetValueNames ()) { if (string.IsNullOrEmpty (s)) { m_defaultlevel = Trans (rk.GetValue (s).ToString ()); } else { m_levellist.Add (s, Trans (rk.GetValue (s).ToString ())); } } } try { m_bIfTrace = ((int) logkey.GetValue ("IfTrace")) != 0; TextWriterTraceListener tw = new TextWriterTraceListener (logkey.GetValue ("TraceFile").ToString ()); System.Diagnostics.Trace.Listeners.Add (tw); System.Diagnostics.Trace.AutoFlush = true; System.Diagnostics.Trace.WriteLine ("Logger() built."); } catch (Exception) { EmergencyMessage (EventLogEntryType.Warning, "Missing TraceFile in registry"); } try { m_bIfUseFixedFormatting = ((int) logkey.GetValue ("IfUseFixedFormatting")) != 0; string FixedFormatting = logkey.GetValue ("FixedFormatting").ToString (); string[] ar = FixedFormatting.Split (new char[] { ',', ' ', ';' }, StringSplitOptions.RemoveEmptyEntries); if (ar.GetUpperBound (0) != 5) { EmergencyMessage (EventLogEntryType.Warning, "The FixedFormatting registry entry is not specifying 6 column widths as expected."); m_bIfUseFixedFormatting = false; } for (int i = 0; i < 6; i++) { m_ColumnWidths[i] = int.Parse (ar[i]); } } catch (Exception) { EmergencyMessage (EventLogEntryType.Warning, "IfUseFixedFormatting or FixedFormatting registry entries"); } } } catch (Exception) { /* Possibly this is the first time LogCtl has ever been used * --------------------------------------------------------- * so create some default settings */ try { using (RegistryKey logkey = Registry.LocalMachine.CreateSubKey ("SOFTWARE\\SWI\\LogCtl")) { logkey.SetValue ("LogFile", "C:\\Logs\\log.log"); using (RegistryKey rk = logkey.CreateSubKey ("LogLevel")) { rk.SetValue ("", "INF"); } logkey.SetValue ("IfTrace", 0); logkey.SetValue ("TraceFile", "C:\\Logs\\trace.log"); logkey.SetValue ("RenameEventName", "Global\\STE LogCtl-Rename"); logkey.SetValue ("IfUseFixedFormatting", 0); logkey.SetValue ("FixedFormatting", "20 12 5 4 13 26"); } } catch (UnauthorizedAccessException) { throw new Exception ("LogCtl could not read or write initialization settings. Please run as administrator and try again."); } catch (Exception e) { throw new Exception (string.Format ("Unexpected exception encountered in LogCtl. {0}", e.Message)); } } /* Prepare m_RenameEvent * --------------------- * add retries, Sept 17, 2009 -- B.Muth */ int retries = 0; TryAgain: try { using (RegistryKey logkey = Registry.LocalMachine.OpenSubKey ("SOFTWARE\\SWI\\LogCtl", false)) { string RenameEventName; RenameEventName = logkey.GetValue ("RenameEventName").ToString (); EventWaitHandleSecurity sec = new EventWaitHandleSecurity (); //EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule ("Everyone", // EventWaitHandleRights.Modify | EventWaitHandleRights.Synchronize, // AccessControlType.Allow); //EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule (new SecurityIdentifier ("S-1-1-0"), EventWaitHandleRights.FullControl, AccessControlType.Allow); // change from 'Everyone' to 'Users' EventWaitHandleAccessRule rule = new EventWaitHandleAccessRule (new SecurityIdentifier ("S-1-5-32-545"), EventWaitHandleRights.FullControl, AccessControlType.Allow); sec.AddAccessRule (rule); bool bCreated; try { m_RenameEvent = new EventWaitHandle (true, EventResetMode.ManualReset, RenameEventName, out bCreated, sec); } catch (Exception e) { EmergencyMessage (EventLogEntryType.Error, string.Format ("EventWaitHandle() failed in an attempt to create the RenameEventname. {0}", e.Message)); if (++retries < 10) { Thread.Sleep (500); goto TryAgain; } m_RenameEvent = null; } } } catch (Exception ) { throw new Exception ("RenameEventName registry entry is missing, or other exception encoutered. Please check the Application Event log."); } }
/// <summary> /// Initializes the synchronization objects needed to deal with multiple instances of the same application. /// </summary> /// <param name = "baseName">The base name of the synchronization objects.</param> /// <param name = "identity">The identity to be associated to the synchronization objects.</param> private void InitializeSynchronizationObjects(string baseName, IdentityReference identity) { string firstInstanceMutexName = baseName + "_FirstInstance"; string serviceInitializationMutexName = baseName + "_ServiceInitialization"; string serviceReadySemaphoreName = baseName + "_ServiceReady"; string signaledToFirstInstanceSemaphoreName = baseName + "_SignaledToFirstInstance"; bool isNew; var eventRule = new EventWaitHandleAccessRule(identity, EventWaitHandleRights.FullControl, AccessControlType.Allow); var eventSecurity = new EventWaitHandleSecurity(); eventSecurity.AddAccessRule(eventRule); var mutexRule = new MutexAccessRule(identity, MutexRights.FullControl, AccessControlType.Allow); var mutexSecurity = new MutexSecurity(); mutexSecurity.AddAccessRule(mutexRule); m_FirstInstanceMutex = new Mutex(false, firstInstanceMutexName, out isNew, mutexSecurity); m_ServiceInitializationMutex = new Mutex(false, serviceInitializationMutexName, out isNew, mutexSecurity); m_ServiceReadySemaphore = new EventWaitHandle(false, EventResetMode.ManualReset, serviceReadySemaphoreName, out isNew, eventSecurity); m_SignaledToFirstInstanceSemaphore = new EventWaitHandle(false, EventResetMode.AutoReset, signaledToFirstInstanceSemaphoreName, out isNew, eventSecurity); }
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); } } }
/// <summary> /// Creates an global event of specified name having empty DACL (again not NULL DACL) /// </summary> /// <param name="mNamedEventName"></param> /// <returns></returns> private EventWaitHandle CreateEvent(string mNamedEventName) { EventWaitHandle handle = null; try { //Create a security object that grants no access. EventWaitHandleSecurity mSec = new EventWaitHandleSecurity(); mSec.AddAccessRule(new EventWaitHandleAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), EventWaitHandleRights.FullControl, AccessControlType.Allow)); bool createdNew; handle = new EventWaitHandle(false, EventResetMode.ManualReset, mNamedEventName, out createdNew, mSec); } catch(WaitHandleCannotBeOpenedException whcboe) { EventLog.WriteEntry("IpcService", string.Format("IpcService::CreateEvent: WaitHandle cannot be opened: {0}", whcboe), EventLogEntryType.Error); } catch(UnauthorizedAccessException uae) { EventLog.WriteEntry("IpcService", string.Format("IpcService::CreateEvent: Unauthorized Access: {0}", uae), EventLogEntryType.Error); } catch(Exception ex) { EventLog.WriteEntry("IpcService", string.Format("IpcService::CreateEvent: Error while creating event {0}", ex), EventLogEntryType.Error); } return handle; }
public AutoCaptureEngine( IEventAggregator events, [ImportMany] IEnumerable<IImageScanner> imageScanners) { this.events = events; this.imageScanners = imageScanners; screenCapture = new ScreenCapture(); var direct3DVersion = Direct3DVersion.Direct3D9SharedMem; CaptureMethod = CaptureMethod.AutoDetect; captureConfig = new CaptureConfig { Direct3DVersion = direct3DVersion }; 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)); captureDxWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\DXHookD3D9Capture", out created, ewsecurity); hookReadyWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, "Global\\DXHookD3D9CaptureReady", out created, ewsecurity); }
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e) { EventWaitHandle result; EventWaitHandle.TryOpenExisting(@"Global\FinishedLoading", EventWaitHandleRights.Synchronize | EventWaitHandleRights.Modify, out result); if (result != null) eHandle = result; else { 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; eHandle = new EventWaitHandle(false, EventResetMode.AutoReset, @"Global\FinishedLoading", out created, security); } Refresh(this,new RoutedEventArgs()); }