use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;
use anyhow::{Context, Result, anyhow, bail};
use serde::Serialize;
use super::channel::Channel;
use super::code::JoinCode;
use super::{Admission, HostReply, JoinRequest, JoinerAck, KeyHandover, KeyRequest};
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
#[derive(Debug)]
pub struct Taken<T> {
pub taken: T,
pub admission: Admission,
pub unacked: Option<String>,
}
pub fn join<T>(
addresses: &[(String, u16)],
code: &JoinCode,
request: &JoinRequest,
take: impl FnOnce(&Admission, &str) -> Result<T>,
) -> Result<Taken<T>> {
let (mut channel, host) = open(addresses, code, request)?;
let admission = match channel.recv_json::<HostReply>()? {
HostReply::Admitted(admission) => *admission,
HostReply::Refused { reason } => bail!("the pairing device refused this device: {reason}"),
HostReply::KeysHandedOver(_) => bail!(
"that device runs `sb pair --restore-keys`, which hands keys to a restore and adds \
no device; run `sb pair` there to pair"
),
};
let (taken, unacked) = answer(&mut channel, take(&admission, &host))?;
Ok(Taken {
taken,
admission,
unacked,
})
}
pub fn fetch_keys<T>(
addresses: &[(String, u16)],
code: &JoinCode,
request: &KeyRequest,
take: impl FnOnce(&KeyHandover) -> Result<T>,
) -> Result<(T, Option<String>)> {
let (mut channel, _) = open(addresses, code, request)?;
let handover = match channel.recv_json::<HostReply>()? {
HostReply::KeysHandedOver(handover) => *handover,
HostReply::Refused { reason } => bail!("the other device refused: {reason}"),
HostReply::Admitted(_) => {
let reason = "this device asked for keys to restore a backup, not to pair";
if let Err(e) = channel.send_json(&JoinerAck::Failed {
reason: reason.into(),
}) {
tracing::warn!("could not tell the other device the restore failed: {e:#}");
}
bail!(
"that device paired this one instead of handing over keys; run `sb pair --restore-keys` there"
)
}
};
answer(&mut channel, take(&handover))
}
pub fn reachable(addresses: &[(String, u16)]) -> Result<()> {
dial(addresses).map(drop)
}
fn open(
addresses: &[(String, u16)],
code: &JoinCode,
request: &impl Serialize,
) -> Result<(Channel, String)> {
let (stream, host) = dial(addresses)?;
let mut channel = Channel::connect(stream, code)?;
channel.send_json(request)?;
Ok((channel, host))
}
fn answer<T>(channel: &mut Channel, taken: Result<T>) -> Result<(T, Option<String>)> {
match taken {
Ok(taken) => {
let unacked = channel
.send_json(&JoinerAck::Joined)
.err()
.map(|e| format!("{e:#}"));
Ok((taken, unacked))
}
Err(e) => {
let reason = format!("{e:#}");
if let Err(send) = channel.send_json(&JoinerAck::Failed { reason }) {
tracing::warn!("could not tell the pairing device the join failed: {send:#}");
}
Err(e)
}
}
}
fn dial(addresses: &[(String, u16)]) -> Result<(TcpStream, String)> {
let mut failures = Vec::new();
for (host, port) in addresses {
let resolved = match (host.as_str(), *port).to_socket_addrs() {
Ok(resolved) => resolved,
Err(e) => {
failures.push(format!("{host}: {e}"));
continue;
}
};
for addr in resolved {
match TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT) {
Ok(stream) => return Ok((stream, host.clone())),
Err(e) => failures.push(format!("{addr}: {e}")),
}
}
}
if addresses.is_empty() {
return Err(anyhow!("no address to reach the pairing device at"));
}
Err(anyhow!(failures.join("; ")))
.context("no pairing device answered; check `sb pair` is running there and the host")
}