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 mapped_path = path.network_path().ok()?;
1003 let network_path = self
1005 .mapped_addrs
1006 .to_pinned_transport_tuple(&mapped_path, &self.endpoint_id)?;
1007 event!(
1008 target: "iroh::_events::path::open",
1009 Level::DEBUG,
1010 remote = %self.endpoint_id.fmt_short(),
1011 %conn_id,
1012 path_id=%path.id(),
1013 %network_path,
1014 );
1015 conn_state.add_open_path(network_path.clone(), path.id(), &self.metrics);
1016 if network_path.is_relay()
1017 && let Err(e) = path.set_max_idle_timeout(Some(RELAY_PATH_MAX_IDLE_TIMEOUT))
1018 {
1019 debug!(?e, "failed to set relay path idle timeout");
1020 }
1021
1022 self.set_path_status(conn_id, path, &network_path);
1023 self.paths
1024 .insert_open_path(network_path.remote(), Source::Connection);
1025 Some(network_path)
1026 }
1027
1028 fn set_path_status(
1029 &mut self,
1030 conn_id: ConnId,
1031 path: &noq::Path,
1032 network_path: &transports::FourTuple,
1033 ) {
1034 let status = self.path_status_for_addr(network_path);
1035 match path.set_status(status) {
1036 Err(error) => warn!(?error, ?network_path, ?status, "set_status failed"),
1037 Ok(prev_status) if prev_status != status => {
1038 event!(
1039 target: "iroh::_events::path::set_status",
1040 Level::DEBUG,
1041 remote = %self.endpoint_id.fmt_short(),
1042 %conn_id,
1043 path_id=%path.id(),
1044 %network_path,
1045 ?status,
1046 ?prev_status,
1047 );
1048 }
1049 Ok(_) => {}
1050 }
1051 }
1052
1053 fn open_path_on_conn(
1054 &mut self,
1055 conn_id: ConnId,
1056 conn_state: &ConnectionState,
1057 conn: &noq::Connection,
1058 open_4tuple: &transports::FourTuple,
1059 ) {
1060 if conn.side().is_server() {
1063 return;
1064 }
1065 if conn_state.paths.values().any(|a| a == open_4tuple) {
1067 return;
1068 }
1069
1070 let mapped_4tuple = self
1071 .mapped_addrs
1072 .to_mapped_tuple(open_4tuple, &self.endpoint_id);
1073 let path_status = self.path_status_for_addr(open_4tuple);
1074
1075 let fut = conn.open_path_ensure(mapped_4tuple, path_status);
1076 match fut.path_id() {
1077 Some(path_id) => {
1078 trace!(%conn_id, %path_id, ?path_status, "opening new path");
1079 }
1080 None => {
1081 let ret = now_or_never(fut);
1082 match ret {
1083 Some(Err(PathError::RemoteCidsExhausted))
1084 | Some(Err(PathError::MaxPathIdReached)) => {
1085 self.scheduled_open_path =
1086 Some(Instant::now() + Duration::from_millis(333));
1087 if !self.pending_open_paths.contains(open_4tuple) {
1091 self.pending_open_paths.push_back(open_4tuple.clone());
1092 }
1093 trace!(?open_4tuple, ?ret, "scheduling open_path");
1094 }
1095 _ => warn!(?ret, "Opening path failed"),
1096 }
1097 }
1098 }
1099 }
1100
1101 fn path_status_for_addr(&self, addr: &transports::FourTuple) -> PathStatus {
1106 if Some(addr) == self.selected_path.as_ref() {
1107 PathStatus::Available
1108 } else {
1109 PathStatus::Backup
1110 }
1111 }
1112
1113 fn local_candidates(&mut self) -> BTreeSet<SocketAddr> {
1115 self.local_direct_addrs
1116 .get()
1117 .iter()
1118 .map(|d| d.addr)
1119 .collect()
1120 }
1121}
1122
1123fn update_qnt_candidates(conn: &noq::Connection, direct_addrs: &BTreeSet<SocketAddr>) {
1128 let noq_candidates = match conn.get_local_nat_traversal_addresses() {
1129 Ok(addrs) => BTreeSet::from_iter(addrs),
1130 Err(err) => {
1131 warn!("failed to get local nat candidates: {err:#}");
1132 return;
1133 }
1134 };
1135 for addr in direct_addrs.difference(&noq_candidates) {
1136 if let Err(err) = conn.add_nat_traversal_address(*addr) {
1137 warn!("failed adding local addr: {err:#}",);
1138 }
1139 }
1140 for addr in noq_candidates.difference(direct_addrs) {
1141 if let Err(err) = conn.remove_nat_traversal_address(*addr) {
1142 warn!("failed removing local addr: {err:#}");
1143 }
1144 }
1145 trace!(?direct_addrs, "updated local QNT addresses");
1146}
1147
1148fn send_datagram<'a>(
1149 sender: &'a mut TransportsSender,
1150 addr: transports::FourTuple,
1151 owned_transmit: OwnedTransmit,
1152) -> impl Future<Output = n0_error::Result<()>> + 'a {
1153 std::future::poll_fn(move |cx| {
1154 let transmit = transports::Transmit {
1155 ecn: owned_transmit.ecn,
1156 contents: owned_transmit.contents.as_ref(),
1157 segment_size: owned_transmit.segment_size,
1158 };
1159
1160 Pin::new(&mut *sender)
1161 .poll_send(cx, &addr, &transmit)
1162 .map(|res| res.with_context(|_| format!("failed to send datagram to {:?}", addr)))
1163 })
1164}
1165
1166async fn send_datagram_to_targets(
1167 sender: Box<TransportsSender>,
1168 transmit: OwnedTransmit,
1169 targets: SmallVec<[transports::FourTuple; 8]>,
1170) {
1171 let mut sends = targets
1172 .into_iter()
1173 .map(|target| {
1174 let mut sender = sender.clone();
1175 let transmit = transmit.clone();
1176 async move {
1177 if let Err(err) = send_datagram(&mut sender, target.clone(), transmit).await {
1178 debug!(?target, "failed to send datagram: {err:#}");
1179 }
1180 }
1181 })
1182 .collect::<FuturesUnordered<_>>();
1183 while sends.next().await.is_some() {}
1184}
1185
1186#[derive(derive_more::Debug)]
1188pub(crate) enum RemoteStateMessage {
1189 #[debug("SendDatagram(..)")]
1198 SendDatagram(Box<TransportsSender>, OwnedTransmit),
1199 #[debug("AddConnection({})", _0.stable_id())]
1207 AddConnection(noq::Connection, oneshot::Sender<PathStateReceiver>),
1208 #[debug("ResolveRemote(..)")]
1217 ResolveRemote(
1218 BTreeSet<TransportAddr>,
1219 oneshot::Sender<Result<(), AddressLookupFailed>>,
1220 ),
1221 RemoteInfo(oneshot::Sender<RemoteInfo>),
1225 NetworkChange { is_major: bool },
1227}
1228
1229#[derive(Debug)]
1233struct HolepunchAttempt {
1234 when: Instant,
1235 local_candidates: BTreeSet<SocketAddr>,
1244 remote_candidates: BTreeSet<SocketAddr>,
1248}
1249
1250#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
1255#[display("{_0}")]
1256struct ConnId(usize);
1257
1258#[derive(Debug)]
1264struct ConnectionState {
1265 handle: WeakConnectionHandle,
1267 path_state: PathStateSender,
1273 paths: FxHashMap<PathId, transports::FourTuple>,
1282 has_been_direct: bool,
1286}
1287
1288impl ConnectionState {
1289 fn add_open_path(
1291 &mut self,
1292 network_path: transports::FourTuple,
1293 path_id: PathId,
1294 metrics: &Arc<SocketMetrics>,
1295 ) {
1296 match network_path {
1297 transports::FourTuple::Ip { .. } => metrics.paths_direct.inc(),
1298 transports::FourTuple::Relay { .. } => metrics.paths_relay.inc(),
1299 transports::FourTuple::Custom { .. } => metrics.paths_custom.inc(),
1300 };
1301 if !self.has_been_direct && network_path.is_ip() {
1302 self.has_been_direct = true;
1303 metrics.num_conns_direct.inc();
1304 }
1305
1306 self.paths.insert(path_id, network_path.clone());
1307 if let Some(conn) = self.handle.upgrade()
1308 && let Some(path) = conn.path(path_id)
1309 {
1310 let handle = path.weak_handle();
1311 self.path_state.record_opened(handle, network_path);
1312 }
1313 }
1314
1315 fn remove_path(
1317 &mut self,
1318 path_id: &PathId,
1319 conn: &noq::Connection,
1320 ) -> Option<transports::FourTuple> {
1321 let addr = self.paths.remove(path_id)?;
1322 self.path_state.record_abandoned(*path_id, conn);
1323 Some(addr)
1324 }
1325}
1326
1327#[derive(Debug)]
1332#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1333pub struct PathSelectionContext<'a> {
1334 current: Option<&'a transports::FourTuple>,
1335 source: PathsSource<'a>,
1336}
1337
1338#[derive(Debug)]
1341enum PathsSource<'a> {
1342 Live(&'a FxHashMap<ConnId, ConnectionState>),
1343 #[cfg(test)]
1344 Test(Vec<PathSelectionData<'a>>),
1345}
1346
1347#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1348impl<'a> PathSelectionContext<'a> {
1349 fn new(
1350 current: Option<&'a transports::FourTuple>,
1351 connections: &'a FxHashMap<ConnId, ConnectionState>,
1352 ) -> Self {
1353 Self {
1354 current,
1355 source: PathsSource::Live(connections),
1356 }
1357 }
1358
1359 #[cfg(test)]
1361 pub(crate) fn for_test(
1362 current: Option<&'a transports::FourTuple>,
1363 paths: Vec<PathSelectionData<'a>>,
1364 ) -> Self {
1365 Self {
1366 current,
1367 source: PathsSource::Test(paths),
1368 }
1369 }
1370
1371 pub fn current(&self) -> Option<&transports::FourTuple> {
1373 self.current
1374 }
1375
1376 pub fn paths(&self) -> Box<dyn Iterator<Item = PathSelectionData<'a>> + '_> {
1381 match &self.source {
1382 PathsSource::Live(connections) => Box::new(
1383 connections
1384 .values()
1385 .filter_map(|state| state.handle.upgrade().map(|conn| (state, conn)))
1386 .flat_map(|(state, conn)| {
1387 state.paths.iter().map(move |(path_id, addr)| {
1388 PathSelectionData::live(addr, *path_id, conn.clone())
1389 })
1390 }),
1391 ),
1392 #[cfg(test)]
1393 PathsSource::Test(paths) => Box::new(paths.iter().cloned()),
1394 }
1395 }
1396}
1397
1398#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1404#[derive(derive_more::Debug, Clone)]
1405pub struct PathSelectionData<'a> {
1406 network_path: &'a transports::FourTuple,
1407 #[debug(skip)]
1408 source: StatsSource,
1409}
1410
1411#[derive(Clone)]
1412enum StatsSource {
1413 Live {
1414 path_id: PathId,
1415 conn: noq::Connection,
1416 },
1417 #[cfg(test)]
1420 Test(Option<Box<PathStats>>),
1421}
1422
1423#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1424impl<'a> PathSelectionData<'a> {
1425 fn live(
1426 network_path: &'a transports::FourTuple,
1427 path_id: PathId,
1428 conn: noq::Connection,
1429 ) -> Self {
1430 Self {
1431 network_path,
1432 source: StatsSource::Live { path_id, conn },
1433 }
1434 }
1435
1436 #[cfg(test)]
1441 pub(crate) fn for_test(
1442 network_path: &'a transports::FourTuple,
1443 stats: Option<PathStats>,
1444 ) -> Self {
1445 Self {
1446 network_path,
1447 source: StatsSource::Test(stats.map(Box::new)),
1448 }
1449 }
1450
1451 pub fn network_path(&self) -> &transports::FourTuple {
1453 self.network_path
1454 }
1455
1456 pub fn stats(&self) -> Option<PathStats> {
1458 match &self.source {
1459 StatsSource::Live { path_id, conn } => conn.path_stats(*path_id),
1460 #[cfg(test)]
1461 StatsSource::Test(stats) => stats.as_deref().copied(),
1462 }
1463 }
1464}
1465
1466#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1470pub trait PathSelector: Send + Sync + std::fmt::Debug + 'static {
1471 fn select(&self, ctx: &PathSelectionContext<'_>) -> PathSelection;
1479}
1480
1481#[derive(Debug, Clone)]
1486#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1487pub struct PathSelection {
1488 selection: Option<transports::FourTuple>,
1489}
1490
1491#[cfg_attr(not(feature = "unstable-custom-transports"), allow(unreachable_pub))]
1492impl PathSelection {
1493 pub fn none() -> Self {
1495 Self { selection: None }
1496 }
1497
1498 pub fn set(&mut self, path: &PathSelectionData<'_>) {
1503 if self.selection.is_some() {
1504 tracing::warn!(
1505 path = %path.network_path(),
1506 "PathSelection already contains a path; ignoring additional path"
1507 );
1508 return;
1509 }
1510 self.selection = Some(path.network_path.clone());
1511 }
1512
1513 pub(crate) fn selected(&self) -> Option<&transports::FourTuple> {
1519 self.selection.as_ref()
1520 }
1521}
1522
1523struct OnClosed {
1528 conn_id: ConnId,
1529 inner: noq::OnClosed,
1530}
1531
1532impl OnClosed {
1533 fn new(conn: &noq::Connection) -> Self {
1534 Self {
1535 conn_id: ConnId(conn.stable_id()),
1536 inner: conn.on_closed(),
1537 }
1538 }
1539}
1540
1541impl Future for OnClosed {
1542 type Output = (ConnId, Closed);
1543
1544 fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1545 let closed = std::task::ready!(Pin::new(&mut self.inner).poll(cx));
1546 Poll::Ready((self.conn_id, closed))
1547 }
1548}
1549
1550fn to_transports_addr(
1552 endpoint_id: EndpointId,
1553 addrs: impl IntoIterator<Item = TransportAddr>,
1554) -> impl Iterator<Item = transports::Addr> {
1555 addrs.into_iter().filter_map(move |addr| match addr {
1556 TransportAddr::Relay(relay_url) => Some(transports::Addr::from((relay_url, endpoint_id))),
1557 TransportAddr::Ip(sockaddr) => Some(transports::Addr::from(sockaddr)),
1558 TransportAddr::Custom(custom_addr) => Some(transports::Addr::from(custom_addr)),
1559 _ => {
1560 warn!(?addr, "Unsupported TransportAddr");
1561 None
1562 }
1563 })
1564}
1565
1566async fn maybe_next<S: Stream + Unpin>(maybe_stream: Option<&mut S>) -> Option<Option<S::Item>> {
1568 match maybe_stream {
1569 None => None,
1570 Some(s) => Some(s.next().await),
1571 }
1572}
1573
1574#[cfg(all(test, not(wasm_browser)))]
1575mod tests {
1576 use super::*;
1577
1578 #[tokio::test]
1579 async fn blocked_relay_does_not_delay_direct_initial() {
1580 let receiver = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap();
1581 let (mut sender, _relay_receiver) = TransportsSender::with_bounded_relay(
1582 1,
1583 [transports::IpConfig::V4 {
1584 ip_net: "127.0.0.1/8".parse().unwrap(),
1585 port: 0,
1586 is_required: true,
1587 is_default: true,
1588 }]
1589 .into_iter(),
1590 );
1591 let relay = transports::FourTuple::Relay {
1592 url: "https://relay.example.invalid".parse().unwrap(),
1593 endpoint_id: iroh_base::SecretKey::from_bytes(&[1; 32]).public(),
1594 };
1595 let transmit = OwnedTransmit {
1596 ecn: None,
1597 contents: bytes::Bytes::from_static(b"initial"),
1598 segment_size: None,
1599 };
1600 send_datagram(&mut sender, relay.clone(), transmit.clone())
1601 .await
1602 .unwrap();
1603 let sends = send_datagram_to_targets(
1604 Box::new(sender),
1605 transmit,
1606 smallvec![
1607 relay,
1608 transports::FourTuple::from_remote(transports::Addr::Ip(
1609 receiver.local_addr().unwrap(),
1610 )),
1611 ],
1612 );
1613 let mut buf = [0; 64];
1614 tokio::select! {
1616 _ = sends => panic!("blocked Relay send unexpectedly completed"),
1617 received = time::timeout(Duration::from_secs(1), receiver.recv(&mut buf)) => {
1618 let len = received.expect("Direct send blocked behind Relay").unwrap();
1619 assert_eq!(&buf[..len], b"initial");
1620 }
1621 }
1622 }
1623}