second_brain_sync/pairing/
join.rs1use std::net::{TcpStream, ToSocketAddrs};
2use std::time::Duration;
3
4use anyhow::{Context, Result, anyhow, bail};
5use serde::Serialize;
6
7use super::channel::Channel;
8use super::code::JoinCode;
9use super::{Admission, HostReply, JoinRequest, JoinerAck, KeyHandover, KeyRequest};
10
11const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
12
13#[derive(Debug)]
15pub struct Taken<T> {
16 pub taken: T,
17 pub admission: Admission,
18 pub unacked: Option<String>,
21}
22
23pub fn join<T>(
28 addresses: &[(String, u16)],
29 code: &JoinCode,
30 request: &JoinRequest,
31 take: impl FnOnce(&Admission, &str) -> Result<T>,
32) -> Result<Taken<T>> {
33 let (mut channel, host) = open(addresses, code, request)?;
34 let admission = match channel.recv_json::<HostReply>()? {
35 HostReply::Admitted(admission) => *admission,
36 HostReply::Refused { reason } => bail!("the pairing device refused this device: {reason}"),
37 HostReply::KeysHandedOver(_) => bail!(
38 "that device runs `sb pair --restore-keys`, which hands keys to a restore and adds \
39 no device; run `sb pair` there to pair"
40 ),
41 };
42 let (taken, unacked) = answer(&mut channel, take(&admission, &host))?;
43 Ok(Taken {
44 taken,
45 admission,
46 unacked,
47 })
48}
49
50pub fn fetch_keys<T>(
54 addresses: &[(String, u16)],
55 code: &JoinCode,
56 request: &KeyRequest,
57 take: impl FnOnce(&KeyHandover) -> Result<T>,
58) -> Result<(T, Option<String>)> {
59 let (mut channel, _) = open(addresses, code, request)?;
60 let handover = match channel.recv_json::<HostReply>()? {
61 HostReply::KeysHandedOver(handover) => *handover,
62 HostReply::Refused { reason } => bail!("the other device refused: {reason}"),
63 HostReply::Admitted(_) => {
64 let reason = "this device asked for keys to restore a backup, not to pair";
65 if let Err(e) = channel.send_json(&JoinerAck::Failed {
66 reason: reason.into(),
67 }) {
68 tracing::warn!("could not tell the other device the restore failed: {e:#}");
69 }
70 bail!(
71 "that device paired this one instead of handing over keys; run `sb pair --restore-keys` there"
72 )
73 }
74 };
75 answer(&mut channel, take(&handover))
76}
77
78pub fn reachable(addresses: &[(String, u16)]) -> Result<()> {
81 dial(addresses).map(drop)
82}
83
84fn open(
85 addresses: &[(String, u16)],
86 code: &JoinCode,
87 request: &impl Serialize,
88) -> Result<(Channel, String)> {
89 let (stream, host) = dial(addresses)?;
90 let mut channel = Channel::connect(stream, code)?;
91 channel.send_json(request)?;
92 Ok((channel, host))
93}
94
95fn answer<T>(channel: &mut Channel, taken: Result<T>) -> Result<(T, Option<String>)> {
98 match taken {
99 Ok(taken) => {
100 let unacked = channel
101 .send_json(&JoinerAck::Joined)
102 .err()
103 .map(|e| format!("{e:#}"));
104 Ok((taken, unacked))
105 }
106 Err(e) => {
107 let reason = format!("{e:#}");
108 if let Err(send) = channel.send_json(&JoinerAck::Failed { reason }) {
109 tracing::warn!("could not tell the pairing device the join failed: {send:#}");
110 }
111 Err(e)
112 }
113 }
114}
115
116fn dial(addresses: &[(String, u16)]) -> Result<(TcpStream, String)> {
117 let mut failures = Vec::new();
118 for (host, port) in addresses {
119 let resolved = match (host.as_str(), *port).to_socket_addrs() {
120 Ok(resolved) => resolved,
121 Err(e) => {
122 failures.push(format!("{host}: {e}"));
123 continue;
124 }
125 };
126 for addr in resolved {
127 match TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT) {
128 Ok(stream) => return Ok((stream, host.clone())),
129 Err(e) => failures.push(format!("{addr}: {e}")),
130 }
131 }
132 }
133 if addresses.is_empty() {
134 return Err(anyhow!("no address to reach the pairing device at"));
135 }
136 Err(anyhow!(failures.join("; ")))
137 .context("no pairing device answered; check `sb pair` is running there and the host")
138}