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::cancel_io(self.pipe_handle);
414        }
415        if let Some(thread) = self.listener_thread.take() {
416            let _ = thread.join();
417        }
418        #[cfg(windows)]
419        {
420            windows_ipc::close(self.pipe_handle);
421        }
422    }
423}
424
425/// Raw `kernel32` named-pipe transport used by the Windows single-instance path.
426///
427/// The pipe name is `\\.\pipe\<sanitized-app-id>`. The primary creates a duplex
428/// byte-mode server instance and listens for newline-separated CLI arguments;
429/// a secondary opens the pipe, writes its arguments, and exits. This module is
430/// compile-gated to Windows and is not exercised on other hosts.
431#[cfg(windows)]
432mod windows_ipc {
433    use std::ffi::c_void;
434    use std::sync::atomic::{AtomicBool, Ordering};
435    use std::sync::Arc;
436
437    type Handle = *mut c_void;
438
439    const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;
440    const PIPE_ACCESS_DUPLEX: u32 = 0x0000_0003;
441    const FILE_FLAG_FIRST_PIPE_INSTANCE: u32 = 0x0008_0000;
442    const PIPE_TYPE_BYTE: u32 = 0x0000_0000;
443    const PIPE_READMODE_BYTE: u32 = 0x0000_0000;
444    const PIPE_WAIT: u32 = 0x0000_0000;
445    const PIPE_REJECT_REMOTE_CLIENTS: u32 = 0x0000_0008;
446    const PIPE_UNLIMITED_INSTANCES: u32 = 255;
447    const GENERIC_WRITE: u32 = 0x4000_0000;
448    const OPEN_EXISTING: u32 = 3;
449    const ERROR_PIPE_BUSY: u32 = 231;
450    const ERROR_NO_DATA: u32 = 232;
451    const ERROR_PIPE_CONNECTED: u32 = 535;
452    const TOKEN_QUERY: u32 = 0x0008;
453    const TOKEN_USER_INFO_CLASS: u32 = 1;
454    const BUFFER_SIZE: u32 = 8192;
455
456    #[link(name = "kernel32")]
457    extern "system" {
458        fn CreateNamedPipeW(
459            name: *const u16,
460            open_mode: u32,
461            pipe_mode: u32,
462            max_instances: u32,
463            out_buffer_size: u32,
464            in_buffer_size: u32,
465            default_timeout: u32,
466            security_attributes: *mut c_void,
467        ) -> Handle;
468        fn ConnectNamedPipe(pipe: Handle, overlapped: *mut c_void) -> i32;
469        fn DisconnectNamedPipe(pipe: Handle) -> i32;
470        fn ReadFile(
471            file: Handle,
472            buffer: *mut u8,
473            bytes_to_read: u32,
474            bytes_read: *mut u32,
475            overlapped: *mut c_void,
476        ) -> i32;
477        fn WriteFile(
478            file: Handle,
479            buffer: *const u8,
480            bytes_to_write: u32,
481            bytes_written: *mut u32,
482            overlapped: *mut c_void,
483        ) -> i32;
484        fn FlushFileBuffers(file: Handle) -> i32;
485        fn CreateFileW(
486            name: *const u16,
487            desired_access: u32,
488            share_mode: u32,
489            security_attributes: *mut c_void,
490            creation_disposition: u32,
491            flags_and_attributes: u32,
492            template_file: Handle,
493        ) -> Handle;
494        fn CancelIoEx(file: Handle, overlapped: *mut c_void) -> i32;
495        fn GetCurrentProcess() -> Handle;
496        fn CloseHandle(object: Handle) -> i32;
497        fn GetLastError() -> u32;
498        fn LocalFree(h_mem: *mut c_void) -> *mut c_void;
499    }
500
501    #[link(name = "advapi32")]
502    extern "system" {
503        fn OpenProcessToken(
504            process_handle: Handle,
505            desired_access: u32,
506            token_handle: *mut Handle,
507        ) -> i32;
508        fn GetTokenInformation(
509            token_handle: Handle,
510            token_information_class: u32,
511            token_information: *mut c_void,
512            token_information_length: u32,
513            return_length: *mut u32,
514        ) -> i32;
515        fn ConvertSidToStringSidW(sid: *mut c_void, string_sid: *mut *mut u16) -> i32;
516        fn ConvertStringSecurityDescriptorToSecurityDescriptorW(
517            string_security_descriptor: *const u16,
518            string_sd_revision: u32,
519            security_descriptor: *mut *mut c_void,
520            security_descriptor_size: *mut u32,
521        ) -> i32;
522    }
523
524    #[repr(C)]
525    struct TokenUserHeader {
526        sid: *mut c_void,
527        attributes: u32,
528    }
529
530    /// Queries the current process user SID string (e.g. `S-1-5-21-...`) for strict per-user pipe DACL.
531    fn current_user_sid_string() -> Option<String> {
532        let mut token: Handle = std::ptr::null_mut();
533        let ok = unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) };
534        if ok == 0 || token.is_null() {
535            return None;
536        }
537        let mut needed: u32 = 0;
538        unsafe {
539            GetTokenInformation(
540                token,
541                TOKEN_USER_INFO_CLASS,
542                std::ptr::null_mut(),
543                0,
544                &mut needed,
545            );
546        }
547        if needed == 0 {
548            unsafe {
549                CloseHandle(token);
550            }
551            return None;
552        }
553        let mut buf = vec![0u8; needed as usize];
554        let info_ok = unsafe {
555            GetTokenInformation(
556                token,
557                TOKEN_USER_INFO_CLASS,
558                buf.as_mut_ptr() as *mut c_void,
559                needed,
560                &mut needed,
561            )
562        };
563        unsafe {
564            CloseHandle(token);
565        }
566        if info_ok == 0 || buf.len() < std::mem::size_of::<TokenUserHeader>() {
567            return None;
568        }
569        let header = unsafe { &*(buf.as_ptr() as *const TokenUserHeader) };
570        if header.sid.is_null() {
571            return None;
572        }
573        let mut sid_wide: *mut u16 = std::ptr::null_mut();
574        let conv_ok = unsafe { ConvertSidToStringSidW(header.sid, &mut sid_wide) };
575        if conv_ok == 0 || sid_wide.is_null() {
576            return None;
577        }
578        let mut len = 0usize;
579        unsafe {
580            while *sid_wide.add(len) != 0 {
581                len += 1;
582            }
583        }
584        let slice = unsafe { std::slice::from_raw_parts(sid_wide, len) };
585        let result = String::from_utf16_lossy(slice);
586        unsafe {
587            LocalFree(sid_wide as *mut c_void);
588        }
589        Some(result)
590    }
591
592    fn pipe_name(app_id: &str) -> Vec<u16> {
593        let sanitized: String = app_id
594            .chars()
595            .map(|ch| {
596                if ch.is_ascii_alphanumeric() || ch == '.' || ch == '-' || ch == '_' {
597                    ch
598                } else {
599                    '-'
600                }
601            })
602            .collect();
603        format!("\\\\.\\pipe\\{}", sanitized)
604            .encode_utf16()
605            .chain(std::iter::once(0))
606            .collect()
607    }
608
609    fn to_handle(value: usize) -> Handle {
610        value as Handle
611    }
612
613    #[repr(C)]
614    struct SecurityAttributes {
615        n_length: u32,
616        lp_security_descriptor: *mut c_void,
617        b_inherit_handle: i32,
618    }
619
620    pub(super) fn forward_to_primary(app_id: &str, args: &[String]) -> bool {
621        let name = pipe_name(app_id);
622        let bytes = super::encode_args(args);
623
624        for _ in 0..40 {
625            let handle = unsafe {
626                CreateFileW(
627                    name.as_ptr(),
628                    GENERIC_WRITE,
629                    0,
630                    std::ptr::null_mut(),
631                    OPEN_EXISTING,
632                    0,
633                    std::ptr::null_mut(),
634                )
635            };
636            if handle != INVALID_HANDLE_VALUE {
637                let mut written = 0u32;
638                let ok = unsafe {
639                    WriteFile(
640                        handle,
641                        bytes.as_ptr(),
642                        bytes.len() as u32,
643                        &mut written,
644                        std::ptr::null_mut(),
645                    )
646                };
647                if ok != 0 {
648                    unsafe {
649                        FlushFileBuffers(handle);
650                    }
651                }
652                unsafe {
653                    CloseHandle(handle);
654                }
655                return ok != 0;
656            }
657            let error = unsafe { GetLastError() };
658            if error != ERROR_PIPE_BUSY {
659                return false;
660            }
661            std::thread::sleep(std::time::Duration::from_millis(25));
662        }
663        false
664    }
665
666    pub(super) fn create_server(app_id: &str) -> Option<usize> {
667        let name = pipe_name(app_id);
668
669        // Enforce explicit Win32 DACL granting Generic All strictly to the current user SID.
670        let mut p_sd: *mut c_void = std::ptr::null_mut();
671        if let Some(user_sid) = current_user_sid_string() {
672            let sddl = format!("D:(A;;GA;;;{})\0", user_sid)
673                .encode_utf16()
674                .collect::<Vec<u16>>();
675            let mut sd_size = 0u32;
676            let has_sd = unsafe {
677                ConvertStringSecurityDescriptorToSecurityDescriptorW(
678                    sddl.as_ptr(),
679                    1, // SDDL_REVISION_1
680                    &mut p_sd,
681                    &mut sd_size,
682                )
683            };
684            if has_sd == 0 {
685                p_sd = std::ptr::null_mut();
686            }
687        }
688
689        let mut sa = SecurityAttributes {
690            n_length: std::mem::size_of::<SecurityAttributes>() as u32,
691            lp_security_descriptor: p_sd,
692            b_inherit_handle: 0,
693        };
694        let sa_ptr = if p_sd.is_null() {
695            std::ptr::null_mut()
696        } else {
697            &mut sa as *mut _ as *mut c_void
698        };
699
700        let handle = unsafe {
701            CreateNamedPipeW(
702                name.as_ptr(),
703                PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE,
704                PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
705                PIPE_UNLIMITED_INSTANCES,
706                BUFFER_SIZE,
707                BUFFER_SIZE,
708                0,
709                sa_ptr,
710            )
711        };
712
713        if !p_sd.is_null() {
714            unsafe {
715                LocalFree(p_sd);
716            }
717        }
718
719        if handle == INVALID_HANDLE_VALUE {
720            None
721        } else {
722            Some(handle as usize)
723        }
724    }
725
726    pub(super) fn cancel_io(handle: usize) {
727        if handle != 0 {
728            unsafe {
729                CancelIoEx(to_handle(handle), std::ptr::null_mut());
730            }
731        }
732    }
733
734    pub(super) fn unblock_server(app_id: &str) {
735        let name = pipe_name(app_id);
736        let handle = unsafe {
737            CreateFileW(
738                name.as_ptr(),
739                GENERIC_WRITE,
740                0,
741                std::ptr::null_mut(),
742                OPEN_EXISTING,
743                0,
744                std::ptr::null_mut(),
745            )
746        };
747        if handle != INVALID_HANDLE_VALUE {
748            unsafe {
749                CloseHandle(handle);
750            }
751        }
752    }
753
754    pub(super) fn spawn_server_listener<F>(
755        handle: usize,
756        running: Arc<AtomicBool>,
757        on_args: Arc<F>,
758    ) -> Result<std::thread::JoinHandle<()>, std::io::Error>
759    where
760        F: Fn(Vec<String>) + Send + Sync + 'static,
761    {
762        std::thread::Builder::new()
763            .name("strata-single-instance-pipe".to_string())
764            .spawn(move || {
765                let pipe = to_handle(handle);
766                let mut buffer = vec![0u8; BUFFER_SIZE as usize];
767
768                while running.load(Ordering::Relaxed) {
769                    let connected = unsafe { ConnectNamedPipe(pipe, std::ptr::null_mut()) };
770                    if connected == 0 {
771                        let error = unsafe { GetLastError() };
772                        if error != ERROR_PIPE_CONNECTED && error != ERROR_NO_DATA {
773                            break;
774                        }
775                    }
776
777                    if !running.load(Ordering::Relaxed) {
778                        unsafe {
779                            DisconnectNamedPipe(pipe);
780                        }
781                        break;
782                    }
783
784                    let mut payload = Vec::new();
785                    loop {
786                        let mut bytes_read = 0u32;
787                        let ok = unsafe {
788                            ReadFile(
789                                pipe,
790                                buffer.as_mut_ptr(),
791                                buffer.len() as u32,
792                                &mut bytes_read,
793                                std::ptr::null_mut(),
794                            )
795                        };
796                        if ok == 0 || bytes_read == 0 {
797                            break;
798                        }
799                        payload.extend_from_slice(&buffer[..bytes_read as usize]);
800                        if (bytes_read as usize) < buffer.len() {
801                            break;
802                        }
803                    }
804
805                    if !payload.is_empty() {
806                        let parsed = super::decode_args(&payload);
807                        on_args(parsed);
808                    }
809
810                    unsafe {
811                        DisconnectNamedPipe(pipe);
812                    }
813                }
814            })
815    }
816
817    pub(super) fn close(handle: usize) {
818        if handle != 0 {
819            unsafe {
820                CloseHandle(to_handle(handle));
821            }
822        }
823    }
824}