second-brain-api 0.13.4

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
Documentation
use std::ffi::CStr;
use std::io::ErrorKind;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream, UdpSocket};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread;
use std::time::Duration;

use anyhow::{Context, Result};
use second_brain_core::keys::DeviceRoute;
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_sync::keyring::Keyring;
use second_brain_sync::mdns::Net;
use second_brain_sync::pairing::{
    Admission, JoinRequest, KeyHandover, KeyRequest, PAIR_LIFETIME, PAIR_PORT, PairingHost,
    SshServer,
};
use second_brain_sync::ssh::read_host_keys;

/// How long a pairing listener stays open without `sb pair` polling it.
pub const POLL_IDLE: Duration = Duration::from_secs(30);
const SSHD_PROBE: Duration = Duration::from_secs(1);
const PORT_RETRIES: u32 = 10;
const PORT_RETRY_WAIT: Duration = Duration::from_millis(100);
/// Never contacted: connecting a UDP socket only picks the local address
/// the route to it would leave from.
const ROUTE_PROBE: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)), 9);

pub struct PairingConfig {
    pub listen_ip: IpAddr,
    pub port: u16,
    pub ssh_host_key_dir: PathBuf,
    pub ssh_port: u16,
    /// Where `sb pair <code>` without a host looks for a pairing device;
    /// None looks nowhere, so only the daemon reaches the LAN.
    pub discovery: Option<Net>,
}

impl Default for PairingConfig {
    fn default() -> Self {
        Self {
            listen_ip: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
            port: PAIR_PORT,
            ssh_host_key_dir: PathBuf::from("/etc/ssh"),
            ssh_port: 22,
            discovery: None,
        }
    }
}

/// The daemon's pairing listener, at most one at a time.
#[derive(Default)]
pub struct Pairing {
    config: PairingConfig,
    host: Mutex<Option<PairingHost>>,
}

impl Pairing {
    pub fn new(config: PairingConfig) -> Self {
        Self {
            config,
            host: Mutex::new(None),
        }
    }

    pub fn discovery(&self) -> Option<&Net> {
        self.config.discovery.as_ref()
    }

    fn slot(&self) -> MutexGuard<'_, Option<PairingHost>> {
        self.host
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    /// This machine's sshd, when it has host keys and something answers on
    /// its port.
    pub fn local_ssh(&self) -> Option<SshServer> {
        let host_keys = read_host_keys(&self.config.ssh_host_key_dir);
        if host_keys.is_empty() {
            return None;
        }
        let local = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), self.config.ssh_port);
        TcpStream::connect_timeout(&local, SSHD_PROBE).ok()?;
        Some(SshServer {
            login: login(),
            port: self.config.ssh_port,
            host_keys,
        })
    }

    /// Closes any earlier listener and binds the port for a new one.
    /// `port` overrides the configured port; without it a taken port falls
    /// back to any free one.
    pub fn reserve(&self, port: Option<u16>) -> Result<TcpListener> {
        if let Some(earlier) = self.slot().take() {
            earlier.close();
        }
        self.bind(port)
    }

    /// Starts serving joins on a listener from `reserve`.
    pub fn start(
        &self,
        listener: TcpListener,
        hosts: Vec<String>,
        admit: Box<dyn Fn(&JoinRequest) -> Result<Admission> + Send + Sync>,
    ) -> Result<u16> {
        self.install(PairingHost::open(
            listener,
            hosts,
            PAIR_LIFETIME,
            POLL_IDLE,
            admit,
        )?)
    }

    /// Starts handing this device's keys to a restoring device on a
    /// listener from `reserve`, for `sb pair --restore-keys`.
    pub fn start_key_handover(
        &self,
        listener: TcpListener,
        hosts: Vec<String>,
        hand_over: Box<dyn Fn(&KeyRequest) -> Result<KeyHandover> + Send + Sync>,
    ) -> Result<u16> {
        self.install(PairingHost::open_key_handover(
            listener,
            hosts,
            PAIR_LIFETIME,
            POLL_IDLE,
            hand_over,
        )?)
    }

    fn install(&self, host: PairingHost) -> Result<u16> {
        let port = host.port();
        if let Some(earlier) = self.slot().replace(host) {
            earlier.close();
        }
        Ok(port)
    }

    fn bind(&self, port: Option<u16>) -> Result<TcpListener> {
        let wanted = port.unwrap_or(self.config.port);
        let addr = SocketAddr::new(self.config.listen_ip, wanted);
        let mut tries = 0;
        loop {
            match TcpListener::bind(addr) {
                Ok(listener) => return Ok(listener),
                Err(e) if e.kind() == ErrorKind::AddrInUse && tries < PORT_RETRIES => {
                    tries += 1;
                    thread::sleep(PORT_RETRY_WAIT);
                }
                Err(e) if e.kind() == ErrorKind::AddrInUse && port.is_none() => {
                    return TcpListener::bind(SocketAddr::new(self.config.listen_ip, 0))
                        .context("opening the pairing listener on a free port");
                }
                Err(e) => {
                    return Err(e)
                        .with_context(|| format!("opening the pairing listener on {addr}"));
                }
            }
        }
    }

    pub fn with_host<T>(&self, f: impl FnOnce(Option<&PairingHost>) -> T) -> T {
        f(self.slot().as_ref())
    }

    pub fn close(&self) -> bool {
        match self.slot().take() {
            Some(host) => {
                let was_open = host.is_open();
                host.close();
                was_open
            }
            None => false,
        }
    }
}

const ROUTE_REFRESH: Duration = Duration::from_secs(600);

/// What this device tells its peers in each handshake about reaching it:
/// its route, and its sshd in its signed row once it has one. Failures are
/// logged, and the next call retries.
pub fn advertise_route(sqlite: &SqliteStore, pairing: &Pairing, name: &str, data_dir: &Path) {
    let ssh = pairing.local_ssh();
    if let Err(e) = sqlite.set_device_route(DeviceRoute {
        machine_id: sqlite.machine_id().to_string(),
        addresses: local_addresses(name),
        ssh_login: ssh.as_ref().and_then(|ssh| ssh.login.clone()),
        ssh_port: ssh.as_ref().map(|ssh| ssh.port),
    }) {
        tracing::warn!("cannot record how peers reach this device: {e:#}");
    }
    if let Some(ssh) = &ssh {
        match Keyring::load(sqlite, data_dir).and_then(|keyring| keyring.sign_own_ssh(ssh)) {
            Ok(true) => tracing::info!("signed this device's sshd into its device row"),
            Ok(false) => {}
            Err(e) => tracing::warn!("cannot sign this device's sshd into its device row: {e:#}"),
        }
    }
}

/// Keeps the advertised route and row current, so a changed address or a
/// newly enabled sshd reaches peers without a restart.
pub fn spawn_route_advertiser(
    sqlite: Arc<SqliteStore>,
    pairing: Arc<Pairing>,
    name: String,
    data_dir: PathBuf,
) {
    let spawned = thread::Builder::new()
        .name("route-advertiser".to_string())
        .spawn(move || {
            loop {
                advertise_route(&sqlite, &pairing, &name, &data_dir);
                thread::sleep(ROUTE_REFRESH);
            }
        });
    if let Err(e) = spawned {
        tracing::error!("cannot start the route advertiser: {e}");
    }
}

/// Where another device on the network may reach this one: the address of
/// the default route, then the host name.
pub fn local_addresses(name: &str) -> Vec<String> {
    let mut addresses = Vec::new();
    let routed = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
        .and_then(|socket| {
            socket.connect(ROUTE_PROBE)?;
            socket.local_addr()
        })
        .map(|addr| addr.ip());
    match routed {
        Ok(ip) if !ip.is_unspecified() && !ip.is_loopback() => addresses.push(ip.to_string()),
        Ok(_) => {}
        Err(e) => tracing::debug!("no routed address for pairing: {e}"),
    }
    if !name.is_empty() && !addresses.iter().any(|a| a == name) {
        addresses.push(name.to_string());
    }
    addresses
}

fn login() -> Option<String> {
    if let Ok(user) = std::env::var("USER")
        && !user.is_empty()
    {
        return Some(user);
    }
    let mut buf = vec![0u8; 4096];
    let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
    let mut found: *mut libc::passwd = std::ptr::null_mut();
    // SAFETY: getpwuid_r writes only into `pwd` and `buf`, whose sizes it is
    // given, and `found` points at `pwd` or is null.
    let rc = unsafe {
        libc::getpwuid_r(
            libc::geteuid(),
            &mut pwd,
            buf.as_mut_ptr().cast(),
            buf.len(),
            &mut found,
        )
    };
    if rc != 0 || found.is_null() || pwd.pw_name.is_null() {
        return None;
    }
    // SAFETY: on success pw_name points at a NUL-terminated string in `buf`.
    let name = unsafe { CStr::from_ptr(pwd.pw_name) };
    name.to_str().ok().map(str::to_string)
}