Skip to main content

nibkeep_net/
lib.rs

1//! Connections between NibKeep replicas on the home network: iroh's QUIC with TLS, no
2//! relays and nothing published to DNS, and replicas found by mDNS on the interfaces of home
3//! networks alone, which announces an endpoint's key and addresses and no names. The API
4//! blocks, so that the engine stays synchronous: a [`Network`] runs its own Tokio runtime,
5//! and a [`Connection`] carries the messages of `nibkeep-sync` as its [`Transport`].
6//!
7//! The connections are specified in `docs/spec/sync.md`, and the reasons for them are in
8//! `docs/Technical-design.md`, section 10.
9
10mod 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
27/// The ALPN of pairing.
28const PAIR: &[u8] = b"nibkeep/pair/1";
29
30/// The ALPN of syncing.
31const SYNC: &[u8] = b"nibkeep/sync/1";
32
33/// The ALPN of invitations to a space.
34const INVITE: &[u8] = b"nibkeep/invite/1";
35
36/// The label of the bytes exported from TLS that bind what is signed to one connection.
37const BINDING: &[u8] = b"EXPORTER-nibkeep-2026-10";
38
39/// How long a side waits for the next message: long enough for the other to save what it
40/// received before it answers.
41const RECEIVE_TIMEOUT: Duration = Duration::from_mins(5);
42
43/// How long a side that was connected to waits for the other to open its stream.
44const STREAM_TIMEOUT: Duration = Duration::from_secs(10);
45
46/// How long closing waits for the other side to read what was sent.
47const CLOSE_TIMEOUT: Duration = Duration::from_secs(3);
48
49/// How often waiting for a device to appear looks again.
50const LOOK_EVERY: Duration = Duration::from_millis(100);
51
52/// Which protocol a connection speaks.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum Protocol {
55	/// Pairing a new replica.
56	Pair,
57	/// Syncing replicas.
58	Sync,
59	/// Inviting a user to a space.
60	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
73/// The UDP port that replicas take connections on unless told otherwise, so that a
74/// firewall can let them through with one rule.
75pub const DEFAULT_PORT: u16 = 53_300;
76
77/// How many ports from the one asked for an endpoint tries, before it takes any: from
78/// 53300 to 53309 by default, one for each library of a computer that waits at once.
79pub const PORTS: u16 = 10;
80
81/// How an endpoint starts.
82#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub struct Options {
84	/// Whether it announces itself on the home network by mDNS and finds the others there;
85	/// without, as in tests, it connects only to addresses it is given.
86	pub discovery: bool,
87	/// The UDP port it takes connections on, or the next free one of [`PORTS`] from it, or
88	/// any free one if they are all taken; `None` for any free port.
89	pub port: Option<u16>,
90	/// Whether it takes connections; one that only connects refuses them at once, so that
91	/// a peer that connects to it learns so, rather than waiting for an answer.
92	pub accept: bool,
93}
94
95impl Options {
96	/// On the home network, at the default port, taking connections.
97	pub const HOME: Self = Self {
98		discovery: true,
99		port: Some(DEFAULT_PORT),
100		accept: true,
101	};
102
103	/// For tests: no discovery, any free port, taking connections.
104	pub const LOCAL: Self = Self {
105		discovery: false,
106		port: None,
107		accept: true,
108	};
109}
110
111/// A connection that another endpoint opened, with its stream, once its handshake is done.
112type Incoming = (Quic, SendStream, RecvStream, Protocol);
113
114/// Why networking failed.
115#[derive(Debug, thiserror::Error)]
116#[non_exhaustive]
117pub enum NetError {
118	/// The endpoint could not start.
119	#[error("cannot start networking: {0}")]
120	Start(String),
121	/// Connecting failed.
122	#[error("cannot connect: {0}")]
123	Connect(String),
124	/// The other endpoint takes no connections now, as one that only connects refuses them:
125	/// a program there syncs once, or does something else that needs no connection.
126	#[error("the other device takes no connections now, as while it syncs by itself")]
127	Refused,
128	/// Nothing came in time.
129	#[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
141/// What connecting failed with: [`NetError::Refused`] where the other endpoint refused the
142/// connection, as one that only connects does.
143fn 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
159/// Whether a connection ended as the other endpoint refused it.
160fn refused(error: &ConnectionError) -> bool {
161	matches!(error, ConnectionError::ConnectionClosed(close)
162		if close.error_code == TransportErrorCode::CONNECTION_REFUSED)
163}
164
165/// What mDNS found: each endpoint seen on the network, with what it announces.
166pub(crate) type Seen = Arc<Mutex<BTreeMap<[u8; 32], Option<String>>>>;
167
168/// This replica's endpoint on the network, which connects to others and takes their
169/// connections.
170pub struct Network {
171	runtime: Arc<Runtime>,
172	endpoint: Endpoint,
173	seen: Seen,
174	/// The addresses of endpoints it was told of, rather than found.
175	known: MemoryLookup,
176	/// The connections that others opened, each taken in once its handshake is done, so
177	/// that one that stalls holds up no other; `None` for one that takes no connections.
178	incoming: Option<tokio::sync::Mutex<tokio::sync::mpsc::Receiver<Incoming>>>,
179	/// What announces this endpoint on the home network, and finds the others; `None`
180	/// without discovery.
181	discovery: Option<discovery::Discovery>,
182	/// The IPv4 port it takes connections on.
183	port: Option<u16>,
184	/// The port asked for, and why it could not be had, if the endpoint took another.
185	port_refused: Option<(u16, String)>,
186}
187
188/// How many connections that others opened wait to be taken.
189const WAITING_CONNECTIONS: usize = 16;
190
191/// Takes in the connections that others open, doing each handshake on its own, until the
192/// endpoint closes; or refuses them all, without `queue`.
193async 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	/// Starts the endpoint with the 32-byte secret of its key, as `options` say.
223	///
224	/// # Errors
225	///
226	/// Returns an error if the runtime or the endpoint cannot start.
227	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			// The first free of the ports from the one asked for, as other libraries of the
247			// computer may have taken some, so that one firewall rule lets them all through.
248			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			// All are taken: any other will do.
258			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			// The port it took, which is another than the one asked for if that was taken.
275			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	/// The IPv4 port it takes connections on.
299	#[must_use]
300	pub const fn port(&self) -> Option<u16> {
301		self.port
302	}
303
304	/// The port it asked for, and why it could not have it, if it took another: as when
305	/// another program of NibKeep has it. A firewall that lets only the ports from that one
306	/// through, [`PORTS`] of them, lets this endpoint's connections through only if it took
307	/// one of them.
308	#[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	/// Tells the endpoint where another is, and what it announces, as if it had found it on
316	/// the network: for tests, and for networks where discovery does not work.
317	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	/// This endpoint's ID: the public half of its key.
330	#[must_use]
331	pub fn endpoint(&self) -> [u8; 32] {
332		*self.endpoint.id().as_bytes()
333	}
334
335	/// The addresses this endpoint takes connections on, as this computer reaches them, for
336	/// connecting without discovery.
337	#[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	/// Adds `text` to what the endpoint announces on the network, or stops announcing any.
355	///
356	/// # Errors
357	///
358	/// Returns an error if the text is too long to announce.
359	pub fn announce(&self, text: Option<&str>) -> Result<(), NetError> {
360		match &self.discovery {
361			Some(discovery) => discovery.announce(text),
362			// Without discovery, only those told of it find this endpoint.
363			None => discovery::check_announced(text),
364		}
365	}
366
367	/// Waits up to `timeout` for an endpoint that announces `text`, other than those in
368	/// `except`, and returns the one with the lowest ID among those found, so that one that
369	/// tries them in turn tries each once.
370	///
371	/// # Errors
372	///
373	/// Returns [`NetError::Timeout`] if none appears in time.
374	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	/// Waits up to `timeout` until every one of `endpoints` is seen on the network, and
391	/// returns those seen by then.
392	#[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	/// Looks at what mDNS found until `found` finds something, for up to `timeout`.
411	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	/// Connects to an endpoint found on the network.
431	///
432	/// # Errors
433	///
434	/// Returns an error if the endpoint cannot be reached, or refuses, within `timeout`.
435	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	/// Connects to an endpoint at these addresses.
446	///
447	/// # Errors
448	///
449	/// As [`Network::connect`].
450	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	/// Waits for another endpoint to connect, for up to `timeout`, or for as long as it
496	/// takes; `None` if none did in time. Connections that fail before they speak a
497	/// protocol of NibKeep are passed by.
498	///
499	/// # Errors
500	///
501	/// Returns an error if the endpoint was closed, or takes no connections.
502	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
533/// A builder that binds `port` on every interface, IPv6 too where there is IPv6.
534fn 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
556/// A connection to another replica: one stream of messages each way.
557pub struct Connection {
558	runtime: Arc<Runtime>,
559	quic: Quic,
560	send: SendStream,
561	/// The messages that came, read off the stream as soon as they come, so that the
562	/// connection holds no data unread while this side saves what came before; each with
563	/// its share of the room it takes.
564	received: tokio::sync::mpsc::UnboundedReceiver<Result<Received, String>>,
565	/// What reads the messages off the stream.
566	reader: tokio::task::JoinHandle<()>,
567	protocol: Protocol,
568	binding: [u8; 32],
569	own: [u8; 32],
570	peer: [u8; 32],
571	/// The remote addresses of the paths the connection has used, to say which when it is
572	/// lost.
573	paths: BTreeSet<String>,
574	/// Why reading failed, once it did, for every later read.
575	failure: Option<String>,
576}
577
578/// How many bytes of messages that came wait to be taken, at most: room for the longest.
579const RECEIVED_ROOM: u32 = 32 * 1024 * 1024;
580
581const _: () = assert!(MAX_MESSAGE_LEN <= RECEIVED_ROOM as usize);
582
583/// A message that came, and the room it takes until it is taken.
584type Received = (Vec<u8>, tokio::sync::OwnedSemaphorePermit);
585
586/// Reads messages off `stream` as they come, into `received`, while they take no more than
587/// `room`, until the stream ends or fails.
588async 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			// The end of the stream, where a message may start, is no failure.
598			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		// The room a message takes is its size, within the room there is, so that one as
610		// large as the room still fits.
611		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	/// Notes the paths the connection uses now.
661	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	/// What went wrong with the connection, with why it closed, if it did, and the paths it
668	/// used, so that a lost connection can be told apart from a refused one.
669	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	/// The protocol it speaks.
682	#[must_use]
683	pub const fn protocol(&self) -> Protocol {
684		self.protocol
685	}
686
687	/// The other side's endpoint ID.
688	#[must_use]
689	pub const fn peer(&self) -> [u8; 32] {
690		self.peer
691	}
692
693	/// Ends the connection, once the other side has read what this side sent, or after a
694	/// few seconds.
695	pub fn close(mut self) {
696		let runtime = self.runtime.clone();
697		runtime.block_on(async {
698			let _ = self.send.finish();
699			// What still comes is read and dropped, which frees its room, until the other
700			// side ends its stream, once it has read this one, and the reader ends.
701			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		// A connection dropped unclosed, as on an error, stops reading, which lets it close.
713		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		// The reader passes on whole messages, or why it stopped.
757		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}