Skip to main content

second_brain_api/
pairing.rs

1use std::ffi::CStr;
2use std::io::ErrorKind;
3use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream, UdpSocket};
4use std::path::{Path, PathBuf};
5use std::sync::{Arc, Mutex, MutexGuard};
6use std::thread;
7use std::time::Duration;
8
9use anyhow::{Context, Result};
10use second_brain_core::keys::DeviceRoute;
11use second_brain_core::sqlite_store::SqliteStore;
12use second_brain_sync::keyring::Keyring;
13use second_brain_sync::mdns::Net;
14use second_brain_sync::pairing::{
15    Admission, JoinRequest, KeyHandover, KeyRequest, PAIR_LIFETIME, PAIR_PORT, PairingHost,
16    SshServer,
17};
18use second_brain_sync::ssh::read_host_keys;
19
20/// How long a pairing listener stays open without `sb pair` polling it.
21pub const POLL_IDLE: Duration = Duration::from_secs(30);
22const SSHD_PROBE: Duration = Duration::from_secs(1);
23const PORT_RETRIES: u32 = 10;
24const PORT_RETRY_WAIT: Duration = Duration::from_millis(100);
25/// Never contacted: connecting a UDP socket only picks the local address
26/// the route to it would leave from.
27const ROUTE_PROBE: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)), 9);
28
29pub struct PairingConfig {
30    pub listen_ip: IpAddr,
31    pub port: u16,
32    pub ssh_host_key_dir: PathBuf,
33    pub ssh_port: u16,
34    /// Where `sb pair <code>` without a host looks for a pairing device;
35    /// None looks nowhere, so only the daemon reaches the LAN.
36    pub discovery: Option<Net>,
37}
38
39impl Default for PairingConfig {
40    fn default() -> Self {
41        Self {
42            listen_ip: IpAddr::V4(Ipv4Addr::UNSPECIFIED),
43            port: PAIR_PORT,
44            ssh_host_key_dir: PathBuf::from("/etc/ssh"),
45            ssh_port: 22,
46            discovery: None,
47        }
48    }
49}
50
51/// The daemon's pairing listener, at most one at a time.
52#[derive(Default)]
53pub struct Pairing {
54    config: PairingConfig,
55    host: Mutex<Option<PairingHost>>,
56}
57
58impl Pairing {
59    pub fn new(config: PairingConfig) -> Self {
60        Self {
61            config,
62            host: Mutex::new(None),
63        }
64    }
65
66    pub fn discovery(&self) -> Option<&Net> {
67        self.config.discovery.as_ref()
68    }
69
70    fn slot(&self) -> MutexGuard<'_, Option<PairingHost>> {
71        self.host
72            .lock()
73            .unwrap_or_else(|poisoned| poisoned.into_inner())
74    }
75
76    /// This machine's sshd, when it has host keys and something answers on
77    /// its port.
78    pub fn local_ssh(&self) -> Option<SshServer> {
79        let host_keys = read_host_keys(&self.config.ssh_host_key_dir);
80        if host_keys.is_empty() {
81            return None;
82        }
83        let local = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), self.config.ssh_port);
84        TcpStream::connect_timeout(&local, SSHD_PROBE).ok()?;
85        Some(SshServer {
86            login: login(),
87            port: self.config.ssh_port,
88            host_keys,
89        })
90    }
91
92    /// Closes any earlier listener and binds the port for a new one.
93    /// `port` overrides the configured port; without it a taken port falls
94    /// back to any free one.
95    pub fn reserve(&self, port: Option<u16>) -> Result<TcpListener> {
96        if let Some(earlier) = self.slot().take() {
97            earlier.close();
98        }
99        self.bind(port)
100    }
101
102    /// Starts serving joins on a listener from `reserve`.
103    pub fn start(
104        &self,
105        listener: TcpListener,
106        hosts: Vec<String>,
107        admit: Box<dyn Fn(&JoinRequest) -> Result<Admission> + Send + Sync>,
108    ) -> Result<u16> {
109        self.install(PairingHost::open(
110            listener,
111            hosts,
112            PAIR_LIFETIME,
113            POLL_IDLE,
114            admit,
115        )?)
116    }
117
118    /// Starts handing this device's keys to a restoring device on a
119    /// listener from `reserve`, for `sb pair --restore-keys`.
120    pub fn start_key_handover(
121        &self,
122        listener: TcpListener,
123        hosts: Vec<String>,
124        hand_over: Box<dyn Fn(&KeyRequest) -> Result<KeyHandover> + Send + Sync>,
125    ) -> Result<u16> {
126        self.install(PairingHost::open_key_handover(
127            listener,
128            hosts,
129            PAIR_LIFETIME,
130            POLL_IDLE,
131            hand_over,
132        )?)
133    }
134
135    fn install(&self, host: PairingHost) -> Result<u16> {
136        let port = host.port();
137        if let Some(earlier) = self.slot().replace(host) {
138            earlier.close();
139        }
140        Ok(port)
141    }
142
143    fn bind(&self, port: Option<u16>) -> Result<TcpListener> {
144        let wanted = port.unwrap_or(self.config.port);
145        let addr = SocketAddr::new(self.config.listen_ip, wanted);
146        let mut tries = 0;
147        loop {
148            match TcpListener::bind(addr) {
149                Ok(listener) => return Ok(listener),
150                Err(e) if e.kind() == ErrorKind::AddrInUse && tries < PORT_RETRIES => {
151                    tries += 1;
152                    thread::sleep(PORT_RETRY_WAIT);
153                }
154                Err(e) if e.kind() == ErrorKind::AddrInUse && port.is_none() => {
155                    return TcpListener::bind(SocketAddr::new(self.config.listen_ip, 0))
156                        .context("opening the pairing listener on a free port");
157                }
158                Err(e) => {
159                    return Err(e)
160                        .with_context(|| format!("opening the pairing listener on {addr}"));
161                }
162            }
163        }
164    }
165
166    pub fn with_host<T>(&self, f: impl FnOnce(Option<&PairingHost>) -> T) -> T {
167        f(self.slot().as_ref())
168    }
169
170    pub fn close(&self) -> bool {
171        match self.slot().take() {
172            Some(host) => {
173                let was_open = host.is_open();
174                host.close();
175                was_open
176            }
177            None => false,
178        }
179    }
180}
181
182const ROUTE_REFRESH: Duration = Duration::from_secs(600);
183
184/// What this device tells its peers in each handshake about reaching it:
185/// its route, and its sshd in its signed row once it has one. Failures are
186/// logged, and the next call retries.
187pub fn advertise_route(sqlite: &SqliteStore, pairing: &Pairing, name: &str, data_dir: &Path) {
188    let ssh = pairing.local_ssh();
189    if let Err(e) = sqlite.set_device_route(DeviceRoute {
190        machine_id: sqlite.machine_id().to_string(),
191        addresses: local_addresses(name),
192        ssh_login: ssh.as_ref().and_then(|ssh| ssh.login.clone()),
193        ssh_port: ssh.as_ref().map(|ssh| ssh.port),
194    }) {
195        tracing::warn!("cannot record how peers reach this device: {e:#}");
196    }
197    if let Some(ssh) = &ssh {
198        match Keyring::load(sqlite, data_dir).and_then(|keyring| keyring.sign_own_ssh(ssh)) {
199            Ok(true) => tracing::info!("signed this device's sshd into its device row"),
200            Ok(false) => {}
201            Err(e) => tracing::warn!("cannot sign this device's sshd into its device row: {e:#}"),
202        }
203    }
204}
205
206/// Keeps the advertised route and row current, so a changed address or a
207/// newly enabled sshd reaches peers without a restart.
208pub fn spawn_route_advertiser(
209    sqlite: Arc<SqliteStore>,
210    pairing: Arc<Pairing>,
211    name: String,
212    data_dir: PathBuf,
213) {
214    let spawned = thread::Builder::new()
215        .name("route-advertiser".to_string())
216        .spawn(move || {
217            loop {
218                advertise_route(&sqlite, &pairing, &name, &data_dir);
219                thread::sleep(ROUTE_REFRESH);
220            }
221        });
222    if let Err(e) = spawned {
223        tracing::error!("cannot start the route advertiser: {e}");
224    }
225}
226
227/// Where another device on the network may reach this one: the address of
228/// the default route, then the host name.
229pub fn local_addresses(name: &str) -> Vec<String> {
230    let mut addresses = Vec::new();
231    let routed = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
232        .and_then(|socket| {
233            socket.connect(ROUTE_PROBE)?;
234            socket.local_addr()
235        })
236        .map(|addr| addr.ip());
237    match routed {
238        Ok(ip) if !ip.is_unspecified() && !ip.is_loopback() => addresses.push(ip.to_string()),
239        Ok(_) => {}
240        Err(e) => tracing::debug!("no routed address for pairing: {e}"),
241    }
242    if !name.is_empty() && !addresses.iter().any(|a| a == name) {
243        addresses.push(name.to_string());
244    }
245    addresses
246}
247
248fn login() -> Option<String> {
249    if let Ok(user) = std::env::var("USER")
250        && !user.is_empty()
251    {
252        return Some(user);
253    }
254    let mut buf = vec![0u8; 4096];
255    let mut pwd: libc::passwd = unsafe { std::mem::zeroed() };
256    let mut found: *mut libc::passwd = std::ptr::null_mut();
257    // SAFETY: getpwuid_r writes only into `pwd` and `buf`, whose sizes it is
258    // given, and `found` points at `pwd` or is null.
259    let rc = unsafe {
260        libc::getpwuid_r(
261            libc::geteuid(),
262            &mut pwd,
263            buf.as_mut_ptr().cast(),
264            buf.len(),
265            &mut found,
266        )
267    };
268    if rc != 0 || found.is_null() || pwd.pw_name.is_null() {
269        return None;
270    }
271    // SAFETY: on success pw_name points at a NUL-terminated string in `buf`.
272    let name = unsafe { CStr::from_ptr(pwd.pw_name) };
273    name.to_str().ok().map(str::to_string)
274}