1mod discovery;
11
12use std::collections::{BTreeMap, BTreeSet};
13use std::fmt::Write as _;
14use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
15use std::sync::{Arc, Mutex, PoisonError};
16use std::time::{Duration, Instant};
17
18use iroh::address_lookup::MemoryLookup;
19use iroh::endpoint::{
20 ConnectError, ConnectingError, Connection as Quic, ConnectionError, RecvStream, SendStream,
21 TransportErrorCode, presets,
22};
23use iroh::{Endpoint, EndpointAddr, EndpointId, SecretKey, TransportAddr};
24use nibkeep_sync::{MAX_MESSAGE_LEN, Transport, TransportError};
25use tokio::runtime::Runtime;
26
27const PAIR: &[u8] = b"nibkeep/pair/1";
29
30const SYNC: &[u8] = b"nibkeep/sync/1";
32
33const INVITE: &[u8] = b"nibkeep/invite/1";
35
36const BINDING: &[u8] = b"EXPORTER-nibkeep-2026-10";
38
39const RECEIVE_TIMEOUT: Duration = Duration::from_mins(5);
42
43const STREAM_TIMEOUT: Duration = Duration::from_secs(10);
45
46const CLOSE_TIMEOUT: Duration = Duration::from_secs(3);
48
49const LOOK_EVERY: Duration = Duration::from_millis(100);
51
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum Protocol {
55 Pair,
57 Sync,
59 Invite,
61}
62
63impl Protocol {
64 const fn alpn(self) -> &'static [u8] {
65 match self {
66 Self::Pair => PAIR,
67 Self::Sync => SYNC,
68 Self::Invite => INVITE,
69 }
70 }
71}
72
73pub const DEFAULT_PORT: u16 = 53_300;
76
77pub const PORTS: u16 = 10;
80
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub struct Options {
84 pub discovery: bool,
87 pub port: Option<u16>,
90 pub accept: bool,
93}
94
95impl Options {
96 pub const HOME: Self = Self {
98 discovery: true,
99 port: Some(DEFAULT_PORT),
100 accept: true,
101 };
102
103 pub const LOCAL: Self = Self {
105 discovery: false,
106 port: None,
107 accept: true,
108 };
109}
110
111type Incoming = (Quic, SendStream, RecvStream, Protocol);
113
114#[derive(Debug, thiserror::Error)]
116#[non_exhaustive]
117pub enum NetError {
118 #[error("cannot start networking: {0}")]
120 Start(String),
121 #[error("cannot connect: {0}")]
123 Connect(String),
124 #[error("the other device takes no connections now, as while it syncs by itself")]
127 Refused,
128 #[error("no device answered in time")]
130 Timeout,
131}
132
133pub(crate) fn start_error(error: impl std::fmt::Display) -> NetError {
134 NetError::Start(error.to_string())
135}
136
137fn connect_error(error: impl std::fmt::Display) -> NetError {
138 NetError::Connect(error.to_string())
139}
140
141fn connecting_error(error: ConnectError) -> NetError {
144 let closed = match &error {
145 ConnectError::Connecting {
146 source: ConnectingError::ConnectionError { source, .. },
147 ..
148 }
149 | ConnectError::Connection { source, .. } => Some(source),
150 _ => None,
151 };
152 if closed.is_some_and(refused) {
153 NetError::Refused
154 } else {
155 connect_error(error)
156 }
157}
158
159fn refused(error: &ConnectionError) -> bool {
161 matches!(error, ConnectionError::ConnectionClosed(close)
162 if close.error_code == TransportErrorCode::CONNECTION_REFUSED)
163}
164
165pub(crate) type Seen = Arc<Mutex<BTreeMap<[u8; 32], Option<String>>>>;
167
168pub struct Network {
171 runtime: Arc<Runtime>,
172 endpoint: Endpoint,
173 seen: Seen,
174 known: MemoryLookup,
176 incoming: Option<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<Incoming>>>,
179 discovery: Option<discovery::Discovery>,
182 port: Option<u16>,
184 port_refused: Option<(u16, String)>,
186}
187
188const WAITING_CONNECTIONS: usize = 16;
190
191async fn take_in(endpoint: Endpoint, queue: Option<tokio::sync::mpsc::Sender<Incoming>>) {
194 while let Some(incoming) = endpoint.accept().await {
195 let Some(queue) = queue.clone() else {
196 incoming.refuse();
197 continue;
198 };
199 tokio::spawn(async move {
200 let Ok(accepting) = incoming.accept() else {
201 return;
202 };
203 let Ok(quic) = accepting.await else {
204 return;
205 };
206 let protocol = match quic.alpn() {
207 PAIR => Protocol::Pair,
208 SYNC => Protocol::Sync,
209 INVITE => Protocol::Invite,
210 _ => return,
211 };
212 if let Ok(Ok((send, receive))) =
213 tokio::time::timeout(STREAM_TIMEOUT, quic.accept_bi()).await
214 {
215 let _ = queue.send((quic, send, receive, protocol)).await;
216 }
217 });
218 }
219}
220
221impl Network {
222 pub fn start(secret: &[u8; 32], options: Options) -> Result<Self, NetError> {
228 let runtime = tokio::runtime::Builder::new_multi_thread()
229 .worker_threads(2)
230 .thread_name("nibkeep-net")
231 .enable_all()
232 .build()
233 .map_err(start_error)?;
234 let seen: Seen = Arc::default();
235 let known = MemoryLookup::new();
236 let endpoint = runtime.block_on(async {
237 let builder = || {
238 Endpoint::builder(presets::Minimal)
239 .secret_key(SecretKey::from_bytes(secret))
240 .alpns(vec![PAIR.to_vec(), SYNC.to_vec(), INVITE.to_vec()])
241 .address_lookup(known.clone())
242 };
243 let Some(first) = options.port else {
244 return Ok::<_, NetError>((builder().bind().await.map_err(start_error)?, None));
245 };
246 let mut refused = None;
249 for port in (first..=first.saturating_add(PORTS - 1)).take(usize::from(PORTS)) {
250 match at(builder(), port).map_err(start_error)?.bind().await {
251 Ok(endpoint) => return Ok((endpoint, refused)),
252 Err(error) => {
253 refused.get_or_insert((first, error.to_string()));
254 }
255 }
256 }
257 Ok((builder().bind().await.map_err(start_error)?, refused))
259 })?;
260 let (endpoint, port_refused) = endpoint;
261 let port = endpoint
262 .bound_sockets()
263 .iter()
264 .find(|address| address.is_ipv4())
265 .map(SocketAddr::port);
266 let (queue, incoming) = if options.accept {
267 let (queue, incoming) = tokio::sync::mpsc::channel(WAITING_CONNECTIONS);
268 (Some(queue), Some(tokio::sync::Mutex::new(incoming)))
269 } else {
270 (None, None)
271 };
272 runtime.spawn(take_in(endpoint.clone(), queue));
273 let discovery = if options.discovery {
274 let port =
276 port.ok_or_else(|| NetError::Start("no IPv4 socket to announce".to_owned()))?;
277 Some(discovery::start(
278 endpoint.id(),
279 port,
280 seen.clone(),
281 known.clone(),
282 )?)
283 } else {
284 None
285 };
286 Ok(Self {
287 runtime: Arc::new(runtime),
288 endpoint,
289 seen,
290 known,
291 incoming,
292 discovery,
293 port,
294 port_refused,
295 })
296 }
297
298 #[must_use]
300 pub const fn port(&self) -> Option<u16> {
301 self.port
302 }
303
304 #[must_use]
309 pub fn port_refused(&self) -> Option<(u16, &str)> {
310 self.port_refused
311 .as_ref()
312 .map(|(port, why)| (*port, why.as_str()))
313 }
314
315 pub fn remember(&self, peer: [u8; 32], addresses: &[SocketAddr], announced: Option<&str>) {
318 if let Ok(id) = EndpointId::from_bytes(&peer) {
319 let addresses = addresses.iter().copied().map(TransportAddr::Ip);
320 self.known
321 .add_endpoint_info(EndpointAddr::from_parts(id, addresses));
322 }
323 self.seen
324 .lock()
325 .unwrap_or_else(PoisonError::into_inner)
326 .insert(peer, announced.map(str::to_owned));
327 }
328
329 #[must_use]
331 pub fn endpoint(&self) -> [u8; 32] {
332 *self.endpoint.id().as_bytes()
333 }
334
335 #[must_use]
338 pub fn local_addresses(&self) -> Vec<SocketAddr> {
339 self.endpoint
340 .bound_sockets()
341 .into_iter()
342 .map(|mut address| {
343 if address.ip().is_unspecified() {
344 address.set_ip(match address.ip() {
345 IpAddr::V4(_) => IpAddr::V4(Ipv4Addr::LOCALHOST),
346 IpAddr::V6(_) => IpAddr::V6(Ipv6Addr::LOCALHOST),
347 });
348 }
349 address
350 })
351 .collect()
352 }
353
354 pub fn announce(&self, text: Option<&str>) -> Result<(), NetError> {
360 match &self.discovery {
361 Some(discovery) => discovery.announce(text),
362 None => discovery::check_announced(text),
364 }
365 }
366
367 pub fn find_announcing(
375 &self,
376 text: &str,
377 except: &BTreeSet<[u8; 32]>,
378 timeout: Duration,
379 ) -> Result<[u8; 32], NetError> {
380 self.wait(timeout, |seen| {
381 seen.iter()
382 .find(|(endpoint, announced)| {
383 announced.as_deref() == Some(text) && !except.contains(*endpoint)
384 })
385 .map(|(endpoint, _)| *endpoint)
386 })
387 .ok_or(NetError::Timeout)
388 }
389
390 #[must_use]
393 pub fn find(&self, endpoints: &BTreeSet<[u8; 32]>, timeout: Duration) -> BTreeSet<[u8; 32]> {
394 let all = self.wait(timeout, |seen| {
395 endpoints
396 .iter()
397 .all(|endpoint| seen.contains_key(endpoint))
398 .then(|| endpoints.clone())
399 });
400 all.unwrap_or_else(|| {
401 let seen = self.seen.lock().unwrap_or_else(PoisonError::into_inner);
402 endpoints
403 .iter()
404 .filter(|endpoint| seen.contains_key(*endpoint))
405 .copied()
406 .collect()
407 })
408 }
409
410 fn wait<T>(
412 &self,
413 timeout: Duration,
414 found: impl Fn(&BTreeMap<[u8; 32], Option<String>>) -> Option<T>,
415 ) -> Option<T> {
416 let started = Instant::now();
417 loop {
418 let seen = self.seen.lock().unwrap_or_else(PoisonError::into_inner);
419 if let Some(found) = found(&seen) {
420 return Some(found);
421 }
422 drop(seen);
423 if started.elapsed() >= timeout {
424 return None;
425 }
426 std::thread::sleep(LOOK_EVERY);
427 }
428 }
429
430 pub fn connect(
436 &self,
437 peer: [u8; 32],
438 protocol: Protocol,
439 timeout: Duration,
440 ) -> Result<Connection, NetError> {
441 let id = EndpointId::from_bytes(&peer).map_err(connect_error)?;
442 self.connect_to(EndpointAddr::new(id), protocol, timeout)
443 }
444
445 pub fn connect_at(
451 &self,
452 peer: [u8; 32],
453 addresses: &[SocketAddr],
454 protocol: Protocol,
455 timeout: Duration,
456 ) -> Result<Connection, NetError> {
457 let id = EndpointId::from_bytes(&peer).map_err(connect_error)?;
458 let addresses = addresses.iter().copied().map(TransportAddr::Ip);
459 self.connect_to(EndpointAddr::from_parts(id, addresses), protocol, timeout)
460 }
461
462 fn connect_to(
463 &self,
464 address: EndpointAddr,
465 protocol: Protocol,
466 timeout: Duration,
467 ) -> Result<Connection, NetError> {
468 let (quic, send, receive) = self.runtime.block_on(async {
469 tokio::time::timeout(timeout, async {
470 let quic = self
471 .endpoint
472 .connect(address, protocol.alpn())
473 .await
474 .map_err(connecting_error)?;
475 let (send, receive) = quic.open_bi().await.map_err(|error| {
476 if refused(&error) {
477 NetError::Refused
478 } else {
479 connect_error(error)
480 }
481 })?;
482 Ok::<_, NetError>((quic, send, receive))
483 })
484 .await
485 .map_err(|_| NetError::Timeout)?
486 })?;
487 Connection::new(
488 self.runtime.clone(),
489 self.endpoint(),
490 (quic, send, receive),
491 protocol,
492 )
493 }
494
495 pub fn accept(&self, timeout: Option<Duration>) -> Result<Option<Connection>, NetError> {
503 let Some(incoming) = &self.incoming else {
504 return Err(NetError::Connect(
505 "this endpoint takes no connections".to_owned(),
506 ));
507 };
508 let accepted = self.runtime.block_on(async {
509 let mut incoming = incoming.lock().await;
510 let next = match timeout {
511 Some(timeout) => match tokio::time::timeout(timeout, incoming.recv()).await {
512 Ok(next) => next,
513 Err(_) => return Ok(None),
514 },
515 None => incoming.recv().await,
516 };
517 next.map(Some)
518 .ok_or_else(|| NetError::Connect("the endpoint was closed".to_owned()))
519 })?;
520 accepted
521 .map(|(quic, send, receive, protocol)| {
522 Connection::new(
523 self.runtime.clone(),
524 self.endpoint(),
525 (quic, send, receive),
526 protocol,
527 )
528 })
529 .transpose()
530 }
531}
532
533fn at(
535 builder: iroh::endpoint::Builder,
536 port: u16,
537) -> Result<iroh::endpoint::Builder, iroh::endpoint::InvalidSocketAddr> {
538 builder
539 .clear_ip_transports()
540 .bind_addr(SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), port))?
541 .bind_addr_with_opts(
542 SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), port),
543 iroh::endpoint::BindOpts::default().set_is_required(false),
544 )
545}
546
547impl Drop for Network {
548 fn drop(&mut self) {
549 let endpoint = self.endpoint.clone();
550 self.runtime.block_on(async {
551 let _ = tokio::time::timeout(CLOSE_TIMEOUT, endpoint.close()).await;
552 });
553 }
554}
555
556pub struct Connection {
558 runtime: Arc<Runtime>,
559 quic: Quic,
560 send: SendStream,
561 received: tokio::sync::mpsc::UnboundedReceiver<Result<Received, String>>,
565 reader: tokio::task::JoinHandle<()>,
567 protocol: Protocol,
568 binding: [u8; 32],
569 own: [u8; 32],
570 peer: [u8; 32],
571 paths: BTreeSet<String>,
574 failure: Option<String>,
576}
577
578const RECEIVED_ROOM: u32 = 32 * 1024 * 1024;
580
581const _: () = assert!(MAX_MESSAGE_LEN <= RECEIVED_ROOM as usize);
582
583type Received = (Vec<u8>, tokio::sync::OwnedSemaphorePermit);
585
586async fn read_messages(
589 mut stream: RecvStream,
590 room: Arc<tokio::sync::Semaphore>,
591 received: tokio::sync::mpsc::UnboundedSender<Result<Received, String>>,
592) {
593 loop {
594 let mut length = [0; 4];
595 match stream.read_exact(&mut length).await {
596 Ok(()) => {}
597 Err(iroh::endpoint::ReadExactError::FinishedEarly(0)) => return,
599 Err(error) => {
600 let _ = received.send(Err(error.to_string()));
601 return;
602 }
603 }
604 let length = u32::from_be_bytes(length);
605 if usize::try_from(length).map_or(true, |length| length > MAX_MESSAGE_LEN) {
606 let _ = received.send(Err("a message too long".to_owned()));
607 return;
608 }
609 let Ok(share) = room
612 .clone()
613 .acquire_many_owned(length.clamp(1, RECEIVED_ROOM))
614 .await
615 else {
616 return;
617 };
618 let mut message = vec![0; length as usize];
619 if let Err(error) = stream.read_exact(&mut message).await {
620 let _ = received.send(Err(error.to_string()));
621 return;
622 }
623 if received.send(Ok((message, share))).is_err() {
624 return;
625 }
626 }
627}
628
629impl Connection {
630 fn new(
631 runtime: Arc<Runtime>,
632 own: [u8; 32],
633 (quic, send, receive): (Quic, SendStream, RecvStream),
634 protocol: Protocol,
635 ) -> Result<Self, NetError> {
636 let mut binding = [0; 32];
637 quic.export_keying_material(&mut binding, BINDING, b"")
638 .map_err(|_| NetError::Connect("cannot bind to the connection".to_owned()))?;
639 let peer = *quic.remote_id().as_bytes();
640 let (sender, received) = tokio::sync::mpsc::unbounded_channel();
641 let room = Arc::new(tokio::sync::Semaphore::new(RECEIVED_ROOM as usize));
642 let reader = runtime.spawn(read_messages(receive, room, sender));
643 let mut connection = Self {
644 runtime,
645 quic,
646 send,
647 received,
648 reader,
649 protocol,
650 binding,
651 own,
652 peer,
653 paths: BTreeSet::new(),
654 failure: None,
655 };
656 connection.note_paths();
657 Ok(connection)
658 }
659
660 fn note_paths(&mut self) {
662 for path in self.quic.paths().iter() {
663 self.paths.insert(format!("{:?}", path.remote_addr()));
664 }
665 }
666
667 fn failed(&self, error: impl std::fmt::Display) -> TransportError {
670 let mut text = error.to_string();
671 if let Some(reason) = self.quic.close_reason() {
672 let _ = write!(text, " ({reason})");
673 }
674 if !self.paths.is_empty() {
675 let paths: Vec<&str> = self.paths.iter().map(String::as_str).collect();
676 let _ = write!(text, "; paths used: {}", paths.join(", "));
677 }
678 TransportError(text)
679 }
680
681 #[must_use]
683 pub const fn protocol(&self) -> Protocol {
684 self.protocol
685 }
686
687 #[must_use]
689 pub const fn peer(&self) -> [u8; 32] {
690 self.peer
691 }
692
693 pub fn close(mut self) {
696 let runtime = self.runtime.clone();
697 runtime.block_on(async {
698 let _ = self.send.finish();
699 let _ = tokio::time::timeout(CLOSE_TIMEOUT, async {
702 while self.received.recv().await.is_some() {}
703 })
704 .await;
705 self.quic.close(0_u32.into(), b"done");
706 });
707 }
708}
709
710impl Drop for Connection {
711 fn drop(&mut self) {
712 self.reader.abort();
714 }
715}
716
717impl Transport for Connection {
718 fn send(&mut self, message: &[u8]) -> Result<(), TransportError> {
719 let length = u32::try_from(message.len())
720 .ok()
721 .filter(|_| message.len() <= MAX_MESSAGE_LEN)
722 .ok_or_else(|| TransportError("a message too long to send".to_owned()))?;
723 let runtime = self.runtime.clone();
724 let sent = runtime.block_on(async {
725 self.send.write_all(&length.to_be_bytes()).await?;
726 self.send.write_all(message).await
727 });
728 match sent {
729 Ok(()) => Ok(()),
730 Err(error) => Err(self.failed(error)),
731 }
732 }
733
734 fn receive(&mut self) -> Result<Vec<u8>, TransportError> {
735 if let Some(failure) = &self.failure {
736 return Err(self.failed(failure));
737 }
738 let runtime = self.runtime.clone();
739 let received = runtime.block_on(async {
740 match tokio::time::timeout(RECEIVE_TIMEOUT, self.received.recv()).await {
741 Ok(Some(Ok((message, _share)))) => Ok(message),
742 Ok(Some(Err(error))) => Err(error),
743 Ok(None) => Err("the other device closed the connection".to_owned()),
744 Err(_) => Err("the other device stopped answering".to_owned()),
745 }
746 });
747 self.note_paths();
748 received.map_err(|error| {
749 let failed = self.failed(&error);
750 self.failure = Some(error);
751 failed
752 })
753 }
754
755 fn has_message(&mut self) -> bool {
756 self.failure.is_some() || !self.received.is_empty()
758 }
759
760 fn binding(&self) -> [u8; 32] {
761 self.binding
762 }
763
764 fn own_endpoint(&self) -> [u8; 32] {
765 self.own
766 }
767
768 fn peer_endpoint(&self) -> [u8; 32] {
769 self.peer
770 }
771}