π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
fix(ensu): handle elevated launches and shutdown
setalp88494b825245
diff --git a/rust/apps/ensu/src-tauri/Cargo.toml b/rust/apps/ensu/src-tauri/Cargo.tomlindex 53a228b28b..141cac04fd 100644--- a/rust/apps/ensu/src-tauri/Cargo.toml+++ b/rust/apps/ensu/src-tauri/Cargo.toml@@ -29,7 +29,7 @@ libc = "0.2.0"rustix = { version = "1.1.4", features = ["fs"] }[target.'cfg(windows)'.dependencies]-windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }+windows-sys = { version = "0.61.2", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_Storage_FileSystem", "Win32_System_SystemInformation", "Win32_System_Threading"] }[target.'cfg(target_os = "linux")'.dependencies]tauri-plugin-single-instance = "2.4.4"diff --git a/rust/apps/ensu/src-tauri/src/single_instance.rs b/rust/apps/ensu/src-tauri/src/single_instance.rsindex e498612601..4f2578020d 100644--- a/rust/apps/ensu/src-tauri/src/single_instance.rs+++ b/rust/apps/ensu/src-tauri/src/single_instance.rs@@ -26,15 +26,51 @@ pub fn plugin() -> TauriPlugin<tauri::Wry> {Ok(())}).on_event(|app, event| {- if matches!(event, tauri::RunEvent::Ready) {- let instance = app.state::<windows::Instance>();- let app = app.clone();- if let Err(error) = instance.listen(move || focus_main_window(&app)) {- logging::log(- "App",- format!("failed to listen for activation error={error}"),- );+ let instance = app.state::<windows::Instance>();+ match event {+ tauri::RunEvent::Ready => {+ let handle = app.clone();+ let result = instance+ .listen(move || {+ let app = handle.clone();+ if let Err(error) = handle.run_on_main_thread(move || {+ if let Err(error) = app+ .state::<windows::Instance>()+ .activate(|| focus_main_window(&app))+ {+ logging::log(+ "App",+ format!(+ "failed to acknowledge activation error={error}"+ ),+ );+ app.exit(1);+ }+ }) {+ logging::log(+ "App",+ format!("failed to dispatch activation error={error}"),+ );+ }+ })+ .and_then(|()| instance.activate(|| {}));+ if let Err(error) = result {+ logging::log(+ "App",+ format!("failed to listen for activation error={error}"),+ );+ app.exit(1);+ }}+ tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit => {+ instance.mark_exiting()+ }+ tauri::RunEvent::WindowEvent {+ label,+ event: tauri::WindowEvent::CloseRequested { .. } | tauri::WindowEvent::Destroyed,+ ..+ } if label == "main" => instance.mark_exiting(),+ _ => {}}}).build()diff --git a/rust/apps/ensu/src-tauri/src/single_instance/windows.rs b/rust/apps/ensu/src-tauri/src/single_instance/windows.rsindex 8b7ce40e7d..2ee1ced0cd 100644--- a/rust/apps/ensu/src-tauri/src/single_instance/windows.rs+++ b/rust/apps/ensu/src-tauri/src/single_instance/windows.rs@@ -1,40 +1,113 @@use std::io;use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};use std::sync::Arc;+use std::sync::atomic::{AtomicBool, Ordering};-use windows_sys::Win32::Foundation::{ERROR_ALREADY_EXISTS, GetLastError, WAIT_OBJECT_0};+use windows_sys::Win32::Foundation::{+ HANDLE, LocalFree, WAIT_ABANDONED_0, WAIT_OBJECT_0, WAIT_TIMEOUT,+};+use windows_sys::Win32::Security::Authorization::{+ ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,+};+use windows_sys::Win32::Security::SECURITY_ATTRIBUTES;use windows_sys::Win32::System::Threading::{- CreateEventW, INFINITE, SetEvent, WaitForSingleObject,+ CREATE_EVENT_MANUAL_RESET, CreateEventExW, CreateMutexExW, EVENT_MODIFY_STATE, INFINITE,+ MUTEX_MODIFY_STATE, ResetEvent, SYNCHRONIZATION_SYNCHRONIZE, SetEvent, WaitForMultipleObjects,+ WaitForSingleObject,};pub(super) struct Instance {+ _ownership: OwnedHandle,activation: Arc<OwnedHandle>,+ acknowledged: OwnedHandle,+ exiting: AtomicBool,}impl Instance {- #[expect(unsafe_code, reason = "Create, own, and signal a named Win32 event")]+ #[expect(+ unsafe_code,+ reason = "Acquire Win32 instance ownership or await activation"+ )]pub(super) fn acquire(identifier: &str) -> io::Result<Option<Self>> {- let event_name = format!("Local\\{identifier}.activation")- .encode_utf16()- .chain(Some(0))- .collect::<Vec<_>>();- let raw_event = unsafe { CreateEventW(std::ptr::null(), 0, 0, event_name.as_ptr()) };- let already_running = unsafe { GetLastError() } == ERROR_ALREADY_EXISTS;- if raw_event.is_null() {- return Err(io::Error::last_os_error());- }- let activation = unsafe { OwnedHandle::from_raw_handle(raw_event) };- if already_running {- if unsafe { SetEvent(activation.as_raw_handle()) } == 0 {- return Err(io::Error::last_os_error());+ let ownership = named_handle(+ &format!("Local\\{identifier}.instance"),+ |attrs, name| unsafe {+ CreateMutexExW(+ attrs,+ name,+ 0,+ SYNCHRONIZATION_SYNCHRONIZE | MUTEX_MODIFY_STATE,+ )+ },+ )?;+ let activation = named_handle(+ &format!("Local\\{identifier}.activation"),+ |attrs, name| unsafe {+ CreateEventExW(+ attrs,+ name,+ 0,+ SYNCHRONIZATION_SYNCHRONIZE | EVENT_MODIFY_STATE,+ )+ },+ )?;+ let acknowledged = named_handle(+ &format!("Local\\{identifier}.activated"),+ |attrs, name| unsafe {+ CreateEventExW(+ attrs,+ name,+ CREATE_EVENT_MANUAL_RESET,+ SYNCHRONIZATION_SYNCHRONIZE | EVENT_MODIFY_STATE,+ )+ },+ )?;+ match unsafe { WaitForSingleObject(ownership.as_raw_handle(), 0) } {+ WAIT_OBJECT_0 | WAIT_ABANDONED_0 => {}+ WAIT_TIMEOUT => {+ if unsafe { ResetEvent(acknowledged.as_raw_handle()) } == 0+ || unsafe { SetEvent(activation.as_raw_handle()) } == 0+ {+ return Err(io::Error::last_os_error());+ }+ let handles = [ownership.as_raw_handle(), acknowledged.as_raw_handle()];+ match unsafe { WaitForMultipleObjects(2, handles.as_ptr(), 0, INFINITE) } {+ WAIT_OBJECT_0 | WAIT_ABANDONED_0 => {}+ result if result == WAIT_OBJECT_0 + 1 => return Ok(None),+ _ => return Err(io::Error::last_os_error()),+ }}- return Ok(None);+ _ => return Err(io::Error::last_os_error()),+ }+ if unsafe { ResetEvent(acknowledged.as_raw_handle()) } == 0 {+ return Err(io::Error::last_os_error());}Ok(Some(Self {+ _ownership: ownership,activation: Arc::new(activation),+ acknowledged,+ exiting: AtomicBool::new(false),}))}+ pub(super) fn mark_exiting(&self) {+ self.exiting.store(true, Ordering::Relaxed);+ }++ #[expect(+ unsafe_code,+ reason = "Acknowledge activation only while the primary is running"+ )]+ pub(super) fn activate(&self, on_activation: impl FnOnce()) -> io::Result<()> {+ if !self.exiting.load(Ordering::Relaxed) {+ on_activation();+ if unsafe { SetEvent(self.acknowledged.as_raw_handle()) } == 0 {+ return Err(io::Error::last_os_error());+ }+ }+ Ok(())+ }+pub(super) fn listen(&self, on_activation: impl Fn() + Send + 'static) -> io::Result<()> {let activation = Arc::clone(&self.activation);std::thread::Builder::new()@@ -57,6 +130,42 @@ impl Instance {}}+#[expect(+ unsafe_code,+ reason = "Create a medium-integrity Win32 object with the token's default ACL"+)]+fn named_handle(+ name: &str,+ create: impl FnOnce(&SECURITY_ATTRIBUTES, *const u16) -> HANDLE,+) -> io::Result<OwnedHandle> {+ let mut descriptor = std::ptr::null_mut();+ if unsafe {+ ConvertStringSecurityDescriptorToSecurityDescriptorW(+ windows_sys::core::w!("S:(ML;;NW;;;ME)"),+ SDDL_REVISION_1,+ &mut descriptor,+ std::ptr::null_mut(),+ )+ } == 0+ {+ return Err(io::Error::last_os_error());+ }+ let attributes = SECURITY_ATTRIBUTES {+ nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,+ lpSecurityDescriptor: descriptor,+ bInheritHandle: 0,+ };+ let name = name.encode_utf16().chain(Some(0)).collect::<Vec<_>>();+ let handle = create(&attributes, name.as_ptr());+ let result = if handle.is_null() {+ Err(io::Error::last_os_error())+ } else {+ Ok(unsafe { OwnedHandle::from_raw_handle(handle) })+ };+ unsafe { LocalFree(descriptor) };+ result+}+#[expect(unsafe_code,reason = "Wait on the activation event while its handle remains owned"