troll 0.3.1

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
use std::{
    fs::{self, File, OpenOptions, TryLockError},
    io::{self, Write},
    path::Path,
    process::{self, Child},
    sync::atomic::{AtomicU64, Ordering},
    thread,
    time::{Duration, Instant},
};

use troll_core::ProbeError;
use troll_probe::SystemProbe;

use crate::cli::Color;

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(unix)]
mod unix;
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
mod unsupported;
#[cfg(target_os = "windows")]
mod windows;

#[cfg(target_os = "linux")]
pub use linux::{
    config_home, data_home, proc_probe, require_listener_probe, setup_ephemeral_range, state_home,
};
#[cfg(target_os = "macos")]
pub use macos::{
    config_home, data_home, proc_probe, require_listener_probe, setup_ephemeral_range, state_home,
};
#[cfg(unix)]
use unix::{create_private_file, set_private_file_permissions};
#[cfg(unix)]
pub use unix::{
    lock_setup_dir, open_store, private_state_dir, service_log_writer, service_shutdown,
};
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
pub use unsupported::{
    config_home, data_home, lock_setup_dir, open_store, private_state_dir, proc_probe,
    require_listener_probe, service_log_writer, service_shutdown, setup_ephemeral_range,
    state_home,
};
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
use unsupported::{create_private_file, set_private_file_permissions};
#[cfg(target_os = "windows")]
pub use windows::{
    config_home, data_home, lock_setup_dir, open_store, private_state_dir, proc_probe,
    require_listener_probe, service_log_writer, service_shutdown, setup_ephemeral_range,
    state_home,
};
#[cfg(target_os = "windows")]
use windows::{create_private_file, set_private_file_permissions};

const SERVICE_LOCK_FILE: &str = "serve.lock";
const SERVICE_LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(50);
const SERVICE_LOCK_STARTUP_WINDOW: Duration = Duration::from_secs(1);
static NEXT_STATE_TEMP: AtomicU64 = AtomicU64::new(0);

pub fn use_color(choice: Color) -> bool {
    crate::style::Style::detect(crate::style::Stream::Stdout, choice, false).has_color()
}

// no-color.org specifies that an empty NO_COLOR does not disable colour.
#[cfg(test)]
fn color_decision(choice: Color, terminal: bool, no_color: Option<&std::ffi::OsStr>) -> bool {
    crate::style::Style::decide(
        crate::style::TerminalFacts {
            is_terminal: terminal,
            no_color_env: no_color.is_some_and(|v| !v.is_empty()),
            ..crate::style::TerminalFacts::default()
        },
        choice,
        false,
    )
    .has_color()
}

pub fn write_private_state_file(dir: &Path, name: &str, contents: &[u8]) -> io::Result<()> {
    private_state_dir(dir)?;
    publish_private_file(dir, name, contents, true)
}

/// Use the same private staging as state files. A first install publishes
/// without replacing any destination that appeared since the caller's check.
pub fn write_setup_file(dir: &Path, name: &str, contents: &[u8], replace: bool) -> io::Result<()> {
    publish_private_file(dir, name, contents, replace)
}

fn publish_private_file(dir: &Path, name: &str, contents: &[u8], replace: bool) -> io::Result<()> {
    let (temp, mut file) = loop {
        let sequence = NEXT_STATE_TEMP.fetch_add(1, Ordering::Relaxed);
        let temp = dir.join(format!(".{name}-{}-{sequence}", process::id()));
        match create_private_file(&temp) {
            Ok(file) => break (temp, file),
            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
            Err(error) => return Err(error),
        }
    };
    let result = (|| {
        set_private_file_permissions(&file)?;
        file.write_all(contents)?;
        file.sync_all()?;
        drop(file);
        let destination = dir.join(name);
        if replace {
            fs::rename(&temp, destination)
        } else {
            fs::hard_link(&temp, destination)
        }
    })();
    if !replace || result.is_err() {
        let _ = fs::remove_file(&temp);
    }
    result
}

/// Keep the returned file open to hold the service lock.
pub fn acquire_service_lock(state_dir: &Path) -> io::Result<Option<File>> {
    private_state_dir(state_dir)?;
    let path = state_dir.join(SERVICE_LOCK_FILE);
    let file = match create_private_file(&path) {
        Ok(file) => file,
        Err(error) if error.kind() == io::ErrorKind::AlreadyExists => open_service_lock(&path)?,
        Err(error) => return Err(error),
    };
    // Integration tests can observe the first contention before releasing their lock.
    #[cfg(debug_assertions)]
    let mut report_contention = std::env::var_os("TROLL_TEST_SERVICE_LOCK_RETRY").is_some();
    let deadline = Instant::now() + SERVICE_LOCK_STARTUP_WINDOW;
    loop {
        match file.try_lock() {
            Ok(()) => return Ok(Some(file)),
            Err(TryLockError::Error(error)) => return Err(error),
            Err(TryLockError::WouldBlock) => {}
        }
        #[cfg(debug_assertions)]
        if std::mem::take(&mut report_contention) {
            let _ = writeln!(io::stderr().lock(), "troll test: serve.lock is busy");
        }
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            return Ok(None);
        }
        thread::sleep(SERVICE_LOCK_RETRY_INTERVAL.min(remaining));
    }
}

fn open_service_lock(path: &Path) -> io::Result<File> {
    if !fs::symlink_metadata(path)?.is_file() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "serve.lock is not a regular file",
        ));
    }
    OpenOptions::new().read(true).write(true).open(path)
}

pub fn probe() -> Result<SystemProbe, ProbeError> {
    let probe = proc_probe();
    require_listener_probe(&probe)?;
    Ok(probe)
}

#[derive(Clone, Copy)]
pub enum StopSignal {
    #[cfg(any(unix, windows))]
    Interrupt,
    #[cfg(unix)]
    Terminate,
    #[cfg(unix)]
    Hangup,
}

impl StopSignal {
    pub fn number(self) -> i32 {
        match self {
            #[cfg(any(unix, windows))]
            Self::Interrupt => 2,
            #[cfg(unix)]
            Self::Terminate => 15,
            #[cfg(unix)]
            Self::Hangup => 1,
        }
    }

    pub fn name(self) -> &'static str {
        match self {
            #[cfg(any(unix, windows))]
            Self::Interrupt => "SIGINT",
            #[cfg(unix)]
            Self::Terminate => "SIGTERM",
            #[cfg(unix)]
            Self::Hangup => "SIGHUP",
        }
    }
}

/// The sole signal send allowed by ADR 0004. The caller owns the wait handle.
pub fn forward_stop_signal_to_own_child(child: &mut Child, received: StopSignal) -> io::Result<()> {
    #[cfg(unix)]
    {
        use std::io::IsTerminal;

        use rustix::{
            io::Errno,
            process::{Pid, Signal, getpgrp},
            termios::tcgetpgrp,
        };

        let signal = match received {
            StopSignal::Interrupt => Signal::INT,
            StopSignal::Terminate => Signal::TERM,
            StopSignal::Hangup => Signal::HUP,
        };
        let stdin = io::stdin();
        if signal != Signal::TERM && stdin.is_terminal() {
            match tcgetpgrp(&stdin) {
                Ok(foreground) if foreground == getpgrp() => return Ok(()),
                // ENOTTY also covers a terminal that is not our controlling terminal.
                Ok(_) | Err(Errno::NOTTY) => {}
                Err(error) => return Err(error.into()),
            }
        }

        // Once try_wait reaps the child, its PID can be reused. If it exits
        // between this check and the send, it remains unreaped in this process.
        if child.try_wait()?.is_some() {
            return Ok(());
        }
        match rustix::process::kill_process(Pid::from_child(child), signal) {
            Ok(()) | Err(Errno::SRCH) => Ok(()),
            Err(error) => Err(error.into()),
        }
    }
    #[cfg(not(unix))]
    {
        let _ = (child, received);
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "forwarding stop signals is unsupported on this platform",
        ))
    }
}

#[cfg(test)]
mod color_tests {
    use super::*;
    use std::ffi::OsStr;

    #[test]
    fn all_color_choices_terminals_and_environment_values() {
        for terminal in [false, true] {
            for (no_color, auto_when_terminal) in [
                (None, true),
                (Some(OsStr::new("")), true),
                (Some(OsStr::new("1")), false),
            ] {
                assert!(color_decision(Color::Always, terminal, no_color));
                assert!(!color_decision(Color::Never, terminal, no_color));
                assert_eq!(
                    color_decision(Color::Auto, terminal, no_color),
                    terminal && auto_when_terminal
                );
            }
        }
    }
}

#[cfg(all(test, unix))]
mod state_home_tests {
    use super::unix::troll_home;
    use std::{ffi::OsStr, path::PathBuf};

    #[test]
    fn state_home_uses_absolute_xdg_or_falls_back_to_absolute_home() {
        let find = |xdg: Option<&str>, home: Option<&str>| {
            troll_home(xdg.map(OsStr::new), home.map(OsStr::new), ".local/state")
        };
        assert_eq!(
            find(Some("/custom/state"), None),
            Some(PathBuf::from("/custom/state/troll"))
        );
        for xdg in [None, Some("relative"), Some("")] {
            assert_eq!(
                find(xdg, Some("/my-home")),
                Some(PathBuf::from("/my-home/.local/state/troll"))
            );
        }
        assert_eq!(find(Some("relative"), Some("also-relative")), None);
    }
}