1use std::{
2 collections::{BTreeSet, VecDeque},
3 net::SocketAddr,
4 pin::Pin,
5 sync::Arc,
6 task::Poll,
7};
8
9use iroh_base::{EndpointId, TransportAddr};
10use n0_error::StackResultExt;
11use n0_future::{
12 FuturesUnordered, FuturesUnorderedBounded, MaybeFuture, MergeUnbounded, Stream, StreamExt,
13 boxed::BoxStream,
14 future::{Boxed, now_or_never},
15 task::JoinSet,
16 time::{self, Duration, Instant},
17};
18use n0_watcher::Watcher;
19use noq::{Closed, PathStats, PathStatus, WeakConnectionHandle};
20use noq_proto::{PathError, PathEvent as NoqPathEvent, PathId, n0_nat_traversal};
21use rustc_hash::FxHashMap;
22use smallvec::{SmallVec, smallvec};
23use tokio::sync::{mpsc, oneshot};
24use tokio_util::sync::CancellationToken;
25use tracing::{Instrument, Level, Span, debug, error, event, info_span, instrument, trace, warn};
26
27use self::path_state::RemotePathState;
28pub(crate) use self::path_watcher::PathStateReceiver;
29pub use self::{
30 path_watcher::{Path, PathEvent, PathEventStream, PathList, PathListIter, PathListStream},
31 remote_info::{RemoteInfo, TransportAddrInfo, TransportAddrUsage},
32};
33use super::{MappedAddrs, Source};
34use crate::{
35 address_lookup::{AddressLookupFailed, AddressLookupServices, Item as AddressLookupItem},
36 endpoint::DirectAddr,
37 socket::{
38 Metrics as SocketMetrics, RELAY_PATH_MAX_IDLE_TIMEOUT,
39 remote_map::remote_state::path_watcher::PathStateSender,
40 transports::{self, OwnedTransmit, TransportsSender},
41 },
42};
43
44mod path_state;
45mod path_watcher;
46mod remote_info;
47
48const HOLEPUNCH_ATTEMPTS_INTERVAL: Duration = Duration::from_secs(5);
53
54const GOOD_ENOUGH_LATENCY: Duration = Duration::from_millis(10);
56
57const UPGRADE_INTERVAL: Duration = Duration::from_secs(60);
67
68const ACTOR_MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
75
76const DATAGRAM_SEND_TIMEOUT: Duration = Duration::from_secs(3);
78const MAX_DATAGRAM_SEND_TASKS: usize = 16;
79
80type PathEvents = MergeUnbounded<
85 Pin<Box<dyn Stream<Item = (ConnId, Result<NoqPathEvent, noq::Lagged>)> + Send + Sync>>,
86>;
87
88type AddrEvents = MergeUnbounded<
92 Pin<
93 Box<
94 dyn Stream<Item = (ConnId, Result<n0_nat_traversal::Event, noq::Lagged>)> + Send + Sync,
95 >,
96 >,
97>;
98
99pub(super) struct RemoteStateActor {
104 connections: FxHashMap<ConnId, ConnectionState>,
106 state: State,
111}
112
113struct State {
115 endpoint_id: EndpointId,
117
118 metrics: Arc<SocketMetrics>,
122 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
126 mapped_addrs: MappedAddrs,
128 address_lookup: AddressLookupServices,
130
131 connections_close: FuturesUnordered<OnClosed>,
135 path_events: PathEvents,
137 addr_events: AddrEvents,
139
140 paths: RemotePathState,
147 last_holepunch: Option<HolepunchAttempt>,
149
150 selected_path: Option<transports::FourTuple>,
159 scheduled_holepunch: Option<Instant>,
161 scheduled_open_path: Option<Instant>,
163 pending_open_paths: VecDeque<transports::FourTuple>,
167
168 address_lookup_stream: Option<BoxStream<Result<AddressLookupItem, AddressLookupFailed>>>,
172
173 path_selector: Arc<dyn PathSelector>,
175}
176
177impl RemoteStateActor {
178 #[allow(clippy::too_many_arguments)]
179 pub(super) fn new(
180 endpoint_id: EndpointId,
181 local_direct_addrs: n0_watcher::Direct<BTreeSet<DirectAddr>>,
182 mapped_addrs: MappedAddrs,
183 metrics: Arc<SocketMetrics>,
184 address_lookup: AddressLookupServices,
185 path_selector: Arc<dyn PathSelector>,
186 ) -> Self {
187 Self {
188 connections: FxHashMap::default(),
189 state: State {
190 endpoint_id,
191 metrics: metrics.clone(),
192 local_direct_addrs,
193 mapped_addrs,
194 address_lookup,
195 connections_close: Default::default(),
196 path_events: Default::default(),
197 addr_events: Default::default(),
198 paths: RemotePathState::new(metrics),
199 last_holepunch: None,
200 selected_path: Default::default(),
201 scheduled_holepunch: None,
202 scheduled_open_path: None,
203 pending_open_paths: VecDeque::new(),
204 address_lookup_stream: None,
205 path_selector,
206 },
207 }
208 }
209
210 pub(super) fn start(
211 self,
212 initial_msgs: Vec<RemoteStateMessage>,
213 tasks: &mut JoinSet<(EndpointId, Vec<RemoteStateMessage>)>,
214 shutdown_token: CancellationToken,
215 parent_span: Span,
216 ) -> mpsc::Sender<RemoteStateMessage> {
217 let (tx, rx) = mpsc::channel(16);
218 let endpoint_id = self.state.endpoint_id;
219
220 tasks.spawn(
226 self.run(initial_msgs, rx, shutdown_token)
227 .instrument(info_span!(
228 parent: parent_span,
229 "RemoteStateActor",
230 remote = %endpoint_id.fmt_short(),
231 )),
232 );
233 tx
234 }
235
236 async fn run(
238 mut self,
239 initial_msgs: Vec<RemoteStateMessage>,
240 mut inbox: mpsc::Receiver<RemoteStateMessage>,
241 shutdown_token: CancellationToken,
242 ) -> (EndpointId, Vec<RemoteStateMessage>) {
243 trace!("actor started");
244 let mut send_tasks = FuturesUnorderedBounded::new(MAX_DATAGRAM_SEND_TASKS);
245 for msg in initial_msgs {
246 self.handle_message(msg, &mut send_tasks);
247 }
248 let idle_timeout = time::sleep(ACTOR_MAX_IDLE_TIMEOUT);
249 n0_future::pin!(idle_timeout);
250
251 let check_connections = time::interval(UPGRADE_INTERVAL);
252 n0_future::pin!(check_connections);
253
254 loop {
255 let scheduled_path_open = match self.state.scheduled_open_path {
256 Some(when) => MaybeFuture::Some(time::sleep_until(when)),
257 None => MaybeFuture::None,
258 };
259 n0_future::pin!(scheduled_path_open);
260 let scheduled_hp = match self.state.scheduled_holepunch {
261 Some(when) => MaybeFuture::Some(time::sleep_until(when)),
262 None => MaybeFuture::None,
263 };
264 n0_future::pin!(scheduled_hp);
265 if !self.is_idle(&inbox) {
266 idle_timeout
267 .as_mut()
268 .reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT);
269 }
270
271 tokio::select! {
272 biased;
273
274 _ = shutdown_token.cancelled() => {
275 trace!("actor cancelled");
276 break;
277 }
278 Some(()) = send_tasks.next(), if !send_tasks.is_empty() => {}
279 msg = inbox.recv() => {
280 match msg {
281 Some(msg) => self.handle_message(msg, &mut send_tasks),
282 None => break,
283 }
284 }
285 Some((id, evt)) = self.state.path_events.next() => {
286 self.handle_path_event(id, evt);
287 }
288 Some((id, evt)) = self.state.addr_events.next() => {
289 trace!(?id, ?evt, "remote addrs updated, triggering holepunching");
290 self.trigger_holepunching();
291 }
292 Some((conn_id, closed)) = self.state.connections_close.next(), if !self.state.connections_close.is_empty() => {
293 self.handle_connection_close(conn_id, closed);
294 }
295 res = self.state.local_direct_addrs.updated() => {
296 if let Err(n0_watcher::Disconnected) = res {
297 trace!("direct address watcher disconnected, shutting down");
298 break;
299 }
300 self.update_local_direct_address();
301 trace!("local addrs updated, triggering holepunching");
302 self.trigger_holepunching();
303 }
304 _ = &mut scheduled_path_open => {
305 trace!("triggering scheduled path_open");
306 self.state.scheduled_open_path = None;
307 let mut addrs = std::mem::take(&mut self.state.pending_open_paths);
308 while let Some(addr) = addrs.pop_front() {
309 self.open_path_on_all_conns(&addr);
310 }
311 }
312 _ = &mut scheduled_hp => {
313 trace!("triggering scheduled holepunching");
314 self.state.scheduled_holepunch = None;
315 self.trigger_holepunching();
316 }
317 Some(item) = maybe_next(self.state.address_lookup_stream.as_mut()), if self.state.address_lookup_stream.is_some() => {
318 self.state.handle_address_lookup_item(item);
319 }
320 _ = check_connections.tick() => {
321 self.check_connections();
322 }
323 _ = &mut idle_timeout => {
324 if self.is_idle(&inbox) {
325 trace!("idle timeout expired and still idle: terminate actor");
326 break;
327 } else {
328 idle_timeout.as_mut().reset(Instant::now() + ACTOR_MAX_IDLE_TIMEOUT);
330 }
331 }
332 }
333 }
334
335 inbox.close();
336 let mut leftover_msgs = Vec::with_capacity(inbox.len());
339 inbox.recv_many(&mut leftover_msgs, inbox.len()).await;
340
341 trace!("actor terminating");
342 (self.state.endpoint_id, leftover_msgs)
343 }
344
345 fn is_idle(&self, inbox: &mpsc::Receiver<RemoteStateMessage>) -> bool {
347 self.connections.is_empty()
348 && inbox.is_empty()
349 && self.state.paths.resolve_requests_is_empty()
350 }
351
352 #[instrument(skip(self))]
354 fn handle_message(
355 &mut self,
356 msg: RemoteStateMessage,
357 send_tasks: &mut FuturesUnorderedBounded<Boxed<()>>,
358 ) {
359 match msg {
360 RemoteStateMessage::SendDatagram(sender, transmit) => {
361 self.state
362 .handle_msg_send_datagram(sender, transmit, send_tasks);
363 }
364 RemoteStateMessage::AddConnection(handle, tx) => {
365 self.handle_msg_add_connection(handle, tx);
366 }
367 RemoteStateMessage::ResolveRemote(addrs, tx) => {
368 self.state.handle_msg_resolve_remote(addrs, tx);
369 }
370 RemoteStateMessage::RemoteInfo(tx) => {
371 let addrs = self.state.paths.to_remote_addrs();
372 let info = RemoteInfo {
373 endpoint_id: self.state.endpoint_id,
374 addrs,
375 };
376 tx.send(info).ok();
377 }
378 RemoteStateMessage::NetworkChange { is_major } => {
379 self.handle_msg_network_change(is_major);
380 }
381 }
382 }
383
384 fn handle_msg_add_connection(
388 &mut self,
389 conn: noq::Connection,
390 tx: oneshot::Sender<PathStateReceiver>,
391 ) {
392 let (path_state_sender, path_state_receiver) = PathStateSender::new();
393 self.state.metrics.num_conns_opened.inc();
394 let conn_id = ConnId(conn.stable_id());
396 self.connections.remove(&conn_id);
397
398 self.state
400 .path_events
401 .push(Box::pin(conn.path_events().map(move |evt| (conn_id, evt))));
402 self.state.addr_events.push(Box::pin(
403 conn.nat_traversal_updates().map(move |evt| (conn_id, evt)),
404 ));
405 self.state.connections_close.push(OnClosed::new(&conn));
406
407 let local_addrs = self.state.local_candidates();
409 update_qnt_candidates(&conn, &local_addrs);
410
411 let conn_state = self
413 .connections
414 .entry(conn_id)
415 .insert_entry(ConnectionState {
416 handle: conn.weak_handle(),
417 path_state: path_state_sender,
418 paths: Default::default(),
419 has_been_direct: false,
420 })
421 .into_mut();
422
423 if let Some(path) = conn.path(PathId::ZERO) {
426 let path_remote = self
427 .state
428 .register_and_configure_path(conn_id, conn_state, &path);
429
430 if let Some(path_remote) = path_remote
431 && !path_remote.is_relay()
432 && conn.side().is_client()
433 {
434 let relays = self
437 .state
438 .paths
439 .addrs()
440 .filter(|addr| addr.is_relay())
441 .map(|addr| transports::FourTuple::from_remote(addr.clone()))
442 .collect::<Vec<_>>();
443 for open_addr in relays {
444 self.state
445 .open_path_on_conn(conn_id, conn_state, &conn, &open_addr);
446 }
447 }
448 }
449 self.trigger_holepunching();
450 self.select_path();
451 tx.send(path_state_receiver).ok();
452 }
453
454 fn handle_msg_network_change(&mut self, is_major: bool) {
456 for conn in self.connections.values() {
458 if let Some(noq_conn) = conn.handle.upgrade() {
459 for (path_id, addr) in &conn.paths {
460 if let Some(path) = noq_conn.path(*path_id) {
461 if let Err(err) = path.ping() {
463 warn!(%err, %path_id, ?addr, "failed to ping path");
464 }
465 }
466 }
467 }
468 }
469
470 if is_major {
471 self.trigger_holepunching();
472 }
473 }
474
475 fn handle_connection_close(&mut self, conn_id: ConnId, closed: Closed) {
476 event!(
477 target: "iroh::_events::conn::closed",
478 Level::DEBUG,
479 %conn_id,
480 remote_id = %self.state.endpoint_id.fmt_short(),
481 reason=?closed.reason,
482 );
483
484 if let Some(conn_state) = self.connections.remove(&conn_id) {
485 self.state.metrics.num_conns_closed.inc();
486 conn_state.path_state.close(closed);
487 }
488 if self.connections.is_empty() {
489 trace!("last connection closed - clearing selected_path");
490 self.state.selected_path = None;
491 }
492 }
493
494 fn update_local_direct_address(&mut self) {
499 let local_addrs = self.state.local_candidates();
500 for conn in self.connections.values().filter_map(|s| s.handle.upgrade()) {
501 update_qnt_candidates(&conn, &local_addrs);
502 }
503 }
505
506 fn trigger_holepunching(&mut self) {
518 if self.connections.is_empty() {
519 trace!("not holepunching: no connections");
520 return;
521 }
522
523 let Some(conn) = self
524 .connections
525 .iter()
526 .filter_map(|(id, state)| state.handle.upgrade().map(|conn| (*id, conn)))
527 .filter(|(_, conn)| conn.side().is_client())
528 .min_by_key(|(id, _)| *id)
529 .map(|(_, conn)| conn)
530 else {
531 trace!("not holepunching: no client connection");
532 return;
533 };
534 let remote_candidates = match conn.get_remote_nat_traversal_addresses() {
535 Ok(addrs) => BTreeSet::from_iter(addrs),
536 Err(err) => {
537 warn!("failed to get nat candidate addresses: {err:#}");
538 return;
539 }
540 };
541 let local_candidates = self.state.local_candidates();
542 let new_candidates = self
543 .state
544 .last_holepunch
545 .as_ref()
546 .map(|last_hp| {
547 trace!(
550 ?last_hp,
551 ?local_candidates,
552 ?remote_candidates,
553 "candidates to holepunch?"
554 );
555 !remote_candidates.is_subset(&last_hp.remote_candidates)
556 || !local_candidates.is_subset(&last_hp.local_candidates)
557 })
558 .unwrap_or(true);
559 if !new_candidates && let Some(ref last_hp) = self.state.last_holepunch {
560 let next_hp = last_hp.when + HOLEPUNCH_ATTEMPTS_INTERVAL;
561 let now = Instant::now();
562 if next_hp > now {
563 trace!(scheduled_in = ?(next_hp - now), "not holepunching: no new addresses");
564 self.state.scheduled_holepunch = Some(next_hp);
565 return;
566 }
567 }
568
569 self.state.do_holepunching(conn);
570 }
571
572 #[instrument(skip(self))]
573 fn handle_path_event(&mut self, conn_id: ConnId, event: Result<NoqPathEvent, noq::Lagged>) {
574 let Ok(event) = event else {
575 warn!("missed a PathEvent, RemoteStateActor lagging");
576 return;
579 };
580 let Some(conn_state) = self.connections.get_mut(&conn_id) else {
581 trace!("event for removed connection");
582 return;
583 };
584 let Some(conn) = conn_state.handle.upgrade() else {
585 trace!("event for closed connection");
586 return;
587 };
588 trace!("path event");
589 match event {
590 NoqPathEvent::Established { id: path_id, .. } => {
591 let Some(path) = conn.path(path_id) else {
592 trace!("path open event for unknown path");
593 return;
594 };
595
596 self.state
597 .register_and_configure_path(conn_id, conn_state, &path);
598 self.select_path();
599 }
600 NoqPathEvent::Abandoned { id, reason, .. } => {
601 let Some(network_path) = conn_state.remove_path(&id, &conn) else {
603 debug!(%id, "path not in path_id_map");
604 return;
605 };
606
607 if !conn_state
612 .paths
613 .values()
614 .any(|tuple| tuple.remote() == network_path.remote())
615 {
616 self.state.paths.abandoned_path(&network_path.remote());
617 }
618
619 event!(
620 target: "iroh::_events::path::abandoned",
621 Level::DEBUG,
622 remote = %self.state.endpoint_id.fmt_short(),
623 %conn_id,
624 path_id = %id,
625 %network_path,
626 ?reason
627 );
628
629 self.select_path();
631 }
632 NoqPathEvent::Discarded { id, path_stats, .. } => {
633 trace!(%id, ?path_stats, "path discarded");
634 }
635 NoqPathEvent::RemoteStatus { .. } | NoqPathEvent::ObservedAddr { .. } => {
636 }
638 _ => {
639 #[cfg(test)]
643 panic!("Unhandled path event: {event:?}");
644 }
645 }
646 }
647
648 #[instrument(skip_all)]
653 fn select_path(&mut self) {
654 let current_path = self.state.selected_path.as_ref();
655 let selected_addr = {
656 let ctx = PathSelectionContext::new(current_path, &self.connections);
657 self.state.path_selector.select(&ctx).selected().cloned()
658 };
659
660 if let Some(addr) = selected_addr
661 && self.state.selected_path.as_ref() != Some(&addr)
662 {
663 let prev_remote = self.state.selected_path.replace(addr.clone());
664 event!(
665 target: "iroh::_events::path::selected",
666 Level::DEBUG,
667 remote = %self.state.endpoint_id.fmt_short(),
668 network_path = %addr,
669 prev_network_path = %prev_remote.map(|p| format!("{p}")).unwrap_or("None".to_string()),
670 );
671 } else {
672 trace!(?current_path, "keeping current path");
673 }
674
675 self.apply_selected_path();
676 }
677
678 fn apply_selected_path(&mut self) {
686 let Some(selected) = self.state.selected_path.clone() else {
687 return;
691 };
692
693 for (conn_id, conn_state) in self.connections.iter() {
694 let Some(conn) = conn_state.handle.upgrade() else {
695 continue;
696 };
697
698 self.state
700 .open_path_on_conn(*conn_id, conn_state, &conn, &selected);
701
702 for (path_id, path_fourtuple) in conn_state.paths.iter() {
703 let Some(path) = conn.path(*path_id) else {
704 continue;
705 };
706
707 if conn.side().is_client()
713 && path_fourtuple.is_ip()
714 && path_fourtuple != &selected
715 && conn_state.paths.values().filter(|a| a.is_ip()).count() > 1
716 {
717 trace!(?path_fourtuple, %conn_id, %path_id, "closing direct path");
718 match path.close() {
719 Err(noq_proto::ClosePathError::MultipathNotNegotiated) => {
720 error!("multipath not negotiated");
721 }
722 Err(noq_proto::ClosePathError::LastOpenPath) => {
723 error!("could not close last open path");
724 }
725 Err(noq_proto::ClosePathError::ClosedPath) => {
726 }
728 Ok(()) => {}
729 }
730 continue;
731 }
732
733 self.state.set_path_status(*conn_id, &path, path_fourtuple);
736 }
737
738 conn_state.path_state.record_selected(&selected);
740 }
741 }
742
743 fn open_path_on_all_conns(&mut self, open_addr: &transports::FourTuple) {
744 for (conn_id, conn_state) in self.connections.iter() {
745 let Some(conn) = conn_state.handle.upgrade() else {
746 continue;
747 };
748 self.state
749 .open_path_on_conn(*conn_id, conn_state, &conn, open_addr);
750 }
751 }
752
753 fn check_connections(&mut self) {
757 let mut is_goodenough = true;
758 for conn_state in self.connections.values() {
759 let mut is_conn_goodenough = false;
760 if let Some(conn) = conn_state.handle.upgrade() {
761 let min_ip_rtt = conn_state
762 .paths
763 .iter()
764 .filter_map(|(path_id, addr)| {
765 if addr.is_ip() {
766 conn.path_stats(*path_id).map(|stats| stats.rtt)
767 } else {
768 None
769 }
770 })
771 .min();
772
773 if let Some(min_ip_rtt) = min_ip_rtt {
774 let is_latency_goodenough = min_ip_rtt <= GOOD_ENOUGH_LATENCY;
775 is_conn_goodenough = is_latency_goodenough;
776 } else {
777 is_conn_goodenough = false;
779 }
780 }
781 is_goodenough &= is_conn_goodenough;
782 }
783
784 if !is_goodenough {
785 debug!("connections are not good enough, triggering holepunching");
786 self.trigger_holepunching();
787 }
788 }
789}
790
791impl State {
792 fn handle_msg_send_datagram(
794 &mut self,
795 sender: Box<TransportsSender>,
796 transmit: OwnedTransmit,
797 send_tasks: &mut FuturesUnorderedBounded<Boxed<()>>,
798 ) {
799 let targets = if let Some(addr) = self.selected_path.as_ref() {
806 trace!(?addr, "sending datagram to selected path");
807
808 smallvec![transports::FourTuple::from_remote(addr.remote())]
812 } else {
813 trace!(
814 paths = ?self.paths.addrs().collect::<Vec<_>>(),
815 "sending datagram to all known paths",
816 );
817 if self.paths.is_empty() {
818 warn!("Cannot send datagrams: No paths to remote endpoint known");
819 }
820
821 let mut targets = SmallVec::new();
822 for addr in self.paths.addrs() {
823 if let transports::Addr::Ip(sockaddr) = addr
826 && self
827 .local_direct_addrs
828 .peek()
829 .iter()
830 .any(|a| a.addr == *sockaddr)
831 {
832 trace!(%sockaddr, "not sending datagram to our own address");
833
834 } else {
838 targets.push(transports::FourTuple::from_remote(addr.clone()));
839 }
840 }
841 targets
845 };
846
847 if targets.is_empty() {
848 return;
849 }
850 let send = Box::pin(
851 async move {
852 if time::timeout(
853 DATAGRAM_SEND_TIMEOUT,
854 send_datagram_to_targets(sender, transmit, targets),
855 )
856 .await
857 .is_err()
858 {
859 debug!("Datagram send timed out");
860 }
861 }
862 .instrument(Span::current()),
863 );
864 if send_tasks.try_push(send).is_err() {
865 debug!("dropping datagram: send task limit reached");
866 }
867 }
868
869 fn handle_msg_resolve_remote(
871 &mut self,
872 addrs: BTreeSet<TransportAddr>,
873 tx: oneshot::Sender<Result<(), AddressLookupFailed>>,
874 ) {
875 let addrs = to_transports_addr(self.endpoint_id, addrs);
876 self.paths.insert_multiple(addrs, Source::App);
877 self.paths.resolve_remote(tx);
878 self.trigger_address_lookup();
880 }
881
882 fn trigger_address_lookup(&mut self) {
887 if self.selected_path.is_some() || self.address_lookup_stream.is_some() {
888 return;
889 }
890 let stream = self.address_lookup.resolve(self.endpoint_id);
891 let stream = stream.filter_map(|item| match item {
892 Ok(Err(_err)) => None,
896 Ok(Ok(item)) => Some(Ok(item)),
897 Err(err) => Some(Err(err)),
898 });
899 self.address_lookup_stream = Some(Box::pin(stream));
900 }
901
902 fn handle_address_lookup_item(
907 &mut self,
908 item: Option<Result<AddressLookupItem, AddressLookupFailed>>,
909 ) {
910 match item {
911 None => {
912 self.paths.address_lookup_finished(Ok(()));
913 self.address_lookup_stream = None;
914 }
915 Some(Err(err)) => {
916 if let AddressLookupFailed::NoServiceConfigured { .. } = err {
917 trace!("Address Lookup not configured");
918 } else {
919 debug!("Address Lookup failed: {err:#}");
920 }
921 self.paths.address_lookup_finished(Err(err));
922 self.address_lookup_stream = None;
923 }
924 Some(Ok(item)) => {
925 if item.endpoint_id() != self.endpoint_id {
926 warn!(
927 ?item,
928 "Address Lookup emitted item for wrong remote endpoint"
929 );
930 } else {
931 let source = Source::AddressLookup {
932 name: item.provenance().to_string(),
933 };
934 let addrs =
935 to_transports_addr(self.endpoint_id, item.into_endpoint_addr().addrs);
936 self.paths.insert_multiple(addrs, source);
937 }
938 }
939 }
940 }
941
942 #[instrument(skip_all)]
944 fn do_holepunching(&mut self, conn: noq::Connection) {
945 self.metrics.holepunch_attempts.inc();
946 let local_candidates = self.local_candidates();
947 match conn.initiate_nat_traversal_round() {
948 Ok(remote_candidates) => {
949 let remote_candidates = remote_candidates
950 .iter()
951 .map(|addr| SocketAddr::new(addr.ip().to_canonical(), addr.port()))
952 .collect();
953 event!(
954 target: "iroh::_events::qnt::init",
955 Level::DEBUG,
956 remote = %self.endpoint_id.fmt_short(),
957 ?local_candidates,
958 ?remote_candidates,
959 );
960 self.last_holepunch = Some(HolepunchAttempt {
961 when: Instant::now(),
962 local_candidates,
963 remote_candidates,
964 });
965 }
966 Err(err) => {
967 debug!("failed to initiate NAT traversal: {err:#}");
968 use noq_proto::n0_nat_traversal::Error;
969 match err {
970 Error::Closed
971 | Error::TooManyAddresses
972 | Error::WrongConnectionSide
973 | Error::ExtensionNotNegotiated => {
974 }
976 Error::Multipath(_) | Error::NotEnoughAddresses => {
977 let now = Instant::now();
979 let next_hp = now + Duration::from_millis(100);
980 trace!(scheduled_in = ?(next_hp - now), "holepunching retry");
981 self.scheduled_holepunch = Some(next_hp);
982 }
983 }
984 }
985 }
986 }
987
988 fn register_and_configure_path(
997 &mut self,
998 conn_id: ConnId,
999 conn_state: &mut ConnectionState,
1000 path: &noq::Path,
1001 ) -> Option<transports::FourTuple> {
1002 let network_path = self
1003 .mapped_addrs
1004 .to_transport_tuple(&path.network_path().ok()?)?;
1005 event!(
1006 target: "iroh::_events::path::open",
1007 Level::DEBUG,
1008 remote = %self.endpoint_id.fmt_short(),
1009 %conn_id,
1010 path_id=%path.id(),
1011 %network_path,
1012 );
1013 conn_state.add_open_path(network_path.clone(), path.id(), &self.metrics);
1014 if network_path.is_relay()
1015 && let Err(e) = path.set_max_idle_timeout(Some(RELAY_PATH_MAX_IDLE_TIMEOUT))
1016 {
1017 debug!(?e, "failed to set relay path idle timeout");
1018 }
1019
1020 self.set_path_status(conn_id, path, &network_path);
1021 self.paths
1022 .insert_open_path(network_path.remote(), Source::Connection);
1023 Some(network_path)
1024 }
1025
1026 fn set_path_status(
1027 &mut self,
1028 conn_id: ConnId,
1029 path: &noq::Path,
1030 network_path: &transports::FourTuple,
1031 ) {
1032 let status = self.path_status_for_addr(network_path);
1033 match path.set_status(status) {
1034 Err(error) => warn!(?error, ?network_path, ?status, "set_status failed"),
1035 Ok(prev_status) if prev_status != status => {
1036 event!(
1037 target: "iroh::_events::path::set_status",
1038 Level::DEBUG,
1039 remote = %self.endpoint_id.fmt_short(),
1040 %conn_id,
1041 path_id=%path.id(),
1042 %network_path,
1043 ?status,
1044 ?prev_status,
1045 );
1046 }
1047 Ok(_) => {}
1048 }
1049 }
1050
1051 fn open_path_on_conn(
1052 &mut self,
1053 conn_id: ConnId,
1054 conn_state: &ConnectionState,
1055 conn: &noq::Connection,
1056 open_4tuple: &transports::FourTuple,
1057 ) {
1058 if conn.side().is_server() {
1061 return;
1062 }
1063 if conn_state.paths.values().any(|a| a == open_4tuple) {
1065 return;
1066 }
1067
1068 let mapped_4tuple = self.mapped_addrs.to_mapped_tuple(open_4tuple);
1069 let path_status = self.path_status_for_addr(open_4tuple);
1070
1071 let fut = conn.open_path_ensure(mapped_4tuple, path_status);
1072 match fut.path_id() {
1073 Some(path_id) => {
1074 trace!(%conn_id, %path_id, ?path_status, "opening new path");
1075 }
1076 None => {
1077 let ret = now_or_never(fut);
1078 match ret {
1079 Some(Err(PathError::RemoteCidsExhausted))
1080 | Some(Err(PathError::MaxPathIdReached)) => {
1081 self.scheduled_open_path =
1082 Some(Instant::now() + Duration::from_millis(333));
1083 if !self.pending_open_paths.contains(open_4tuple) {
1087 self.pending_open_paths.push_back(open_4tuple.clone());
1088 }
1089 trace!(?open_4tuple, ?ret, "scheduling open_path");
1090 }
1091 _ => warn!(?ret, "Opening path failed"),
1092 }
1093 }
1094 }
1095 }
1096
1097 fn path_status_for_addr(&self, addr: &transports::FourTuple) -> PathStatus {
1102 if Some(addr) == self.selected_path.as_ref() {
1103 PathStatus::Available
1104 } else {
1105 PathStatus::Backup
1106 }
1107 }
1108
1109 fn local_candidates(&mut self) -> BTreeSet<SocketAddr> {
1111 self.local_direct_addrs
1112 .get()
1113 .iter()
1114 .map(|d| d.addr)
1115 .collect()
1116 }
1117}
1118
1119fn update_qnt_candidates(conn: &noq::Connection, direct_addrs: &BTreeSet<SocketAddr>) {
1124 let noq_candidates = match conn.get_local_nat_traversal_addresses() {
1125 Ok(addrs) => BTreeSet::from_iter(addrs),
1126 Err(err) => {
1127 warn!("failed to get local nat candidates: {err:#}");
1128 return;
1129 }
1130 };
1131 for addr in direct_addrs.difference(&noq_candidates) {
1132 if let Err(err) = conn.add_nat_traversal_address(*addr) {
1133 warn!("failed adding local addr: {err:#}",);
1134 }
1135 }
1136 for addr in noq_candidates.difference(direct_addrs) {
1137 if let Err(err) = conn.remove_nat_traversal_address(*addr) {
1138 warn!("failed removing local addr: {err:#}");
1139 }
1140 }
1141 trace!(?direct_addrs, "updated local QNT addresses");
1142}
1143
1144fn send_datagram<'a>(
1145 sender: &'a mut TransportsSender,
1146 addr: transports::FourTuple,
1147 owned_transmit: OwnedTransmit,
1148) -> impl Future<Output = n0_error::Result<()>> + 'a {
1149 std::future::poll_fn(move |cx| {
1150 let transmit = transports::Transmit {
1151 ecn: owned_transmit.ecn,
1152 contents: owned_transmit.contents.as_ref(),
1153 segment_size: owned_transmit.segment_size,
1154 };
1155
1156 Pin::new(&mut *sender)
1157 .poll_send(cx, &addr, &transmit)
1158 .map(|res| res.with_context(|_| format!("failed to send datagram to {:?}", addr)))
1159 })
1160}
1161
1162async fn send_datagram_to_targets(
1163 sender: Box<TransportsSender>,
1164 transmit: OwnedTransmit,
1165 targets: SmallVec<[transports::FourTuple; 8]>,
1166) {
1167 let mut sends = targets
1168 .into_iter()
1169 .map(|target| {
1170 let mut sender = sender.clone();
1171 let transmit = transmit.clone();
1172 async move {
1173 if let Err(err) = send_datagram(&mut sender, target.clone(), transmit).await {
1174 debug!(?target, "failed to send datagram: {err:#}");
1175 }
1176 }
1177 })
1178 .collect::<FuturesUnordered<_>>();
1179 while sends.next().await.is_some() {}
1180}
1181
1182#[derive(derive_more::Debug)]
1184pub(crate) enum RemoteStateMessage {
1185 #[debug("SendDatagram(..)")]
1194 SendDatagram(Box<TransportsSender>, OwnedTransmit),
1195 #[debug("AddConnection({})", _0.stable_id())]
1203 AddConnection(noq::Connection, oneshot::Sender<PathStateReceiver>),
1204 #[debug("ResolveRemote(..)")]
1213 ResolveRemote(
1214 BTreeSet<TransportAddr>,
1215 oneshot::Sender<Result<(), AddressLookupFailed>>,
1216 ),
1217 RemoteInfo(oneshot::Sender<RemoteInfo>),
1221 NetworkChange { is_major: bool },
1223}
1224
1225#[derive(Debug)]
1229struct HolepunchAttempt {
1230 when: Instant,
1231 local_candidates: BTreeSet<SocketAddr>,
1240 remote_candidates: BTreeSet<SocketAddr>,
1244}
1245
1246#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
1251#[display("{_0}")]
1252struct ConnId(usize);
1253
1254#[derive(Debug)]
1260struct ConnectionState {
1261 handle: WeakConnectionHandle,
1263 path_state: PathStateSender,
1269 paths: FxHashMap<PathId, transports::FourTuple>,
1278 has_been_direct: bool,
1282}
1283
1284impl ConnectionState {
1285 fn add_open_path(
1287 &mut self,
1288 network_path: transports::FourTuple,
1289 path_id: PathId,
1290 metrics: &Arc<SocketMetrics>,
1291 ) {
1292 match network_path {
1293 transports::FourTuple::Ip { .. } => metrics.paths_direct.inc(),
1294 transports::FourTuple::Relay { .. } => metrics.paths_relay.inc(),
1295 transports::FourTuple::Custom { .. } => metrics.paths_custom.inc(),
1296 };
1297 if !self.has_been_direct && network_path.is_ip() {
1298 self.has_been_direct = true;
1299 metrics.num_conns_direct.inc();
1300 }
1301
1302 self.paths.insert(path_id, network_path.clone());
1303 if let Some(conn) = self.handle.upgrade()
1304 && let Some(path) = conn.path(path_id)
1305 {
1306 let handle = path.weak_handle();
1307 self.path_state.record_opened(handle, network_path);
1308 }
1309 }
1310
1311 fn remove_path(
1313 &mut self,
1314 path_id: &PathId,
1315 conn: &noq::Connection,
1316 ) -> Option<transports::FourTuple> {
1317 let addr = self.paths.remove(path_id)?;
1318 self.path_state.record_abandoned(*path_id, conn);
1319 Some(addr)
1320 }
1321}
1322
1323#[derive(Debug)]
1328#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1329pub struct PathSelectionContext<'a> {
1330 current: Option<&'a transports::FourTuple>,
1331 source: PathsSource<'a>,
1332}
1333
1334#[derive(Debug)]
1337enum PathsSource<'a> {
1338 Live(&'a FxHashMap<ConnId, ConnectionState>),
1339 #[cfg(test)]
1340 Test(Vec<PathSelectionData<'a>>),
1341}
1342
1343#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1344impl<'a> PathSelectionContext<'a> {
1345 fn new(
1346 current: Option<&'a transports::FourTuple>,
1347 connections: &'a FxHashMap<ConnId, ConnectionState>,
1348 ) -> Self {
1349 Self {
1350 current,
1351 source: PathsSource::Live(connections),
1352 }
1353 }
1354
1355 #[cfg(test)]
1357 pub(crate) fn for_test(
1358 current: Option<&'a transports::FourTuple>,
1359 paths: Vec<PathSelectionData<'a>>,
1360 ) -> Self {
1361 Self {
1362 current,
1363 source: PathsSource::Test(paths),
1364 }
1365 }
1366
1367 pub fn current(&self) -> Option<&transports::FourTuple> {
1369 self.current
1370 }
1371
1372 pub fn paths(&self) -> Box<dyn Iterator<Item = PathSelectionData<'a>> + '_> {
1377 match &self.source {
1378 PathsSource::Live(connections) => Box::new(
1379 connections
1380 .values()
1381 .filter_map(|state| state.handle.upgrade().map(|conn| (state, conn)))
1382 .flat_map(|(state, conn)| {
1383 state.paths.iter().map(move |(path_id, addr)| {
1384 PathSelectionData::live(addr, *path_id, conn.clone())
1385 })
1386 }),
1387 ),
1388 #[cfg(test)]
1389 PathsSource::Test(paths) => Box::new(paths.iter().cloned()),
1390 }
1391 }
1392}
1393
1394#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1400#[derive(derive_more::Debug, Clone)]
1401pub struct PathSelectionData<'a> {
1402 network_path: &'a transports::FourTuple,
1403 #[debug(skip)]
1404 source: StatsSource,
1405}
1406
1407#[derive(Clone)]
1408enum StatsSource {
1409 Live {
1410 path_id: PathId,
1411 conn: noq::Connection,
1412 },
1413 #[cfg(test)]
1416 Test(Option<Box<PathStats>>),
1417}
1418
1419#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1420impl<'a> PathSelectionData<'a> {
1421 fn live(
1422 network_path: &'a transports::FourTuple,
1423 path_id: PathId,
1424 conn: noq::Connection,
1425 ) -> Self {
1426 Self {
1427 network_path,
1428 source: StatsSource::Live { path_id, conn },
1429 }
1430 }
1431
1432 #[cfg(test)]
1437 pub(crate) fn for_test(
1438 network_path: &'a transports::FourTuple,
1439 stats: Option<PathStats>,
1440 ) -> Self {
1441 Self {
1442 network_path,
1443 source: StatsSource::Test(stats.map(Box::new)),
1444 }
1445 }
1446
1447 pub fn network_path(&self) -> &transports::FourTuple {
1449 self.network_path
1450 }
1451
1452 pub fn stats(&self) -> Option<PathStats> {
1454 match &self.source {
1455 StatsSource::Live { path_id, conn } => conn.path_stats(*path_id),
1456 #[cfg(test)]
1457 StatsSource::Test(stats) => stats.as_deref().copied(),
1458 }
1459 }
1460}
1461
1462#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1466pub trait PathSelector: Send + Sync + std::fmt::Debug + 'static {
1467 fn select(&self, ctx: &PathSelectionContext<'_>) -> PathSelection;
1475}
1476
1477#[derive(Debug, Clone)]
1482#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1483pub struct PathSelection {
1484 selection: Option<transports::FourTuple>,
1485}
1486
1487#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1488impl PathSelection {
1489 pub fn none() -> Self {
1491 Self { selection: None }
1492 }
1493
1494 pub fn set(&mut self, path: &PathSelectionData<'_>) {
1499 if self.selection.is_some() {
1500 tracing::warn!(
1501 path = %path.network_path(),
1502 "PathSelection already contains a path; ignoring additional path"
1503 );
1504 return;
1505 }
1506 self.selection = Some(path.network_path.clone());
1507 }
1508
1509 pub(crate) fn selected(&self) -> Option<&transports::FourTuple> {
1515 self.selection.as_ref()
1516 }
1517}
1518
1519struct OnClosed {
1524 conn_id: ConnId,
1525 inner: noq::OnClosed,
1526}
1527
1528impl OnClosed {
1529 fn new(conn: &noq::Connection) -> Self {
1530 Self {
1531 conn_id: ConnId(conn.stable_id()),
1532 inner: conn.on_closed(),
1533 }
1534 }
1535}
1536
1537impl Future for OnClosed {
1538 type Output = (ConnId, Closed);
1539
1540 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1541 let closed = std::task::ready!(Pin::new(&mut self.inner).poll(cx));
1542 Poll::Ready((self.conn_id, closed))
1543 }
1544}
1545
1546fn to_transports_addr(
1548 endpoint_id: EndpointId,
1549 addrs: impl IntoIterator<Item = TransportAddr>,
1550) -> impl Iterator<Item = transports::Addr> {
1551 addrs.into_iter().filter_map(move |addr| match addr {
1552 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))),
1553 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)),
1554 TransportAddr::Custom(custom_addr) => Some(transports::Addr::from(custom_addr)),
1555 _ => {
1556 warn!(?addr, "Unsupported TransportAddr");
1557 None
1558 }
1559 })
1560}
1561
1562async fn maybe_next<S: Stream + Unpin>(maybe_stream: Option<&mut S>) -> Option<Option<S::Item>> {
1564 match maybe_stream {
1565 None => None,
1566 Some(s) => Some(s.next().await),
1567 }
1568}
1569
1570#[cfg(all(test, not(wasm_browser)))]
1571mod tests {
1572 use super::*;
1573
1574 #[tokio::test]
1575 async fn blocked_relay_does_not_delay_direct_initial() {
1576 let receiver = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
1577 let (mut sender, _relay_receiver) = TransportsSender::with_bounded_relay(
1578 1,
1579 [transports::IpConfig::V4 {
1580 ip_net: "127.0.0.1/8".parse().unwrap(),
1581 port: 0,
1582 is_required: true,
1583 is_default: true,
1584 }]
1585 .into_iter(),
1586 );
1587 let relay = transports::FourTuple::Relay {
1588 url: "https://relay.example.invalid".parse().unwrap(),
1589 endpoint_id: iroh_base::SecretKey::from_bytes(&[1; 32]).public(),
1590 };
1591 let transmit = OwnedTransmit {
1592 ecn: None,
1593 contents: bytes::Bytes::from_static(b"initial"),
1594 segment_size: None,
1595 };
1596 send_datagram(&mut sender, relay.clone(), transmit.clone())
1597 .await
1598 .unwrap();
1599 let sends = send_datagram_to_targets(
1600 Box::new(sender),
1601 transmit,
1602 smallvec![
1603 relay,
1604 transports::FourTuple::from_remote(transports::Addr::Ip(
1605 receiver.local_addr().unwrap(),
1606 )),
1607 ],
1608 );
1609 let mut buf = [0; 64];
1610 tokio::select! {
1612 _ = sends => panic!("blocked Relay send unexpectedly completed"),
1613 received = time::timeout(Duration::from_secs(1), receiver.recv(&mut buf)) => {
1614 let len = received.expect("Direct send blocked behind Relay").unwrap();
1615 assert_eq!(&buf[..len], b"initial");
1616 }
1617 }
1618 }
1619}