diff --git a/pr/3775/docs/src/iroh/magicsock/remote_map/remote_state.rs.html b/pr/3775/docs/src/iroh/magicsock/remote_map/remote_state.rs.html index 81f40f9a11..83e39216fb 100644 --- a/pr/3775/docs/src/iroh/magicsock/remote_map/remote_state.rs.html +++ b/pr/3775/docs/src/iroh/magicsock/remote_map/remote_state.rs.html @@ -258,455 +258,455 @@ 258 n0_future::pin!(idle_timeout); 259 let mut needs_holepunching_watcher = self.needs_holepunching.watch(); 260 -261 loop { -262 let scheduled_path_open = match self.scheduled_open_path { -263 Some(when) => MaybeFuture::Some(time::sleep_until(when)), -264 None => MaybeFuture::None, -265 }; -266 n0_future::pin!(scheduled_path_open); -267 let scheduled_hp = match self.scheduled_holepunch { -268 Some(when) => MaybeFuture::Some(time::sleep_until(when)), -269 None => MaybeFuture::None, -270 }; -271 n0_future::pin!(scheduled_hp); -272 if !inbox.is_idle() || !self.connections.is_empty() { -273 idle_timeout -274 .as_mut() -275 .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); -276 } -277 let check_connections = time::interval(CHECK_CONNECTIONS_INTERVAL); -278 n0_future::pin!(check_connections); -279 -280 tokio::select! { -281 biased; -282 msg = inbox.recv() => { -283 match msg { -284 Some(msg) => self.handle_message(msg).await, -285 None => break, -286 } -287 } -288 Some((id, evt)) = self.path_events.next() => { -289 self.handle_path_event(id, evt); -290 } -291 Some((id, evt)) = self.addr_events.next() => { -292 trace!(?id, ?evt, "remote addrs updated, triggering holepunching"); -293 self.trigger_holepunching(); -294 } -295 Some(conn_id) = self.connections_close.next(), if !self.connections_close.is_empty() => { -296 self.handle_connection_close(conn_id); -297 } -298 res = self.local_direct_addrs.updated() => { -299 if let Err(n0_watcher::Disconnected) = res { -300 trace!("direct address watcher disconnected, shutting down"); -301 break; -302 } -303 self.local_addrs_updated(); -304 trace!("local addrs updated, triggering holepunching"); -305 self.trigger_holepunching(); -306 } -307 _ = &mut scheduled_path_open => { -308 trace!("triggering scheduled path_open"); -309 self.scheduled_open_path = None; -310 let mut addrs = std::mem::take(&mut self.pending_open_paths); -311 while let Some(addr) = addrs.pop_front() { -312 self.open_path(&addr); -313 } -314 } -315 _ = &mut scheduled_hp => { -316 trace!("triggering scheduled holepunching"); -317 self.scheduled_holepunch = None; -318 self.trigger_holepunching(); -319 } -320 item = self.discovery_stream.next() => { -321 self.handle_discovery_item(item); -322 } -323 need_hp = needs_holepunching_watcher.updated() => { -324 if matches!(need_hp, Ok(true)) { -325 self.trigger_holepunching(); -326 } -327 } -328 _ = check_connections.tick() => { -329 self.check_connections(); -330 } -331 _ = &mut idle_timeout => { -332 if self.connections.is_empty() && inbox.close_if_idle() { -333 trace!("idle timeout expired and still idle: terminate actor"); -334 break; -335 } else { -336 // Seems like we weren't really idle, so we reset -337 idle_timeout.as_mut().reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); -338 } -339 } -340 } -341 } -342 trace!("actor terminating"); -343 } -344 -345 /// Handles an actor message. -346 /// -347 /// Error returns are fatal and kill the actor. -348 #[instrument(skip(self))] -349 async fn handle_message(&mut self, msg: RemoteStateMessage) { -350 // trace!("handling message"); -351 match msg { -352 RemoteStateMessage::SendDatagram(sender, transmit) => { -353 self.handle_msg_send_datagram(sender, transmit).await; -354 } -355 RemoteStateMessage::AddConnection(handle, tx) => { -356 self.handle_msg_add_connection(handle, tx); -357 } -358 RemoteStateMessage::ResolveRemote(addrs, tx) => { -359 self.handle_msg_resolve_remote(addrs, tx); -360 } -361 RemoteStateMessage::RemoteInfo(tx) => { -362 let addrs = self.paths.to_remote_addrs(); -363 let info = RemoteInfo { -364 endpoint_id: self.endpoint_id, -365 addrs, -366 }; -367 tx.send(info).ok(); -368 } -369 } -370 } -371 -372 /// Handles regularly checking if any paths need hole punching currently -373 fn check_connections(&mut self) { -374 let mut is_goodenough = true; -375 for conn in self.connections.values() { -376 // If we have at least 1 non relay path, we consider the connection good enough for now -377 // TODO: evaluate other criteria, like current RTT etc -378 let is_conn_goodenough = conn.open_paths.iter().any(|(_, addr)| !addr.is_relay()); -379 is_goodenough &= is_conn_goodenough; -380 } -381 -382 if !is_goodenough { -383 debug!("connections are not good enough, noting holepunch"); -384 self.trigger_holepunching(); -385 } -386 } -387 -388 /// Handles [`RemoteStateMessage::SendDatagram`]. -389 async fn handle_msg_send_datagram( -390 &mut self, -391 mut sender: TransportsSender, -392 transmit: OwnedTransmit, -393 ) { -394 // Sending datagrams might fail, e.g. because we don't have the right transports set -395 // up to handle sending this owned transmit to. -396 // After all, we try every single path that we know (relay URL, IP address), even -397 // though we might not have a relay transport or ip-capable transport set up. -398 // So these errors must not be fatal for this actor (or even this operation). -399 -400 if let Some(addr) = self.selected_path.get() { -401 trace!(?addr, "sending datagram to selected path"); -402 -403 if let Err(err) = send_datagram(&mut sender, addr.clone(), transmit).await { -404 debug!(?addr, "failed to send datagram on selected_path: {err:#}"); -405 } -406 } else { -407 trace!( -408 paths = ?self.paths.addrs().collect::<Vec<_>>(), -409 "sending datagram to all known paths", -410 ); -411 if self.paths.is_empty() { -412 warn!("Cannot send datagrams: No paths to remote endpoint known"); -413 } -414 -415 for addr in self.paths.addrs() { -416 // We never want to send to our local addresses. -417 // The local address set is updated in the main loop so we can use `peek` here. -418 if let transports::Addr::Ip(sockaddr) = addr -419 && self -420 .local_direct_addrs -421 .peek() -422 .iter() -423 .any(|a| a.addr == *sockaddr) -424 { -425 trace!(%sockaddr, "not sending datagram to our own address"); -426 } else if let Err(err) = -427 send_datagram(&mut sender, addr.clone(), transmit.clone()).await -428 { -429 debug!(?addr, "failed to send datagram: {err:#}"); -430 } -431 } -432 // This message is received *before* a connection is added. So we do -433 // not yet have a connection to holepunch. Instead we trigger -434 // holepunching when AddConnection is received. -435 } -436 } -437 -438 /// Handles [`RemoteStateMessage::AddConnection`]. -439 /// -440 /// Error returns are fatal and kill the actor. -441 fn handle_msg_add_connection( -442 &mut self, -443 handle: WeakConnectionHandle, -444 tx: oneshot::Sender<PathsWatcher>, -445 ) { -446 let pub_open_paths = Watchable::default(); -447 if let Some(conn) = handle.upgrade() { -448 self.metrics.num_conns_opened.inc(); -449 // Remove any conflicting stable_ids from the local state. -450 let conn_id = ConnId(conn.stable_id()); -451 self.connections.remove(&conn_id); -452 -453 // Hook up paths, NAT addresses and connection closed event streams. -454 self.path_events.push(Box::pin( -455 BroadcastStream::new(conn.path_events()).map(move |evt| (conn_id, evt)), -456 )); -457 self.addr_events.push(Box::pin( -458 BroadcastStream::new(conn.nat_traversal_updates()).map(move |evt| (conn_id, evt)), -459 )); -460 self.connections_close.push(OnClosed::new(&conn)); -461 -462 // Add local addrs to the connection -463 let local_addrs = self -464 .local_direct_addrs -465 .get() -466 .iter() -467 .map(|d| d.addr) -468 .collect::<BTreeSet<_>>(); -469 Self::set_local_addrs(&conn, &local_addrs); -470 -471 // Store the connection -472 let conn_state = self -473 .connections -474 .entry(conn_id) -475 .insert_entry(ConnectionState { -476 handle: handle.clone(), -477 pub_open_paths: pub_open_paths.clone(), -478 paths: Default::default(), -479 open_paths: Default::default(), -480 path_ids: Default::default(), -481 }) -482 .into_mut(); -483 -484 // Store PathId(0), set path_status and select best path, check if holepunching -485 // is needed. -486 if let Some(path) = conn.path(PathId::ZERO) -487 && let Ok(socketaddr) = path.remote_address() -488 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) -489 { -490 trace!(?path_remote, "added new connection"); -491 let path_remote_is_ip = path_remote.is_ip(); -492 let status = match path_remote { -493 transports::Addr::Ip(_) => PathStatus::Available, -494 transports::Addr::Relay(_, _) => PathStatus::Backup, -495 }; -496 path.set_status(status).ok(); -497 conn_state.add_open_path(path_remote.clone(), PathId::ZERO); -498 self.paths -499 .insert_open_path(path_remote.clone(), Source::Connection { _0: Private }); -500 self.select_path(); -501 -502 if path_remote_is_ip { -503 // We may have raced this with a relay address. Try and add any -504 // relay addresses we have back. -505 let relays = self -506 .paths -507 .addrs() -508 .filter(|a| a.is_relay()) -509 .cloned() -510 .collect::<Vec<_>>(); -511 for remote in relays { -512 self.open_path(&remote); -513 } -514 } -515 } -516 self.trigger_holepunching(); -517 } -518 tx.send(PathsWatcher::new( -519 pub_open_paths.watch(), -520 self.selected_path.watch(), -521 handle, -522 )) -523 .ok(); -524 } -525 -526 /// Handles [`RemoteStateMessage::ResolveRemote`]. -527 fn handle_msg_resolve_remote( -528 &mut self, -529 addrs: BTreeSet<TransportAddr>, -530 tx: oneshot::Sender<Result<(), DiscoveryError>>, -531 ) { -532 let addrs = to_transports_addr(self.endpoint_id, addrs); -533 self.paths.insert_multiple(addrs, Source::App); -534 self.paths.resolve_remote(tx); -535 // Start discovery if we have no selected path. -536 self.trigger_discovery(); -537 } -538 -539 fn handle_connection_close(&mut self, conn_id: ConnId) { -540 if self.connections.remove(&conn_id).is_some() { -541 self.metrics.num_conns_closed.inc(); -542 } -543 if self.connections.is_empty() { -544 trace!("last connection closed - clearing selected_path"); -545 self.selected_path.set(None).ok(); -546 } -547 } -548 -549 fn handle_discovery_item(&mut self, item: Option<Result<DiscoveryItem, DiscoveryError>>) { -550 match item { -551 None => { -552 self.discovery_stream = Either::Left(n0_future::stream::pending()); -553 self.paths.discovery_finished(Ok(())); -554 } -555 Some(Err(err)) => { -556 warn!("Discovery failed: {err:#}"); -557 self.discovery_stream = Either::Left(n0_future::stream::pending()); -558 self.paths.discovery_finished(Err(err)); -559 } -560 Some(Ok(item)) => { -561 if item.endpoint_id() != self.endpoint_id { -562 warn!(?item, "Discovery emitted item for wrong remote endpoint"); -563 } else { -564 let source = Source::Discovery { -565 name: item.provenance().to_string(), -566 }; -567 let addrs = -568 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs); -569 self.paths.insert_multiple(addrs, source); -570 } -571 } -572 } -573 } -574 -575 /// Triggers discovery for the remote endpoint, if needed. -576 /// -577 /// Does not start discovery if we have a selected path or if discovery is currently running. -578 fn trigger_discovery(&mut self) { -579 if self.selected_path.get().is_some() || matches!(self.discovery_stream, Either::Right(_)) { -580 return; -581 } -582 match self.discovery.resolve(self.endpoint_id) { -583 Some(stream) => self.discovery_stream = Either::Right(SyncStream::new(stream)), -584 None => self.paths.discovery_finished(Ok(())), -585 } -586 } -587 -588 /// Sets the current local addresses to QNT's state to all connections -589 fn local_addrs_updated(&mut self) { -590 let local_addrs = self -591 .local_direct_addrs -592 .get() -593 .iter() -594 .map(|d| d.addr) -595 .collect::<BTreeSet<_>>(); -596 -597 for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) { -598 Self::set_local_addrs(&conn, &local_addrs); -599 } -600 // todo: trace -601 } -602 -603 /// Sets the current local addresses to QNT's state -604 fn set_local_addrs(conn: &quinn::Connection, local_addrs: &BTreeSet<SocketAddr>) { -605 let quinn_local_addrs = match conn.get_local_nat_traversal_addresses() { -606 Ok(addrs) => BTreeSet::from_iter(addrs), -607 Err(err) => { -608 warn!("failed to get local nat candidates: {err:#}"); -609 return; -610 } -611 }; -612 for addr in local_addrs.difference(&quinn_local_addrs) { -613 if let Err(err) = conn.add_nat_traversal_address(*addr) { -614 warn!("failed adding local addr: {err:#}",); -615 } -616 } -617 for addr in quinn_local_addrs.difference(local_addrs) { -618 if let Err(err) = conn.remove_nat_traversal_address(*addr) { -619 warn!("failed removing local addr: {err:#}"); -620 } -621 } -622 trace!(?local_addrs, "updated local QNT addresses"); -623 } -624 -625 /// Triggers holepunching to the remote endpoint. -626 /// -627 /// This will manage the entire process of holepunching with the remote endpoint. -628 /// -629 /// - Holepunching happens on the Connection with the lowest [`ConnId`] which is a -630 /// client. -631 /// - Both endpoints may initiate holepunching if both have a client connection. -632 /// - Any opened paths are opened on all other connections without holepunching. -633 /// - If there are no changes in local or remote candidate addresses since the -634 /// last attempt **and** there was a recent attempt, a trigger_holepunching call -635 /// will be scheduled instead. -636 fn trigger_holepunching(&mut self) { -637 if self.connections.is_empty() { -638 trace!("not holepunching: no connections"); -639 return; -640 } -641 -642 let Some(conn) = self -643 .connections -644 .iter() -645 .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn))) -646 .filter(|(_, conn)| conn.side().is_client()) -647 .min_by_key(|(id, _)| *id) -648 .map(|(_, conn)| conn) -649 else { -650 trace!("not holepunching: no client connection"); -651 return; -652 }; -653 let remote_candidates = match conn.get_remote_nat_traversal_addresses() { -654 Ok(addrs) => BTreeSet::from_iter(addrs), -655 Err(err) => { -656 warn!("failed to get nat candidate addresses: {err:#}"); -657 return; -658 } -659 }; -660 let local_candidates: BTreeSet<SocketAddr> = self -661 .local_direct_addrs -662 .get() -663 .iter() -664 .map(|daddr| daddr.addr) -665 .collect(); -666 let new_candidates = self -667 .last_holepunch -668 .as_ref() -669 .map(|last_hp| { -670 // Addrs are allowed to disappear, but if there are new ones we need to -671 // holepunch again. -672 trace!( -673 ?last_hp, -674 ?local_candidates, -675 ?remote_candidates, -676 "candidates to holepunch?" -677 ); -678 !remote_candidates.is_subset(&last_hp.remote_candidates) -679 || !local_candidates.is_subset(&last_hp.local_candidates) -680 }) -681 .unwrap_or(true); -682 if !new_candidates { -683 if let Some(ref last_hp) = self.last_holepunch { -684 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL; -685 let now = Instant::now(); -686 if next_hp > now { -687 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses"); -688 self.scheduled_holepunch = Some(next_hp); -689 return; -690 } -691 } -692 } -693 -694 self.do_holepunching(conn); -695 } -696 -697 /// Unconditionally perform holepunching. -698 #[instrument(skip_all)] -699 fn do_holepunching(&mut self, conn: quinn::Connection) { -700 self.metrics.nat_traversal.inc(); -701 let local_candidates = self -702 .local_direct_addrs -703 .get() -704 .iter() -705 .map(|daddr| daddr.addr) -706 .collect::<BTreeSet<_>>(); -707 -708 // try up to 3 times, with a short delay -709 match conn.initiate_nat_traversal_round() { +261 let check_connections = time::interval(CHECK_CONNECTIONS_INTERVAL); +262 n0_future::pin!(check_connections); +263 +264 loop { +265 let scheduled_path_open = match self.scheduled_open_path { +266 Some(when) => MaybeFuture::Some(time::sleep_until(when)), +267 None => MaybeFuture::None, +268 }; +269 n0_future::pin!(scheduled_path_open); +270 let scheduled_hp = match self.scheduled_holepunch { +271 Some(when) => MaybeFuture::Some(time::sleep_until(when)), +272 None => MaybeFuture::None, +273 }; +274 n0_future::pin!(scheduled_hp); +275 if !inbox.is_idle() || !self.connections.is_empty() { +276 idle_timeout +277 .as_mut() +278 .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); +279 } +280 +281 tokio::select! { +282 biased; +283 msg = inbox.recv() => { +284 match msg { +285 Some(msg) => self.handle_message(msg).await, +286 None => break, +287 } +288 } +289 Some((id, evt)) = self.path_events.next() => { +290 self.handle_path_event(id, evt); +291 } +292 Some((id, evt)) = self.addr_events.next() => { +293 trace!(?id, ?evt, "remote addrs updated, triggering holepunching"); +294 self.trigger_holepunching(); +295 } +296 Some(conn_id) = self.connections_close.next(), if !self.connections_close.is_empty() => { +297 self.handle_connection_close(conn_id); +298 } +299 res = self.local_direct_addrs.updated() => { +300 if let Err(n0_watcher::Disconnected) = res { +301 trace!("direct address watcher disconnected, shutting down"); +302 break; +303 } +304 self.local_addrs_updated(); +305 trace!("local addrs updated, triggering holepunching"); +306 self.trigger_holepunching(); +307 } +308 _ = &mut scheduled_path_open => { +309 trace!("triggering scheduled path_open"); +310 self.scheduled_open_path = None; +311 let mut addrs = std::mem::take(&mut self.pending_open_paths); +312 while let Some(addr) = addrs.pop_front() { +313 self.open_path(&addr); +314 } +315 } +316 _ = &mut scheduled_hp => { +317 trace!("triggering scheduled holepunching"); +318 self.scheduled_holepunch = None; +319 self.trigger_holepunching(); +320 } +321 item = self.discovery_stream.next() => { +322 self.handle_discovery_item(item); +323 } +324 need_hp = needs_holepunching_watcher.updated() => { +325 if matches!(need_hp, Ok(true)) { +326 self.trigger_holepunching(); +327 } +328 } +329 _ = check_connections.tick() => { +330 self.check_connections(); +331 } +332 _ = &mut idle_timeout => { +333 if self.connections.is_empty() && inbox.close_if_idle() { +334 trace!("idle timeout expired and still idle: terminate actor"); +335 break; +336 } else { +337 // Seems like we weren't really idle, so we reset +338 idle_timeout.as_mut().reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT); +339 } +340 } +341 } +342 } +343 trace!("actor terminating"); +344 } +345 +346 /// Handles an actor message. +347 /// +348 /// Error returns are fatal and kill the actor. +349 #[instrument(skip(self))] +350 async fn handle_message(&mut self, msg: RemoteStateMessage) { +351 // trace!("handling message"); +352 match msg { +353 RemoteStateMessage::SendDatagram(sender, transmit) => { +354 self.handle_msg_send_datagram(sender, transmit).await; +355 } +356 RemoteStateMessage::AddConnection(handle, tx) => { +357 self.handle_msg_add_connection(handle, tx); +358 } +359 RemoteStateMessage::ResolveRemote(addrs, tx) => { +360 self.handle_msg_resolve_remote(addrs, tx); +361 } +362 RemoteStateMessage::RemoteInfo(tx) => { +363 let addrs = self.paths.to_remote_addrs(); +364 let info = RemoteInfo { +365 endpoint_id: self.endpoint_id, +366 addrs, +367 }; +368 tx.send(info).ok(); +369 } +370 } +371 } +372 +373 /// Handles regularly checking if any paths need hole punching currently +374 fn check_connections(&mut self) { +375 let mut is_goodenough = true; +376 for conn in self.connections.values() { +377 // If we have at least 1 non relay path, we consider the connection good enough for now +378 // TODO: evaluate other criteria, like current RTT etc +379 let is_conn_goodenough = conn.open_paths.iter().any(|(_, addr)| !addr.is_relay()); +380 is_goodenough &= is_conn_goodenough; +381 } +382 +383 if !is_goodenough { +384 debug!("connections are not good enough, noting holepunch"); +385 self.trigger_holepunching(); +386 } +387 } +388 +389 /// Handles [`RemoteStateMessage::SendDatagram`]. +390 async fn handle_msg_send_datagram( +391 &mut self, +392 mut sender: TransportsSender, +393 transmit: OwnedTransmit, +394 ) { +395 // Sending datagrams might fail, e.g. because we don't have the right transports set +396 // up to handle sending this owned transmit to. +397 // After all, we try every single path that we know (relay URL, IP address), even +398 // though we might not have a relay transport or ip-capable transport set up. +399 // So these errors must not be fatal for this actor (or even this operation). +400 +401 if let Some(addr) = self.selected_path.get() { +402 trace!(?addr, "sending datagram to selected path"); +403 +404 if let Err(err) = send_datagram(&mut sender, addr.clone(), transmit).await { +405 debug!(?addr, "failed to send datagram on selected_path: {err:#}"); +406 } +407 } else { +408 trace!( +409 paths = ?self.paths.addrs().collect::<Vec<_>>(), +410 "sending datagram to all known paths", +411 ); +412 if self.paths.is_empty() { +413 warn!("Cannot send datagrams: No paths to remote endpoint known"); +414 } +415 +416 for addr in self.paths.addrs() { +417 // We never want to send to our local addresses. +418 // The local address set is updated in the main loop so we can use `peek` here. +419 if let transports::Addr::Ip(sockaddr) = addr +420 && self +421 .local_direct_addrs +422 .peek() +423 .iter() +424 .any(|a| a.addr == *sockaddr) +425 { +426 trace!(%sockaddr, "not sending datagram to our own address"); +427 } else if let Err(err) = +428 send_datagram(&mut sender, addr.clone(), transmit.clone()).await +429 { +430 debug!(?addr, "failed to send datagram: {err:#}"); +431 } +432 } +433 // This message is received *before* a connection is added. So we do +434 // not yet have a connection to holepunch. Instead we trigger +435 // holepunching when AddConnection is received. +436 } +437 } +438 +439 /// Handles [`RemoteStateMessage::AddConnection`]. +440 /// +441 /// Error returns are fatal and kill the actor. +442 fn handle_msg_add_connection( +443 &mut self, +444 handle: WeakConnectionHandle, +445 tx: oneshot::Sender<PathsWatcher>, +446 ) { +447 let pub_open_paths = Watchable::default(); +448 if let Some(conn) = handle.upgrade() { +449 self.metrics.num_conns_opened.inc(); +450 // Remove any conflicting stable_ids from the local state. +451 let conn_id = ConnId(conn.stable_id()); +452 self.connections.remove(&conn_id); +453 +454 // Hook up paths, NAT addresses and connection closed event streams. +455 self.path_events.push(Box::pin( +456 BroadcastStream::new(conn.path_events()).map(move |evt| (conn_id, evt)), +457 )); +458 self.addr_events.push(Box::pin( +459 BroadcastStream::new(conn.nat_traversal_updates()).map(move |evt| (conn_id, evt)), +460 )); +461 self.connections_close.push(OnClosed::new(&conn)); +462 +463 // Add local addrs to the connection +464 let local_addrs = self +465 .local_direct_addrs +466 .get() +467 .iter() +468 .map(|d| d.addr) +469 .collect::<BTreeSet<_>>(); +470 Self::set_local_addrs(&conn, &local_addrs); +471 +472 // Store the connection +473 let conn_state = self +474 .connections +475 .entry(conn_id) +476 .insert_entry(ConnectionState { +477 handle: handle.clone(), +478 pub_open_paths: pub_open_paths.clone(), +479 paths: Default::default(), +480 open_paths: Default::default(), +481 path_ids: Default::default(), +482 }) +483 .into_mut(); +484 +485 // Store PathId(0), set path_status and select best path, check if holepunching +486 // is needed. +487 if let Some(path) = conn.path(PathId::ZERO) +488 && let Ok(socketaddr) = path.remote_address() +489 && let Some(path_remote) = self.relay_mapped_addrs.to_transport_addr(socketaddr) +490 { +491 trace!(?path_remote, "added new connection"); +492 let path_remote_is_ip = path_remote.is_ip(); +493 let status = match path_remote { +494 transports::Addr::Ip(_) => PathStatus::Available, +495 transports::Addr::Relay(_, _) => PathStatus::Backup, +496 }; +497 path.set_status(status).ok(); +498 conn_state.add_open_path(path_remote.clone(), PathId::ZERO); +499 self.paths +500 .insert_open_path(path_remote.clone(), Source::Connection { _0: Private }); +501 self.select_path(); +502 +503 if path_remote_is_ip { +504 // We may have raced this with a relay address. Try and add any +505 // relay addresses we have back. +506 let relays = self +507 .paths +508 .addrs() +509 .filter(|a| a.is_relay()) +510 .cloned() +511 .collect::<Vec<_>>(); +512 for remote in relays { +513 self.open_path(&remote); +514 } +515 } +516 } +517 self.trigger_holepunching(); +518 } +519 tx.send(PathsWatcher::new( +520 pub_open_paths.watch(), +521 self.selected_path.watch(), +522 handle, +523 )) +524 .ok(); +525 } +526 +527 /// Handles [`RemoteStateMessage::ResolveRemote`]. +528 fn handle_msg_resolve_remote( +529 &mut self, +530 addrs: BTreeSet<TransportAddr>, +531 tx: oneshot::Sender<Result<(), DiscoveryError>>, +532 ) { +533 let addrs = to_transports_addr(self.endpoint_id, addrs); +534 self.paths.insert_multiple(addrs, Source::App); +535 self.paths.resolve_remote(tx); +536 // Start discovery if we have no selected path. +537 self.trigger_discovery(); +538 } +539 +540 fn handle_connection_close(&mut self, conn_id: ConnId) { +541 if self.connections.remove(&conn_id).is_some() { +542 self.metrics.num_conns_closed.inc(); +543 } +544 if self.connections.is_empty() { +545 trace!("last connection closed - clearing selected_path"); +546 self.selected_path.set(None).ok(); +547 } +548 } +549 +550 fn handle_discovery_item(&mut self, item: Option<Result<DiscoveryItem, DiscoveryError>>) { +551 match item { +552 None => { +553 self.discovery_stream = Either::Left(n0_future::stream::pending()); +554 self.paths.discovery_finished(Ok(())); +555 } +556 Some(Err(err)) => { +557 warn!("Discovery failed: {err:#}"); +558 self.discovery_stream = Either::Left(n0_future::stream::pending()); +559 self.paths.discovery_finished(Err(err)); +560 } +561 Some(Ok(item)) => { +562 if item.endpoint_id() != self.endpoint_id { +563 warn!(?item, "Discovery emitted item for wrong remote endpoint"); +564 } else { +565 let source = Source::Discovery { +566 name: item.provenance().to_string(), +567 }; +568 let addrs = +569 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs); +570 self.paths.insert_multiple(addrs, source); +571 } +572 } +573 } +574 } +575 +576 /// Triggers discovery for the remote endpoint, if needed. +577 /// +578 /// Does not start discovery if we have a selected path or if discovery is currently running. +579 fn trigger_discovery(&mut self) { +580 if self.selected_path.get().is_some() || matches!(self.discovery_stream, Either::Right(_)) { +581 return; +582 } +583 match self.discovery.resolve(self.endpoint_id) { +584 Some(stream) => self.discovery_stream = Either::Right(SyncStream::new(stream)), +585 None => self.paths.discovery_finished(Ok(())), +586 } +587 } +588 +589 /// Sets the current local addresses to QNT's state to all connections +590 fn local_addrs_updated(&mut self) { +591 let local_addrs = self +592 .local_direct_addrs +593 .get() +594 .iter() +595 .map(|d| d.addr) +596 .collect::<BTreeSet<_>>(); +597 +598 for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) { +599 Self::set_local_addrs(&conn, &local_addrs); +600 } +601 // todo: trace +602 } +603 +604 /// Sets the current local addresses to QNT's state +605 fn set_local_addrs(conn: &quinn::Connection, local_addrs: &BTreeSet<SocketAddr>) { +606 let quinn_local_addrs = match conn.get_local_nat_traversal_addresses() { +607 Ok(addrs) => BTreeSet::from_iter(addrs), +608 Err(err) => { +609 warn!("failed to get local nat candidates: {err:#}"); +610 return; +611 } +612 }; +613 for addr in local_addrs.difference(&quinn_local_addrs) { +614 if let Err(err) = conn.add_nat_traversal_address(*addr) { +615 warn!("failed adding local addr: {err:#}",); +616 } +617 } +618 for addr in quinn_local_addrs.difference(local_addrs) { +619 if let Err(err) = conn.remove_nat_traversal_address(*addr) { +620 warn!("failed removing local addr: {err:#}"); +621 } +622 } +623 trace!(?local_addrs, "updated local QNT addresses"); +624 } +625 +626 /// Triggers holepunching to the remote endpoint. +627 /// +628 /// This will manage the entire process of holepunching with the remote endpoint. +629 /// +630 /// - Holepunching happens on the Connection with the lowest [`ConnId`] which is a +631 /// client. +632 /// - Both endpoints may initiate holepunching if both have a client connection. +633 /// - Any opened paths are opened on all other connections without holepunching. +634 /// - If there are no changes in local or remote candidate addresses since the +635 /// last attempt **and** there was a recent attempt, a trigger_holepunching call +636 /// will be scheduled instead. +637 fn trigger_holepunching(&mut self) { +638 if self.connections.is_empty() { +639 trace!("not holepunching: no connections"); +640 return; +641 } +642 +643 let Some(conn) = self +644 .connections +645 .iter() +646 .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn))) +647 .filter(|(_, conn)| conn.side().is_client()) +648 .min_by_key(|(id, _)| *id) +649 .map(|(_, conn)| conn) +650 else { +651 trace!("not holepunching: no client connection"); +652 return; +653 }; +654 let remote_candidates = match conn.get_remote_nat_traversal_addresses() { +655 Ok(addrs) => BTreeSet::from_iter(addrs), +656 Err(err) => { +657 warn!("failed to get nat candidate addresses: {err:#}"); +658 return; +659 } +660 }; +661 let local_candidates: BTreeSet<SocketAddr> = self +662 .local_direct_addrs +663 .get() +664 .iter() +665 .map(|daddr| daddr.addr) +666 .collect(); +667 let new_candidates = self +668 .last_holepunch +669 .as_ref() +670 .map(|last_hp| { +671 // Addrs are allowed to disappear, but if there are new ones we need to +672 // holepunch again. +673 trace!( +674 ?last_hp, +675 ?local_candidates, +676 ?remote_candidates, +677 "candidates to holepunch?" +678 ); +679 !remote_candidates.is_subset(&last_hp.remote_candidates) +680 || !local_candidates.is_subset(&last_hp.local_candidates) +681 }) +682 .unwrap_or(true); +683 if !new_candidates { +684 if let Some(ref last_hp) = self.last_holepunch { +685 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL; +686 let now = Instant::now(); +687 if next_hp > now { +688 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses"); +689 self.scheduled_holepunch = Some(next_hp); +690 return; +691 } +692 } +693 } +694 +695 self.do_holepunching(conn); +696 } +697 +698 /// Unconditionally perform holepunching. +699 #[instrument(skip_all)] +700 fn do_holepunching(&mut self, conn: quinn::Connection) { +701 self.metrics.nat_traversal.inc(); +702 let local_candidates = self +703 .local_direct_addrs +704 .get() +705 .iter() +706 .map(|daddr| daddr.addr) +707 .collect::<BTreeSet<_>>(); +708 +709 match conn.initiate_nat_traversal_round() { 710 Ok(remote_candidates) => { 711 let remote_candidates = remote_candidates 712 .iter()