Skip to main content

strata_platform/
single_instance.rs

1//! Single-Instance Mutex and Inter-Process Communication (IPC) Window Focusing.
2//!
3//! Prevents duplicate application processes from opening when an executable is launched
4//! repeatedly, automatically forwarding CLI arguments to the primary instance and requesting
5//! window focusing / un-minimization.
6//!
7//! Unix hosts use a domain socket in `$XDG_RUNTIME_DIR` (falling back to `/tmp`). Windows
8//! hosts use a named pipe at `\\.\pipe\<sanitized-app-id>`. Both transports forward
9//! newline-separated CLI arguments to the primary instance.
10
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::sync::Arc;
13
14#[cfg(unix)]
15use std::path::PathBuf;
16
17/// Status result when attempting to acquire a single-instance application lock.
18#[derive(Debug)]
19pub enum SingleInstanceStatus {
20    /// This process is the primary instance and acquired the exclusive mutex.
21    Primary(SingleInstanceLock),
22    /// A primary instance is already running; CLI arguments were forwarded and this process should exit.
23    SecondaryExited,
24}
25
26/// Serializes a slice of arguments into length-prefixed binary wire format.
27///
28/// Wire format:
29/// - 4-byte little-endian u32: argument count `N`
30/// - For each argument:
31///   - 4-byte little-endian u32: byte length `L`
32///   - `L` UTF-8 payload bytes
33pub fn encode_args(args: &[String]) -> Vec<u8> {
34    let mut buf = Vec::new();
35    buf.extend_from_slice(&(args.len() as u32).to_le_bytes());
36    for arg in args {
37        let bytes = arg.as_bytes();
38        buf.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
39        buf.extend_from_slice(bytes);
40    }
41    buf
42}
43
44/// Decodes arguments from the length-prefixed binary wire format.
45///
46/// Provides graceful backwards-compatible fallback for null-separated and newline-separated
47/// payloads if length-prefixed framing is absent.
48pub fn decode_args(payload: &[u8]) -> Vec<String> {
49    if payload.len() >= 4 {
50        let count = u32::from_le_bytes(payload[0..4].try_into().unwrap()) as usize;
51        let mut offset = 4;
52        let mut args = Vec::with_capacity(count.min(1024));
53        let mut ok = true;
54        for _ in 0..count {
55            if offset + 4 > payload.len() {
56                ok = false;
57                break;
58            }
59            let len = u32::from_le_bytes(payload[offset..offset + 4].try_into().unwrap()) as usize;
60            offset += 4;
61            if offset + len > payload.len() {
62                ok = false;
63                break;
64            }
65            if let Ok(s) = std::str::from_utf8(&payload[offset..offset + len]) {
66                args.push(s.to_string());
67            } else {
68                args.push(String::from_utf8_lossy(&payload[offset..offset + len]).into_owned());
69            }
70            offset += len;
71        }
72        if ok && offset == payload.len() {
73            return args;
74        }
75    }
76
77    // Backwards-compatible fallback: null-byte or newline delimited payload
78    if let Ok(raw) = std::str::from_utf8(payload) {
79        if raw.contains('\0') {
80            return raw.split('\0').map(|s| s.to_string()).collect();
81        }
82        return raw
83            .lines()
84            .map(|s| s.to_string())
85            .filter(|s| !s.is_empty())
86            .collect();
87    }
88
89    Vec::new()
90}
91
92/// Mutex handle holding the single-instance lock and IPC listener thread.
93#[derive(Debug)]
94pub struct SingleInstanceLock {
95    app_id: String,
96    running: Arc<AtomicBool>,
97    #[cfg(unix)]
98    socket_path: PathBuf,
99    #[cfg(windows)]
100    pipe_handle: usize,
101    listener_thread: Option<std::thread::JoinHandle<()>>,
102}
103
104impl SingleInstanceLock {
105    /// Attempts to acquire an exclusive single-instance application lock for the given application ID.
106    ///
107    /// If another instance is already running, forwards `args` to it and returns
108    /// `SingleInstanceStatus::SecondaryExited`.
109    ///
110    /// If this is the first instance, binds the IPC channel and invokes `on_secondary_args` whenever
111    /// subsequent processes launch.
112    pub fn acquire<F>(
113        app_id: &str,
114        args: &[String],
115        on_secondary_args: F,
116    ) -> Result<SingleInstanceStatus, std::io::Error>
117    where
118        F: Fn(Vec<String>) + Send + Sync + 'static,
119    {
120        #[cfg(unix)]
121        {
122            let runtime_dir = match std::env::var_os("XDG_RUNTIME_DIR") {
123                Some(p) => PathBuf::from(p),
124                None => {
125                    extern "C" {
126                        fn getuid() -> u32;
127                    }
128                    let uid = unsafe { getuid() };
129                    let dir = PathBuf::from(format!("/tmp/strata-runtime-{}", uid));
130                    use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
131
132                    if let Ok(meta) = std::fs::symlink_metadata(&dir) {
133                        if meta.file_type().is_symlink() {
134                            return Err(std::io::Error::new(
135                                std::io::ErrorKind::PermissionDenied,
136                                format!("Security violation: runtime directory {:?} is an insecure symlink (CWE-59)", dir),
137                            ));
138                        }
139                        if meta.uid() != uid {
140                            return Err(std::io::Error::new(
141                                std::io::ErrorKind::PermissionDenied,
142                                format!("Security violation: runtime directory {:?} is not owned by current user (uid {})", dir, uid),
143                            ));
144                        }
145                        if meta.permissions().mode() & 0o777 != 0o700 {
146                            let _ = std::fs::set_permissions(
147                                &dir,
148                                std::fs::Permissions::from_mode(0o700),
149                            );
150                        }
151                    } else {
152                        let mut builder = std::fs::DirBuilder::new();
153                        builder.mode(0o700);
154                        if let Err(e) = builder.create(&dir) {
155                            if e.kind() != std::io::ErrorKind::AlreadyExists {
156                                return Err(e);
157                            }
158                        }
159                        let meta = std::fs::symlink_metadata(&dir)?;
160                        if meta.file_type().is_symlink() || meta.uid() != uid {
161                            return Err(std::io::Error::new(
162                                std::io::ErrorKind::PermissionDenied,
163                                format!("Security violation: created runtime directory {:?} failed verification", dir),
164                            ));
165                        }
166                        let _ =
167                            std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700));
168                    }
169                    dir
170                }
171            };
172            Self::acquire_in_dir(app_id, args, &runtime_dir, on_secondary_args)
173        }
174        #[cfg(windows)]
175        {
176            Self::acquire_windows(app_id, args, on_secondary_args)
177        }
178        #[cfg(not(any(unix, windows)))]
179        {
180            let _ = (args, on_secondary_args);
181            Ok(SingleInstanceStatus::Primary(Self::handle_only(app_id)))
182        }
183    }
184
185    /// Acquires the lock inside an explicit runtime directory.
186    ///
187    /// This is the testable form of [`SingleInstanceLock::acquire`]: callers can
188    /// point it at a private directory instead of mutating process environment
189    /// variables. On Windows the runtime directory is ignored because the named
190    /// pipe namespace is global.
191    pub fn acquire_in_dir<F>(
192        app_id: &str,
193        args: &[String],
194        runtime_dir: &std::path::Path,
195        on_secondary_args: F,
196    ) -> Result<SingleInstanceStatus, std::io::Error>
197    where
198        F: Fn(Vec<String>) + Send + Sync + 'static,
199    {
200        #[cfg(unix)]
201        {
202            Self::acquire_unix(app_id, args, runtime_dir, on_secondary_args)
203        }
204        #[cfg(windows)]
205        {
206            let _ = runtime_dir;
207            Self::acquire_windows(app_id, args, on_secondary_args)
208        }
209        #[cfg(not(any(unix, windows)))]
210        {
211            let _ = (runtime_dir, args, on_secondary_args);
212            Ok(SingleInstanceStatus::Primary(Self::handle_only(app_id)))
213        }
214    }
215
216    #[cfg(not(any(unix, windows)))]
217    fn handle_only(app_id: &str) -> Self {
218        Self {
219            app_id: app_id.to_string(),
220            running: Arc::new(AtomicBool::new(true)),
221            listener_thread: None,
222        }
223    }
224
225    #[cfg(unix)]
226    fn acquire_unix<F>(
227        app_id: &str,
228        args: &[String],
229        runtime_dir: &std::path::Path,
230        on_secondary_args: F,
231    ) -> Result<SingleInstanceStatus, std::io::Error>
232    where
233        F: Fn(Vec<String>) + Send + Sync + 'static,
234    {
235        use std::io::Write;
236        use std::os::unix::net::{UnixListener, UnixStream};
237
238        let socket_name = format!("{}.sock", app_id.replace('/', "_"));
239        let socket_path = runtime_dir.join(socket_name);
240
241        // Security check: remove any untrusted symlink before socket binding (CWE-59)
242        if let Ok(meta) = std::fs::symlink_metadata(&socket_path) {
243            if meta.file_type().is_symlink() {
244                let _ = std::fs::remove_file(&socket_path);
245            }
246        }
247
248        // Try binding the socket as the primary instance.
249        match UnixListener::bind(&socket_path) {
250            Ok(listener) => {
251                use std::os::unix::fs::PermissionsExt;
252                let _ =
253                    std::fs::set_permissions(&socket_path, std::fs::Permissions::from_mode(0o600));
254                Ok(SingleInstanceStatus::Primary(Self::establish_unix(
255                    app_id,
256                    listener,
257                    socket_path,
258                    on_secondary_args,
259                )?))
260            }
261            Err(e) if e.kind() == std::io::ErrorKind::AddrInUse => {
262                // The path exists. Connect to determine whether the owner is live.
263                match UnixStream::connect(&socket_path) {
264                    Ok(mut stream) => {
265                        // Primary is running: forward CLI arguments and exit cleanly.
266                        let payload = encode_args(args);
267                        let _ = stream.write_all(&payload);
268                        let _ = stream.flush();
269                        let _ = stream.shutdown(std::net::Shutdown::Write);
270                        Ok(SingleInstanceStatus::SecondaryExited)
271                    }
272                    Err(_) => {
273                        // Stale socket left by a crashed primary. Remove and rebind.
274                        let _ = std::fs::remove_file(&socket_path);
275                        let listener = UnixListener::bind(&socket_path)?;
276                        use std::os::unix::fs::PermissionsExt;
277                        let _ = std::fs::set_permissions(
278                            &socket_path,
279                            std::fs::Permissions::from_mode(0o600),
280                        );
281                        Ok(SingleInstanceStatus::Primary(Self::establish_unix(
282                            app_id,
283                            listener,
284                            socket_path,
285                            on_secondary_args,
286                        )?))
287                    }
288                }
289            }
290            Err(e) => Err(e),
291        }
292    }
293
294    #[cfg(unix)]
295    fn establish_unix<F>(
296        app_id: &str,
297        listener: std::os::unix::net::UnixListener,
298        socket_path: PathBuf,
299        on_secondary_args: F,
300    ) -> Result<Self, std::io::Error>
301    where
302        F: Fn(Vec<String>) + Send + Sync + 'static,
303    {
304        let running = Arc::new(AtomicBool::new(true));
305        let on_args = Arc::new(on_secondary_args);
306        let thread = Self::spawn_unix_listener(listener, Arc::clone(&running), on_args)?;
307        Ok(Self {
308            app_id: app_id.to_string(),
309            running,
310            socket_path,
311            listener_thread: Some(thread),
312        })
313    }
314
315    #[cfg(unix)]
316    fn spawn_unix_listener<F>(
317        listener: std::os::unix::net::UnixListener,
318        running: Arc<AtomicBool>,
319        on_args: Arc<F>,
320    ) -> Result<std::thread::JoinHandle<()>, std::io::Error>
321    where
322        F: Fn(Vec<String>) + Send + Sync + 'static,
323    {
324        use std::io::Read;
325
326        listener.set_nonblocking(true)?;
327
328        let handle = std::thread::Builder::new()
329            .name("strata-single-instance-listener".to_string())
330            .spawn(move || {
331                while running.load(Ordering::Relaxed) {
332                    match listener.accept() {
333                        Ok((mut stream, _)) => {
334                            let _ = stream.set_nonblocking(false);
335                            let mut payload = Vec::new();
336                            if stream.read_to_end(&mut payload).is_ok() {
337                                let parsed_args = decode_args(&payload);
338                                on_args(parsed_args);
339                            }
340                        }
341                        Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
342                            std::thread::sleep(std::time::Duration::from_millis(50));
343                        }
344                        Err(_) => break,
345                    }
346                }
347            })?;
348        Ok(handle)
349    }
350
351    #[cfg(windows)]
352    fn acquire_windows<F>(
353        app_id: &str,
354        args: &[String],
355        on_secondary_args: F,
356    ) -> Result<SingleInstanceStatus, std::io::Error>
357    where
358        F: Fn(Vec<String>) + Send + Sync + 'static,
359    {
360        // If a primary already owns the pipe, forward arguments and exit.
361        if windows_ipc::forward_to_primary(app_id, args) {
362            return Ok(SingleInstanceStatus::SecondaryExited);
363        }
364
365        let handle = match windows_ipc::create_server(app_id) {
366            Some(handle) => handle,
367            None => {
368                // Another process won the first-instance race after our initial
369                // connect attempt; forward to it instead of failing.
370                let create_error = std::io::Error::last_os_error();
371                if windows_ipc::forward_to_primary(app_id, args) {
372                    return Ok(SingleInstanceStatus::SecondaryExited);
373                }
374                return Err(create_error);
375            }
376        };
377
378        let running = Arc::new(AtomicBool::new(true));
379        let on_args = Arc::new(on_secondary_args);
380        let thread = match windows_ipc::spawn_server_listener(handle, Arc::clone(&running), on_args)
381        {
382            Ok(t) => t,
383            Err(error) => {
384                windows_ipc::close(handle);
385                return Err(error);
386            }
387        };
388
389        Ok(SingleInstanceStatus::Primary(Self {
390            app_id: app_id.to_string(),
391            running,
392            pipe_handle: handle,
393            listener_thread: Some(thread),
394        }))
395    }
396
397    /// Returns the unique application identifier for this lock.
398    pub fn app_id(&self) -> &str {
399        &self.app_id
400    }
401}
402
403impl Drop for SingleInstanceLock {
404    fn drop(&mut self) {
405        self.running.store(false, Ordering::Relaxed);
406        #[cfg(unix)]
407        {
408            let _ = std::fs::remove_file(&self.socket_path);
409        }
410        #[cfg(windows)]
411        {
412            windows_ipc::unblock_server(&self.app_id);
413            windows_ipc::close(self.pipe_handle);
414        }
415        if let Some(thread) = self.listener_thread.take() {
416            let _ = thread.join();
417        }
418    }
419}
420
421/// Raw `kernel32` named-pipe transport used by the Windows single-instance path.
422///
423/// The pipe name is `\\.\pipe\<sanitized-app-id>`. The primary creates a duplex
424/// byte-mode server instance and listens for newline-separated CLI arguments;
425/// a secondary opens the pipe, writes its arguments, and exits. This module is
426/// compile-gated to Windows and is not exercised on other hosts.
427#[cfg(windows)]
428mod windows_ipc {
429    use std::ffi::c_void;
430    use std::sync::atomic::{AtomicBool, Ordering};
431    use std::sync::Arc;
432
433    type Handle = *mut c_void;
434
435    const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;
436    const PIPE_ACCESS_DUPLEX: u32 = 0x0000_0003;
437    const FILE_FLAG_FIRST_PIPE_INSTANCE: u32 = 0x0008_0000;
438    const PIPE_TYPE_BYTE: u32 = 0x0000_0000;
439    const PIPE_READMODE_BYTE: u32 = 0x0000_0000;
440    const PIPE_WAIT: u32 = 0x0000_0000;
441    const PIPE_UNLIMITED_INSTANCES: u32 = 255;
442    const GENERIC_WRITE: u32 = 0x4000_0000;
443    const OPEN_EXISTING: u32 = 3;
444    const ERROR_PIPE_BUSY: u32 = 231;
445    const ERROR_PIPE_CONNECTED: u32 = 535;
446    const BUFFER_SIZE: u32 = 8192;
447
448    #[link(name = "kernel32")]
449    extern "system" {
450        fn CreateNamedPipeW(
451            name: *const u16,
452            open_mode: u32,
453            pipe_mode: u32,
454            max_instances: u32,
455            out_buffer_size: u32,
456            in_buffer_size: u32,
457            default_timeout: u32,
458            security_attributes: *mut c_void,
459        ) -> Handle;
460        fn ConnectNamedPipe(pipe: Handle, overlapped: *mut c_void) -> i32;
461        fn DisconnectNamedPipe(pipe: Handle) -> i32;
462        fn ReadFile(
463            file: Handle,
464            buffer: *mut u8,
465            bytes_to_read: u32,
466            bytes_read: *mut u32,
467            overlapped: *mut c_void,
468        ) -> i32;
469        fn WriteFile(
470            file: Handle,
471            buffer: *const u8,
472            bytes_to_write: u32,
473            bytes_written: *mut u32,
474            overlapped: *mut c_void,
475        ) -> i32;
476        fn CreateFileW(
477            name: *const u16,
478            desired_access: u32,
479            share_mode: u32,
480            security_attributes: *mut c_void,
481            creation_disposition: u32,
482            flags_and_attributes: u32,
483            template_file: Handle,
484        ) -> Handle;
485        fn CloseHandle(object: Handle) -> i32;
486        fn GetLastError() -> u32;
487        fn LocalFree(h_mem: *mut c_void) -> *mut c_void;
488    }
489
490    #[link(name = "advapi32")]
491    extern "system" {
492        fn ConvertStringSecurityDescriptorToSecurityDescriptorW(
493            string_security_descriptor: *const u16,
494            string_sd_revision: u32,
495            security_descriptor: *mut *mut c_void,
496            security_descriptor_size: *mut u32,
497        ) -> i32;
498    }
499
500    fn pipe_name(app_id: &str) -> Vec<u16> {
501        let sanitized: String = app_id
502            .chars()
503            .map(|ch| {
504                if ch.is_ascii_alphanumeric() || ch == '.' || ch == '-' || ch == '_' {
505                    ch
506                } else {
507                    '-'
508                }
509            })
510            .collect();
511        format!("\\\\.\\pipe\\{}", sanitized)
512            .encode_utf16()
513            .chain(std::iter::once(0))
514            .collect()
515    }
516
517    fn to_handle(value: usize) -> Handle {
518        value as Handle
519    }
520
521    #[repr(C)]
522    struct SecurityAttributes {
523        n_length: u32,
524        lp_security_descriptor: *mut c_void,
525        b_inherit_handle: i32,
526    }
527
528    pub(super) fn forward_to_primary(app_id: &str, args: &[String]) -> bool {
529        let name = pipe_name(app_id);
530        let bytes = super::encode_args(args);
531
532        for _ in 0..40 {
533            let handle = unsafe {
534                CreateFileW(
535                    name.as_ptr(),
536                    GENERIC_WRITE,
537                    0,
538                    std::ptr::null_mut(),
539                    OPEN_EXISTING,
540                    0,
541                    std::ptr::null_mut(),
542                )
543            };
544            if handle != INVALID_HANDLE_VALUE {
545                let mut written = 0u32;
546                let ok = unsafe {
547                    WriteFile(
548                        handle,
549                        bytes.as_ptr(),
550                        bytes.len() as u32,
551                        &mut written,
552                        std::ptr::null_mut(),
553                    )
554                };
555                unsafe {
556                    CloseHandle(handle);
557                }
558                return ok != 0;
559            }
560            let error = unsafe { GetLastError() };
561            if error != ERROR_PIPE_BUSY {
562                return false;
563            }
564            std::thread::sleep(std::time::Duration::from_millis(25));
565        }
566        false
567    }
568
569    pub(super) fn create_server(app_id: &str) -> Option<usize> {
570        let name = pipe_name(app_id);
571
572        // Enforce explicit Win32 DACL: Allow Generic All strictly to Principal Self (PS) / Owner
573        let sddl = "D:(A;;GA;;;PS)\0".encode_utf16().collect::<Vec<u16>>();
574        let mut p_sd: *mut c_void = std::ptr::null_mut();
575        let mut sd_size = 0u32;
576        let has_sd = unsafe {
577            ConvertStringSecurityDescriptorToSecurityDescriptorW(
578                sddl.as_ptr(),
579                1, // SDDL_REVISION_1
580                &mut p_sd,
581                &mut sd_size,
582            )
583        };
584
585        let mut sa = SecurityAttributes {
586            n_length: std::mem::size_of::<SecurityAttributes>() as u32,
587            lp_security_descriptor: if has_sd != 0 {
588                p_sd
589            } else {
590                std::ptr::null_mut()
591            },
592            b_inherit_handle: 0,
593        };
594
595        let handle = unsafe {
596            CreateNamedPipeW(
597                name.as_ptr(),
598                PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
599                PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
600                PIPE_UNLIMITED_INSTANCES,
601                BUFFER_SIZE,
602                BUFFER_SIZE,
603                0,
604                &mut sa as *mut _ as *mut c_void,
605            )
606        };
607
608        if !p_sd.is_null() {
609            unsafe {
610                LocalFree(p_sd);
611            }
612        }
613
614        if handle == INVALID_HANDLE_VALUE {
615            None
616        } else {
617            Some(handle as usize)
618        }
619    }
620
621    pub(super) fn unblock_server(app_id: &str) {
622        let name = pipe_name(app_id);
623        let handle = unsafe {
624            CreateFileW(
625                name.as_ptr(),
626                GENERIC_WRITE,
627                0,
628                std::ptr::null_mut(),
629                OPEN_EXISTING,
630                0,
631                std::ptr::null_mut(),
632            )
633        };
634        if handle != INVALID_HANDLE_VALUE {
635            unsafe {
636                CloseHandle(handle);
637            }
638        }
639    }
640
641    pub(super) fn spawn_server_listener<F>(
642        handle: usize,
643        running: Arc<AtomicBool>,
644        on_args: Arc<F>,
645    ) -> Result<std::thread::JoinHandle<()>, std::io::Error>
646    where
647        F: Fn(Vec<String>) + Send + Sync + 'static,
648    {
649        std::thread::Builder::new()
650            .name("strata-single-instance-pipe".to_string())
651            .spawn(move || {
652                let pipe = to_handle(handle);
653                let mut buffer = vec![0u8; BUFFER_SIZE as usize];
654
655                while running.load(Ordering::Relaxed) {
656                    let connected = unsafe { ConnectNamedPipe(pipe, std::ptr::null_mut()) };
657                    if connected == 0 {
658                        let error = unsafe { GetLastError() };
659                        if error != ERROR_PIPE_CONNECTED {
660                            break;
661                        }
662                    }
663
664                    if !running.load(Ordering::Relaxed) {
665                        unsafe {
666                            DisconnectNamedPipe(pipe);
667                        }
668                        break;
669                    }
670
671                    let mut payload = Vec::new();
672                    loop {
673                        let mut bytes_read = 0u32;
674                        let ok = unsafe {
675                            ReadFile(
676                                pipe,
677                                buffer.as_mut_ptr(),
678                                buffer.len() as u32,
679                                &mut bytes_read,
680                                std::ptr::null_mut(),
681                            )
682                        };
683                        if ok == 0 || bytes_read == 0 {
684                            break;
685                        }
686                        payload.extend_from_slice(&buffer[..bytes_read as usize]);
687                        if (bytes_read as usize) < buffer.len() {
688                            break;
689                        }
690                    }
691
692                    if !payload.is_empty() {
693                        let parsed = super::decode_args(&payload);
694                        on_args(parsed);
695                    }
696
697                    unsafe {
698                        DisconnectNamedPipe(pipe);
699                    }
700                }
701            })
702    }
703
704    pub(super) fn close(handle: usize) {
705        if handle != 0 {
706            unsafe {
707                CloseHandle(to_handle(handle));
708            }
709        }
710    }
711}