1use std::io::ErrorKind;
2use std::net::{SocketAddr, TcpListener, TcpStream};
3use std::sync::{Arc, Mutex, MutexGuard};
4use std::thread;
5use std::time::{Duration, Instant};
6
7use anyhow::{Context, Result};
8use zeroize::Zeroizing;
9
10use super::channel::{Accepted, Channel};
11use super::code::HostSecrets;
12use super::{
13 Admission, HostReply, JoinRequest, JoinerAck, KeyHandover, KeyRequest, MAX_WRONG_TRIES,
14};
15
16const ACCEPT_POLL: Duration = Duration::from_millis(100);
17const PROVE_LIMIT: Duration = Duration::from_secs(20);
20const ACK_WAIT: Duration = Duration::from_secs(120);
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub enum HostOutcome {
25 Waiting,
26 Paired {
27 machine_id: String,
28 name: String,
29 },
30 HandedOver {
32 name: String,
33 },
34 Expired,
36 Closed,
39}
40
41pub struct HostStatus {
42 pub outcome: HostOutcome,
43 pub code: Zeroizing<String>,
44 pub invite: Zeroizing<String>,
45 pub wrong_tries: u32,
47 pub retired: u32,
49 pub remaining: Duration,
50 pub last_error: Option<String>,
52}
53
54struct State {
55 secrets: Arc<HostSecrets>,
56 wrong_tries: u32,
57 retired: u32,
58 outcome: HostOutcome,
59 last_poll: Instant,
60 last_error: Option<String>,
61}
62
63struct Shared {
64 state: Mutex<State>,
65 hosts: Vec<String>,
66 port: u16,
67 deadline: Instant,
68 idle: Duration,
69}
70
71impl Shared {
72 fn lock(&self) -> MutexGuard<'_, State> {
73 self.state
74 .lock()
75 .unwrap_or_else(|poisoned| poisoned.into_inner())
76 }
77}
78
79type Admit = dyn Fn(&JoinRequest) -> Result<Admission> + Send + Sync;
80type HandOver = dyn Fn(&KeyRequest) -> Result<KeyHandover> + Send + Sync;
81
82enum Serve {
84 Admit(Box<Admit>),
85 HandOver(Box<HandOver>),
86}
87
88pub struct PairingHost {
91 shared: Arc<Shared>,
92 hands_over_keys: bool,
93}
94
95impl PairingHost {
96 pub fn open(
99 listener: TcpListener,
100 hosts: Vec<String>,
101 lifetime: Duration,
102 idle: Duration,
103 admit: Box<Admit>,
104 ) -> Result<Self> {
105 Self::serving(listener, hosts, lifetime, idle, Serve::Admit(admit))
106 }
107
108 pub fn open_key_handover(
112 listener: TcpListener,
113 hosts: Vec<String>,
114 lifetime: Duration,
115 idle: Duration,
116 hand_over: Box<HandOver>,
117 ) -> Result<Self> {
118 Self::serving(listener, hosts, lifetime, idle, Serve::HandOver(hand_over))
119 }
120
121 fn serving(
122 listener: TcpListener,
123 hosts: Vec<String>,
124 lifetime: Duration,
125 idle: Duration,
126 serve_as: Serve,
127 ) -> Result<Self> {
128 listener
129 .set_nonblocking(true)
130 .context("making the pairing listener non-blocking")?;
131 let port = listener.local_addr()?.port();
132 let now = Instant::now();
133 let shared = Arc::new(Shared {
134 state: Mutex::new(State {
135 secrets: Arc::new(HostSecrets::generate()),
136 wrong_tries: 0,
137 retired: 0,
138 outcome: HostOutcome::Waiting,
139 last_poll: now,
140 last_error: None,
141 }),
142 hosts,
143 port,
144 deadline: now + lifetime,
145 idle,
146 });
147 let served = shared.clone();
148 let hands_over_keys = matches!(serve_as, Serve::HandOver(_));
149 thread::Builder::new()
150 .name("pairing-listener".into())
151 .spawn(move || serve(&listener, &served, &serve_as))
152 .context("starting the pairing listener")?;
153 Ok(Self {
154 shared,
155 hands_over_keys,
156 })
157 }
158
159 pub fn hands_over_keys(&self) -> bool {
161 self.hands_over_keys
162 }
163
164 pub fn port(&self) -> u16 {
165 self.shared.port
166 }
167
168 pub fn hosts(&self) -> &[String] {
169 &self.shared.hosts
170 }
171
172 pub fn status(&self) -> HostStatus {
174 let mut state = self.shared.lock();
175 let now = Instant::now();
176 state.last_poll = now;
177 HostStatus {
178 outcome: state.outcome.clone(),
179 code: state.secrets.code(),
180 invite: state.secrets.invite(&self.shared.hosts, self.shared.port),
181 wrong_tries: state.wrong_tries,
182 retired: state.retired,
183 remaining: self.shared.deadline.saturating_duration_since(now),
184 last_error: state.last_error.clone(),
185 }
186 }
187
188 pub fn close(&self) {
189 let mut state = self.shared.lock();
190 if state.outcome == HostOutcome::Waiting {
191 state.outcome = HostOutcome::Closed;
192 }
193 }
194
195 pub fn is_open(&self) -> bool {
196 self.shared.lock().outcome == HostOutcome::Waiting
197 }
198}
199
200impl Drop for PairingHost {
203 fn drop(&mut self) {
204 self.close();
205 }
206}
207
208fn serve(listener: &TcpListener, shared: &Shared, admit: &Serve) {
209 loop {
210 {
211 let mut state = shared.lock();
212 if state.outcome != HostOutcome::Waiting {
213 return;
214 }
215 let now = Instant::now();
216 if now >= shared.deadline {
217 state.outcome = HostOutcome::Expired;
218 return;
219 }
220 if now.duration_since(state.last_poll) > shared.idle {
221 state.outcome = HostOutcome::Closed;
222 return;
223 }
224 }
225 match listener.accept() {
226 Ok((stream, peer)) => take(stream, peer, shared, admit),
227 Err(e) if e.kind() == ErrorKind::WouldBlock => thread::sleep(ACCEPT_POLL),
228 Err(e) => {
229 tracing::warn!("the pairing listener failed to accept: {e}");
230 thread::sleep(ACCEPT_POLL);
231 }
232 }
233 }
234}
235
236fn take(stream: TcpStream, peer: SocketAddr, shared: &Shared, admit: &Serve) {
237 if let Err(e) = stream.set_nonblocking(false) {
238 tracing::warn!("pairing: dropping a connection from {peer}: {e}");
239 return;
240 }
241 let secrets = shared.lock().secrets.clone();
242 let (mut channel, first) = match Channel::accept(stream, &secrets, Instant::now() + PROVE_LIMIT)
243 {
244 Accepted::Opened { channel, first } => (channel, first),
245 Accepted::WrongCode => {
246 wrong_try(shared, &secrets, peer);
247 return;
248 }
249 Accepted::Broken(e) => {
250 tracing::info!("pairing: a connection from {peer} broke off: {e:#}");
251 return;
252 }
253 };
254 let still_open =
255 || shared.lock().outcome == HostOutcome::Waiting && Instant::now() < shared.deadline;
256 match finish(&mut channel, &first, admit, &still_open) {
257 Ok(outcome) => {
258 match &outcome {
259 HostOutcome::HandedOver { name } => {
260 tracing::info!("pairing: handed this device's keys to {name} at {peer}");
261 }
262 HostOutcome::Paired { machine_id, name } => {
263 tracing::info!("pairing: added device {name} ({machine_id}) from {peer}");
264 }
265 _ => {}
266 }
267 let mut state = shared.lock();
268 state.outcome = outcome;
269 state.last_error = None;
270 }
271 Err(e) => {
272 tracing::warn!("pairing: a join from {peer} did not complete: {e:#}");
273 shared.lock().last_error = Some(format!("{e:#}"));
274 }
275 }
276}
277
278fn finish(
279 channel: &mut Channel,
280 first: &[u8],
281 serve_as: &Serve,
282 still_open: &dyn Fn() -> bool,
283) -> Result<HostOutcome> {
284 let (name, on_ack, reply) = match serve_as {
285 Serve::Admit(admit) => {
286 let request: JoinRequest = match serde_json::from_slice(first) {
287 Ok(request) => request,
288 Err(e) if serde_json::from_slice::<KeyRequest>(first).is_ok() => {
289 refuse(
290 channel,
291 "this device is pairing, not handing over keys; run `sb pair \
292 --restore-keys` on it to restore a backup",
293 )?;
294 return Err(e).context("refused a restore asking for keys");
295 }
296 Err(e) => return Err(e).context("decoding the joining device's request"),
297 };
298 refuse_if_closed(channel, &request.name, still_open)?;
299 let admission = admit(&request).or_else(|e| refused(channel, &request.name, e))?;
300 (
301 request.name.clone(),
302 HostOutcome::Paired {
303 machine_id: request.machine_id,
304 name: request.name,
305 },
306 HostReply::Admitted(Box::new(admission)),
307 )
308 }
309 Serve::HandOver(hand_over) => {
310 let request: KeyRequest = match serde_json::from_slice(first) {
311 Ok(request) => request,
312 Err(e) if serde_json::from_slice::<JoinRequest>(first).is_ok() => {
313 refuse(
314 channel,
315 "this device hands over keys to restore a backup and adds no device; \
316 run `sb pair` on it to pair",
317 )?;
318 return Err(e).context("refused a join while handing over keys");
319 }
320 Err(e) => return Err(e).context("decoding the restoring device's request"),
321 };
322 refuse_if_closed(channel, &request.name, still_open)?;
323 let handover = hand_over(&request).or_else(|e| refused(channel, &request.name, e))?;
324 (
325 request.name.clone(),
326 HostOutcome::HandedOver { name: request.name },
327 HostReply::KeysHandedOver(Box::new(handover)),
328 )
329 }
330 };
331 channel.send_json(&reply)?;
332 channel.set_read_timeout(ACK_WAIT)?;
333 match channel.recv_json::<JoinerAck>()? {
334 JoinerAck::Joined => Ok(on_ack),
335 JoinerAck::Failed { reason } => {
336 anyhow::bail!("{name} could not store what it was sent: {reason}")
337 }
338 }
339}
340
341fn refuse(channel: &mut Channel, reason: &str) -> Result<()> {
342 channel.send_json(&HostReply::Refused {
343 reason: reason.into(),
344 })
345}
346
347fn refuse_if_closed(
348 channel: &mut Channel,
349 name: &str,
350 still_open: &dyn Fn() -> bool,
351) -> Result<()> {
352 if still_open() {
353 return Ok(());
354 }
355 refuse(
356 channel,
357 "pairing on that device was closed or ran out; run `sb pair` there again",
358 )?;
359 anyhow::bail!("refused {name}: pairing had closed")
360}
361
362fn refused<T>(channel: &mut Channel, name: &str, error: anyhow::Error) -> Result<T> {
363 let reason = format!("{error:#}");
364 refuse(channel, &reason)?;
365 anyhow::bail!("refused {name}: {reason}")
366}
367
368fn wrong_try(shared: &Shared, tried: &Arc<HostSecrets>, peer: SocketAddr) {
369 let mut state = shared.lock();
370 if !Arc::ptr_eq(&state.secrets, tried) {
371 return;
372 }
373 state.wrong_tries += 1;
374 tracing::warn!(
375 "pairing: a wrong code from {peer} ({} of {MAX_WRONG_TRIES})",
376 state.wrong_tries
377 );
378 if state.wrong_tries >= MAX_WRONG_TRIES {
379 state.secrets = Arc::new(HostSecrets::generate());
380 state.wrong_tries = 0;
381 state.retired += 1;
382 tracing::warn!("pairing: the code was retired after {MAX_WRONG_TRIES} wrong tries");
383 }
384}