Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

5.8 KB
Raw Blame
//! A read-only answer to "what is rustyfiles showing?" for the user's own scripts and launchers: a named pipe that answers every
//! connection with one text (JSON, made by the app) and closes.
//!
//! WHY (issue 690: "automation tools currently cannot observe what it is showing ... A small state API would let it hand off
//! cleanly"). Opening folders works through the command line already; reading the open folders and the selection back did not.
//!
//! SAFETY OF IT. Off unless the user turns it on (the app decides). The pipe's security descriptor lets in only the user who runs
//! rustyfiles, SYSTEM and administrators: a named pipe's default one gives every account read access, and other users of the same PC
//! must not read one's open folders. Nothing is ever read FROM the pipe: whatever a client writes is ignored, so it cannot ask for
//! anything else. Each answer is made afresh for the connection.

use std::time::Duration;

use windows::Win32::Foundation::{CloseHandle, HANDLE, HLOCAL, LocalFree};
use windows::Win32::Security::Authorization::{ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1};
use windows::Win32::Security::{PSECURITY_DESCRIPTOR, SECURITY_ATTRIBUTES};
use windows::Win32::Storage::FileSystem::{
    CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_GENERIC_READ, FILE_SHARE_NONE, OPEN_EXISTING, PIPE_ACCESS_OUTBOUND, ReadFile, WriteFile,
};
use windows::Win32::System::Pipes::{
    ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_UNLIMITED_INSTANCES, PIPE_WAIT, WaitNamedPipeW,
};
use windows::core::PCWSTR;

use crate::wide::wide;

/// The pipe's name: per user and session, so two users (or one user's two sessions) never meet.
pub fn pipe_name() -> String {
    let user = std::env::var("USERNAME").unwrap_or_default().to_lowercase();
    format!(r"\\.\pipe\rustyfiles-state-{user}-{}", crate::single_instance::session_id())
}

/// The security descriptor: full access for the user (by SID), SYSTEM and administrators; nobody else.
fn sddl(sid: &str) -> String {
    format!("D:P(A;;GA;;;{sid})(A;;GA;;;SY)(A;;GA;;;BA)")
}

/// Serves the pipe on a thread of its own for as long as the process lives: each connection gets `answer()` and is closed. `false`
/// when it could not be set up (no SID, or the pipe could not be made).
pub fn serve(answer: impl Fn() -> String + Send + 'static) -> bool {
    let Some(sid) = crate::dock::startuser::current_sid() else { return false };
    let name = pipe_name();
    let mut sd = PSECURITY_DESCRIPTOR::default();
    let text = wide(sddl(&sid));
    if unsafe { ConvertStringSecurityDescriptorToSecurityDescriptorW(PCWSTR(text.as_ptr()), SDDL_REVISION_1, &mut sd, None) }.is_err() {
        return false;
    }
    let sd_addr = sd.0 as usize;
    std::thread::Builder::new()
        .name("rf-state-pipe".into())
        .spawn(move || {
            let w = wide(&name);
            loop {
                let attrs = SECURITY_ATTRIBUTES { nLength: size_of::<SECURITY_ATTRIBUTES>() as u32, lpSecurityDescriptor: sd_addr as *mut _, bInheritHandle: false.into() };
                let pipe = unsafe {
                    CreateNamedPipeW(
                        PCWSTR(w.as_ptr()),
                        PIPE_ACCESS_OUTBOUND,
                        PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
                        PIPE_UNLIMITED_INSTANCES,
                        1 << 20,
                        0,
                        0,
                        Some(&attrs),
                    )
                };
                if pipe.is_invalid() {
                    log::warn!("state pipe: could not be made");
                    break;
                }
                let connected = unsafe { ConnectNamedPipe(pipe, None) }.is_ok() || unsafe { windows::Win32::Foundation::GetLastError() } == windows::Win32::Foundation::ERROR_PIPE_CONNECTED;
                if connected {
                    let text = answer();
                    let mut wrote = 0u32;
                    let _ = unsafe { WriteFile(pipe, Some(text.as_bytes()), Some(&mut wrote), None) };
                    let _ = unsafe { windows::Win32::Storage::FileSystem::FlushFileBuffers(pipe) };
                    let _ = unsafe { DisconnectNamedPipe(pipe) };
                }
                let _ = unsafe { CloseHandle(pipe) };
            }
            let _ = unsafe { LocalFree(Some(HLOCAL(sd_addr as *mut _))) };
        })
        .is_ok()
}

/// Asks the running rustyfiles for its state (`None`: none answers, or the state API is off).
pub fn ask(wait: Duration) -> Option<String> {
    let w = wide(pipe_name());
    unsafe {
        let _ = WaitNamedPipeW(PCWSTR(w.as_ptr()), wait.as_millis().min(u32::MAX as u128) as u32);
        let h: HANDLE = CreateFileW(PCWSTR(w.as_ptr()), FILE_GENERIC_READ.0, FILE_SHARE_NONE, None, OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES(0), None).ok()?;
        let mut out = Vec::new();
        let mut buf = vec![0u8; 64 * 1024];
        loop {
            let mut got = 0u32;
            if ReadFile(h, Some(&mut buf), Some(&mut got), None).is_err() || got == 0 {
                break;
            }
            out.extend_from_slice(&buf[..got as usize]);
        }
        let _ = CloseHandle(h);
        String::from_utf8(out).ok()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn the_descriptor_names_only_the_user_system_and_admins() {
        assert_eq!(sddl("S-1-5-21-1-2-3-1001"), "D:P(A;;GA;;;S-1-5-21-1-2-3-1001)(A;;GA;;;SY)(A;;GA;;;BA)");
    }

    #[test]
    fn an_answer_goes_through() {
        assert!(serve(|| "{\"ok\":true}".to_string()));
        let got = (0..50).find_map(|_| {
            std::thread::sleep(Duration::from_millis(20));
            ask(Duration::from_millis(200))
        });
        assert_eq!(got.as_deref(), Some("{\"ok\":true}"));
    }
}