iroh/socket/transports/relay/
actor.rs

1//! The relay actor.
2//!
3//! The [`RelayActor`] handles all the relay connections.  It is helped by the
4//! [`ActiveRelayActor`] which handles a single relay connection.
5//!
6//! - The [`RelayActor`] manages all connections to relay servers.
7//!   - It starts a new [`ActiveRelayActor`] for each relay server needed.
8//!   - The [`ActiveRelayActor`] will exit when unused.
9//!     - Unless it is for the home relay, this one never exits.
10//!   - Each [`ActiveRelayActor`] uses a relay [`Client`].
11//!     - The relay [`Client`] is a `Stream` and `Sink` directly connected to the
12//!       `TcpStream` connected to the relay server.
13//!   - Each [`ActiveRelayActor`] will try and maintain a connection with the relay server.
14//!     - If connections fail, exponential backoff is used for reconnections.
15//! - When `AsyncUdpSocket` needs to send datagrams:
16//!   - It puts them on a queue to the [`RelayActor`].
17//!   - The [`RelayActor`] ensures the correct [`ActiveRelayActor`] is running and
18//!     forwards datagrams to it.
19//!   - The ActiveRelayActor sends datagrams directly to the relay server.
20//! - The relay receive path is:
21//!   - Whenever [`ActiveRelayActor`] is connected it reads from the underlying `TcpStream`.
22//!   - Received datagrams are placed on an mpsc channel that now bypasses the
23//!     [`RelayActor`] and goes straight to the `AsyncUpdSocket` interface.
24//!
25//! [`Client`]: iroh_relay::client::Client
26
27#[cfg(test)]
28use std::net::SocketAddr;
29use std::{
30    collections::{BTreeMap, BTreeSet},
31    future::Future,
32    net::IpAddr,
33    pin::{Pin, pin},
34    sync::{
35        Arc,
36        atomic::{AtomicBool, Ordering},
37    },
38};
39
40use backon::{Backoff, BackoffBuilder, ExponentialBuilder};
41use iroh_base::{EndpointId, RelayUrl, SecretKey};
42use iroh_relay::{
43    self as relay, PingTracker, RelayMap,
44    client::{Client, ConnectError, RecvError, SendError},
45    protos::{
46        handshake,
47        relay::{ClientToRelayMsg, Datagrams, RelayToClientMsg, Status},
48    },
49};
50use n0_error::{AnyError, e, stack_error};
51use n0_future::{
52    FuturesUnorderedBounded, MaybeFuture, SinkExt, StreamExt,
53    task::{JoinError, JoinSet},
54    time::{self, Duration, Instant, MissedTickBehavior},
55};
56use n0_watcher::Watchable;
57use netwatch::interfaces;
58use tokio::sync::{mpsc, oneshot};
59use tokio_util::sync::CancellationToken;
60use tracing::{Instrument, Level, debug, error, event, info, info_span, instrument, trace, warn};
61use url::Url;
62
63#[cfg(not(wasm_browser))]
64use crate::dns::DnsResolver;
65use crate::{endpoint::RelayStatus, net_report::Report, socket::Metrics as SocketMetrics};
66
67/// How long a non-home relay connection needs to be idle (last written to) before we close it.
68const RELAY_INACTIVE_CLEANUP_TIME: Duration = Duration::from_secs(60);
69
70/// Interval in which we ping the relay server to ensure the connection is alive.
71///
72/// The default QUIC max_idle_timeout is 30s, so setting that to half this time gives some
73/// chance of recovering.
74const PING_INTERVAL: Duration = Duration::from_secs(15);
75
76/// Number of datagrams which can be sent to the relay server in one batch.
77///
78/// This means while this batch is sending to the server no other relay protocol frames can
79/// be sent to the server, e.g. no Ping frames or so.  While the maximum packet size is
80/// rather large, each item can typically be expected to up to 1500 or the max GSO size.
81const SEND_DATAGRAM_BATCH_SIZE: usize = 20;
82
83/// Timeout for establishing the relay connection.
84///
85/// This includes DNS, dialing the server, upgrading the connection, and completing the
86/// handshake.
87const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
88
89/// Time after which the [`ActiveRelayActor`] will drop undeliverable datagrams.
90///
91/// When the [`ActiveRelayActor`] is not connected it can not deliver datagrams.  However it
92/// will still receive datagrams to send from the [`RelayActor`].  If connecting takes
93/// longer than this timeout datagrams will be dropped.
94///
95/// This value is set to 3 times the QUIC initial Probe Timeout (PTO).
96const UNDELIVERABLE_DATAGRAM_TIMEOUT: Duration = Duration::from_secs(3);
97
98/// Timeout for closing the relay connection gracefully.
99///
100/// Must stay below the time the [`RelayActor`] waits for its [`ActiveRelayActor`]s to shut down.
101const CLOSE_TIMEOUT: Duration = Duration::from_secs(1);
102
103/// An actor which handles the connection to a single relay server.
104///
105/// It is responsible for maintaining the connection to the relay server and handling all
106/// communication with it.
107///
108/// The actor shuts down itself on inactivity: inactivity is determined when no more
109/// datagrams are being queued to send.
110///
111/// This actor has 3 main states it can be in, each has it's dedicated run loop:
112///
113/// - Dialing the relay server.
114///
115///   This will continuously dial the server until connected, using exponential backoff if
116///   it can not connect.  See [`ActiveRelayActor::run_dialing`].
117///
118/// - Connected to the relay server.
119///
120///   This state allows receiving from the relay server, though sending is idle in this
121///   state.  See [`ActiveRelayActor::run_connected`].
122///
123/// - Sending to the relay server.
124///
125///   This is a sub-state of `connected` so the actor can still be receiving from the relay
126///   server at this time.  However it is actively sending data to the server so can not
127///   consume any further items from inboxes which will result in sending more data to the
128///   server until the actor goes back to the `connected` state.
129///
130/// All these are driven from the top-level [`ActiveRelayActor::run`] loop.
131#[derive(Debug)]
132struct ActiveRelayActor {
133    // The inboxes and channels this actor communicates over.
134    /// Inbox for messages which should be handled without any blocking.
135    prio_inbox: mpsc::Receiver<ActiveRelayPrioMessage>,
136    /// Inbox for messages which involve sending to the relay server.
137    inbox: mpsc::Receiver<ActiveRelayMessage>,
138    /// Queue for received relay datagrams.
139    relay_datagrams_recv: mpsc::Sender<RelayRecvDatagram>,
140    /// Channel on which we queue packets to send to the relay.
141    relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
142
143    // Other actor state.
144    /// The relay server for this actor.
145    url: RelayUrl,
146    /// Builder which can repeatedly build a relay client.
147    relay_client_builder: relay::client::ClientBuilder,
148    /// Whether or not this is the home relay server.
149    ///
150    /// The home relay server needs to maintain it's connection to the relay server, even if
151    /// the relay actor is otherwise idle.
152    is_home_relay: bool,
153    /// When this expires the actor has been idle and should shut down.
154    ///
155    /// Unless it is managing the home relay connection.  Inactivity is only tracked on the
156    /// last datagram sent to the relay, received datagrams will trigger QUIC ACKs which is
157    /// sufficient to keep active connections open.
158    inactive_timeout: Pin<Box<time::Sleep>>,
159    /// Token indicating the [`ActiveRelayActor`] should stop.
160    stop_token: CancellationToken,
161    metrics: Arc<SocketMetrics>,
162    my_relay: HomeRelayWatch,
163}
164
165#[derive(Debug)]
166enum ActiveRelayMessage {
167    /// Triggers a connection check to the relay server.
168    ///
169    /// Sometimes it is known the local network interfaces have changed in which case it
170    /// might be prudent to check if the relay connection is still working.  `Vec<IpAddr>`
171    /// should contain the current local IP addresses.  If the connection uses a local
172    /// socket with an IP address in this list the relay server will be pinged.  If the
173    /// connection uses a local socket with an IP address not in this list the server will
174    /// always re-connect.
175    CheckConnection { local_ips: Vec<IpAddr> },
176    /// Sets this relay as the home relay, or not.
177    SetHomeRelay(bool),
178    #[cfg(test)]
179    GetLocalAddr(oneshot::Sender<Option<SocketAddr>>),
180    #[cfg(test)]
181    PingServer(oneshot::Sender<()>),
182}
183
184/// Messages for the [`ActiveRelayActor`] which should never block.
185///
186/// Most messages in the [`ActiveRelayMessage`] enum trigger sending to the relay server,
187/// which can be blocking.  So the actor may not always be processing that inbox.  Messages
188/// here are processed immediately.
189#[derive(Debug)]
190enum ActiveRelayPrioMessage {
191    /// Returns whether or not this relay can reach the EndpointId.
192    HasEndpointRoute(EndpointId, oneshot::Sender<bool>),
193}
194
195/// Configuration needed to start an [`ActiveRelayActor`].
196#[derive(Debug)]
197struct ActiveRelayActorOptions {
198    url: RelayUrl,
199    prio_inbox_: mpsc::Receiver<ActiveRelayPrioMessage>,
200    inbox: mpsc::Receiver<ActiveRelayMessage>,
201    relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
202    relay_datagrams_recv: mpsc::Sender<RelayRecvDatagram>,
203    connection_opts: RelayConnectionOptions,
204    stop_token: CancellationToken,
205    metrics: Arc<SocketMetrics>,
206    my_relay: HomeRelayWatch,
207}
208
209/// Configuration needed to create a connection to a relay server.
210#[derive(Debug, Clone)]
211struct RelayConnectionOptions {
212    secret_key: SecretKey,
213    #[cfg(not(wasm_browser))]
214    dns_resolver: DnsResolver,
215    proxy_url: Option<Url>,
216    prefer_ipv6: Arc<AtomicBool>,
217    tls_config: rustls::ClientConfig,
218    auth_token: Option<String>,
219}
220
221/// Possible reasons for a failed relay connection.
222#[allow(missing_docs)]
223#[stack_error(derive, add_meta)]
224enum RelayConnectionError {
225    #[error("Failed to connect to relay server")]
226    Dial { source: DialError },
227    #[error("Failed to handshake with relay server")]
228    Handshake { source: RunError },
229    #[error("Lost connection to relay server")]
230    Established { source: RunError },
231}
232
233#[allow(missing_docs)]
234#[stack_error(derive, add_meta)]
235enum RunError {
236    #[error("Send timeout")]
237    SendTimeout,
238    #[error("Ping timeout")]
239    PingTimeout,
240    #[error("Local IP no longer valid")]
241    LocalIpInvalid,
242    #[error("No local address")]
243    LocalAddrMissing,
244    #[error("Stream closed by server.")]
245    StreamClosedServer,
246    #[error("Client stream read failed")]
247    ClientStreamRead {
248        #[error(std_err)]
249        source: RecvError,
250    },
251    #[error("Client stream write failed")]
252    ClientStreamWrite {
253        #[error(std_err)]
254        source: SendError,
255    },
256}
257
258#[allow(missing_docs)]
259#[stack_error(derive, add_meta)]
260enum DialError {
261    #[error("timeout (>{timeout:?}) trying to establish a connection")]
262    Timeout { timeout: Duration },
263    #[error("unable to connect")]
264    Connect { source: ConnectError },
265}
266
267impl ActiveRelayActor {
268    fn new(opts: ActiveRelayActorOptions) -> Self {
269        let ActiveRelayActorOptions {
270            url,
271            prio_inbox_: prio_inbox,
272            inbox,
273            relay_datagrams_send,
274            relay_datagrams_recv,
275            connection_opts,
276            stop_token,
277            metrics,
278            my_relay,
279        } = opts;
280        let relay_client_builder = Self::create_relay_builder(url.clone(), connection_opts);
281        ActiveRelayActor {
282            prio_inbox,
283            inbox,
284            relay_datagrams_recv,
285            relay_datagrams_send,
286            url,
287            relay_client_builder,
288            is_home_relay: false,
289            inactive_timeout: Box::pin(time::sleep(RELAY_INACTIVE_CLEANUP_TIME)),
290            stop_token,
291            metrics,
292            my_relay,
293        }
294    }
295
296    fn create_relay_builder(
297        url: RelayUrl,
298        opts: RelayConnectionOptions,
299    ) -> relay::client::ClientBuilder {
300        let RelayConnectionOptions {
301            secret_key,
302            #[cfg(not(wasm_browser))]
303            dns_resolver,
304            proxy_url,
305            prefer_ipv6,
306            tls_config,
307            auth_token,
308        } = opts;
309
310        let mut builder = relay::client::ClientBuilder::new(
311            url,
312            secret_key,
313            #[cfg(not(wasm_browser))]
314            dns_resolver,
315        )
316        .tls_client_config(tls_config)
317        .address_family_selector(move || prefer_ipv6.load(Ordering::Relaxed));
318        if let Some(proxy_url) = proxy_url {
319            builder = builder.proxy_url(proxy_url);
320        }
321
322        if let Some(token) = auth_token {
323            builder = builder.auth_token(token);
324        }
325        builder
326    }
327
328    /// The main actor run loop.
329    ///
330    /// Primarily switches between the dialing and connected states.
331    async fn run(mut self) {
332        let mut backoff = Self::build_backoff();
333
334        while let Err(err) = self.run_once().await {
335            debug!("{err:#}");
336            let was_established = matches!(err, RelayConnectionError::Established { .. });
337            let last_failure = Some(Arc::new(RelayConnectionFailure::new(err)));
338            self.my_relay.set_status(
339                &self.url,
340                RelayConnectionState::Disconnected { last_failure },
341            );
342            if !was_established {
343                // If dialing failed, or if the relay connection failed before we received a pong,
344                // we wait an exponentially increasing time until we attempt to reconnect again.
345                let Some(delay) = backoff.next() else {
346                    debug!("retries exceeded");
347                    break;
348                };
349                debug!("retry in {delay:?}");
350                if !self.sleep_backoff(delay).await {
351                    break;
352                }
353            } else {
354                // If the relay connection remained established long enough so that we received a pong
355                // from the relay server, we reset the backoff and attempt to reconnect immediately.
356                backoff = Self::build_backoff();
357            }
358        }
359        debug!("exiting");
360    }
361
362    /// Waits out a reconnect backoff delay while still answering priority messages.
363    ///
364    /// Other active relays may query [`ActiveRelayPrioMessage::HasEndpointRoute`] on this
365    /// relay while it is backing off, e.g. when [`RelayActor`] is looking for an existing
366    /// relay connection to an endpoint. Answering immediately (with `false`, since a
367    /// disconnected relay cannot have an endpoint route) keeps that lookup from stalling
368    /// for however long is left of this relay's own unrelated backoff.
369    ///
370    /// The inbox and the inactivity timeout are served as in [`Self::run_dialing`], whose
371    /// dial can fail before it gets to them.
372    ///
373    /// Returns `false` if the actor should shut down instead of retrying.
374    async fn sleep_backoff(&mut self, delay: Duration) -> bool {
375        let sleep = time::sleep(delay);
376        tokio::pin!(sleep);
377        loop {
378            tokio::select! {
379                biased;
380                _ = self.stop_token.cancelled() => {
381                    debug!("Shutdown.");
382                    return false;
383                }
384                msg = self.prio_inbox.recv() => {
385                    let Some(msg) = msg else {
386                        warn!("Priority inbox closed, shutdown.");
387                        return false;
388                    };
389                    match msg {
390                        ActiveRelayPrioMessage::HasEndpointRoute(_peer, sender) => {
391                            sender.send(false).ok();
392                        }
393                    }
394                }
395                msg = self.inbox.recv() => {
396                    let Some(msg) = msg else {
397                        debug!("Inbox closed, shutdown.");
398                        return false;
399                    };
400                    self.handle_msg_while_disconnected(msg);
401                }
402                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
403                    debug!(?RELAY_INACTIVE_CLEANUP_TIME, "Inactive, exiting.");
404                    return false;
405                }
406                _ = &mut sleep => return true,
407            }
408        }
409    }
410
411    /// Handles an inbox message while not connected to the relay server.
412    fn handle_msg_while_disconnected(&mut self, msg: ActiveRelayMessage) {
413        match msg {
414            ActiveRelayMessage::SetHomeRelay(is_home) => {
415                self.set_home_relay(is_home);
416            }
417            ActiveRelayMessage::CheckConnection { .. } => {}
418            #[cfg(test)]
419            ActiveRelayMessage::GetLocalAddr(sender) => {
420                sender.send(None).ok();
421            }
422            #[cfg(test)]
423            ActiveRelayMessage::PingServer(sender) => {
424                drop(sender);
425            }
426        }
427    }
428
429    fn build_backoff() -> impl Backoff {
430        ExponentialBuilder::new()
431            .with_min_delay(Duration::from_millis(10))
432            .with_max_delay(Duration::from_secs(16))
433            .with_jitter()
434            .without_max_times()
435            .build()
436    }
437
438    /// Attempt to connect to the relay, and run the connected actor loop.
439    ///
440    /// Returns `Ok(())` if the actor loop should shut down. Returns an error if dialing failed,
441    /// or if the relay connection failed while connected. In both cases, the connection should
442    /// be retried with a backoff.
443    #[allow(clippy::result_large_err)]
444    async fn run_once(&mut self) -> Result<(), RelayConnectionError> {
445        self.my_relay
446            .set_status(&self.url, RelayConnectionState::Connecting);
447        let client = match self.run_dialing().instrument(info_span!("dialing")).await {
448            Some(Ok(client)) => client,
449            Some(Err(err)) => {
450                self.metrics.relay_conns_failed.inc();
451                return Err(e!(RelayConnectionError::Dial, err));
452            }
453            None => return Ok(()),
454        };
455        self.my_relay
456            .set_status(&self.url, RelayConnectionState::Connected);
457        self.metrics.relay_conns_success.inc();
458        let res = self
459            .run_connected(client)
460            .instrument(info_span!("connected"))
461            .await;
462        self.metrics.relay_conns_closed.inc();
463        res
464    }
465
466    fn reset_inactive_timeout(&mut self) {
467        self.inactive_timeout
468            .as_mut()
469            .reset(Instant::now() + RELAY_INACTIVE_CLEANUP_TIME);
470    }
471
472    fn set_home_relay(&mut self, is_home: bool) {
473        let prev = std::mem::replace(&mut self.is_home_relay, is_home);
474        if self.is_home_relay != prev {
475            event!(
476                target: "iroh::_events::relay::home_changed",
477                Level::DEBUG,
478                url = %self.url,
479                home_relay = self.is_home_relay,
480            );
481        }
482    }
483
484    /// Actor loop when connecting to the relay server.
485    ///
486    /// Returns `None` if the actor needs to shut down.  Returns `Some(Ok(client))` when the
487    /// connection is established, and `Some(Err(err))` if dialing the relay failed.
488    async fn run_dialing(&mut self) -> Option<Result<iroh_relay::client::Client, DialError>> {
489        trace!("Actor loop: connecting to relay.");
490
491        // We regularly flush the relay_datagrams_send queue so it is not full of stale
492        // packets while reconnecting.  Those datagrams are dropped and the QUIC congestion
493        // controller will have to handle this (DISCO packets do not yet have retry).  This
494        // is not an ideal mechanism, an alternative approach would be to use
495        // e.g. ConcurrentQueue with force_push, though now you might still send very stale
496        // packets when eventually connected.  So perhaps this is a reasonable compromise.
497        let mut send_datagram_flush = time::interval(UNDELIVERABLE_DATAGRAM_TIMEOUT);
498        send_datagram_flush.set_missed_tick_behavior(MissedTickBehavior::Delay);
499        send_datagram_flush.reset(); // Skip the immediate interval
500
501        let dialing_fut = self.dial_relay();
502        tokio::pin!(dialing_fut);
503        loop {
504            tokio::select! {
505                biased;
506                _ = self.stop_token.cancelled() => {
507                    debug!("Shutdown.");
508                    break None;
509                }
510                msg = self.prio_inbox.recv() => {
511                    let Some(msg) = msg else {
512                        warn!("Priority inbox closed, shutdown.");
513                        break None;
514                    };
515                    match msg {
516                        ActiveRelayPrioMessage::HasEndpointRoute(_peer, sender) => {
517                            sender.send(false).ok();
518                        }
519                    }
520                }
521                res = &mut dialing_fut => {
522                    match res {
523                        Ok(client) => {
524                            break Some(Ok(client));
525                        }
526                        Err(err) => {
527                            break Some(Err(err));
528                        }
529                    }
530                }
531                msg = self.inbox.recv() => {
532                    let Some(msg) = msg else {
533                        debug!("Inbox closed, shutdown.");
534                        break None;
535                    };
536                    self.handle_msg_while_disconnected(msg);
537                }
538                _ = send_datagram_flush.tick() => {
539                    self.reset_inactive_timeout();
540                    let mut logged = false;
541                    while self.relay_datagrams_send.try_recv().is_ok() {
542                        if !logged {
543                            debug!(?UNDELIVERABLE_DATAGRAM_TIMEOUT, "Dropping datagrams to send.");
544                            logged = true;
545                        }
546                    }
547                }
548                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
549                    debug!(?RELAY_INACTIVE_CLEANUP_TIME, "Inactive, exiting.");
550                    break None;
551                }
552            }
553        }
554    }
555
556    /// Returns a future which will complete once connected to the relay server.
557    ///
558    /// The future only completes once the connection is established and retries
559    /// connections.  It currently does not ever return `Err` as the retries continue
560    /// forever.
561    // This is using `impl Future` to return a future without a reference to self.
562    fn dial_relay(&self) -> impl Future<Output = Result<Client, DialError>> + use<> {
563        let client_builder = self.relay_client_builder.clone();
564        async move {
565            match time::timeout(CONNECT_TIMEOUT, client_builder.connect()).await {
566                Ok(Ok(client)) => Ok(client),
567                Ok(Err(err)) => Err(e!(DialError::Connect, err)),
568                Err(_) => Err(e!(DialError::Timeout {
569                    timeout: CONNECT_TIMEOUT
570                })),
571            }
572        }
573    }
574
575    /// Runs the actor loop when connected to a relay server.
576    ///
577    /// Returns `Ok` if the actor needs to shut down.  `Err` is returned if the connection
578    /// to the relay server is lost.
579    #[allow(clippy::result_large_err)]
580    async fn run_connected(
581        &mut self,
582        client: iroh_relay::client::Client,
583    ) -> Result<(), RelayConnectionError> {
584        trace!("Actor loop: connected to relay");
585        event!(
586            target: "iroh::_events::relay::connected",
587            Level::DEBUG,
588            url = %self.url,
589            home_relay = self.is_home_relay,
590        );
591
592        let (mut client_stream, client_sink) = client.split();
593        let mut client_sink = client_sink.sink_map_err(|e| e!(RunError::ClientStreamWrite, e));
594
595        let mut state = ConnectedRelayState {
596            ping_tracker: PingTracker::default(),
597            endpoints_present: BTreeSet::new(),
598            last_packet_src: None,
599            pong_pending: None,
600            established: false,
601            rate_limited: false,
602            #[cfg(test)]
603            test_pong: None,
604        };
605
606        // A buffer to pass through multiple datagrams at once as an optimisation.
607        let mut send_datagrams_buf = Vec::with_capacity(SEND_DATAGRAM_BATCH_SIZE);
608
609        // Regularly send pings so we know the connection is healthy.
610        // The first ping will be sent immediately.
611        let mut ping_interval = time::interval(PING_INTERVAL);
612        ping_interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
613
614        let res = loop {
615            if let Some(data) = state.pong_pending.take() {
616                let fut = client_sink.send(ClientToRelayMsg::Pong(data));
617                self.run_sending(fut, &mut state, &mut client_stream)
618                    .await?;
619            }
620            tokio::select! {
621                biased;
622                _ = self.stop_token.cancelled() => {
623                    debug!("Shutdown.");
624                    break Ok(());
625                }
626                msg = self.prio_inbox.recv() => {
627                    let Some(msg) = msg else {
628                        warn!("Priority inbox closed, shutdown.");
629                        break Ok(());
630                    };
631                    match msg {
632                        ActiveRelayPrioMessage::HasEndpointRoute(peer, sender) => {
633                            let has_peer = state.endpoints_present.contains(&peer);
634                            sender.send(has_peer).ok();
635                        }
636                    }
637                }
638                _ = state.ping_tracker.timeout() => {
639                    break Err(e!(RunError::PingTimeout));
640                }
641                _ = ping_interval.tick() => {
642                    let data = state.ping_tracker.new_ping();
643                    let fut = client_sink.send(ClientToRelayMsg::Ping(data));
644                    self.run_sending(fut, &mut state, &mut client_stream).await?;
645                }
646                msg = self.inbox.recv() => {
647                    let Some(msg) = msg else {
648                        warn!("Inbox closed, shutdown.");
649                        break Ok(());
650                    };
651                    match msg {
652                        ActiveRelayMessage::SetHomeRelay(is_home) => {
653                            self.set_home_relay(is_home);
654                            // We are in `run_connected`, so if we just became the home
655                            // relay, publish `Connected` (the `RelayActor` only sets
656                            // `Connecting` on the URL change since it cannot know our
657                            // actual state).
658                            if is_home {
659                                self.my_relay
660                                    .set_status(&self.url, RelayConnectionState::Connected);
661                            }
662                        }
663                        ActiveRelayMessage::CheckConnection { local_ips } => {
664                            match client_stream.local_addr() {
665                                Some(addr) if local_ips.contains(&addr.ip()) => {
666                                    let data = state.ping_tracker.new_ping();
667                                    let fut = client_sink.send(ClientToRelayMsg::Ping(data));
668                                    self.run_sending(fut, &mut state, &mut client_stream).await?;
669                                }
670                                Some(_) => break Err(e!(RunError::LocalIpInvalid)),
671                                None => break Err(e!(RunError::LocalAddrMissing)),
672                            }
673                        }
674                        #[cfg(test)]
675                        ActiveRelayMessage::GetLocalAddr(sender) => {
676                            let addr = client_stream.local_addr();
677                            sender.send(addr).ok();
678                        }
679                        #[cfg(test)]
680                        ActiveRelayMessage::PingServer(sender) => {
681                            let data = rand::random();
682                            state.test_pong = Some((data, sender));
683                            let fut = client_sink.send(ClientToRelayMsg::Ping(data));
684                            self.run_sending(fut, &mut state, &mut client_stream).await?;
685                        }
686                    }
687                }
688                count = self.relay_datagrams_send.recv_many(
689                    &mut send_datagrams_buf,
690                    SEND_DATAGRAM_BATCH_SIZE,
691                ) => {
692                    if count == 0 {
693                        warn!("Datagram inbox closed, shutdown");
694                        break Ok(());
695                    };
696                    self.reset_inactive_timeout();
697                    // TODO(frando): can we avoid the clone here?
698                    let metrics = self.metrics.clone();
699                    let packet_iter = send_datagrams_buf.drain(..).map(|item| {
700                        metrics.send_relay.inc_by(item.datagrams.contents.len() as _);
701                        Ok(ClientToRelayMsg::Datagrams {
702                            dst_endpoint_id: item.remote_endpoint,
703                            datagrams: item.datagrams,
704                        })
705                    });
706                    let mut packet_stream = n0_future::stream::iter(packet_iter);
707                    let fut = client_sink.send_all(&mut packet_stream);
708                    self.run_sending(fut, &mut state, &mut client_stream).await?;
709                }
710                msg = client_stream.next() => {
711                    let Some(msg) = msg else {
712                        break Err(e!(RunError::StreamClosedServer));
713                    };
714                    match msg {
715                        Ok(msg) => {
716                            self.handle_relay_msg(msg, &mut state);
717                            // reset the ping timer, we have just received a message
718                            ping_interval.reset();
719                        },
720                        Err(err) => break Err(e!(RunError::ClientStreamRead, err)),
721                    }
722                }
723                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
724                    debug!("Inactive for {RELAY_INACTIVE_CLEANUP_TIME:?}, exiting (running).");
725                    break Ok(());
726                }
727            }
728        };
729
730        if res.is_ok() {
731            self.run_closing(client_sink.close()).await;
732        }
733
734        res.map_err(|err| state.map_err(err))
735    }
736
737    /// Closes the relay connection, answering priority messages until it closes or
738    /// [`CLOSE_TIMEOUT`] passes.
739    async fn run_closing(&mut self, close: impl Future<Output = Result<(), RunError>>) {
740        let mut close = pin!(time::timeout(CLOSE_TIMEOUT, close));
741        loop {
742            tokio::select! {
743                biased;
744                res = &mut close => {
745                    match res {
746                        Ok(Ok(())) => {}
747                        Ok(Err(err)) => debug!("Failed to close client sink gracefully: {err:#}"),
748                        Err(_) => debug!("Relay server did not close within {CLOSE_TIMEOUT:?}."),
749                    }
750                    return;
751                }
752                Some(msg) = self.prio_inbox.recv() => {
753                    match msg {
754                        ActiveRelayPrioMessage::HasEndpointRoute(_peer, sender) => {
755                            sender.send(false).ok();
756                        }
757                    }
758                }
759            }
760        }
761    }
762
763    fn handle_relay_msg(&mut self, msg: RelayToClientMsg, state: &mut ConnectedRelayState) {
764        match msg {
765            RelayToClientMsg::Datagrams {
766                remote_endpoint_id,
767                datagrams,
768            } => {
769                trace!(len = datagrams.contents.len(), "received msg");
770                // If this is a new sender, register a route for this peer.
771                if state
772                    .last_packet_src
773                    .as_ref()
774                    .map(|p| *p != remote_endpoint_id)
775                    .unwrap_or(true)
776                {
777                    // Avoid map lookup with high throughput single peer.
778                    state.last_packet_src = Some(remote_endpoint_id);
779                    state.endpoints_present.insert(remote_endpoint_id);
780                }
781
782                if let Err(err) = self.relay_datagrams_recv.try_send(RelayRecvDatagram {
783                    url: self.url.clone(),
784                    src: remote_endpoint_id,
785                    datagrams,
786                }) {
787                    warn!("Dropping received relay packet: {err:#}");
788                }
789            }
790            RelayToClientMsg::EndpointGone(endpoint_id) => {
791                state.endpoints_present.remove(&endpoint_id);
792            }
793            RelayToClientMsg::Ping(data) => state.pong_pending = Some(data),
794            RelayToClientMsg::Pong(data) => {
795                #[cfg(test)]
796                {
797                    if let Some((expected_data, sender)) = state.test_pong.take() {
798                        if data == expected_data {
799                            sender.send(()).ok();
800                        } else {
801                            state.test_pong = Some((expected_data, sender));
802                        }
803                    }
804                }
805                state.ping_tracker.pong_received(data);
806                state.established = true;
807            }
808            RelayToClientMsg::Status(status) => match status {
809                Status::Healthy => info!("Relay server reports: {status}"),
810                Status::RateLimited => {
811                    warn!("{status}");
812                    // The relay sends this at most once per connection, but do not rely
813                    // on the remote for the metric to count connections.
814                    if !state.rate_limited {
815                        state.rate_limited = true;
816                        self.metrics.relay_conns_ratelimited.inc();
817                    }
818                }
819                _ => warn!("Relay server reports problem: {status}"),
820            },
821            RelayToClientMsg::Restarting { .. } => {
822                trace!("Ignoring {msg:?}")
823            }
824            // Deprecated variants, kept for backwards compatibility with older relay protocol versions.
825            RelayToClientMsg::Health { problem } => {
826                warn!("Relay server reports problem: {problem}");
827            }
828            _ => unreachable!(
829                "got unknown RelayToClientMsg but iroh is released in sync with iroh-relay"
830            ),
831        }
832    }
833
834    /// Run the actor main loop while sending to the relay server.
835    ///
836    /// While sending the actor should not read any inboxes which will give it more things
837    /// to send to the relay server.
838    ///
839    /// # Returns
840    ///
841    /// On `Err` the relay connection should be disconnected.  An `Ok` return means either
842    /// the actor should shut down, consult the [`ActiveRelayActor::stop_token`] and
843    /// [`ActiveRelayActor::inactive_timeout`] for this, or the send was successful.
844    #[instrument(name = "tx", skip_all)]
845    #[allow(clippy::result_large_err)]
846    async fn run_sending<T>(
847        &mut self,
848        sending_fut: impl Future<Output = Result<T, RunError>>,
849        state: &mut ConnectedRelayState,
850        client_stream: &mut iroh_relay::client::ClientStream,
851    ) -> Result<(), RelayConnectionError> {
852        // we use the same time as for our ping interval
853        let send_timeout = PING_INTERVAL;
854
855        let mut timeout = pin!(time::sleep(send_timeout));
856        let mut sending_fut = pin!(sending_fut);
857        let res = loop {
858            tokio::select! {
859                biased;
860                _ = self.stop_token.cancelled() => {
861                    break Ok(());
862                }
863                _ = &mut timeout => {
864                    break Err(e!(RunError::SendTimeout));
865                }
866                msg = self.prio_inbox.recv() => {
867                    let Some(msg) = msg else {
868                        warn!("Priority inbox closed, shutdown.");
869                        break Ok(());
870                    };
871                    match msg {
872                        ActiveRelayPrioMessage::HasEndpointRoute(peer, sender) => {
873                            let has_peer = state.endpoints_present.contains(&peer);
874                            sender.send(has_peer).ok();
875                        }
876                    }
877                }
878                res = &mut sending_fut => {
879                    match res {
880                        Ok(_) => break Ok(()),
881                        Err(err) => break Err(err),
882                    }
883                }
884                _ = state.ping_tracker.timeout() => {
885                    break Err(e!(RunError::PingTimeout));
886                }
887                // No need to read the inbox or datagrams to send.
888                msg = client_stream.next() => {
889                    let Some(msg) = msg else {
890                        break Err(e!(RunError::StreamClosedServer));
891                    };
892                    match msg {
893                        Ok(msg) => self.handle_relay_msg(msg, state),
894                        Err(err) => break Err(e!(RunError::ClientStreamRead, err)),
895                    }
896                }
897                _ = &mut self.inactive_timeout, if !self.is_home_relay => {
898                    debug!("Inactive for {RELAY_INACTIVE_CLEANUP_TIME:?}, exiting (sending).");
899                    break Ok(());
900                }
901            }
902        };
903        res.map_err(|err| state.map_err(err))
904    }
905}
906
907/// Shared state when the [`ActiveRelayActor`] is connected to a relay server.
908///
909/// Common state between [`ActiveRelayActor::run_connected`] and
910/// [`ActiveRelayActor::run_sending`].
911#[derive(Debug)]
912struct ConnectedRelayState {
913    /// Tracks pings we have sent, awaits pong replies.
914    ping_tracker: PingTracker,
915    /// Endpoints which are reachable via this relay server.
916    endpoints_present: BTreeSet<EndpointId>,
917    /// The [`EndpointId`] from whom we received the last packet.
918    ///
919    /// This is to avoid a slower lookup in the [`ConnectedRelayState::endpoints_present`] map
920    /// when we are only communicating to a single remote endpoint.
921    last_packet_src: Option<EndpointId>,
922    /// A pong we need to send ASAP.
923    pong_pending: Option<[u8; 8]>,
924    /// Whether the connection is to be considered established.
925    ///
926    /// This is set to `true` once a pong was received from the server.
927    established: bool,
928    /// Whether the relay reported that it is rate-limiting this connection.
929    ///
930    /// Used to count each affected connection only once.
931    rate_limited: bool,
932    #[cfg(test)]
933    test_pong: Option<([u8; 8], oneshot::Sender<()>)>,
934}
935
936impl ConnectedRelayState {
937    fn map_err(&self, error: RunError) -> RelayConnectionError {
938        if self.established {
939            e!(RelayConnectionError::Established, error)
940        } else {
941            e!(RelayConnectionError::Handshake, error)
942        }
943    }
944}
945
946pub(super) enum RelayActorMessage {
947    MaybeCloseRelaysOnRebind,
948    NetworkChange {
949        report: Report,
950    },
951    /// Trigger an immediate health check on all relay connections.
952    ///
953    /// Sent after a major network change to detect broken connections faster
954    /// using RTT-based timeouts instead of the default 5s ping timeout.
955    CheckConnectionAfterNetworkChange,
956}
957
958#[derive(Debug, Clone)]
959pub(crate) struct RelaySendItem {
960    /// The destination for the datagrams.
961    pub(crate) remote_endpoint: EndpointId,
962    /// The home relay of the remote endpoint.
963    pub(crate) url: RelayUrl,
964    /// One or more datagrams to send.
965    pub(crate) datagrams: Datagrams,
966}
967
968pub(super) struct RelayActor {
969    config: Config,
970    /// Queue on which to put received datagrams.
971    relay_datagram_recv_queue: mpsc::Sender<RelayRecvDatagram>,
972    /// The actors managing each currently used relay server.
973    ///
974    /// These actors will exit when they have any inactivity.  Otherwise they will keep
975    /// trying to maintain a connection to the relay server as needed.
976    active_relays: BTreeMap<RelayUrl, ActiveRelayHandle>,
977    /// The tasks for the [`ActiveRelayActor`]s in `active_relays` above.
978    active_relay_tasks: JoinSet<()>,
979    cancel_token: CancellationToken,
980}
981
982#[derive(Debug, Clone)]
983pub(crate) struct Config {
984    pub my_relay: HomeRelayWatch,
985    pub secret_key: SecretKey,
986    #[cfg(not(wasm_browser))]
987    pub dns_resolver: DnsResolver,
988    /// Proxy
989    pub proxy_url: Option<Url>,
990    /// If the last net_report report, reports IPv6 to be available.
991    pub ipv6_reported: Arc<AtomicBool>,
992    pub tls_config: rustls::ClientConfig,
993    pub metrics: Arc<SocketMetrics>,
994    /// Per-relay configuration. Consulted when starting a connection to
995    /// look up the auth token and any future per-relay options.
996    pub relay_map: RelayMap,
997}
998
999/// Connection state of the home relay.
1000///
1001/// Published via [`HomeRelayWatch`] so that [`Endpoint::online`] and the public
1002/// [`Endpoint::home_relay_status`] watcher can observe the connection state.
1003/// This type is `pub(crate)`; the public surface lives on
1004/// [`crate::endpoint::RelayStatus`], and this enum is intentionally free to
1005/// evolve without affecting the public API.
1006///
1007/// [`Endpoint::online`]: crate::Endpoint::online
1008/// [`Endpoint::home_relay_status`]: crate::Endpoint::home_relay_status
1009#[derive(Debug, Clone)]
1010pub(crate) enum RelayConnectionState {
1011    /// Dialing or performing the relay handshake.
1012    Connecting,
1013    /// Connected and handshaked.
1014    Connected,
1015    /// Not connected. Either the connection was lost after having been
1016    /// established, or an attempt to connect failed.
1017    ///
1018    /// `last_failure` carries the most recent connection failure, if any. The
1019    /// initial transition into this state (before any attempt has produced
1020    /// an error) carries `None`.
1021    ///
1022    /// The `Arc` is compared by pointer identity: each new failure produces
1023    /// a fresh allocation, so the watcher fires on every new error.
1024    Disconnected {
1025        last_failure: Option<Arc<RelayConnectionFailure>>,
1026    },
1027}
1028
1029impl RelayConnectionState {
1030    pub(crate) fn is_connected(&self) -> bool {
1031        matches!(self, Self::Connected)
1032    }
1033
1034    pub(crate) fn last_failure(&self) -> Option<&RelayConnectionFailure> {
1035        match self {
1036            Self::Disconnected { last_failure } => last_failure.as_deref(),
1037            _ => None,
1038        }
1039    }
1040}
1041
1042impl PartialEq for RelayConnectionState {
1043    fn eq(&self, other: &Self) -> bool {
1044        match (self, other) {
1045            (Self::Connecting, Self::Connecting) | (Self::Connected, Self::Connected) => true,
1046            (Self::Disconnected { last_failure: a }, Self::Disconnected { last_failure: b }) => {
1047                match (a, b) {
1048                    (None, None) => true,
1049                    (Some(a), Some(b)) => Arc::ptr_eq(a, b),
1050                    _ => false,
1051                }
1052            }
1053            _ => false,
1054        }
1055    }
1056}
1057
1058impl Eq for RelayConnectionState {}
1059
1060/// A failed attempt to connect to a relay server, or a lost connection.
1061///
1062/// Contains the type-erased error, together with whatever we could classify from it
1063/// while the concrete error type was still at hand.
1064#[derive(Debug)]
1065pub(crate) struct RelayConnectionFailure {
1066    error: AnyError,
1067    auth_denied_reason: Option<String>,
1068}
1069
1070impl RelayConnectionFailure {
1071    fn new(error: RelayConnectionError) -> Self {
1072        Self {
1073            auth_denied_reason: auth_denied_reason(&error).map(ToOwned::to_owned),
1074            error: AnyError::from(error),
1075        }
1076    }
1077
1078    /// Returns the type-erased error.
1079    pub(crate) fn error(&self) -> &AnyError {
1080        &self.error
1081    }
1082
1083    /// Returns the reason if the relay server denied our authentication.
1084    pub(crate) fn auth_denied_reason(&self) -> Option<&str> {
1085        self.auth_denied_reason.as_deref()
1086    }
1087}
1088
1089/// Returns the reason if `error` was caused by the relay server denying our authentication.
1090fn auth_denied_reason(error: &RelayConnectionError) -> Option<&str> {
1091    match error {
1092        RelayConnectionError::Dial {
1093            source:
1094                DialError::Connect {
1095                    source:
1096                        ConnectError::Handshake {
1097                            source: handshake::Error::ServerDeniedAuth { reason, .. },
1098                            ..
1099                        },
1100                    ..
1101                },
1102            ..
1103        } => Some(reason),
1104        _ => None,
1105    }
1106}
1107
1108/// Shared watchable for the home relay URL and connection status.
1109///
1110/// Owned by [`RelayActor`] and cloned into each [`ActiveRelayActor`].
1111///
1112/// # Write discipline
1113///
1114/// The [`RelayActor`] writes the URL (via [`Self::set`] and [`Self::clear`]).
1115/// Each [`ActiveRelayActor`] updates only the status (via [`Self::set_status`]),
1116/// which guards against stale writes: if another relay has become home since this actor
1117/// was designated, the write is silently dropped.
1118#[derive(Debug, Clone)]
1119pub(crate) struct HomeRelayWatch {
1120    inner: Watchable<Option<RelayStatus>>,
1121}
1122
1123impl Default for HomeRelayWatch {
1124    fn default() -> Self {
1125        Self {
1126            inner: Watchable::new(None),
1127        }
1128    }
1129}
1130
1131impl HomeRelayWatch {
1132    /// Set the home relay URL and status. Used by [`RelayActor`] on relay changes.
1133    fn set(&self, url: RelayUrl, state: RelayConnectionState) {
1134        let _ = self.inner.set(Some(RelayStatus::new(url, state)));
1135    }
1136
1137    /// Clear the home relay (no preferred relay). Used by [`RelayActor`].
1138    fn clear(&self) {
1139        let _ = self.inner.set(None);
1140    }
1141
1142    /// Update the status, but only if `url` is still the current home relay.
1143    ///
1144    /// This is the only write method [`ActiveRelayActor`] should use. It prevents a
1145    /// demoted actor from overwriting a newer home relay's status: the [`RelayActor`]
1146    /// updates the URL in the watchable *before* sending `SetHomeRelay(false)`, so by
1147    /// the time the old actor tries to write, the URL no longer matches.
1148    fn set_status(&self, url: &RelayUrl, state: RelayConnectionState) {
1149        if self.inner.get().as_ref().map(RelayStatus::url) == Some(url) {
1150            let _ = self.inner.set(Some(RelayStatus::new(url.clone(), state)));
1151        }
1152    }
1153
1154    fn get(&self) -> Option<RelayStatus> {
1155        self.inner.get()
1156    }
1157
1158    pub(crate) fn watch(&self) -> n0_watcher::Direct<Option<RelayStatus>> {
1159        self.inner.watch()
1160    }
1161}
1162
1163impl RelayActor {
1164    pub(super) fn new(
1165        config: Config,
1166        relay_datagram_recv_queue: mpsc::Sender<RelayRecvDatagram>,
1167        cancel_token: CancellationToken,
1168    ) -> Self {
1169        Self {
1170            config,
1171            relay_datagram_recv_queue,
1172            active_relays: Default::default(),
1173            active_relay_tasks: JoinSet::new(),
1174            cancel_token,
1175        }
1176    }
1177
1178    pub(super) async fn run(
1179        mut self,
1180        mut receiver: mpsc::Receiver<RelayActorMessage>,
1181        mut datagram_send_channel: mpsc::Receiver<RelaySendItem>,
1182    ) {
1183        // When this future is present, it is sending pending datagrams to an
1184        // ActiveRelayActor.  We can not process further datagrams during this time.
1185        let mut datagram_send_fut = std::pin::pin!(MaybeFuture::None);
1186
1187        loop {
1188            tokio::select! {
1189                biased;
1190                _ = self.cancel_token.cancelled() => {
1191                    debug!("shutting down");
1192                    break;
1193                }
1194                Some(res) = self.active_relay_tasks.join_next() => {
1195                    log_active_relay_task_result(res);
1196                    self.reap_active_relays();
1197                }
1198                msg = receiver.recv() => {
1199                    let Some(msg) = msg else {
1200                        debug!("Inbox dropped, shutting down.");
1201                        break;
1202                    };
1203                    let cancel_token = self.cancel_token.child_token();
1204                    cancel_token.run_until_cancelled(self.handle_msg(msg)).await;
1205                }
1206                // Only poll for new datagrams if we are not blocked on sending them.
1207                item = datagram_send_channel.recv(), if datagram_send_fut.is_none() => {
1208                    let Some(item) = item else {
1209                        debug!("Datagram send channel dropped, shutting down.");
1210                        break;
1211                    };
1212                    let token = self.cancel_token.child_token();
1213                    if let Some(Some(fut)) = token.run_until_cancelled(
1214                        self.try_send_datagram(item)
1215                    ).await {
1216                        datagram_send_fut.as_mut().set_future(fut);
1217                    }
1218                }
1219                // Only poll this future if it is in use.
1220                _ = &mut datagram_send_fut, if datagram_send_fut.is_some() => {
1221                    datagram_send_fut.as_mut().set_none();
1222                }
1223            }
1224        }
1225
1226        // try shutdown
1227        if time::timeout(Duration::from_secs(3), self.close_all_active_relays())
1228            .await
1229            .is_err()
1230        {
1231            warn!("Failed to shut down all ActiveRelayActors");
1232        }
1233    }
1234
1235    async fn handle_msg(&mut self, msg: RelayActorMessage) {
1236        match msg {
1237            RelayActorMessage::NetworkChange { report } => {
1238                self.on_network_change(report).await;
1239            }
1240            RelayActorMessage::MaybeCloseRelaysOnRebind => {
1241                self.maybe_close_relays_on_rebind().await;
1242            }
1243            RelayActorMessage::CheckConnectionAfterNetworkChange => {
1244                self.check_connection_after_network_change().await;
1245            }
1246        }
1247    }
1248
1249    /// Sends datagrams to the correct [`ActiveRelayActor`], or returns a future.
1250    ///
1251    /// If the datagram can not be sent immediately, because the destination channel is
1252    /// full, a future is returned that will complete once the datagrams have been sent to
1253    /// the [`ActiveRelayActor`].
1254    async fn try_send_datagram(
1255        &mut self,
1256        item: RelaySendItem,
1257    ) -> Option<impl Future<Output = ()> + use<>> {
1258        let url = item.url.clone();
1259        let handle = self
1260            .active_relay_handle_for_endpoint(&item.url, &item.remote_endpoint)
1261            .await;
1262        match handle.datagrams_send_queue.try_send(item) {
1263            Ok(()) => None,
1264            Err(mpsc::error::TrySendError::Closed(_)) => {
1265                warn!(?url, "Dropped datagram(s): ActiveRelayActor closed.");
1266                None
1267            }
1268            Err(mpsc::error::TrySendError::Full(item)) => {
1269                let sender = handle.datagrams_send_queue.clone();
1270                let fut = async move {
1271                    if sender.send(item).await.is_err() {
1272                        warn!(?url, "Dropped datagram(s): ActiveRelayActor closed.");
1273                    }
1274                };
1275                Some(fut)
1276            }
1277        }
1278    }
1279
1280    async fn on_network_change(&mut self, report: Report) {
1281        let prev = self.config.my_relay.get();
1282        let prev_url = prev.as_ref().map(RelayStatus::url);
1283        if report.preferred_relay.as_ref() == prev_url {
1284            // No change.
1285            return;
1286        }
1287
1288        if let Some(relay_url) = report.preferred_relay {
1289            self.config.metrics.relay_home_change.inc();
1290
1291            // On change, notify all currently connected relay servers and
1292            // start connecting to our home relay if we are not already.
1293            info!("home is now relay {}, was {:?}", relay_url, prev_url);
1294            // Publish `Connecting` initially. If an `ActiveRelayActor` already
1295            // exists for this URL it will republish its actual status (e.g.
1296            // `Connected`) when it receives the `SetHomeRelay(true)` message
1297            // sent below.
1298            self.config
1299                .my_relay
1300                .set(relay_url.clone(), RelayConnectionState::Connecting);
1301            self.set_home_relay(Some(relay_url)).await;
1302        } else {
1303            self.config.my_relay.clear();
1304            self.set_home_relay(None).await;
1305        }
1306    }
1307
1308    async fn set_home_relay(&mut self, home_url: Option<RelayUrl>) {
1309        let home_url_ref = home_url.as_ref();
1310        n0_future::join_all(self.active_relays.iter().map(|(url, handle)| async move {
1311            let is_preferred = Some(url) == home_url_ref;
1312            handle
1313                .inbox_addr
1314                .send(ActiveRelayMessage::SetHomeRelay(is_preferred))
1315                .await
1316                .ok()
1317        }))
1318        .await;
1319        // Ensure we have an ActiveRelayActor for the current home relay.
1320        if let Some(home_url) = home_url {
1321            self.active_relay_handle(home_url);
1322        }
1323    }
1324
1325    /// Returns the handle for the [`ActiveRelayActor`] to reach `remote_endpoint`.
1326    ///
1327    /// The endpoint is expected to be reachable on `url`, but if no [`ActiveRelayActor`] for
1328    /// `url` exists but another existing [`ActiveRelayActor`] already knows about the endpoint,
1329    /// that other endpoint is used.
1330    async fn active_relay_handle_for_endpoint(
1331        &mut self,
1332        url: &RelayUrl,
1333        remote_endpoint: &EndpointId,
1334    ) -> ActiveRelayHandle {
1335        if let Some(handle) = self.active_relays.get(url) {
1336            return handle.clone();
1337        }
1338
1339        let mut found_relay: Option<RelayUrl> = None;
1340        // If we don't have an open connection to the remote endpoint's home relay, see if
1341        // we have an open connection to a relay endpoint where we'd heard from that peer
1342        // already.  E.g. maybe they dialed our home relay recently.
1343        {
1344            // Futures which return Some(RelayUrl) if the relay knows about the remote endpoint.
1345            let check_futs = self.active_relays.iter().map(|(url, handle)| async move {
1346                let (tx, rx) = oneshot::channel();
1347                handle
1348                    .prio_inbox_addr
1349                    .send(ActiveRelayPrioMessage::HasEndpointRoute(
1350                        *remote_endpoint,
1351                        tx,
1352                    ))
1353                    .await
1354                    .ok();
1355                match rx.await {
1356                    Ok(true) => Some(url.clone()),
1357                    _ => None,
1358                }
1359            });
1360            let mut futures = FuturesUnorderedBounded::from_iter(check_futs);
1361            while let Some(maybe_url) = futures.next().await {
1362                if maybe_url.is_some() {
1363                    found_relay = maybe_url;
1364                    break;
1365                }
1366            }
1367        }
1368        let url = found_relay.unwrap_or(url.clone());
1369        self.active_relay_handle(url)
1370    }
1371
1372    /// Returns the handle of the [`ActiveRelayActor`].
1373    fn active_relay_handle(&mut self, url: RelayUrl) -> ActiveRelayHandle {
1374        match self.active_relays.get(&url) {
1375            Some(e) => e.clone(),
1376            None => {
1377                let handle = self.start_active_relay(url.clone());
1378                if Some(&url) == self.config.my_relay.get().as_ref().map(RelayStatus::url)
1379                    && let Err(err) = handle
1380                        .inbox_addr
1381                        .try_send(ActiveRelayMessage::SetHomeRelay(true))
1382                {
1383                    error!("Home relay not set, send to new actor failed: {err:#}.");
1384                }
1385                self.active_relays.insert(url, handle.clone());
1386                self.log_active_relay();
1387                handle
1388            }
1389        }
1390    }
1391
1392    fn start_active_relay(&mut self, url: RelayUrl) -> ActiveRelayHandle {
1393        debug!(?url, "Adding relay connection");
1394
1395        let auth_token = self
1396            .config
1397            .relay_map
1398            .get(&url)
1399            .and_then(|cfg| cfg.auth_token.clone());
1400        let connection_opts = RelayConnectionOptions {
1401            secret_key: self.config.secret_key.clone(),
1402            #[cfg(not(wasm_browser))]
1403            dns_resolver: self.config.dns_resolver.clone(),
1404            proxy_url: self.config.proxy_url.clone(),
1405            prefer_ipv6: self.config.ipv6_reported.clone(),
1406            tls_config: self.config.tls_config.clone(),
1407            auth_token,
1408        };
1409
1410        // TODO: Replace 64 with PER_CLIENT_SEND_QUEUE_DEPTH once that's unused
1411        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(64);
1412        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(32);
1413        let (inbox_tx, inbox_rx) = mpsc::channel(64);
1414        let span = info_span!("active-relay", %url);
1415        let opts = ActiveRelayActorOptions {
1416            url,
1417            prio_inbox_: prio_inbox_rx,
1418            inbox: inbox_rx,
1419            relay_datagrams_send: send_datagram_rx,
1420            relay_datagrams_recv: self.relay_datagram_recv_queue.clone(),
1421            connection_opts,
1422            stop_token: self.cancel_token.child_token(),
1423            metrics: self.config.metrics.clone(),
1424            my_relay: self.config.my_relay.clone(),
1425        };
1426        let actor = ActiveRelayActor::new(opts);
1427        self.active_relay_tasks.spawn(
1428            async move {
1429                actor.run().await;
1430            }
1431            .instrument(span),
1432        );
1433        let handle = ActiveRelayHandle {
1434            prio_inbox_addr: prio_inbox_tx,
1435            inbox_addr: inbox_tx,
1436            datagrams_send_queue: send_datagram_tx,
1437        };
1438        self.log_active_relay();
1439        handle
1440    }
1441
1442    /// Triggers an immediate health check on all relay connections after a network change.
1443    async fn check_connection_after_network_change(&mut self) {
1444        self.send_check_connection().await;
1445    }
1446
1447    /// Closes the relay connections not originating from a local IP address.
1448    ///
1449    /// Called in response to a rebind, any relay connection originating from an address
1450    /// that's not known to be currently a local IP address should be closed.  All the other
1451    /// relay connections are pinged.
1452    async fn maybe_close_relays_on_rebind(&mut self) {
1453        self.send_check_connection().await;
1454        self.log_active_relay();
1455    }
1456
1457    /// Sends a [`ActiveRelayMessage::CheckConnection`] to all active relays with current
1458    /// local IPs.
1459    async fn send_check_connection(&self) {
1460        #[cfg(not(wasm_browser))]
1461        let ifs = interfaces::State::new().await;
1462        #[cfg(not(wasm_browser))]
1463        let local_ips: Vec<_> = ifs
1464            .interfaces
1465            .values()
1466            .flat_map(|netif| netif.addrs())
1467            .map(|ipnet| ipnet.addr())
1468            .collect();
1469        // In browsers, we don't have this information. This will do the right thing
1470        // in the ActiveRelayActor, though.
1471        #[cfg(wasm_browser)]
1472        let local_ips = Vec::new();
1473        let send_futs = self.active_relays.values().map(|handle| {
1474            let local_ips = local_ips.clone();
1475            async move {
1476                handle
1477                    .inbox_addr
1478                    .send(ActiveRelayMessage::CheckConnection { local_ips })
1479                    .await
1480                    .ok();
1481            }
1482        });
1483        n0_future::join_all(send_futs).await;
1484    }
1485
1486    /// Cleans up [`ActiveRelayActor`]s which have stopped running.
1487    fn reap_active_relays(&mut self) {
1488        self.active_relays
1489            .retain(|_url, handle| !handle.inbox_addr.is_closed());
1490
1491        // Make sure home relay exists
1492        if let Some(status) = self.config.my_relay.get() {
1493            self.active_relay_handle(status.url().clone());
1494        }
1495        self.log_active_relay();
1496    }
1497
1498    /// Stops all [`ActiveRelayActor`]s and awaits for them to finish.
1499    async fn close_all_active_relays(&mut self) {
1500        self.cancel_token.cancel();
1501        let mut tasks = std::mem::take(&mut self.active_relay_tasks);
1502        // Drain instead of `join_all`, which panics on any `JoinError`.
1503        while let Some(res) = tasks.join_next().await {
1504            log_active_relay_task_result(res);
1505        }
1506
1507        self.log_active_relay();
1508    }
1509
1510    fn log_active_relay(&self) {
1511        debug!("{} active relay conns{}", self.active_relays.len(), {
1512            let mut s = String::new();
1513            if !self.active_relays.is_empty() {
1514                s += ":";
1515                for endpoint in self.active_relay_sorted() {
1516                    s += &format!(" relay-{endpoint}");
1517                }
1518            }
1519            s
1520        });
1521    }
1522
1523    fn active_relay_sorted(&self) -> impl Iterator<Item = RelayUrl> + use<> {
1524        let mut ids: Vec<_> = self.active_relays.keys().cloned().collect();
1525        ids.sort();
1526
1527        ids.into_iter()
1528    }
1529}
1530
1531/// Reports how one [`ActiveRelayActor`] task ended, in the run loop and on shutdown.
1532fn log_active_relay_task_result(res: Result<(), JoinError>) {
1533    match res {
1534        Ok(()) => (),
1535        Err(err) if err.is_panic() => error!("ActiveRelayActor task panicked: {err:#?}"),
1536        Err(err) if err.is_cancelled() => error!("ActiveRelayActor cancelled: {err:#?}"),
1537        Err(err) => error!("ActiveRelayActor failed: {err:#?}"),
1538    }
1539}
1540
1541/// Handle to one [`ActiveRelayActor`].
1542#[derive(Debug, Clone)]
1543struct ActiveRelayHandle {
1544    prio_inbox_addr: mpsc::Sender<ActiveRelayPrioMessage>,
1545    inbox_addr: mpsc::Sender<ActiveRelayMessage>,
1546    datagrams_send_queue: mpsc::Sender<RelaySendItem>,
1547}
1548
1549/// A single datagram received from a relay server.
1550///
1551/// This could be either a QUIC or DISCO packet.
1552#[derive(Debug)]
1553pub(crate) struct RelayRecvDatagram {
1554    pub(crate) url: RelayUrl,
1555    pub(crate) src: EndpointId,
1556    pub(crate) datagrams: Datagrams,
1557}
1558
1559#[cfg(test)]
1560mod tests {
1561    use std::{
1562        sync::{Arc, atomic::AtomicBool},
1563        time::Duration,
1564    };
1565
1566    use iroh_base::{EndpointId, RelayUrl, SecretKey};
1567    use iroh_relay::{
1568        PingTracker,
1569        protos::relay::Datagrams,
1570        tls::{CaTlsConfig, default_provider},
1571    };
1572    use n0_error::{AnyError as Error, Result, StackResultExt, StdResultExt};
1573    use n0_tracing_test::traced_test;
1574    use tokio::sync::{mpsc, oneshot};
1575    use tokio_util::{sync::CancellationToken, task::AbortOnDropHandle};
1576    use tracing::{Instrument, info, info_span};
1577
1578    use super::{
1579        ActiveRelayActor, ActiveRelayActorOptions, ActiveRelayHandle, ActiveRelayMessage,
1580        ActiveRelayPrioMessage, Config, RELAY_INACTIVE_CLEANUP_TIME, RelayActor, RelayActorMessage,
1581        RelayConnectionOptions, RelayMap, RelayRecvDatagram, RelaySendItem, Report,
1582        UNDELIVERABLE_DATAGRAM_TIMEOUT,
1583    };
1584    use crate::{dns::DnsResolver, metrics::SocketMetrics, test_utils};
1585
1586    /// Abort stands in for the runtime drop that triggers this in the wild:
1587    /// `join_next` yields a cancelled `JoinError` either way.
1588    #[tokio::test]
1589    #[traced_test]
1590    async fn close_all_active_relays_survives_a_cancelled_task() {
1591        let (relay_datagram_recv_queue, _recv_rx) = mpsc::channel(1);
1592        let config = Config {
1593            my_relay: Default::default(),
1594            secret_key: SecretKey::from_bytes(&[0u8; 32]),
1595            dns_resolver: DnsResolver::new(),
1596            proxy_url: None,
1597            ipv6_reported: Arc::new(AtomicBool::new(false)),
1598            tls_config: CaTlsConfig::insecure_skip_verify()
1599                .client_config(default_provider())
1600                .expect("infallible"),
1601            metrics: Default::default(),
1602            relay_map: RelayMap::empty(),
1603        };
1604        let mut actor =
1605            RelayActor::new(config, relay_datagram_recv_queue, CancellationToken::new());
1606
1607        let handle = actor.active_relay_tasks.spawn(std::future::pending::<()>());
1608        handle.abort();
1609
1610        // Panicked with `join_all`.
1611        actor.close_all_active_relays().await;
1612
1613        assert!(actor.active_relay_tasks.is_empty());
1614        assert!(logs_contain("ActiveRelayActor cancelled"));
1615    }
1616
1617    #[tokio::test]
1618    async fn no_preferred_relay_demotes_home_relay() {
1619        let (relay_datagram_recv_queue, _recv_rx) = mpsc::channel(1);
1620        let config = Config {
1621            my_relay: Default::default(),
1622            secret_key: SecretKey::from_bytes(&[0u8; 32]),
1623            dns_resolver: DnsResolver::new(),
1624            proxy_url: None,
1625            ipv6_reported: Arc::new(AtomicBool::new(false)),
1626            tls_config: CaTlsConfig::insecure_skip_verify()
1627                .client_config(default_provider())
1628                .expect("infallible"),
1629            metrics: Default::default(),
1630            relay_map: RelayMap::empty(),
1631        };
1632        let mut actor =
1633            RelayActor::new(config, relay_datagram_recv_queue, CancellationToken::new());
1634        let url: RelayUrl = "https://relay.invalid".parse().unwrap();
1635        let (prio_inbox_addr, _prio_inbox_rx) = mpsc::channel(1);
1636        let (inbox_addr, mut inbox_rx) = mpsc::channel(1);
1637        let (datagrams_send_queue, _datagrams_send_rx) = mpsc::channel(1);
1638        let handle = ActiveRelayHandle {
1639            prio_inbox_addr,
1640            inbox_addr,
1641            datagrams_send_queue,
1642        };
1643        actor.active_relays.insert(url.clone(), handle);
1644
1645        let report = Report {
1646            preferred_relay: Some(url),
1647            ..Default::default()
1648        };
1649        actor.on_network_change(report).await;
1650        let msg = inbox_rx.try_recv();
1651        assert!(
1652            matches!(msg, Ok(ActiveRelayMessage::SetHomeRelay(true))),
1653            "{msg:?}"
1654        );
1655
1656        actor.on_network_change(Report::default()).await;
1657        assert_eq!(actor.config.my_relay.get(), None);
1658        let msg = inbox_rx.try_recv();
1659        assert!(
1660            matches!(msg, Ok(ActiveRelayMessage::SetHomeRelay(false))),
1661            "{msg:?}"
1662        );
1663    }
1664
1665    /// Starts a new [`ActiveRelayActor`].
1666    #[allow(clippy::too_many_arguments)]
1667    fn start_active_relay_actor(
1668        secret_key: SecretKey,
1669        stop_token: CancellationToken,
1670        url: RelayUrl,
1671        prio_inbox_rx: mpsc::Receiver<ActiveRelayPrioMessage>,
1672        inbox_rx: mpsc::Receiver<ActiveRelayMessage>,
1673        relay_datagrams_send: mpsc::Receiver<RelaySendItem>,
1674        relay_datagrams_recv: mpsc::Sender<RelayRecvDatagram>,
1675        metrics: Arc<SocketMetrics>,
1676        span: tracing::Span,
1677    ) -> AbortOnDropHandle<()> {
1678        let opts = ActiveRelayActorOptions {
1679            url,
1680            prio_inbox_: prio_inbox_rx,
1681            inbox: inbox_rx,
1682            relay_datagrams_send,
1683            relay_datagrams_recv,
1684            connection_opts: RelayConnectionOptions {
1685                secret_key,
1686                dns_resolver: DnsResolver::new(),
1687                proxy_url: None,
1688                prefer_ipv6: Arc::new(AtomicBool::new(true)),
1689                tls_config: CaTlsConfig::insecure_skip_verify()
1690                    .client_config(default_provider())
1691                    .expect("infallible"),
1692                auth_token: None,
1693            },
1694            stop_token,
1695            metrics,
1696            my_relay: Default::default(),
1697        };
1698        let task = tokio::spawn(ActiveRelayActor::new(opts).run().instrument(span));
1699        AbortOnDropHandle::new(task)
1700    }
1701
1702    /// Starts an [`ActiveRelayActor`] as an "iroh echo endpoint".
1703    ///
1704    /// This actor will connect to the relay server, pretending to be an iroh endpoint, and echo
1705    /// back any datagram it receives from the relay.  This is used by the
1706    /// [`ActiveRelayActor`] under test to check connectivity works.
1707    fn start_echo_endpoint(relay_url: RelayUrl) -> (EndpointId, AbortOnDropHandle<()>) {
1708        let secret_key = SecretKey::from_bytes(&[8u8; 32]);
1709        let (recv_datagram_tx, mut recv_datagram_rx) = mpsc::channel(16);
1710        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
1711        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
1712        let (inbox_tx, inbox_rx) = mpsc::channel(16);
1713        let cancel_token = CancellationToken::new();
1714        let actor_task = start_active_relay_actor(
1715            secret_key.clone(),
1716            cancel_token.clone(),
1717            relay_url.clone(),
1718            prio_inbox_rx,
1719            inbox_rx,
1720            send_datagram_rx,
1721            recv_datagram_tx,
1722            Default::default(),
1723            info_span!("echo-endpoint"),
1724        );
1725        let echo_task = tokio::spawn({
1726            let relay_url = relay_url.clone();
1727            async move {
1728                loop {
1729                    let datagram = recv_datagram_rx.recv().await;
1730                    if let Some(recv) = datagram {
1731                        let RelayRecvDatagram {
1732                            url: _,
1733                            src,
1734                            datagrams,
1735                        } = recv;
1736                        info!(from = %src.fmt_short(), "Received datagram");
1737                        let send = RelaySendItem {
1738                            remote_endpoint: src,
1739                            url: relay_url.clone(),
1740                            datagrams,
1741                        };
1742                        send_datagram_tx.send(send).await.ok();
1743                    }
1744                }
1745            }
1746            .instrument(info_span!("echo-task"))
1747        });
1748        let echo_task = AbortOnDropHandle::new(echo_task);
1749        let supervisor_task = tokio::spawn(async move {
1750            let _guard = cancel_token.drop_guard();
1751            // move the inboxes here so it is not dropped, as this stops the actor.
1752            let _prio_inbox_tx = prio_inbox_tx;
1753            let _inbox_tx = inbox_tx;
1754            tokio::select! {
1755                biased;
1756                _ = actor_task => (),
1757                _ = echo_task => (),
1758            };
1759        });
1760        let supervisor_task = AbortOnDropHandle::new(supervisor_task);
1761        (secret_key.public(), supervisor_task)
1762    }
1763
1764    /// Sends a message to the echo endpoint, receives the response.
1765    ///
1766    /// This takes care of retry and timeout.  Because we don't know when both the
1767    /// endpoint-under-test and the echo endpoint will be ready and datagrams aren't queued to send
1768    /// forever, we have to retry a few times.
1769    async fn send_recv_echo(
1770        item: RelaySendItem,
1771        tx: &mpsc::Sender<RelaySendItem>,
1772        rx: &mut mpsc::Receiver<RelayRecvDatagram>,
1773    ) -> Result<()> {
1774        tokio::time::timeout(Duration::from_secs(10), async move {
1775            loop {
1776                let res = tokio::time::timeout(UNDELIVERABLE_DATAGRAM_TIMEOUT, async {
1777                    tx.send(item.clone()).await.std_context("send item")?;
1778                    let RelayRecvDatagram {
1779                        url: _,
1780                        src: _,
1781                        datagrams,
1782                    } = rx.recv().await.unwrap();
1783
1784                    assert_eq!(datagrams, item.datagrams);
1785
1786                    Ok::<_, Error>(())
1787                })
1788                .await;
1789                if res.is_ok() {
1790                    break;
1791                }
1792            }
1793        })
1794        .await
1795        .expect("overall timeout exceeded");
1796        Ok(())
1797    }
1798
1799    /// Starts a [`RelayActor`] and returns its inbox, both datagram queues and its task.
1800    fn setup_relay_actor() -> (
1801        mpsc::Sender<RelayActorMessage>,
1802        mpsc::Sender<RelaySendItem>,
1803        mpsc::Receiver<RelayRecvDatagram>,
1804        AbortOnDropHandle<()>,
1805    ) {
1806        let (datagram_recv_tx, datagram_recv_rx) = mpsc::channel(16);
1807        let config = Config {
1808            my_relay: Default::default(),
1809            secret_key: SecretKey::from_bytes(&[1u8; 32]),
1810            dns_resolver: DnsResolver::new(),
1811            proxy_url: None,
1812            ipv6_reported: Arc::new(AtomicBool::new(false)),
1813            tls_config: CaTlsConfig::insecure_skip_verify()
1814                .client_config(default_provider())
1815                .expect("infallible"),
1816            metrics: Default::default(),
1817            relay_map: RelayMap::empty(),
1818        };
1819        let actor = RelayActor::new(config, datagram_recv_tx, CancellationToken::new());
1820        let (msg_tx, msg_rx) = mpsc::channel(128);
1821        let (datagram_send_tx, datagram_send_rx) = mpsc::channel(256);
1822        let task = AbortOnDropHandle::new(tokio::spawn(actor.run(msg_rx, datagram_send_rx)));
1823        (msg_tx, datagram_send_tx, datagram_recv_rx, task)
1824    }
1825
1826    #[tokio::test]
1827    #[traced_test]
1828    async fn test_active_relay_reconnect() -> Result {
1829        let (_relay_map, relay_url, _server) = test_utils::run_relay_server().await?;
1830        let (peer_endpoint, _echo_endpoint_task) = start_echo_endpoint(relay_url.clone());
1831
1832        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
1833        let (datagram_recv_tx, mut datagram_recv_rx) = mpsc::channel(16);
1834        let (send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
1835        let (_prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
1836        let (inbox_tx, inbox_rx) = mpsc::channel(16);
1837        let cancel_token = CancellationToken::new();
1838        let metrics = Arc::new(SocketMetrics::default());
1839        let task = start_active_relay_actor(
1840            secret_key,
1841            cancel_token.clone(),
1842            relay_url.clone(),
1843            prio_inbox_rx,
1844            inbox_rx,
1845            send_datagram_rx,
1846            datagram_recv_tx.clone(),
1847            metrics.clone(),
1848            info_span!("actor-under-test"),
1849        );
1850
1851        // Send a datagram to our echo endpoint.
1852        info!("first echo");
1853        let hello_send_item = RelaySendItem {
1854            remote_endpoint: peer_endpoint,
1855            url: relay_url.clone(),
1856            datagrams: Datagrams::from(b"hello"),
1857        };
1858        send_recv_echo(
1859            hello_send_item.clone(),
1860            &send_datagram_tx,
1861            &mut datagram_recv_rx,
1862        )
1863        .await?;
1864
1865        // Now ask to check the connection, triggering a ping but no reconnect.
1866        let (tx, rx) = oneshot::channel();
1867        inbox_tx
1868            .send(ActiveRelayMessage::GetLocalAddr(tx))
1869            .await
1870            .std_context("send get local addr msg")?;
1871
1872        let local_addr = rx
1873            .await
1874            .std_context("wait for local addr msg")?
1875            .context("no local addr")?;
1876        info!(?local_addr, "check connection with addr");
1877        inbox_tx
1878            .send(ActiveRelayMessage::CheckConnection {
1879                local_ips: vec![local_addr.ip()],
1880            })
1881            .await
1882            .std_context("send check connection message")?;
1883
1884        // Sync the ActiveRelayActor. Ping blocks it and we want to be sure it has handled
1885        // another inbox message before continuing.
1886        let (tx, rx) = oneshot::channel();
1887        inbox_tx
1888            .send(ActiveRelayMessage::GetLocalAddr(tx))
1889            .await
1890            .std_context("send get local addr msg")?;
1891        rx.await.std_context("recv send local addr msg")?;
1892
1893        // Echo should still work.
1894        info!("second echo");
1895        send_recv_echo(
1896            hello_send_item.clone(),
1897            &send_datagram_tx,
1898            &mut datagram_recv_rx,
1899        )
1900        .await?;
1901
1902        // Now ask to check the connection, this will reconnect without pinging because we
1903        // do not supply any "valid" local IP addresses.
1904        info!("check connection");
1905        inbox_tx
1906            .send(ActiveRelayMessage::CheckConnection {
1907                local_ips: Vec::new(),
1908            })
1909            .await
1910            .std_context("send check connection msg")?;
1911
1912        // Give some time to reconnect, mostly to sort logs rather than functional.
1913        tokio::time::sleep(Duration::from_millis(10)).await;
1914
1915        // Echo should still work.
1916        info!("third echo");
1917        send_recv_echo(
1918            hello_send_item.clone(),
1919            &send_datagram_tx,
1920            &mut datagram_recv_rx,
1921        )
1922        .await?;
1923
1924        // Shut down the actor.
1925        cancel_token.cancel();
1926        task.await.std_context("wait for task to finish")?;
1927
1928        // The actor connected once at startup and once more after the connection check
1929        // failed.
1930        assert_eq!(metrics.relay_conns_success.get(), 2);
1931        assert_eq!(
1932            metrics.relay_conns_closed.get(),
1933            2,
1934            "the connections are counted as closed once the actor stops"
1935        );
1936
1937        Ok(())
1938    }
1939
1940    #[tokio::test]
1941    #[traced_test]
1942    async fn test_active_relay_inactive() -> Result {
1943        let (_relay_map, relay_url, _server) = test_utils::run_relay_server().await?;
1944
1945        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
1946        let (datagram_recv_tx, _datagram_recv_rx) = mpsc::channel(16);
1947        let (_send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
1948        let (_prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
1949        let (inbox_tx, inbox_rx) = mpsc::channel(16);
1950        let cancel_token = CancellationToken::new();
1951        let metrics = Arc::new(SocketMetrics::default());
1952        let mut task = start_active_relay_actor(
1953            secret_key,
1954            cancel_token.clone(),
1955            relay_url,
1956            prio_inbox_rx,
1957            inbox_rx,
1958            send_datagram_rx,
1959            datagram_recv_tx,
1960            metrics.clone(),
1961            info_span!("actor-under-test"),
1962        );
1963
1964        // Wait until the actor is connected to the relay server.
1965        tokio::time::timeout(Duration::from_secs(5), async {
1966            loop {
1967                let (tx, rx) = oneshot::channel();
1968                inbox_tx.send(ActiveRelayMessage::PingServer(tx)).await.ok();
1969                if tokio::time::timeout(Duration::from_millis(200), rx)
1970                    .await
1971                    .map(|resp| resp.is_ok())
1972                    .unwrap_or_default()
1973                {
1974                    break;
1975                }
1976            }
1977        })
1978        .await
1979        .std_context("timeout")?;
1980
1981        assert_eq!(metrics.relay_conns_success.get(), 1);
1982        assert_eq!(
1983            metrics.relay_conns_closed.get(),
1984            0,
1985            "the connection is only counted as closed once it is gone"
1986        );
1987
1988        // We now have an idling ActiveRelayActor.  If we advance time just a little it
1989        // should stay alive.
1990        info!("Stepping time forwards by RELAY_INACTIVE_CLEANUP_TIME / 2");
1991        tokio::time::pause();
1992        tokio::time::advance(RELAY_INACTIVE_CLEANUP_TIME / 2).await;
1993        tokio::time::resume();
1994
1995        assert!(
1996            tokio::time::timeout(Duration::from_millis(100), &mut task)
1997                .await
1998                .is_err(),
1999            "actor task terminated"
2000        );
2001
2002        // If we advance time a lot it should finish.
2003        info!("Stepping time forwards by RELAY_INACTIVE_CLEANUP_TIME");
2004        tokio::time::pause();
2005        tokio::time::advance(RELAY_INACTIVE_CLEANUP_TIME).await;
2006        tokio::time::resume();
2007
2008        // We resume time for these timeouts, as there's actual I/O happening,
2009        // for example closing the TCP stream, so we actually need the tokio
2010        // runtime to idle a bit while the kernel is doing its thing.
2011        assert!(
2012            tokio::time::timeout(Duration::from_secs(1), task)
2013                .await
2014                .is_ok(),
2015            "actor task still running"
2016        );
2017
2018        // The actor may have reconnected while we advanced time, because a ping to the relay
2019        // server can time out while time is frozen, so we do not assert an exact count here.
2020        assert_eq!(
2021            metrics.relay_conns_closed.get(),
2022            metrics.relay_conns_success.get(),
2023            "all connections are counted as closed once the actor stops"
2024        );
2025
2026        cancel_token.cancel();
2027        Ok(())
2028    }
2029
2030    #[tokio::test]
2031    #[traced_test]
2032    async fn undialable_relay_does_not_stall_relay_actor_on_network_changes() -> Result {
2033        let (_relay_map, relay_url, _server) = test_utils::run_relay_server().await?;
2034        let (peer_endpoint, _echo_endpoint_task) = start_echo_endpoint(relay_url.clone());
2035        let (msg_tx, datagram_send_tx, mut datagram_recv_rx, _task) = setup_relay_actor();
2036        let undialable = RelaySendItem {
2037            remote_endpoint: SecretKey::from_bytes(&[2u8; 32]).public(),
2038            url: "x://h/".parse().unwrap(),
2039            datagrams: Datagrams::from(b"lost"),
2040        };
2041        datagram_send_tx
2042            .send(undialable)
2043            .await
2044            .std_context("relay actor alive")?;
2045        let hello = RelaySendItem {
2046            remote_endpoint: peer_endpoint,
2047            url: relay_url,
2048            datagrams: Datagrams::from(b"hello"),
2049        };
2050        send_recv_echo(hello.clone(), &datagram_send_tx, &mut datagram_recv_rx).await?;
2051
2052        for _ in 0..100 {
2053            assert!(
2054                msg_tx
2055                    .send(RelayActorMessage::CheckConnectionAfterNetworkChange)
2056                    .await
2057                    .is_ok(),
2058                "relay actor alive"
2059            );
2060        }
2061
2062        send_recv_echo(hello, &datagram_send_tx, &mut datagram_recv_rx).await
2063    }
2064
2065    #[tokio::test(start_paused = true)]
2066    #[traced_test]
2067    async fn undialable_relay_actor_exits_when_inactive() -> Result {
2068        let (datagram_recv_tx, _datagram_recv_rx) = mpsc::channel(16);
2069        let (_send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
2070        let (_prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
2071        let (_inbox_tx, inbox_rx) = mpsc::channel(16);
2072        let task = start_active_relay_actor(
2073            SecretKey::from_bytes(&[1u8; 32]),
2074            CancellationToken::new(),
2075            "x://h/".parse().unwrap(),
2076            prio_inbox_rx,
2077            inbox_rx,
2078            send_datagram_rx,
2079            datagram_recv_tx,
2080            Default::default(),
2081            info_span!("actor-under-test"),
2082        );
2083        tokio::time::timeout(RELAY_INACTIVE_CLEANUP_TIME * 2, task)
2084            .await
2085            .std_context("actor task still running")?
2086            .std_context("actor task failed")?;
2087        Ok(())
2088    }
2089
2090    #[tokio::test]
2091    #[traced_test]
2092    async fn active_relay_answers_routes_and_exits_when_server_ignores_close() -> Result {
2093        let (_relay_map, _relay_url, server) = test_utils::run_relay_server().await?;
2094        let server_addr = server.https_addr().context("no https addr")?;
2095        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
2096        let proxy_url: RelayUrl = format!("https://{}", listener.local_addr()?)
2097            .parse()
2098            .unwrap();
2099        let (freeze_tx, freeze_rx) = oneshot::channel::<()>();
2100        let proxy = tokio::spawn(async move {
2101            let (mut client, _) = listener.accept().await?;
2102            let mut server = tokio::net::TcpStream::connect(server_addr).await?;
2103            tokio::select! {
2104                _ = tokio::io::copy_bidirectional(&mut client, &mut server) => {}
2105                _ = freeze_rx => {}
2106            }
2107            Ok::<_, std::io::Error>((client, server))
2108        });
2109
2110        let (datagram_recv_tx, _datagram_recv_rx) = mpsc::channel(16);
2111        let (_send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
2112        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
2113        let (inbox_tx, inbox_rx) = mpsc::channel(16);
2114        let stop = CancellationToken::new();
2115        let task = start_active_relay_actor(
2116            SecretKey::from_bytes(&[1u8; 32]),
2117            stop.clone(),
2118            proxy_url,
2119            prio_inbox_rx,
2120            inbox_rx,
2121            send_datagram_rx,
2122            datagram_recv_tx,
2123            Default::default(),
2124            info_span!("actor-under-test"),
2125        );
2126        tokio::time::timeout(Duration::from_secs(5), async {
2127            loop {
2128                let (tx, rx) = oneshot::channel();
2129                inbox_tx.send(ActiveRelayMessage::PingServer(tx)).await.ok();
2130                if tokio::time::timeout(Duration::from_millis(200), rx)
2131                    .await
2132                    .map(|resp| resp.is_ok())
2133                    .unwrap_or_default()
2134                {
2135                    break;
2136                }
2137            }
2138        })
2139        .await
2140        .std_context("timeout")?;
2141
2142        freeze_tx.send(()).ok();
2143        let _frozen_streams = proxy
2144            .await
2145            .std_context("proxy task failed")?
2146            .std_context("proxy io failed")?;
2147        stop.cancel();
2148
2149        let (tx, rx) = oneshot::channel();
2150        let peer = SecretKey::from_bytes(&[2u8; 32]).public();
2151        prio_inbox_tx
2152            .send(ActiveRelayPrioMessage::HasEndpointRoute(peer, tx))
2153            .await
2154            .std_context("actor gone")?;
2155        let has_route = tokio::time::timeout(Duration::from_secs(5), rx)
2156            .await
2157            .std_context("no route reply while closing")?
2158            .std_context("route query dropped")?;
2159        assert!(!has_route);
2160
2161        tokio::time::timeout(Duration::from_secs(5), task)
2162            .await
2163            .std_context("actor task still running")?
2164            .std_context("actor task failed")?;
2165        Ok(())
2166    }
2167
2168    #[tokio::test]
2169    async fn test_ping_tracker() {
2170        tokio::time::pause();
2171        let mut tracker = PingTracker::default();
2172
2173        let ping0 = tracker.new_ping();
2174
2175        let res = tokio::time::timeout(Duration::from_secs(1), tracker.timeout()).await;
2176        assert!(res.is_err(), "no ping timeout has elapsed yet");
2177
2178        tracker.pong_received(ping0);
2179        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
2180        assert!(res.is_err(), "ping completed before timeout");
2181
2182        let _ping1 = tracker.new_ping();
2183
2184        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
2185        assert!(res.is_ok(), "ping timeout should have happened");
2186
2187        let _ping2 = tracker.new_ping();
2188
2189        tokio::time::sleep(Duration::from_secs(10)).await;
2190        let res = tokio::time::timeout(Duration::from_millis(1), tracker.timeout()).await;
2191        assert!(res.is_ok(), "ping timeout happened in the past");
2192
2193        let res = tokio::time::timeout(Duration::from_secs(10), tracker.timeout()).await;
2194        assert!(res.is_err(), "ping timeout should only happen once");
2195    }
2196
2197    #[tokio::test]
2198    #[traced_test]
2199    async fn test_prio_inbox_answered_during_backoff() {
2200        tokio::time::pause();
2201        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
2202        let peer = SecretKey::from_bytes(&[2u8; 32]).public();
2203        let url: RelayUrl = "https://relay.invalid".parse().unwrap();
2204        let (prio_inbox_tx, prio_inbox_rx) = mpsc::channel(8);
2205        let (_inbox_tx, inbox_rx) = mpsc::channel(16);
2206        let (_send_datagram_tx, send_datagram_rx) = mpsc::channel(16);
2207        let (recv_datagram_tx, _recv_datagram_rx) = mpsc::channel(16);
2208        let opts = ActiveRelayActorOptions {
2209            url,
2210            prio_inbox_: prio_inbox_rx,
2211            inbox: inbox_rx,
2212            relay_datagrams_send: send_datagram_rx,
2213            relay_datagrams_recv: recv_datagram_tx,
2214            connection_opts: RelayConnectionOptions {
2215                secret_key,
2216                dns_resolver: DnsResolver::new(),
2217                proxy_url: None,
2218                prefer_ipv6: Arc::new(AtomicBool::new(true)),
2219                tls_config: CaTlsConfig::insecure_skip_verify()
2220                    .client_config(default_provider())
2221                    .expect("infallible"),
2222                auth_token: None,
2223            },
2224            stop_token: CancellationToken::new(),
2225            metrics: Default::default(),
2226            my_relay: Default::default(),
2227        };
2228        let mut actor = ActiveRelayActor::new(opts);
2229
2230        let backoff = tokio::spawn(async move {
2231            let keep_running = actor.sleep_backoff(Duration::from_secs(10)).await;
2232            (actor, keep_running)
2233        });
2234
2235        // Query the actor while it waits out the backoff delay. The reply must
2236        // arrive well before the delay elapses; before the backoff wait
2237        // serviced the priority inbox, this reply only arrived after the
2238        // remaining backoff delay (up to 16s).
2239        let (tx, rx) = oneshot::channel();
2240        prio_inbox_tx
2241            .send(ActiveRelayPrioMessage::HasEndpointRoute(peer, tx))
2242            .await
2243            .expect("actor alive");
2244        let reply = tokio::time::timeout(Duration::from_secs(1), rx)
2245            .await
2246            .expect("no reply within 1s of a 10s backoff")
2247            .expect("sender dropped");
2248        assert!(!reply, "a disconnected relay has no endpoint routes");
2249
2250        // The backoff itself still runs to completion.
2251        let (_actor, keep_running) = backoff.await.expect("backoff task panicked");
2252        assert!(keep_running, "backoff should complete normally");
2253    }
2254
2255    #[test]
2256    fn test_home_relay_watch_url_guard() {
2257        use super::{HomeRelayWatch, RelayConnectionState};
2258        use crate::endpoint::RelayStatus;
2259
2260        let watch = HomeRelayWatch::default();
2261        let a: RelayUrl = "https://a.example.com".parse().unwrap();
2262        let b: RelayUrl = "https://b.example.com".parse().unwrap();
2263
2264        // Actor A becomes home and connects
2265        watch.set(a.clone(), RelayConnectionState::Connecting);
2266        watch.set_status(&a, RelayConnectionState::Connected);
2267        assert_eq!(
2268            watch.get(),
2269            Some(RelayStatus::new(a.clone(), RelayConnectionState::Connected)),
2270        );
2271
2272        // RelayActor migrates home to B
2273        watch.set(b.clone(), RelayConnectionState::Connecting);
2274
2275        // Old actor A tries to write -- rejected because URL changed
2276        watch.set_status(
2277            &a,
2278            RelayConnectionState::Disconnected { last_failure: None },
2279        );
2280        assert_eq!(
2281            watch.get(),
2282            Some(RelayStatus::new(
2283                b.clone(),
2284                RelayConnectionState::Connecting
2285            )),
2286        );
2287
2288        // Actor B writes normally
2289        watch.set_status(&b, RelayConnectionState::Connected);
2290        assert_eq!(
2291            watch.get(),
2292            Some(RelayStatus::new(b, RelayConnectionState::Connected)),
2293        );
2294    }
2295}