1//! Live presence and Live Share: who else has the notebook open, the page they are on and
2//! their caret, straight from one Snowbound to another, or through a relay (`crates/relay`)
3//! where they aren't on one network; and a notebook one machine holds opened on another
4//! (`share`). Peers find each other with mDNS (`_snowbound._tcp`) or in the relay's room, and
5//! meet through a secret both hold, a room's or a code typed on both, which SPAKE2 turns into
6//! the keys every frame after the opening is sealed with. Each connection has a thread reading
7//! and one writing. A connection whose frames arrive out of order is dropped and met again
8//! from scratch.
9
10pub use ::relay::code;
11mod group;
12pub mod proxy;
13mod relay;
14pub mod share;
15mod transport;
16pub use transport::Trouble;
17pub mod wire;
18pub use wire::{Caret, Guid, Hello, Presence, Spot};
19
20use mdns_sd::{IfKind, ServiceDaemon, ServiceEvent, ServiceInfo};
21use minicbor::Encode;
22use std::{
23 collections::BTreeMap,
24 io::{self, Read, Write},
25 net::{IpAddr, Ipv4Addr, Shutdown, SocketAddr, TcpListener, TcpStream},
26 sync::{
27 Arc, Mutex,
28 atomic::{AtomicBool, AtomicU64, Ordering},
29 mpsc,
30 },
31 thread,
32 time::{Duration, Instant},
33};
34use wire::{Sealer, Side, kind};
35
36const SERVICE: &str = "_snowbound._tcp.local.";
37/// How long a connection may be quiet before a ping, and before the peer counts as gone.
38const PING: Duration = Duration::from_secs(15);
39const GONE: Duration = Duration::from_secs(45);
40const OPENING: Duration = Duration::from_secs(5);
41/// The most often presence goes to a peer.
42const PRESENCE_EVERY: Duration = Duration::from_millis(100);
43/// The longest wait before meeting again.
44const PATIENCE: Duration = Duration::from_secs(30);
45/// Wrong tries of a code met off any relay before it admits no one new, as a relay burns one.
46const TRIES: u32 = 5;
47
48mod model;
49pub use model::{Event, Peer, Reach, Relayed, Room};
50use model::{code_parts, hex};
51
52/// Presence on the network while it lives; dropping it leaves.
53pub struct Live {
54 shared: Arc<Shared>,
55 address: SocketAddr,
56}
57
58struct Shared {
59 me: Hello,
60 room: Room,
61 secret: Vec<u8>,
62 reach: Option<Reach>,
63 state: Mutex<State>,
64 #[allow(clippy::type_complexity)]
65 events: Box<dyn Fn(&Arc<Shared>, Event) + Send + Sync>,
66 stopped: AtomicBool,
67 connections: AtomicU64,
68}
69
70#[derive(Default)]
71struct State {
72 presence: Presence,
73 /// Counts changes to `presence`, so a writer sends only the newest.
74 generation: u64,
75 peers: BTreeMap<[u8; 16], Link>,
76 dialing: BTreeMap<SocketAddr, thread::Thread>,
77 /// The code others type, once known.
78 code: Option<String>,
79 /// The relay connection open now, to hang up on leaving.
80 relay: Option<Arc<relay::Socket>>,
81 relayed: Option<Relayed>,
82 /// Meetings that failed on the secret: wrong codes tried here, or this end's.
83 failed: u32,
84 /// The code admits no one new.
85 burned: bool,
86 /// The Live Share version of the last peer met that speaks another.
87 outdated: Option<u16>,
88 daemon: Option<ServiceDaemon>,
89}
90
91impl State {
92 /// The relay's group, in a notebook's room while the relay is reached.
93 fn group(&self) -> Option<&relay::Group> {
94 self.relay.as_ref()?.group.as_ref()
95 }
96}
97
98/// Presence sent at most every `PRESENCE_EVERY`, and only the newest.
99#[derive(Default)]
100struct Paced {
101 due: Option<Instant>,
102 last: Option<Instant>,
103 sent: Option<u64>,
104}
105
106impl Paced {
107 /// How long to wait for news: until presence is due, else `idle`.
108 fn wait(&self, idle: Duration) -> Duration {
109 self.due
110 .map_or(idle, |due| due.saturating_duration_since(Instant::now()))
111 }
112
113 /// Hears that presence changed.
114 fn changed(&mut self) {
115 let last = self.last;
116 self.due
117 .get_or_insert_with(|| last.map_or_else(Instant::now, |at| at + PRESENCE_EVERY));
118 }
119
120 /// The presence to send now, where it is due and new.
121 fn due(&mut self, state: &Mutex<State>) -> Option<Presence> {
122 self.due.filter(|due| *due <= Instant::now())?;
123 self.due = None;
124 let state = state.lock().unwrap();
125 if self.sent == Some(state.generation) {
126 return None;
127 }
128 (self.sent, self.last) = (Some(state.generation), Some(Instant::now()));
129 Some(state.presence.clone())
130 }
131}
132
133struct Link {
134 connection: u64,
135 peer: Peer,
136 line: Line,
137 pipe: Arc<dyn Pipe>,
138}
139
140/// How a connection to a peer went, as the next dial to it takes it.
141enum Ran {
142 Met,
143 /// It broke before the peers met.
144 Failed,
145 /// Another try would end the same way.
146 Hopeless,
147}
148
149/// What a connection's writer sends next.
150enum Out {
151 /// The newest presence.
152 Presence,
153 Frame(u16, Vec<u8>),
154 /// A `Bye`, after which it hangs up.
155 Bye(Vec<u8>),
156}
157
158/// The way to one connected peer: frames sent on it go after those sent before.
159#[derive(Clone)]
160pub struct Line(mpsc::Sender<Out>);
161
162impl Line {
163 pub fn send(&self, kind: u16, body: &impl Encode<()>) -> io::Result<()> {
164 let body = minicbor::to_vec(body).map_err(io::Error::other)?;
165 self.0
166 .send(Out::Frame(kind, body))
167 .map_err(|_| io::ErrorKind::NotConnected.into())
168 }
169
170 /// Says `reason` after the frames sent before, then hangs up.
171 pub fn hang_up(&self, reason: &str) {
172 let bye = minicbor::to_vec(wire::Bye {
173 reason: reason.into(),
174 })
175 .unwrap_or_default();
176 let _ = self.0.send(Out::Bye(bye));
177 }
178}
179
180/// A stream to one peer, read by one thread and written by another: a TCP connection, or
181/// one carried through a relay.
182trait Pipe: Send + Sync {
183 fn read(&self, buffer: &mut [u8]) -> io::Result<usize>;
184 fn write(&self, bytes: &[u8]) -> io::Result<usize>;
185 fn set_read_timeout(&self, timeout: Duration) -> io::Result<()>;
186 /// Hangs up, ending the thread reading.
187 fn shutdown(&self);
188 /// Whether it goes straight to the peer, which is better than through a relay.
189 fn direct(&self) -> bool;
190 /// Hears whether the peer at the other end knew the secret.
191 fn met(&self, _met: bool) {}
192 /// Hears that the stream failed, after which this end meets its peers again.
193 fn broken(&self) {}
194}
195
196impl Pipe for TcpStream {
197 fn read(&self, buffer: &mut [u8]) -> io::Result<usize> {
198 Read::read(&mut &*self, buffer)
199 }
200
201 fn write(&self, bytes: &[u8]) -> io::Result<usize> {
202 Write::write(&mut &*self, bytes)
203 }
204
205 fn set_read_timeout(&self, timeout: Duration) -> io::Result<()> {
206 TcpStream::set_read_timeout(self, Some(timeout))
207 }
208
209 fn shutdown(&self) {
210 let _ = TcpStream::shutdown(self, Shutdown::Both);
211 }
212
213 fn direct(&self) -> bool {
214 true
215 }
216}
217
218impl Read for &dyn Pipe {
219 fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
220 Pipe::read(*self, buffer)
221 }
222}
223
224impl Write for &dyn Pipe {
225 fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
226 Pipe::write(*self, bytes)
227 }
228
229 fn flush(&mut self) -> io::Result<()> {
230 Ok(())
231 }
232}
233
234impl Live {
235 /// Starts listening as `me` in `room`, advertised and looked for where `reach` says, or
236 /// not at all with `None`, leaving peers to `connect`, and in the room at `relay`
237 /// (`wss://live.example.net`) where given. `events` runs on a network thread.
238 pub fn start(
239 me: Hello,
240 room: &Room,
241 reach: Option<Reach>,
242 relay: Option<&str>,
243 events: impl Fn(Event) + Send + Sync + 'static,
244 ) -> io::Result<Live> {
245 Self::start_with(me, room, reach, relay, move |_, event| events(event))
246 }
247
248 fn start_with(
249 me: Hello,
250 room: &Room,
251 reach: Option<Reach>,
252 relay: Option<&str>,
253 events: impl Fn(&Arc<Shared>, Event) + Send + Sync + 'static,
254 ) -> io::Result<Live> {
255 let host = match reach {
256 Some(Reach::Network) => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
257 Some(Reach::Loopback) | None => IpAddr::V4(Ipv4Addr::LOCALHOST),
258 };
259 let listener = TcpListener::bind((host, 0))?;
260 let mut address = listener.local_addr()?;
261 if address.ip().is_unspecified() {
262 address.set_ip(IpAddr::V4(Ipv4Addr::LOCALHOST));
263 }
264 let code = match room {
265 Room::Code { code, .. } => match code_parts(code) {
266 (Some(number), secret) => code::format(number, &secret),
267 // Off any relay, the end sharing a secret alone numbers it itself.
268 (None, secret) if relay.is_none() => {
269 let mut number = [0; 4];
270 getrandom::fill(&mut number)
271 .map_err(|_| io::Error::other("System random source failed"))?;
272 code::format(u32::from_le_bytes(number) % code::NAMEPLATES, &secret)
273 }
274 (None, _) => None,
275 },
276 Room::Notebook(_) => None,
277 };
278 let shared = Arc::new(Shared {
279 me,
280 room: room.clone(),
281 secret: room.secret(),
282 reach,
283 state: Mutex::new(State {
284 code,
285 ..State::default()
286 }),
287 events: Box::new(events),
288 stopped: AtomicBool::new(false),
289 connections: AtomicU64::new(0),
290 });
291 if let Some(relay) = relay {
292 relay::join(&shared, relay, address.port())?;
293 }
294 let accepting = Arc::clone(&shared);
295 thread::Builder::new()
296 .name("live accept".into())
297 .spawn(move || {
298 for stream in listener.incoming() {
299 if accepting.stopped.load(Ordering::Acquire) {
300 return;
301 }
302 if let (Ok(stream), Some(tag)) = (stream, accepting.tag()) {
303 let shared = Arc::clone(&accepting);
304 thread::spawn(move || shared.run(Arc::new(stream), Side::Responder, &tag));
305 }
306 }
307 })?;
308 shared.advertise(address.port());
309 Ok(Live { shared, address })
310 }
311
312 /// Where this end listens.
313 pub fn address(&self) -> SocketAddr {
314 self.address
315 }
316
317 /// The code others type to meet this end: the one it was given, or the one the relay
318 /// or this end numbered.
319 pub fn code(&self) -> Option<String> {
320 self.shared.state.lock().unwrap().code.clone()
321 }
322
323 /// How the relay last answered.
324 pub fn relayed(&self) -> Relayed {
325 let state = self.shared.state.lock().unwrap();
326 state.relayed.clone().unwrap_or(Relayed::Unknown)
327 }
328
329 /// Meetings that failed on the secret: wrong tries of this end's code, or this end's own
330 /// wrong code.
331 pub fn failed(&self) -> u32 {
332 self.shared.state.lock().unwrap().failed
333 }
334
335 /// The Live Share version of the last peer met that speaks another, which one of the two
336 /// must update to meet.
337 pub fn other_version(&self) -> Option<u16> {
338 self.shared.state.lock().unwrap().outdated
339 }
340
341 /// Whether this end's code had too many wrong tries and admits no one new.
342 pub fn burned(&self) -> bool {
343 self.shared.state.lock().unwrap().burned
344 }
345
346 /// Connects to a peer at `address` that discovery did not find.
347 pub fn connect(&self, address: SocketAddr) {
348 self.shared.dial(address);
349 }
350
351 /// Says where this end is now; peers hear only the newest of quick changes, at most every
352 /// tenth of a second.
353 pub fn set_presence(&self, presence: Presence) {
354 let mut state = self.shared.state.lock().unwrap();
355 if state.presence == presence {
356 return;
357 }
358 state.presence = presence;
359 state.generation += 1;
360 for link in state.peers.values() {
361 if self.shared.carries_presence(&*link.pipe) {
362 let _ = link.line.0.send(Out::Presence);
363 }
364 }
365 if let Some(group) = state.group() {
366 group.send(relay::Out::Presence);
367 }
368 }
369
370 /// The peers in the room now, by id.
371 pub fn peers(&self) -> Vec<Peer> {
372 self.shared.peers()
373 }
374
375 /// A way to send to this room's peers that doesn't keep it open.
376 pub fn sender(&self) -> Sender {
377 Sender(Arc::downgrade(&self.shared))
378 }
379
380 /// The line to `peer`, while it is connected.
381 pub fn line(&self, peer: &[u8; 16]) -> Option<Line> {
382 let state = self.shared.state.lock().unwrap();
383 state.peers.get(peer).map(|link| link.line.clone())
384 }
385
386 /// Says `reason` to every peer and leaves, waiting a moment for them to hear it.
387 pub fn leave(self, reason: &str) {
388 let bye = minicbor::to_vec(wire::Bye {
389 reason: reason.into(),
390 })
391 .unwrap_or_default();
392 for link in self.shared.state.lock().unwrap().peers.values() {
393 let _ = link.line.0.send(Out::Bye(bye.clone()));
394 }
395 let deadline = Instant::now() + Duration::from_secs(1);
396 while !self.shared.state.lock().unwrap().peers.is_empty() && Instant::now() < deadline {
397 thread::sleep(Duration::from_millis(20));
398 }
399 }
400}
401
402/// Sends to a room's peers while the room is open.
403#[derive(Clone)]
404pub struct Sender(std::sync::Weak<Shared>);
405
406impl Sender {
407 /// Sends message `kind` holding `body` to the peers `to` names, or to everyone: once to
408 /// the room's group through the relay, and to each peer met directly.
409 pub fn send(&self, kind: u16, body: &impl Encode<()>, to: Option<&[[u8; 16]]>) {
410 let (Some(shared), Ok(body)) = (self.0.upgrade(), minicbor::to_vec(body)) else {
411 return;
412 };
413 let state = shared.state.lock().unwrap();
414 let group = state.group();
415 let named = |id: &[u8; 16]| to.is_none_or(|to| to.contains(id));
416 let mut slots = Vec::new();
417 for (id, link) in state.peers.iter().filter(|(id, _)| named(id)) {
418 match group {
419 Some(group) if !link.pipe.direct() => slots.extend(group.slot(id)),
420 _ => {
421 let _ = link.line.0.send(Out::Frame(kind, body.clone()));
422 }
423 }
424 }
425 let Some(group) = group else {
426 return;
427 };
428 match to {
429 None => group.send(relay::Out::Frame(kind, body, None)),
430 Some(to) => {
431 let unlinked = to.iter().filter(|id| !state.peers.contains_key(*id));
432 slots.extend(unlinked.filter_map(|id| group.slot(id)));
433 if !slots.is_empty() {
434 group.send(relay::Out::Frame(kind, body, Some(slots)));
435 }
436 }
437 }
438 }
439}
440
441impl Drop for Live {
442 fn drop(&mut self) {
443 self.shared.stopped.store(true, Ordering::Release);
444 // Wakes the accepting thread to see it has stopped.
445 let _ = TcpStream::connect_timeout(&self.address, OPENING);
446 let mut state = self.shared.state.lock().unwrap();
447 for dial in state.dialing.values() {
448 dial.unpark();
449 }
450 if let Some(daemon) = state.daemon.take() {
451 let _ = daemon.shutdown();
452 }
453 for link in state.peers.values() {
454 link.pipe.shutdown();
455 }
456 if let Some(relay) = &state.relay {
457 relay.hang_up();
458 }
459 }
460}
461
462impl Shared {
463 fn gone(&self, hello: &Arc<Hello>) -> bool {
464 !self.state.lock().unwrap().peers.contains_key(&hello.peer)
465 }
466
467 /// Whether `hello` is how a peer is in the room now: its link, or its place in the group.
468 fn connected(&self, hello: &Arc<Hello>) -> bool {
469 let current = |peer: &Peer| Arc::ptr_eq(&peer.hello, hello);
470 let state = self.state.lock().unwrap();
471 !self.stopped.load(Ordering::Acquire)
472 && (state
473 .peers
474 .get(&hello.peer)
475 .is_some_and(|link| current(&link.peer))
476 || state.group().is_some_and(|group| {
477 (group.members.lock().unwrap().values())
478 .any(|member| member.peer.as_ref().is_some_and(current))
479 }))
480 }
481
482 /// The peers in the room: those met directly, and the rest as the relay's group or a
483 /// stream through the relay last heard of them.
484 fn peers(&self) -> Vec<Peer> {
485 let state = self.state.lock().unwrap();
486 let mut peers = BTreeMap::new();
487 if let Some(group) = state.group() {
488 for member in group.members.lock().unwrap().values() {
489 if let Some(peer) = &member.peer {
490 peers.insert(peer.hello.peer, peer.clone());
491 }
492 }
493 }
494 for (id, link) in &state.peers {
495 if link.pipe.direct() || !peers.contains_key(id) {
496 peers.insert(*id, link.peer.clone());
497 }
498 }
499 peers.into_values().collect()
500 }
501
502 /// Whether peer `id` is met directly, which is where it says everything.
503 fn direct(&self, id: &[u8; 16]) -> bool {
504 let state = self.state.lock().unwrap();
505 state.peers.get(id).is_some_and(|link| link.pipe.direct())
506 }
507
508 /// Whether presence goes on `pipe`: not on a stream through the relay in a notebook's
509 /// room, whose group carries it.
510 fn carries_presence(&self, pipe: &dyn Pipe) -> bool {
511 pipe.direct() || matches!(self.room, Room::Code { .. })
512 }
513
514 /// The room's tag as it stands: a code's, once numbered.
515 fn tag(&self) -> Option<String> {
516 match &self.room {
517 Room::Code { .. } => code_parts(self.state.lock().unwrap().code.as_deref()?)
518 .0
519 .map(|number| format!("code-{number}")),
520 room => room.tag(),
521 }
522 }
523
524 /// Advertises this end on `port` once its room has a tag, where its reach says, and
525 /// connects to the peers in its room that discovery finds with a higher id than its own,
526 /// which leave the connecting to it.
527 fn advertise(self: &Arc<Self>, port: u16) {
528 let (Some(reach), Some(tag)) = (self.reach, self.tag()) else {
529 return;
530 };
531 let mut state = self.state.lock().unwrap();
532 if state.daemon.is_some() || self.stopped.load(Ordering::Acquire) {
533 return;
534 }
535 match discover(self, reach, tag, port) {
536 Ok(daemon) => state.daemon = Some(daemon),
537 Err(error) => eprintln!("Live: no discovery: {error}"),
538 }
539 }
540
541 fn knows(&self, peer: &str) -> bool {
542 let state = self.state.lock().unwrap();
543 state.peers.keys().any(|id| hex(id) == peer)
544 }
545
546 /// Keeps one dial to `address`, meeting again after a transport failure.
547 fn dial(self: &Arc<Self>, address: SocketAddr) {
548 let mut state = self.state.lock().unwrap();
549 if self.stopped.load(Ordering::Acquire)
550 || state.burned
551 || state.dialing.contains_key(&address)
552 {
553 return;
554 }
555 let shared = Arc::downgrade(self);
556 let dialing = thread::spawn(move || {
557 let mut wait = Duration::from_secs(1);
558 let ours = |state: &State| {
559 (state.dialing.get(&address))
560 .is_some_and(|dial| dial.id() == thread::current().id())
561 };
562 loop {
563 let Some(live) = shared.upgrade() else {
564 return;
565 };
566 let state = live.state.lock().unwrap();
567 if live.stopped.load(Ordering::Acquire) || state.burned || !ours(&state) {
568 break;
569 }
570 drop(state);
571 let Some(tag) = live.tag() else {
572 break;
573 };
574 drop(live);
575 if let Ok(stream) = TcpStream::connect_timeout(&address, OPENING) {
576 let Some(live) = shared.upgrade() else {
577 return;
578 };
579 let began = Instant::now();
580 match live.run(Arc::new(stream), Side::Initiator, &tag) {
581 // One the peer ends at once, as a duplicate it refuses, is no meeting.
582 Ran::Met if began.elapsed() >= OPENING => wait = Duration::from_secs(1),
583 Ran::Met | Ran::Failed => {}
584 Ran::Hopeless => break,
585 }
586 }
587 thread::park_timeout(wait);
588 wait = (wait * 2).min(PATIENCE);
589 }
590 if let Some(live) = shared.upgrade() {
591 let mut state = live.state.lock().unwrap();
592 if ours(&state) {
593 state.dialing.remove(&address);
594 }
595 }
596 });
597 state.dialing.insert(address, dialing.thread().clone());
598 }
599
600 /// Stops dialling `address` once its connection, if any, ends.
601 fn undial(&self, address: SocketAddr) {
602 if let Some(dial) = self.state.lock().unwrap().dialing.remove(&address) {
603 dial.unpark();
604 }
605 }
606
607 /// Counts a meeting that failed on the secret: the end sharing a code burns it after too
608 /// many, and an end that typed one gives up at once.
609 fn failed(self: &Arc<Self>) {
610 let mut state = self.state.lock().unwrap();
611 state.failed += 1;
612 match &self.room {
613 Room::Code { owner: true, .. } if state.failed >= TRIES => state.burned = true,
614 Room::Code { owner: false, .. } => self.stopped.store(true, Ordering::Release),
615 _ => {}
616 }
617 drop(state);
618 (self.events)(self, Event::Changed);
619 }
620
621 /// Meets the peer at the other end of `pipe` in room `tag`, then reads from it until it
622 /// goes.
623 fn run(self: Arc<Self>, pipe: Arc<dyn Pipe>, side: Side, tag: &str) -> Ran {
624 if self.stopped.load(Ordering::Acquire) || self.state.lock().unwrap().burned {
625 pipe.shutdown();
626 return Ran::Hopeless;
627 }
628 let mut stream: &dyn Pipe = &*pipe;
629 let met = (|| {
630 stream.set_read_timeout(OPENING)?;
631 let (mut send, mut receive) = wire::open(&mut stream, side, tag, &self.secret)?;
632 send.send(&mut stream, kind::HELLO, &self.me)?;
633 let (first, body) = receive.receive(&mut stream)?;
634 if first != kind::HELLO {
635 return Err(io::Error::new(io::ErrorKind::InvalidData, "No hello"));
636 }
637 let hello: Hello = minicbor::decode(&body)
638 .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "A malformed hello"))?;
639 stream.set_read_timeout(GONE)?;
640 Ok((send, receive, hello))
641 })();
642 let other = (met.as_ref().err())
643 .and_then(|error| error.get_ref()?.downcast_ref::<wire::Version>())
644 .copied();
645 let (send, mut receive, hello) = match met {
646 Ok(met) => {
647 pipe.met(true);
648 met
649 }
650 Err(error) => {
651 eprintln!("Live: no meeting in {tag}: {error}");
652 if let Some(wire::Version(version)) = other {
653 // Another version guessed nothing: no keys were agreed.
654 pipe.met(true);
655 self.state.lock().unwrap().outdated = Some(version);
656 if matches!(self.room, Room::Code { owner: false, .. }) {
657 self.stopped.store(true, Ordering::Release);
658 }
659 (self.events)(&self, Event::Changed);
660 } else if error.kind() == io::ErrorKind::InvalidData {
661 pipe.met(false);
662 self.failed();
663 } else {
664 pipe.broken();
665 }
666 pipe.shutdown();
667 return match other.is_none() && error.kind() != io::ErrorKind::InvalidData {
668 true => Ran::Failed,
669 false => Ran::Hopeless,
670 };
671 }
672 };
673 let peer = hello.peer;
674 let name = hello.name.clone();
675 let hello = Arc::new(hello);
676 let connection = self.connections.fetch_add(1, Ordering::Relaxed);
677 let (out, outgoing) = mpsc::channel();
678 let line = Line(out);
679 let retired = {
680 let mut state = self.state.lock().unwrap();
681 // A peer met both directly and through a relay keeps the direct connection, as
682 // both ends then agree. A stream through the relay comes only from a slot newer
683 // than the one it replaces, whose stream the relay may not yet have seen go.
684 let kept = match state.peers.get(&peer) {
685 _ if peer == self.me.peer => false,
686 Some(link) => !link.pipe.direct(),
687 None => true,
688 };
689 if !kept {
690 drop(state);
691 pipe.shutdown();
692 return Ran::Hopeless;
693 }
694 state.peers.insert(
695 peer,
696 Link {
697 connection,
698 peer: Peer {
699 hello: Arc::clone(&hello),
700 presence: None,
701 },
702 line: line.clone(),
703 pipe: Arc::clone(&pipe),
704 },
705 )
706 };
707 if let Some(retired) = retired {
708 retired.pipe.shutdown();
709 }
710 if self.carries_presence(&*pipe) {
711 let _ = line.0.send(Out::Presence);
712 }
713 let writing = Arc::clone(&pipe);
714 let shared = Arc::clone(&self);
715 thread::spawn(move || shared.write(&*writing, send, outgoing));
716 (self.events)(&self, Event::Met(&hello, &line));
717 (self.events)(&self, Event::Changed);
718 let ended = loop {
719 let (message, body) = match receive.receive(&mut stream) {
720 Ok(frame) => frame,
721 Err(error) => break Some(error),
722 };
723 match message {
724 kind::HELLO | kind::PING => {}
725 kind::PRESENCE => {
726 let Ok(presence) = minicbor::decode::<Presence>(&body) else {
727 break None;
728 };
729 if let Some(link) = self.state.lock().unwrap().peers.get_mut(&peer)
730 && link.connection == connection
731 {
732 link.peer.presence = Some(presence);
733 }
734 (self.events)(&self, Event::Changed);
735 }
736 kind => {
737 (self.events)(
738 &self,
739 Event::Frame {
740 from: &hello,
741 kind,
742 body: &body,
743 },
744 );
745 // The peer hangs up after its bye.
746 if kind == kind::BYE {
747 break None;
748 }
749 }
750 }
751 };
752 if let Some(error) = ended {
753 eprintln!("Live: the connection to {name} broke ({error}); meeting again");
754 pipe.broken();
755 }
756 pipe.shutdown();
757 let mut state = self.state.lock().unwrap();
758 if state
759 .peers
760 .get(&peer)
761 .is_some_and(|link| link.connection == connection)
762 {
763 state.peers.remove(&peer);
764 drop(state);
765 (self.events)(&self, Event::Left(&hello));
766 (self.events)(&self, Event::Changed);
767 }
768 Ran::Met
769 }
770
771 /// Sends the newest presence when woken, at most every `PRESENCE_EVERY`, frames as they
772 /// come, and a ping when quiet.
773 fn write(&self, pipe: &dyn Pipe, mut send: Sealer, outgoing: mpsc::Receiver<Out>) {
774 let mut stream = pipe;
775 let mut paced = Paced::default();
776 loop {
777 let result = match outgoing.recv_timeout(paced.wait(PING)) {
778 Ok(Out::Presence) => {
779 paced.changed();
780 Ok(())
781 }
782 Ok(Out::Frame(kind, body)) => send.send_encoded(&mut stream, kind, &body),
783 Ok(Out::Bye(body)) => {
784 let _ = send.send_encoded(&mut stream, kind::BYE, &body);
785 pipe.shutdown();
786 return;
787 }
788 Err(mpsc::RecvTimeoutError::Timeout) if paced.due.is_none() => {
789 send.send(&mut stream, kind::PING, &())
790 }
791 Err(mpsc::RecvTimeoutError::Timeout) => Ok(()),
792 Err(mpsc::RecvTimeoutError::Disconnected) => return,
793 };
794 let result = result.and_then(|()| match paced.due(&self.state) {
795 Some(presence) => send.send(&mut stream, kind::PRESENCE, &presence),
796 None => Ok(()),
797 });
798 if result.is_err() {
799 pipe.broken();
800 pipe.shutdown();
801 return;
802 }
803 }
804 }
805}
806
807/// Advertises `shared` as in room `tag` on `port` and connects to the peers in its room that
808/// discovery finds with a higher id than its own.
809fn discover(
810 shared: &Arc<Shared>,
811 reach: Reach,
812 tag: String,
813 port: u16,
814) -> mdns_sd::Result<ServiceDaemon> {
815 let daemon = ServiceDaemon::new()?;
816 let id = hex(&shared.me.peer);
817 let properties = [("v", "1"), ("room", tag.as_str()), ("peer", id.as_str())];
818 let host = format!("snowbound-{id}.local.");
819 let info = match reach {
820 Reach::Network => {
821 ServiceInfo::new(SERVICE, &id, &host, "", port, &properties[..])?.enable_addr_auto()
822 }
823 Reach::Loopback => {
824 daemon.disable_interface(IfKind::All)?;
825 daemon.enable_interface(IfKind::LoopbackV4)?;
826 ServiceInfo::new(
827 SERVICE,
828 &id,
829 &host,
830 IpAddr::V4(Ipv4Addr::LOCALHOST),
831 port,
832 &properties[..],
833 )?
834 }
835 };
836 daemon.register(info)?;
837 let found = daemon.browse(SERVICE)?;
838 let shared = Arc::downgrade(shared);
839 thread::Builder::new()
840 .name("live discovery".into())
841 .spawn(move || {
842 // Where each peer found was dialled, to stop once it is no longer advertised.
843 let mut dialled = BTreeMap::new();
844 while let Ok(event) = found.recv() {
845 let service = match event {
846 ServiceEvent::ServiceResolved(service) => service,
847 ServiceEvent::ServiceRemoved(_, name) => {
848 if let (Some(address), Some(shared)) =
849 (dialled.remove(&name), shared.upgrade())
850 {
851 shared.undial(address);
852 }
853 continue;
854 }
855 _ => continue,
856 };
857 let Some(shared) = shared.upgrade() else {
858 return;
859 };
860 let (Some(room), Some(peer)) = (
861 service.get_property_val_str("room"),
862 service.get_property_val_str("peer"),
863 ) else {
864 continue;
865 };
866 if room != tag || peer <= id.as_str() || shared.knows(peer) {
867 continue;
868 }
869 let mut addresses: Vec<IpAddr> =
870 service.addresses.iter().map(|ip| ip.to_ip_addr()).collect();
871 addresses.sort_by_key(|ip| (!ip.is_ipv4(), !ip.is_loopback()));
872 if let Some(ip) = addresses.first() {
873 let address = SocketAddr::new(*ip, service.port);
874 // A peer found again at another address is no longer at the old one.
875 if let Some(old) = dialled.insert(service.fullname.clone(), address)
876 && old != address
877 {
878 shared.undial(old);
879 }
880 shared.dial(address);
881 }
882 }
883 })
884 .map_err(|error| mdns_sd::Error::Msg(error.to_string()))?;
885 Ok(daemon)
886}
887
888/// `text` with `%XX` escapes decoded, as a URL's name and password.
889fn decode(text: &str) -> String {
890 let bytes = text.as_bytes();
891 let mut decoded = Vec::with_capacity(bytes.len());
892 let mut at = 0;
893 while at < bytes.len() {
894 match text
895 .get(at + 1..at + 3)
896 .filter(|_| bytes[at] == b'%')
897 .and_then(|hex| u8::from_str_radix(hex, 16).ok())
898 {
899 Some(byte) => {
900 decoded.push(byte);
901 at += 3;
902 }
903 None => {
904 decoded.push(bytes[at]);
905 at += 1;
906 }
907 }
908 }
909 String::from_utf8_lossy(&decoded).into_owned()
910}
911
912#[cfg(test)]
913mod tests;