Skip to main content

second_brain_api/
discovery.rs

1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
3
4use anyhow::Result;
5use second_brain_core::sqlite_store::SqliteStore;
6use second_brain_sync::mdns::{self, Advert, Net, Responder};
7use second_brain_sync::pairing::PairingHost;
8
9use crate::pairing::Pairing;
10
11const SSH_PORT: u16 = 22;
12
13/// What this daemon answers mDNS queries with, read on each query (each
14/// second on macOS): its sshd under its machine id once it holds a sync
15/// identity, and the pairing listener while one is open. A listener handing
16/// keys to a restore is never advertised, so no joining device dials it by
17/// mistake. A store that cannot be read is warned about once until a read
18/// succeeds, through `failing`.
19pub fn adverts(
20    sqlite: &SqliteStore,
21    pairing: &Pairing,
22    name: &str,
23    failing: &AtomicBool,
24) -> Vec<Advert> {
25    let own = sqlite.machine_id();
26    let mut adverts = Vec::new();
27    match device_advert(sqlite) {
28        Ok(advert) => {
29            failing.store(false, Ordering::Relaxed);
30            adverts.extend(advert);
31        }
32        Err(e) if !failing.swap(true, Ordering::Relaxed) => {
33            tracing::warn!("cannot read what to advertise this device's sshd with: {e:#}")
34        }
35        Err(_) => {}
36    }
37    let pairs = |h: &&PairingHost| h.is_open() && !h.hands_over_keys();
38    if let Some(port) = pairing.with_host(|host| host.filter(pairs).map(|h| h.port())) {
39        adverts.push(mdns::pairing_advert(name, own, port));
40    }
41    adverts
42}
43
44/// The route the route advertiser keeps current goes first, so a stopped
45/// or moved sshd shows without a new signed row.
46fn device_advert(sqlite: &SqliteStore) -> Result<Option<Advert>> {
47    let own = sqlite.machine_id();
48    let Some(row) = sqlite.device_record(own)? else {
49        return Ok(None);
50    };
51    if row.revoked {
52        return Ok(None);
53    }
54    let record = row.current.record;
55    let route = sqlite.device_route(own)?.unwrap_or_default();
56    let Some(login) = route.ssh_login.or(record.ssh_login) else {
57        return Ok(None);
58    };
59    let port = route
60        .ssh_port
61        .or(record.ssh_port)
62        .filter(|port| *port != 0)
63        .unwrap_or(SSH_PORT);
64    Ok(Some(mdns::device_advert(own, &login, port)))
65}
66
67/// None, with a warning, when the responder cannot start (another program
68/// holding port 5353 without sharing it, say); lookups by peers then fall
69/// back to the addresses they hold.
70pub fn spawn_responder(
71    net: &Net,
72    sqlite: Arc<SqliteStore>,
73    pairing: Arc<Pairing>,
74    name: String,
75) -> Option<Responder> {
76    let failing = AtomicBool::new(false);
77    let adverts = Arc::new(move || adverts(&sqlite, &pairing, &name, &failing));
78    match Responder::spawn(net, adverts) {
79        Ok(responder) => Some(responder),
80        Err(e) => {
81            tracing::warn!("cannot answer mDNS lookups for this device: {e:#}");
82            None
83        }
84    }
85}