troll 0.3.2

The port manager that guards the bridge: permanent claims, expiring leases, and a live view of who listens where.
use std::{
    ffi::OsStr,
    fs::{self, DirBuilder, File, OpenOptions},
    future::Future,
    io::{self, Write},
    os::{
        fd::AsFd,
        unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt},
    },
    path::{Path, PathBuf},
};

use troll_core::Store;

pub(super) fn troll_home(
    xdg: Option<&OsStr>,
    home: Option<&OsStr>,
    fallback: &str,
) -> Option<PathBuf> {
    xdg.map(Path::new)
        .filter(|path| path.is_absolute())
        .map(Path::to_path_buf)
        .or_else(|| {
            home.map(Path::new)
                .filter(|path| path.is_absolute())
                .map(|path| path.join(fallback))
        })
        .map(|base| base.join("troll"))
}

pub fn open_store(home: impl Into<PathBuf>) -> Store {
    Store::new(home)
}

pub fn private_state_dir(path: &Path) -> io::Result<()> {
    DirBuilder::new().recursive(true).mode(0o700).create(path)?;
    let metadata = fs::symlink_metadata(path)?;
    if !metadata.is_dir() || metadata.permissions().mode() & 0o077 != 0 {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "expected a private state directory with no group or other access",
        ));
    }
    Ok(())
}

pub(super) fn create_private_file(path: &Path) -> io::Result<File> {
    OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)
}

pub(super) fn set_private_file_permissions(file: &File) -> io::Result<()> {
    file.set_permissions(fs::Permissions::from_mode(0o600))
}

/// Create missing user configuration directories privately, leaving existing
/// directory modes alone. Hold the directory lock across read and install.
pub fn lock_setup_dir(dir: &Path) -> io::Result<File> {
    DirBuilder::new().recursive(true).mode(0o700).create(dir)?;
    let directory = File::open(dir)?;
    directory.lock()?;
    Ok(directory)
}

pub fn service_log_writer() -> io::Result<Box<dyn Write + Send>> {
    // Keep the writer off the process-wide Stderr mutex, even during a stalled write.
    let file = io::stderr().as_fd().try_clone_to_owned().map(File::from)?;
    Ok(Box::new(file))
}

pub fn service_shutdown() -> io::Result<impl Future<Output = ()>> {
    use tokio::signal::unix::{SignalKind, signal};

    let mut interrupt = signal(SignalKind::interrupt())?;
    let mut terminate = signal(SignalKind::terminate())?;
    Ok(async move {
        tokio::select! {
            _ = interrupt.recv() => {}
            _ = terminate.recv() => {}
        }
    })
}