torrentdht 0.1.1

DHT discovery with mTLS handshake handoff; optional BitTorrent when the host opts in
Documentation
//! Persist DHT routing table across restarts (KDL snapshot under host state root).

use std::net::SocketAddr;
use std::path::{Path, PathBuf};

use kdl::{KdlDocument, KdlNode};

use crate::config::Config;
use crate::dht::node_id::NodeId;
use crate::dht::routing::{NodeEntry, RoutingTable};
use crate::error::{Error, Result};
use crate::integrity::{open_tracked, seal_tracked, IntegrityConfig};
use crate::net::DialGate;

const LEGACY_RELATIVE: &str = ".torrentdht/dht-routing.kdl";
const STATE_RELATIVE: &str = "dht-routing.kdl";

/// Contact list restored from a routing snapshot (before DialGate filtering).
pub type RoutingContacts = Vec<(NodeId, SocketAddr)>;

fn state_paths(cfg: &Config) -> (PathBuf, PathBuf) {
    cfg.client_state_file(STATE_RELATIVE)
}

pub fn default_persist_path(cfg: &Config) -> PathBuf {
    let (jail, relative) = state_paths(cfg);
    jail.join(relative)
}

pub fn save_routing_table(
    cfg: &Config,
    table: &RoutingTable,
    integrity: &IntegrityConfig,
) -> Result<()> {
    let (jail, relative) = state_paths(cfg);
    save_routing_table_at(&jail, &relative, table, integrity)
}

pub fn save_routing_table_at(
    jail: &Path,
    relative: &Path,
    table: &RoutingTable,
    integrity: &IntegrityConfig,
) -> Result<()> {
    let mut doc = KdlDocument::new();
    let mut children = KdlDocument::new();

    let mut local = KdlNode::new("local-id");
    local.push(hex_id(&table.local_id()));
    children.nodes_mut().push(local);

    for entry in table.all_entries() {
        let mut node = KdlNode::new("node");
        node.push(format!("id:{}", hex_id(&entry.id)));
        node.push(format!("addr:{}", entry.addr));
        children.nodes_mut().push(node);
    }
    let mut root = KdlNode::new("dht-routing");
    root.set_children(children);
    doc.nodes_mut().push(root);
    let context = format!("dht-routing:{}", relative.display());
    let sealed = seal_tracked(integrity, doc.to_string().as_bytes(), &context)?;
    crate::security::write_bytes_under_root(jail, relative, &sealed)
}

/// Parse snapshot: optional stable local NodeId + contact list (pre DialGate filter).
pub fn load_routing_snapshot(
    cfg: &Config,
    integrity: &IntegrityConfig,
) -> Result<(Option<NodeId>, RoutingContacts)> {
    let (jail, relative) = state_paths(cfg);
    match load_routing_snapshot_at(&jail, &relative, integrity) {
        Ok(result) => Ok(result),
        Err(err) if cfg.state_dir.is_none() => {
            // Already using legacy relative under download_dir.
            Err(err)
        }
        Err(_) => {
            // Migration: try legacy path under download_dir if host just set state_dir.
            load_routing_snapshot_at(
                &cfg.download_dir,
                Path::new(LEGACY_RELATIVE),
                integrity,
            )
        }
    }
}

pub fn load_routing_snapshot_at(
    jail: &Path,
    relative: &Path,
    integrity: &IntegrityConfig,
) -> Result<(Option<NodeId>, RoutingContacts)> {
    let data = match crate::security::read_bytes_under_root(jail, relative) {
        Ok(data) => data,
        Err(Error::Io(err)) if err.kind() == std::io::ErrorKind::NotFound => {
            return Ok((None, Vec::new()));
        }
        Err(Error::Store(msg)) if msg.contains("No such file") || msg.contains("not found") => {
            return Ok((None, Vec::new()));
        }
        Err(err) => return Err(Error::Dht(format!("read dht routing snapshot: {err}"))),
    };
    let context = format!("dht-routing:{}", relative.display());
    let plain = match open_tracked(integrity, &data, &context) {
        Ok(plain) => plain,
        Err(err) => {
            // Never accept unauthenticated cleartext KDL. A forged snapshot would
            // restore attacker-chosen local-id / contacts. Legacy cleartext files
            // must be deleted or re-saved under host integrity (fail closed).
            return Err(Error::Dht(format!(
                "dht routing snapshot integrity open failed (refusing cleartext fallback): {err}"
            )));
        }
    };
    let text = std::str::from_utf8(&plain)
        .map_err(|err| Error::Dht(format!("dht routing snapshot utf-8: {err}")))?;
    let doc = text
        .parse::<KdlDocument>()
        .map_err(|err| Error::Dht(format!("parse dht routing snapshot: {err}")))?;
    let Some(children) = doc.get("dht-routing").and_then(|n| n.children()) else {
        return Ok((None, Vec::new()));
    };
    let mut local_id = None;
    let mut contacts = Vec::new();
    for node in children.nodes() {
        match node.name().value() {
            "local-id" => {
                let id_hex = node
                    .entries()
                    .first()
                    .and_then(|e| e.value().as_string())
                    .ok_or_else(|| Error::Dht("dht local-id missing value".into()))?;
                local_id = Some(parse_node_id(id_hex)?);
            }
            "node" => {
                let id_hex = node
                    .entries()
                    .first()
                    .and_then(|e| e.value().as_string())
                    .and_then(|s| s.strip_prefix("id:"))
                    .ok_or_else(|| Error::Dht("dht node missing id".into()))?;
                let addr_str = node
                    .entries()
                    .get(1)
                    .and_then(|e| e.value().as_string())
                    .and_then(|s| s.strip_prefix("addr:"))
                    .ok_or_else(|| Error::Dht("dht node missing addr".into()))?;
                let id = parse_node_id(id_hex)?;
                let addr: SocketAddr = addr_str
                    .parse()
                    .map_err(|_| Error::Dht(format!("invalid dht node addr: {addr_str}")))?;
                contacts.push((id, addr));
            }
            _ => {}
        }
    }
    Ok((local_id, contacts))
}

/// Load contacts into `table`. Returns `(persisted local NodeId if present, contact count)`.
pub fn load_routing_table(
    cfg: &Config,
    table: &mut RoutingTable,
    dial_gate: DialGate,
    integrity: &IntegrityConfig,
) -> Result<(Option<NodeId>, usize)> {
    let (local_id, contacts) = load_routing_snapshot(cfg, integrity)?;
    let mut loaded = 0usize;
    for (id, addr) in contacts {
        if !dial_gate.allows(addr) {
            continue;
        }
        table.upsert(NodeEntry::new(id, addr));
        loaded += 1;
    }
    Ok((local_id, loaded))
}

fn hex_id(id: &NodeId) -> String {
    id.as_bytes()
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

fn parse_node_id(hex: &str) -> Result<NodeId> {
    if hex.len() != 40 {
        return Err(Error::Dht("dht node id must be 40 hex chars".into()));
    }
    let mut bytes = [0u8; 20];
    for (idx, chunk) in hex.as_bytes().chunks(2).enumerate() {
        let part = std::str::from_utf8(chunk).map_err(|_| Error::Dht("bad node id hex".into()))?;
        bytes[idx] =
            u8::from_str_radix(part, 16).map_err(|_| Error::Dht("bad node id hex".into()))?;
    }
    Ok(NodeId::from_bytes(bytes))
}