Skip to main content

ts_runtime/
lib.rs

1#![doc = include_str!("../README.md")]
2
3extern crate ts_netstack_smoltcp as netstack;
4
5use core::time::Duration;
6use std::sync::Arc;
7
8use kameo::{
9    actor::{ActorRef, Spawn, WeakActorRef},
10    mailbox::Signal,
11};
12use netstack::netcore::Channel;
13use tokio::sync::watch;
14
15use crate::{
16    control_runner::ControlRunner, dataplane::DataplaneActor, direct::DirectManager,
17    forwarder_actor::ForwarderActor, multiderp::Multiderp, netstack_actor::NetstackActor,
18};
19
20/// Pcap stream framer for debug packet capture (`CapturePcap`).
21pub mod capture;
22/// Control runner.
23pub mod control_runner;
24mod dataplane;
25mod derp_latency;
26/// Device connection-state tracking ([`DeviceState`]) and typed registration outcome
27/// ([`RegistrationError`]).
28pub mod device_state;
29mod direct;
30mod env;
31mod error;
32/// Fallback TCP handler registry (`tsnet.Server.RegisterFallbackTCPHandler` parity).
33pub mod fallback_tcp;
34mod forwarder_actor;
35/// Client-side Funnel ingress termination (`tsnet`'s `ListenFunnel` data path).
36pub mod funnel;
37mod magic_dns;
38mod multiderp;
39mod netstack_actor;
40mod packetfilter;
41pub mod peer_tracker;
42mod peerapi;
43mod peerapi_doh;
44mod route_updater;
45/// Stored Serve config + accept-loop runtime (`tsnet`'s `Get/SetServeConfig` + serving runtime).
46pub mod serve;
47mod src_filter;
48/// Netmap status snapshot, WhoIs, and watcher types.
49pub mod status;
50/// Taildrop peer-to-peer file transfer store.
51pub mod taildrop;
52pub mod taildrop_send;
53/// Tailnet-Lock (TKA) chain-sync orchestration: bootstrap + offer/send driver (the runtime layer
54/// that bridges the `ts_control` sync RPCs and the `ts_tka` chain logic).
55mod tka_sync;
56#[cfg(feature = "tun")]
57mod tun_actor;
58
59pub use device_state::{DeviceState, RegistrationError};
60pub(crate) use env::Env;
61pub use error::{Error, ErrorKind};
62pub use status::{FileTarget, NetcheckReport, RegionLatency, Status, StatusNode, WhoIs};
63pub use ts_dataplane::{CaptureHook, CapturePath};
64
65use crate::peer_tracker::PeerTracker;
66
67/// The runtime for a tailscale device.
68pub struct Runtime {
69    /// Reference to the control actor.
70    pub control: ActorRef<ControlRunner>,
71    dataplane: ActorRef<DataplaneActor>,
72    /// Reference to the direct (disco/UDP underlay) manager, retained so [`Runtime::rebind`] can
73    /// ask it to re-bind the underlay socket on a network/link change.
74    direct: ActorRef<DirectManager>,
75    /// Reference to the application netstack actor. `None` in TUN transport mode, where there is
76    /// no userspace application netstack (the application data path is a real kernel TUN device).
77    netstack: Option<WeakActorRef<NetstackActor>>,
78    /// Reference to the peer tracker for peer lookups.
79    pub peer_tracker: WeakActorRef<PeerTracker>,
80    /// Fallback TCP handler registry, bound to the application netstack. `None` in TUN transport
81    /// mode (no application netstack exists to attach it to).
82    fallback_tcp: Option<fallback_tcp::FallbackTcpManager>,
83    /// Reference to the forwarder actor, retained so [`Runtime::set_advertise_routes`] can push a
84    /// new accept/dial route table onto the running forwarder (the local half of advertising
85    /// routes). Without this the strong ref would drop after the startup `GetChannel` and the
86    /// forwarder would be reachable only via the message bus.
87    forwarder: ActorRef<ForwarderActor>,
88    /// Reference to the multiderp manager, retained so [`Runtime::status`] can resolve each
89    /// relayed peer's DERP region id to its region **code** (`ipnstate.PeerStatus.Relay`). Without
90    /// this the strong ref would drop after startup (it is cloned into the direct manager + route
91    /// updater) and the region-code map would be unreachable.
92    multiderp: ActorRef<Multiderp>,
93    env: Env,
94    shutdown: watch::Sender<bool>,
95    /// Sender side of the exit-node selector `watch` cell. Held privately here (not on the cloned
96    /// `Env`, which keeps only the read side) so that only `Runtime::set_exit_node` can mutate the
97    /// selection; the route updater and source filter re-read it via [`Env::exit_node`].
98    exit_node_tx: watch::Sender<Option<ts_control::ExitNodeSelector>>,
99    /// Receiver mirroring the *active* (resolved + fail-closed) exit node's stable id, fed by the
100    /// route updater. Read by [`Runtime::status`] / [`Runtime::active_exit_node`] to report which
101    /// exit node traffic is actually egressing through (vs. the merely-configured selector).
102    active_exit_rx: watch::Receiver<Option<ts_control::StableNodeId>>,
103    /// Receiver for the device connection-state cell, fed by the control runner. Read by
104    /// [`Runtime::watch_state`] and [`Runtime::wait_until_running`].
105    state_rx: watch::Receiver<DeviceState>,
106    /// Receiver for the retained peer-capability grants, fed by the packet-filter updater. Read by
107    /// [`Runtime::whois`] to resolve the flow-scoped cap map (Go `apitype.WhoIsResponse.CapMap`).
108    cap_grants_rx: watch::Receiver<packetfilter::CapGrants>,
109    /// Live advertised-route preference (explicit subnet routes + the exit-node flag), seeded from
110    /// the startup config. [`Runtime::set_advertise_routes`] and [`set_advertise_exit_node`] each
111    /// mutate their part under this lock then re-send the composed set, so the two compose.
112    advertise: std::sync::Mutex<AdvertiseState>,
113}
114
115impl Runtime {
116    /// Spawn a new runtime with the given parameters for connecting to a tailnet.
117    pub async fn spawn(
118        config: ts_control::Config,
119        auth_key: Option<String>,
120        keys: ts_keys::NodeState,
121    ) -> Result<Self, Error> {
122        let (shutdown_tx, shutdown_rx) = watch::channel(false);
123
124        // The exit-node selector is a live `watch` cell so `Device::set_exit_node` can change it at
125        // runtime. `new_with_exit_tx` returns the `Sender` (mutation capability) separately so it is
126        // retained privately on the `Runtime`, while only the `Receiver` (the readers' contract)
127        // lives on the cloned `Env`. The initial value comes from `ForwarderConfig.exit_node`.
128        let (env, exit_node_tx) = Env::new_with_exit_tx(
129            keys,
130            shutdown_rx,
131            env::ForwarderConfig::from_control_config(&config),
132        );
133
134        // Both userspace netstacks (application + forwarder) share one netstack config. Honor the
135        // per-deployment TCP buffer knob when set, otherwise fall back to the netstack default.
136        let netstack_config = netstack_config_from(config.tcp_buffer_size);
137
138        let dataplane = DataplaneActor::spawn(env.clone());
139
140        let (netstack_id, netstack_up, netstack_down) =
141            dataplane.ask(dataplane::NewOverlayTransport).await?;
142
143        // A second overlay transport feeds the dedicated any-IP forwarder netstack. Inbound packets
144        // for advertised subnet routes / the exit-node default route are routed here (see
145        // `route_updater`), keeping forwarded flows off the application netstack.
146        let (forwarder_id, forwarder_up, forwarder_down) =
147            dataplane.ask(dataplane::NewOverlayTransport).await?;
148
149        let multiderp = Multiderp::spawn((env.clone(), dataplane.clone()));
150
151        // Spawn the direct (disco) underlay manager before the route updater. Its `on_start`
152        // binds the UDP socket and registers its transport synchronously, so by the time the
153        // route updater asks it for the direct transport id it is guaranteed to be available.
154        let direct = DirectManager::spawn((env.clone(), dataplane.clone(), multiderp.clone()));
155
156        // Spawn the forwarder before the route updater. Its `on_start` builds the forwarder
157        // netstack, enables any-IP acceptance, and starts the per-port accept loops synchronously,
158        // so by the time the route updater begins delivering advertised prefixes to
159        // `forwarder_id` the netstack is already draining its transport.
160        let forwarder = ForwarderActor::spawn((
161            env.clone(),
162            netstack_config.clone(),
163            forwarder_up,
164            forwarder_down,
165        ));
166        // Force `on_start` to finish (any-IP enabled, accept loops live) before the route updater
167        // can route the first inbound flow to `forwarder_id`: an `ask` blocks until the actor has
168        // started.
169        //
170        // The forwarder netstack's overlay `Channel` is reused by the TUN application path for
171        // recursive / exit-node-DoH MagicDNS forwarding (TUN mode has no application netstack of its
172        // own, but the forwarder netstack runs in both modes and egresses over the overlay — the
173        // anti-leak property `forward_query`/`forward_doh` require). Only the `tun` Tun arm consumes
174        // it, so it is unused when the `tun` feature is off — allow that without warn-as-error.
175        #[cfg_attr(not(feature = "tun"), allow(unused_variables))]
176        let (forwarder_channel,) = forwarder.ask(forwarder_actor::GetChannel).await?;
177
178        // The route updater is the single authoritative resolver of the active (resolved,
179        // fail-closed) exit node; it publishes the resolved stable id into this watch cell so
180        // `Runtime::status` can report which exit is actually engaged (not just configured).
181        let (active_exit_tx, active_exit_rx) = watch::channel(None);
182        route_updater::RouteUpdater::spawn((
183            multiderp.clone(),
184            direct.clone(),
185            env.clone(),
186            netstack_id,
187            forwarder_id,
188            active_exit_tx,
189        ));
190        // The packet-filter updater also surfaces the retained cap-grants (for flow-scoped WhoIs)
191        // through a `watch` cell whose receiver the `Runtime` holds — the bus has no replay, so a
192        // `watch` is how `Runtime::whois` reads the current grants on demand.
193        let (cap_grants_tx, cap_grants_rx) = watch::channel(Default::default());
194        packetfilter::PacketfilterUpdater::spawn((env.clone(), cap_grants_tx));
195        src_filter::SourceFilterUpdater::spawn(env.clone());
196        let peer_tracker = PeerTracker::spawn(env.clone()).downgrade();
197
198        // Select the application data path from the transport mode. The forwarder/egress path
199        // above is UNCHANGED in both modes — TUN mode only swaps the application data path, never
200        // the forwarder. `config` is moved into `ControlRunner::spawn` below, so branch on a
201        // borrow and clone the small `TunConfig` where needed before the move.
202        //
203        // - Netstack (the default, and the only reachable arm when the `tun` feature is off):
204        //   spawn the application netstack + MagicDNS responder + fallback-TCP registry, all on
205        //   the `netstack_up`/`netstack_down` overlay seam.
206        // - Tun: spawn `TunActor` on that same overlay seam instead; no application netstack and
207        //   no MagicDNS responder exist, and `netstack`/`fallback_tcp` are `None`.
208        // - Tun requested but built without the `tun` feature: hard-error (a config/build
209        //   mismatch knowable at spawn time). NEVER silently fall back to netstack.
210        let (netstack, fallback_tcp) = match &config.transport_mode {
211            ts_control::TransportMode::Netstack => {
212                let netstack = NetstackActor::spawn((
213                    env.clone(),
214                    netstack_config,
215                    netstack_up,
216                    netstack_down,
217                ));
218
219                // Fetch the netstack channel while we still hold the strong ActorRef, then spawn
220                // the MagicDNS responder on it. Fire-and-forget: like src_filter/route_updater,
221                // it's owned by the message bus and isn't stored on `Runtime`.
222                let (channel,) = netstack.ask(netstack_actor::GetChannel).await?;
223                // The fallback-TCP registry attaches to the application netstack — the same one
224                // that carries the embedder's explicit `Device::tcp_listen` sockets — so a
225                // fallback handler sees exactly the inbound flows no explicit listener matched.
226                let fallback_tcp = fallback_tcp::FallbackTcpManager::new(channel.clone());
227                magic_dns::MagicDnsActor::spawn((env.clone(), channel));
228
229                (Some(netstack.downgrade()), Some(fallback_tcp))
230            }
231
232            #[cfg(feature = "tun")]
233            ts_control::TransportMode::Tun(tun_cfg) => {
234                // Reuse the same `netstack_up`/`netstack_down` overlay-transport pair that would
235                // have fed the netstack — it is just the application-side overlay seam (the name
236                // is historical). No NetstackActor / MagicDnsActor is spawned.
237                tun_actor::TunActor::spawn((
238                    env.clone(),
239                    tun_cfg.clone(),
240                    netstack_up,
241                    netstack_down,
242                    // Host-route gating inputs derived from `Env`: subnet routes are only steered
243                    // into the TUN when `--accept-routes` is set, and the host `/0` only when the
244                    // embedder configured an exit node. See `tun_actor::host_routes_from_node`.
245                    tun_actor::HostRouteGating {
246                        accept_routes: env.accept_routes,
247                        exit_node_configured: env.exit_node().is_some(),
248                    },
249                    // Reuse the forwarder netstack's overlay `Channel` for recursive / exit-node-DoH
250                    // MagicDNS forwarding in the TUN datapath (TUN mode has no application netstack
251                    // Channel of its own). Egresses over the overlay — anti-leak preserved.
252                    forwarder_channel.clone(),
253                ));
254
255                (None, None)
256            }
257
258            #[cfg(not(feature = "tun"))]
259            ts_control::TransportMode::Tun(_) => {
260                return Err(Error {
261                    kind: ErrorKind::TunUnavailable,
262                    target_actor: None,
263                    message_ty: None,
264                });
265            }
266        };
267
268        // Device connection-state cell. Created here (not inside the actor) so the control runner's
269        // `on_start` can publish `Failed`/`NeedsLogin` and still return `Err` without the sender
270        // being tied to a `Self` that never gets constructed on a hard registration failure.
271        let (state_tx, state_rx) = watch::channel(DeviceState::Connecting);
272
273        // Seed the live advertised-route preference from the startup config before `config` moves
274        // into the control runner, so the runtime setters compose against the configured baseline.
275        let advertise = std::sync::Mutex::new(AdvertiseState {
276            routes: config.advertise_routes.clone(),
277            exit_node: config.advertise_exit_node,
278        });
279
280        let control = ControlRunner::spawn(control_runner::Params {
281            config,
282            auth_key,
283            env: env.clone(),
284            state_tx,
285        });
286
287        Ok(Self {
288            control,
289            dataplane,
290            direct,
291            peer_tracker,
292            fallback_tcp,
293            forwarder,
294            multiderp,
295            netstack,
296            env,
297            shutdown: shutdown_tx,
298            exit_node_tx,
299            active_exit_rx,
300            state_rx,
301            cap_grants_rx,
302            advertise,
303        })
304    }
305
306    /// Register a fallback TCP handler consulted for every inbound TCP flow that matches no
307    /// explicit listener (`tsnet.Server.RegisterFallbackTCPHandler` parity).
308    ///
309    /// The returned [`fallback_tcp::FallbackTcpHandle`] deregisters the handler when dropped. See
310    /// [`fallback_tcp`] for the dispatch contract and anti-leak guarantees.
311    ///
312    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
313    /// application netstack to attach a fallback handler to.
314    pub fn register_fallback_tcp_handler(
315        &self,
316        cb: Arc<
317            dyn Fn(core::net::SocketAddr, core::net::SocketAddr) -> fallback_tcp::FallbackDecision
318                + Send
319                + Sync,
320        >,
321    ) -> Result<fallback_tcp::FallbackTcpHandle, Error> {
322        Ok(self
323            .fallback_tcp
324            .as_ref()
325            .ok_or(Error {
326                kind: ErrorKind::UnsupportedInTunMode,
327                target_actor: None,
328                message_ty: None,
329            })?
330            .register(cb))
331    }
332
333    /// Get a channel to send commands to the netstack.
334    ///
335    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
336    /// application netstack.
337    pub async fn channel(&self) -> Result<Channel, Error> {
338        let (channel,) = self
339            .netstack
340            .as_ref()
341            .ok_or(Error {
342                kind: ErrorKind::UnsupportedInTunMode,
343                target_actor: None,
344                message_ty: None,
345            })?
346            .upgrade()
347            .ok_or(Error {
348                kind: ErrorKind::ActorGone,
349                target_actor: None,
350                message_ty: None,
351            })?
352            .ask(netstack_actor::GetChannel)
353            .await?;
354
355        Ok(channel)
356    }
357
358    /// The Taildrop file store, if Taildrop is enabled (`taildrop_dir` configured and the store
359    /// initialized). `None` when disabled — fail-closed. Shared with the peerAPI Taildrop server so
360    /// the embedder's read APIs and the receive path see the same on-disk store.
361    pub fn taildrop_store(&self) -> Option<Arc<crate::taildrop::TaildropStore>> {
362        self.env.taildrop_store.clone()
363    }
364
365    /// The shared Funnel ingress slot the peerAPI `/v0/ingress` route reads per connection.
366    ///
367    /// `Device::listen_funnel` installs a [`FunnelManager`](crate::funnel::FunnelManager)'s sink here
368    /// to make the route live (the peerAPI server is already running from startup). Returns a clone of
369    /// the runtime-lifetime `Arc` so the device can write the slot without restarting the server. See
370    /// [`crate::funnel`] for the ingress data path.
371    pub fn funnel_ingress_slot(&self) -> crate::funnel::FunnelIngressSlot {
372        self.env.funnel_ingress.clone()
373    }
374
375    /// The shared "Funnel ingress listener active" flag (the same `Arc` the control session reads to
376    /// set `HostInfo.IngressEnabled`). `Device::listen_funnel` flips it `true` while a funnel listener
377    /// is up so control routes Funnel traffic to this node; clearing it advertises no live endpoint.
378    pub fn ingress_active_flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
379        self.env.ingress_active.clone()
380    }
381
382    /// Install (`Some`) or clear (`None`) the debug packet-capture hook on the running dataplane.
383    /// `Some(hook)` tees every plaintext packet crossing the datapath to `hook` until it is cleared;
384    /// `None` stops capture. Mirrors Go `tstun.Wrapper.InstallCaptureHook` / `ClearCaptureSink`.
385    pub async fn install_capture(
386        &self,
387        hook: Option<ts_dataplane::CaptureHook>,
388    ) -> Result<(), Error> {
389        self.dataplane
390            .ask(dataplane::InstallCapture { hook })
391            .await
392            .map_err(Into::into)
393    }
394
395    /// Re-bind the underlay UDP socket after a network/link change (Wi-Fi switch, sleep/wake). The
396    /// embedder's own link monitor calls this (the engine owns the socket re-bind; the embedder owns
397    /// OS netmon). Re-binds the socket (same-port-preferred, IPv4-only invariant preserved) and
398    /// resets the now-stale local NAT mapping — clearing learned reflexive addresses and every
399    /// confirmed direct path while keeping candidate endpoints, so peers re-probe over the new socket
400    /// and relay over DERP (never a direct host dial) until a path re-confirms. Peers, control, the
401    /// netmap, disco state, and DERP are untouched. A no-op when the underlay is inert (bind failed
402    /// at startup, DERP-only). Mirrors Go magicsock `Conn.Rebind` + `resetEndpointStates`.
403    pub async fn rebind(&self) -> Result<(), Error> {
404        self.direct.ask(direct::Rebind).await.map_err(Error::from)
405    }
406
407    /// A snapshot of the local netmap: this node plus every known peer.
408    ///
409    /// Combines the self node held by the control runner with the peer set held by the peer
410    /// tracker. Mirrors tsnet's `LocalClient::Status`.
411    ///
412    /// `self_node` is `None` until the first netmap update has been received from control. Peer
413    /// entries carry no online/user/capability data (see the [`status`] module docs for that gap).
414    pub async fn status(&self) -> Result<Status, Error> {
415        let self_node_domain = self.control.ask(control_runner::SelfNode).await?;
416        // The MagicDNS suffix is the self node's FQDN minus its host label — already split into
417        // `Node.tailnet` at decode time (Go derives it the same way in `NetworkMap.MagicDNSSuffix`).
418        // Capture it before the domain `Node` is mapped away into a `StatusNode`.
419        let magic_dns_suffix = self_node_domain.as_ref().and_then(|n| n.tailnet.clone());
420        let self_node = self_node_domain.as_ref().map(StatusNode::from_node);
421
422        let peers_with_ids = self
423            .peer_tracker
424            .upgrade()
425            .ok_or(Error {
426                kind: ErrorKind::ActorGone,
427                target_actor: None,
428                message_ty: None,
429            })?
430            .ask(peer_tracker::GetStatus)
431            .await?;
432
433        // Join per-peer connectivity (Go `PeerStatus.CurAddr`): one batched query to the direct
434        // manager for every peer's current trusted direct endpoint, then fill `cur_addr` on each
435        // `StatusNode`. A peer absent from the map is relayed via DERP (`cur_addr = None`). This is a
436        // live snapshot — the direct path can expire/re-confirm between calls (matches Go's snapshot
437        // semantics). The `watch_netmap` stream intentionally carries no connectivity (it is a netmap
438        // watch, not a path-state watch, and does not re-fire on direct↔relay flips).
439        let ids: Vec<ts_transport::PeerId> = peers_with_ids.iter().map(|(id, _)| *id).collect();
440        let best_addrs = self
441            .direct
442            .ask(direct::BestAddrs { ids: ids.clone() })
443            .await
444            .unwrap_or_default();
445
446        // For the peers with NO direct path (relayed via DERP), resolve the region CODE they relay
447        // through (Go `PeerStatus.Relay`). One batched ask to multiderp; `cur_addr` and `relay` are
448        // mutually exclusive for a routed peer, mirroring Go's empty-vs-set strings.
449        let relay_ids: Vec<ts_transport::PeerId> = ids
450            .into_iter()
451            .filter(|id| !best_addrs.contains_key(id))
452            .collect();
453        let relay_codes = if relay_ids.is_empty() {
454            Default::default()
455        } else {
456            self.multiderp
457                .ask(multiderp::RelayCodesForPeers { ids: relay_ids })
458                .await
459                .unwrap_or_default()
460        };
461
462        let peers = peers_with_ids
463            .into_iter()
464            .map(|(id, mut node)| match best_addrs.get(&id).copied() {
465                Some(addr) => {
466                    node.cur_addr = Some(addr);
467                    node
468                }
469                None => {
470                    node.relay = relay_codes.get(&id).cloned();
471                    node
472                }
473            })
474            .collect();
475
476        Ok(Status {
477            self_node,
478            peers,
479            active_exit_node: self.active_exit_node(),
480            magic_dns_suffix,
481        })
482    }
483
484    /// List the tailnet peers this node can Taildrop a file *to* (Go LocalAPI `FileTargets`).
485    ///
486    /// Mirrors the upstream send-path filter (`feature/taildrop` `Extension::FileTargets`): a peer
487    /// qualifies when it advertises a reachable peerAPI **and** is either owned by the same user as
488    /// this node **or** explicitly granted the file-sharing-target capability. The whole list is
489    /// gated on this node holding the file-sharing capability (control sets it when the admin enables
490    /// Taildrop) — absent that, an empty list (fail-closed, not an error, matching how the receive
491    /// store returns empty when disabled). Results are sorted by the peer's MagicDNS name.
492    ///
493    /// Targets are listed regardless of current online state (upstream's `FileTargets` does not gate
494    /// on online either; an offline target's send will simply time out). The self node is never
495    /// included. Returns empty before the first netmap.
496    ///
497    /// Divergence from Go: the upstream filter also excludes `tvOS` peers, which this fork cannot
498    /// reproduce (the domain node carries no OS string); the impact is negligible — the actual send
499    /// fail-closes if such a peer refused the transfer.
500    pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
501        // Node-level gate: this node must hold the file-sharing capability (Taildrop enabled by the
502        // admin). Read it off the self node's cap map, like Go's `hasCapFileSharing()`.
503        let self_node = self.control.ask(control_runner::SelfNode).await?;
504        let Some(self_node) = self_node else {
505            return Ok(Vec::new()); // no netmap yet
506        };
507        if !self_node.can_share_files() {
508            return Ok(Vec::new()); // Taildrop not enabled for the tailnet — fail-closed
509        }
510        let self_user_id = self_node.user_id;
511
512        let peers = self
513            .peer_tracker
514            .upgrade()
515            .ok_or(Error {
516                kind: ErrorKind::ActorGone,
517                target_actor: None,
518                message_ty: None,
519            })?
520            .ask(peer_tracker::AllPeers)
521            .await?;
522
523        // Eligibility + ordering live in `build_file_targets` (pure, unit-tested in `status`).
524        Ok(status::build_file_targets(peers, self_user_id))
525    }
526
527    /// The stable id of the exit node traffic is currently egressing through, or `None` if none is
528    /// engaged. This is the route updater's resolved + fail-closed answer (see
529    /// [`Status::active_exit_node`](crate::status::Status::active_exit_node)): it differs from the
530    /// configured [`exit_node`](Self::exit_node) selector, which may name a peer that is absent or
531    /// no longer advertising a default route (in which case egress is dropped and this returns
532    /// `None`).
533    pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
534        self.active_exit_rx.borrow().clone()
535    }
536
537    /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
538    ///
539    /// Returns the signed JWT, or the token RPC's own [`ts_control::IdTokenError`]. The kameo
540    /// delegated-reply send error is flattened: a handler error carries the real `IdTokenError`,
541    /// any other send failure (actor shutdown / mailbox closed) is surfaced as
542    /// [`ts_control::IdTokenError::NetworkError`].
543    pub async fn fetch_id_token(
544        &self,
545        audience: String,
546    ) -> Result<String, ts_control::IdTokenError> {
547        self.control
548            .ask(control_runner::FetchIdToken { audience })
549            .await
550            .map_err(flatten_send_err)
551    }
552
553    /// Log this node out of the tailnet: deregister it by expiring its current node key.
554    ///
555    /// Forwards to the control runner, which re-POSTs `/machine/register` with a past expiry over a
556    /// fresh Noise channel. This is a control-plane state change only — it does NOT shut the runtime
557    /// down (the caller follows with [`graceful_shutdown`](Self::graceful_shutdown)) and does not
558    /// touch the on-disk node key. The kameo delegated-reply send error is flattened the same way as
559    /// [`fetch_id_token`](Self::fetch_id_token): a handler error carries the real
560    /// [`ts_control::LogoutError`]; any other send failure (actor shutdown / mailbox closed) is
561    /// surfaced as [`ts_control::LogoutError::NetworkError`].
562    pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
563        self.control
564            .ask(control_runner::Logout)
565            .await
566            .map_err(flatten_logout_send_err)
567    }
568
569    /// Publish a `TXT` DNS record for this node via control's `/machine/set-dns` (Go
570    /// `LocalClient.SetDNS`).
571    ///
572    /// Forwards to the control runner, which POSTs the record over a fresh Noise channel. The kameo
573    /// delegated-reply send error is flattened the same way as [`fetch_id_token`](Self::fetch_id_token):
574    /// a handler error carries the real [`ts_control::SetDnsError`]; any other send failure (actor
575    /// shutdown / mailbox closed) is surfaced as [`ts_control::SetDnsError::NetworkError`].
576    pub async fn set_dns(
577        &self,
578        name: String,
579        value: String,
580    ) -> Result<(), ts_control::SetDnsError> {
581        self.control
582            .ask(control_runner::SetDns { name, value })
583            .await
584            .map_err(flatten_set_dns_send_err)
585    }
586
587    /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` (`acme` feature).
588    ///
589    /// Mirrors [`fetch_id_token`](Self::fetch_id_token): forwards to the control runner, which runs
590    /// the client-side ACME DNS-01 flow on a spawned task and publishes the challenge TXT via the
591    /// node's set-dns RPC. The kameo delegated-reply send error is flattened — a handler error
592    /// carries the real [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox
593    /// closed) is surfaced as a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control
594    /// plane 501s on set-dns.
595    #[cfg(feature = "acme")]
596    pub async fn get_certificate(
597        &self,
598        name: String,
599    ) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
600        self.control
601            .ask(control_runner::GetCertificate { name })
602            .await
603            .map_err(flatten_cert_send_err)
604    }
605
606    /// Resolve which node owns a tailnet source address.
607    ///
608    /// Maps the destination IP of `addr` to its owning node. Mirrors tsnet's `LocalClient::WhoIs`.
609    /// Returns `None` if no peer holds that tailnet IP.
610    ///
611    /// The returned [`WhoIs`] additionally carries the **flow-scoped** peer-capability grants
612    /// ([`WhoIs::cap_map`], Go `apitype.WhoIsResponse.CapMap`): the caps control's packet-filter
613    /// application rules authorize for traffic from THIS node (the flow source) to `addr` (the
614    /// destination). Empty when no grant matches. (The node-level cap map rides
615    /// [`WhoIs::capabilities`].)
616    pub async fn whois(&self, addr: core::net::SocketAddr) -> Result<Option<WhoIs>, Error> {
617        let whois = self
618            .peer_tracker
619            .upgrade()
620            .ok_or(Error {
621                kind: ErrorKind::ActorGone,
622                target_actor: None,
623                message_ty: None,
624            })?
625            .ask(peer_tracker::Whois { addr })
626            .await?;
627
628        let Some(mut whois) = whois else {
629            return Ok(None);
630        };
631
632        // Fill the flow-scoped cap map: src = this node's own tailnet IP (of the dst's family),
633        // dst = the queried address. A grant applies when src ∈ its src prefixes AND dst ∈ its dst
634        // prefixes (Go `Filter.CapsWithValues`). Resolve our own IP from the self node; if it isn't
635        // known yet, leave the map empty (no grants resolvable without a source).
636        let dst = addr.ip();
637        if let Some(self_node) = self.control.ask(control_runner::SelfNode).await? {
638            let src: core::net::IpAddr = if dst.is_ipv6() {
639                self_node.tailnet_address.ipv6.addr().into()
640            } else {
641                self_node.tailnet_address.ipv4.addr().into()
642            };
643            let grants = self.cap_grants_rx.borrow();
644            whois.cap_map = ts_packetfilter_state::caps_for(&grants, src, dst);
645        }
646
647        Ok(Some(whois))
648    }
649
650    /// The current direct-path status to the peer holding tailnet IP `dst`: its confirmed direct UDP
651    /// endpoint and that path's last-measured RTT, or `None` when there is no direct path right now
652    /// (the peer is relayed via DERP, is unknown, or has no disco key).
653    ///
654    /// The latency is the RTT of the most recent disco ping/pong that confirmed the path — a live
655    /// snapshot up to one probe interval stale, NOT a fresh on-demand round-trip (that is a separate,
656    /// heavier capability). Mirrors the direct-path latency Go surfaces for `ipnstate.PeerStatus`.
657    pub async fn direct_path(
658        &self,
659        dst: core::net::IpAddr,
660    ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
661        let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
662            kind: ErrorKind::ActorGone,
663            target_actor: None,
664            message_ty: None,
665        })?;
666
667        // Resolve the tailnet IP to its node, then to its disco key. No node / no disco key ⇒ no
668        // direct path is possible (a peer with no disco key can only be reached via DERP).
669        let Some(node) = peer_tracker
670            .ask(peer_tracker::PeerByTailnetIp { ip: dst })
671            .await?
672        else {
673            return Ok(None);
674        };
675        let Some(disco) = node.disco_key else {
676            return Ok(None);
677        };
678
679        self.direct
680            .ask(direct::DirectPathLatency { disco })
681            .await
682            .map_err(Into::into)
683    }
684
685    /// Send a disco ping to the peer holding tailnet IP `dst` **now** and await the pong, returning
686    /// the fresh round-trip latency and the endpoint that answered, or `None` if no pong arrives
687    /// within `timeout` (or the peer is unknown / has no disco key / no candidate path). This is the
688    /// true on-demand `PingType::Disco` (Go `tailscale ping`), as opposed to
689    /// [`direct_path`](Self::direct_path) which reports the last periodic probe's RTT.
690    ///
691    /// The ping round-trip is awaited OFF the direct manager's mailbox (we take a `MagicSock` handle
692    /// and await on it directly), so a slow/timing-out ping never blocks the actor.
693    pub async fn ping_disco(
694        &self,
695        dst: core::net::IpAddr,
696        timeout: Duration,
697    ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
698        let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
699            kind: ErrorKind::ActorGone,
700            target_actor: None,
701            message_ty: None,
702        })?;
703
704        let Some(node) = peer_tracker
705            .ask(peer_tracker::PeerByTailnetIp { ip: dst })
706            .await?
707        else {
708            return Ok(None);
709        };
710        let Some(disco) = node.disco_key else {
711            return Ok(None);
712        };
713
714        // Cheap synchronous handle fetch, then await the ping OFF the actor mailbox.
715        let Some(sock) = self.direct.ask(direct::SockHandle).await? else {
716            return Ok(None);
717        };
718        // A `ping_now` error is an underlay UDP send failure (not an actor problem); surface it as a
719        // reply-level error. A timed-out / unanswered ping is `Ok(None)`, not an error.
720        sock.ping_now(&disco, timeout).await.map_err(|_| Error {
721            kind: ErrorKind::ReplyErr,
722            target_actor: None,
723            message_ty: None,
724        })
725    }
726
727    /// Change the selected exit node at runtime (the equivalent of Go `tsnet`'s
728    /// `LocalClient.EditPrefs(ExitNodeID/ExitNodeIP)`), without recreating the device.
729    ///
730    /// Updates the live exit-node selector, then asks the peer tracker to re-broadcast the current
731    /// peer set so the route updater and source filter re-resolve the new selector immediately.
732    /// `None` clears the exit node (internet-bound traffic is then dropped, fail-closed, unless this
733    /// node egresses directly). The selection is re-resolved against the live peer set, so passing a
734    /// selector for a peer not yet in the netmap simply takes effect once that peer appears.
735    pub async fn set_exit_node(
736        &self,
737        selector: Option<ts_control::ExitNodeSelector>,
738    ) -> Result<(), Error> {
739        // Update the live cell every reader borrows from. `send_replace` keeps the value current
740        // even with no active receivers (none can have dropped while the runtime is up, but it is
741        // the right non-failing primitive here).
742        self.exit_node_tx.send_replace(selector);
743
744        // Trigger an immediate re-resolution: the route updater (outbound routes + DoH delegation)
745        // and the source filter (inbound validation) both recompute on an `Arc<PeerState>`, so a
746        // re-broadcast applies the new exit without waiting for the next netmap update.
747        self.peer_tracker
748            .upgrade()
749            .ok_or(Error {
750                kind: ErrorKind::ActorGone,
751                target_actor: None,
752                message_ty: None,
753            })?
754            .ask(peer_tracker::RepublishState)
755            .await
756            .map_err(Into::into)
757    }
758
759    /// The currently-selected exit node, or `None` if none is selected.
760    pub fn exit_node(&self) -> Option<ts_control::ExitNodeSelector> {
761        self.env.exit_node()
762    }
763
764    /// Change the set of subnet routes this node advertises at runtime (Go `tailscale set
765    /// --advertise-routes`). Applies BOTH halves together so the wire and the data path agree:
766    ///
767    /// 1. **Wire** — re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
768    ///    (so control grants the node the subnet-router role for exactly these prefixes).
769    /// 2. **Local** — swap the forwarder's accept/dial route table (so the node actually forwards the
770    ///    prefixes it advertises). New flows see the new set; in-flight flows keep their routing.
771    ///
772    /// `routes` is filtered to the IPv4-only, deduplicated set this fork can honor (IPv6 prefixes are
773    /// dropped under the IPv6-off posture — we never advertise a route we won't forward), so the wire
774    /// and forwarder are fed the identical final set. This sets the explicit subnet prefixes only; it
775    /// does NOT touch the exit-node `0.0.0.0/0` advertisement (a separate concern).
776    pub async fn set_advertise_routes(&self, routes: Vec<ipnet::IpNet>) -> Result<(), Error> {
777        // Update the explicit-subnet part of the live preference, keep the exit-node flag, and
778        // re-send the composed set. Composes with `set_advertise_exit_node` (neither clobbers the
779        // other's contribution to `Hostinfo.RoutableIPs`).
780        let composed = {
781            let mut adv = self.advertise.lock().unwrap_or_else(|p| p.into_inner());
782            adv.routes = routes;
783            compose_advertised_routes(adv.routes.clone(), adv.exit_node)
784        };
785        self.apply_advertised_routes(composed).await
786    }
787
788    /// Advertise (or stop advertising) this node as an **exit node** — the `0.0.0.0/0` default route
789    /// (Go `tailscale set --advertise-exit-node`). Composes with
790    /// [`set_advertise_routes`](Self::set_advertise_routes): toggling the exit node re-sends the
791    /// explicit subnet routes plus (when `enable`) `0.0.0.0/0`, so the two preferences are
792    /// independent. Like `set_advertise_routes`, this both re-advertises `Hostinfo.RoutableIPs` to
793    /// control AND updates the forwarder's accept/dial set, applied together. Control still gates
794    /// whether the advertised exit node is actually *usable* by peers (this only advertises it).
795    pub async fn set_advertise_exit_node(&self, enable: bool) -> Result<(), Error> {
796        let composed = {
797            let mut adv = self.advertise.lock().unwrap_or_else(|p| p.into_inner());
798            adv.exit_node = enable;
799            compose_advertised_routes(adv.routes.clone(), adv.exit_node)
800        };
801        self.apply_advertised_routes(composed).await
802    }
803
804    /// Push a freshly-composed advertised-route set to BOTH halves: the forwarder's accept/dial
805    /// table (local) FIRST — so the node forwards a prefix before control grants it, never the
806    /// reverse — then re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
807    /// (wire). `composed` is already filtered + exit-node-folded by [`compose_advertised_routes`].
808    async fn apply_advertised_routes(&self, composed: Vec<ipnet::IpNet>) -> Result<(), Error> {
809        self.forwarder
810            .ask(forwarder_actor::UpdateRoutes {
811                routes: composed.clone(),
812            })
813            .await?;
814        self.control
815            .ask(control_runner::SetAdvertiseRoutes { routes: composed })
816            .await
817            .map_err(Into::into)
818    }
819
820    /// Subscribe to netmap peer-change events.
821    ///
822    /// Returns a [`watch::Receiver`] whose value is the current set of peer [`StatusNode`]s,
823    /// updated on every netmap state update from control. Mirrors tsnet's `WatchIPNBus`. Await
824    /// [`watch::Receiver::changed`](tokio::sync::watch::Receiver::changed) to react to peers
825    /// joining, leaving, or changing.
826    pub async fn watch_netmap(&self) -> Result<watch::Receiver<Vec<StatusNode>>, Error> {
827        self.peer_tracker
828            .upgrade()
829            .ok_or(Error {
830                kind: ErrorKind::ActorGone,
831                target_actor: None,
832                message_ty: None,
833            })?
834            .ask(peer_tracker::WatchNetmap)
835            .await
836            .map_err(Into::into)
837    }
838
839    /// The current device connection-[`DeviceState`].
840    pub fn device_state(&self) -> DeviceState {
841        self.state_rx.borrow().clone()
842    }
843
844    /// Watch the device connection-[`DeviceState`] (`Connecting` → `Running` / `NeedsLogin` /
845    /// `Expired` / `Failed`).
846    ///
847    /// Returns a [`watch::Receiver`]; await
848    /// [`changed`](tokio::sync::watch::Receiver::changed) to react push-style to control connection
849    /// transitions instead of polling [`status`](Self::status). The initial value is the current
850    /// state. Note: a transient per-reconnect dip back to `Connecting` is **not** currently
851    /// emitted (control transparently reconnects below this layer); the state reflects registration
852    /// outcome and node-key expiry.
853    pub fn watch_state(&self) -> watch::Receiver<DeviceState> {
854        self.state_rx.clone()
855    }
856
857    /// Wait until the device finishes registering, returning a typed outcome.
858    ///
859    /// Resolves `Ok(())` once the device reaches [`DeviceState::Running`]. Returns a typed
860    /// [`RegistrationError`] otherwise — the actionable distinction between "retry", "re-pair", and
861    /// "drive interactive login" that replaces polling [`ipv4_addr`](Self::ipv4_addr) in a loop:
862    /// - `AuthRejected` — bad/expired/unknown auth key. **Permanent** (re-pair).
863    /// - `NeedsLogin(url)` — interactive authorization required (no usable auth key). **Not
864    ///   permanent**: the runtime keeps retrying and will reach `Running` once the user authorizes
865    ///   the URL. An **auth-key** caller should treat this as a failure; an **interactive** caller
866    ///   should ignore this return and instead drive the flow via [`watch_state`](Self::watch_state)
867    ///   (this method returns the URL eagerly rather than blocking for the whole login).
868    /// - `NetworkUnreachable` — control unreachable. **Transient** (retry).
869    /// - `Timeout` — no settled state within `timeout`.
870    ///
871    /// `KeyExpired` is not produced by this initial wait (a node key expires only *after* it has
872    /// come up); observe post-registration expiry via [`watch_state`](Self::watch_state).
873    /// `timeout` of `None` waits indefinitely for a settled state.
874    pub async fn wait_until_running(
875        &self,
876        timeout: Option<Duration>,
877    ) -> Result<(), RegistrationError> {
878        device_state::wait_for_running(self.state_rx.clone(), timeout).await
879    }
880
881    /// Attempt to shut down the runtime gracefully.
882    ///
883    /// Returns false if the shutdown timed out. It is still shut down if it timed out, just
884    /// more violently and with possible resource leaks.
885    pub async fn graceful_shutdown(self, timeout: Option<Duration>) -> bool {
886        self.shutdown.send_replace(true);
887
888        async fn _shutdown_all(runtime: Runtime) {
889            // See the note in `Drop` for why we only need to stop these actors to bring down the
890            // whole runtime.
891
892            let _ignore = runtime.control.stop_gracefully().await;
893            let _ignore = runtime.dataplane.stop_gracefully().await;
894            let _ignore = runtime.env.bus.stop_gracefully().await;
895
896            tokio::join![
897                runtime.control.wait_for_shutdown(),
898                runtime.dataplane.wait_for_shutdown(),
899                runtime.env.bus.wait_for_shutdown(),
900            ];
901        }
902
903        let fut = _shutdown_all(self);
904
905        match timeout {
906            Some(timeout) => tokio::time::timeout(timeout, fut).await.is_ok(),
907            None => {
908                fut.await;
909                true
910            }
911        }
912    }
913}
914
915impl Drop for Runtime {
916    fn drop(&mut self) {
917        // We must have already run `graceful_shutdown`: on the happy path, this does nothing, but
918        // if it timed out, we need to make sure the actors are dead so we don't leak them and their
919        // dependents.
920        if *self.shutdown.borrow() {
921            self.control.kill();
922            self.dataplane.kill();
923            self.env.bus.kill();
924            return;
925        }
926
927        self.shutdown.send_replace(true);
928
929        // Actors shut down when the last ActorRef to them is dropped (as nothing can send them
930        // messages anymore). If we don't hold an ActorRef in Runtime, in general the only thing
931        // that has one is the MessageBus, which each actor subscribes to for a subset of messages.
932        // Hence, if we shut down the bus, most actors die as well.
933
934        // First shut down the actors we have an ActorRef to:
935        try_shutdown(&self.control);
936        try_shutdown(&self.dataplane);
937
938        // Then shutdown the message bus, stopping the rest of the actors:
939        try_shutdown(&self.env.bus);
940    }
941}
942
943fn try_shutdown(a: &ActorRef<impl kameo::Actor>) {
944    if let Err(e) = a.mailbox_sender().try_send(Signal::Stop) {
945        tracing::error!(error = %e, "graceful shutdown failed, killing actor");
946        a.kill();
947    }
948}
949
950/// Build the netstack config shared by both userspace netstacks (application + forwarder) from the
951/// per-deployment `tcp_buffer_size` knob.
952///
953/// `None` keeps the netstack default (256 KiB/direction); `Some(n)` overrides it (e.g. a smaller
954/// window on a memory-constrained exit node forwarding many concurrent flows — see
955/// [`netstack::netcore::Config::tcp_buffer_size`]). Factored out of [`Runtime::spawn`] so the
956/// None-default / Some-override mapping is unit-testable without standing up the actor system.
957fn netstack_config_from(tcp_buffer_size: Option<usize>) -> netstack::netcore::Config {
958    let mut c = netstack::netcore::Config::default();
959    if let Some(tcp_buffer_size) = tcp_buffer_size {
960        c.tcp_buffer_size = tcp_buffer_size;
961    }
962    c
963}
964
965/// Filter a requested advertise-route set to the IPv4-only, deduplicated set this fork can honor,
966/// mirroring [`ts_control::Config::advertised_routes`] so a runtime `set_advertise_routes` feeds the
967/// wire (control grant) and the forwarder (accept/dial table) the identical final set. IPv6 prefixes
968/// are dropped under the IPv6-off posture — we never advertise a route we won't forward. Order is
969/// preserved (first occurrence wins). Factored out so the filter is unit-testable without an actor.
970fn filter_advertise_routes(routes: Vec<ipnet::IpNet>) -> Vec<ipnet::IpNet> {
971    let mut filtered: Vec<ipnet::IpNet> = Vec::new();
972    for net in routes {
973        if matches!(net, ipnet::IpNet::V4(_)) {
974            if !filtered.contains(&net) {
975                filtered.push(net);
976            }
977        } else {
978            tracing::warn!(prefix = %net, "dropping IPv6 advertise route (IPv6-off posture)");
979        }
980    }
981    filtered
982}
983
984/// Compose the final advertised-route set from the explicit subnet `routes` and the exit-node flag,
985/// mirroring [`ts_control::Config::advertised_routes`]: the IPv4-only, deduplicated subnet prefixes,
986/// plus `0.0.0.0/0` appended when `exit_node` is set. This is the single source of truth both
987/// runtime advertise mutators (`set_advertise_routes`, `set_advertise_exit_node`) feed, so the two
988/// compose instead of clobbering. Factored out so the composition is unit-testable without an actor.
989fn compose_advertised_routes(routes: Vec<ipnet::IpNet>, exit_node: bool) -> Vec<ipnet::IpNet> {
990    let mut filtered = filter_advertise_routes(routes);
991    if exit_node {
992        let default_v4 = ipnet::IpNet::V4(
993            ipnet::Ipv4Net::new(core::net::Ipv4Addr::UNSPECIFIED, 0)
994                .expect("0.0.0.0/0 is a valid prefix"),
995        );
996        if !filtered.contains(&default_v4) {
997            filtered.push(default_v4);
998        }
999    }
1000    filtered
1001}
1002
1003/// The runtime's live advertised-route preference: the explicit subnet routes plus whether this node
1004/// advertises itself as an exit node. Held behind a `Mutex` on the [`Runtime`] so
1005/// [`Runtime::set_advertise_routes`] and [`Runtime::set_advertise_exit_node`] each mutate their own
1006/// part and re-send the composed set — they compose rather than clobber (Go `EditPrefs` keeps
1007/// `AdvertiseRoutes` and the exit-node advertisement as independent prefs that both feed
1008/// `Hostinfo.RoutableIPs`).
1009#[derive(Debug, Default, Clone)]
1010struct AdvertiseState {
1011    /// The explicit subnet prefixes (pre-filter; the last value passed to `set_advertise_routes`).
1012    routes: Vec<ipnet::IpNet>,
1013    /// Whether this node advertises the exit-node default route (`0.0.0.0/0`).
1014    exit_node: bool,
1015}
1016
1017/// Flatten a kameo delegated-reply [`SendError`] for the id-token RPC into the RPC's own
1018/// [`ts_control::IdTokenError`].
1019///
1020/// A [`SendError::HandlerError`](kameo::error::SendError::HandlerError) carries the real
1021/// `IdTokenError` produced by the handler and is surfaced verbatim. Any other send failure (actor
1022/// not running / stopped, mailbox full, send timeout) is a delivery problem rather than an RPC
1023/// result, so it collapses to a transient [`ts_control::IdTokenError::NetworkError`]. Factored out
1024/// of [`Runtime::fetch_id_token`] so this mapping is unit-testable without standing up an actor.
1025fn flatten_send_err<M>(
1026    e: kameo::error::SendError<M, ts_control::IdTokenError>,
1027) -> ts_control::IdTokenError {
1028    match e {
1029        kameo::error::SendError::HandlerError(err) => err,
1030        _ => ts_control::IdTokenError::NetworkError,
1031    }
1032}
1033
1034/// Flatten a kameo `SendError` from the `Logout` ask into a [`ts_control::LogoutError`].
1035///
1036/// A `HandlerError` carries the real `LogoutError` from the control RPC and is surfaced verbatim;
1037/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
1038/// problem, not a logout result — collapses to the transient [`ts_control::LogoutError::NetworkError`]
1039/// (logout is idempotent, so a retry after a delivery failure is safe). Factored out of
1040/// [`Runtime::logout`] so the mapping is unit-testable without standing up an actor.
1041fn flatten_logout_send_err<M>(
1042    e: kameo::error::SendError<M, ts_control::LogoutError>,
1043) -> ts_control::LogoutError {
1044    match e {
1045        kameo::error::SendError::HandlerError(err) => err,
1046        _ => ts_control::LogoutError::NetworkError,
1047    }
1048}
1049
1050/// Flatten a kameo `SendError` from the `SetDns` ask into a [`ts_control::SetDnsError`].
1051///
1052/// A `HandlerError` carries the real `SetDnsError` from the set-dns RPC and is surfaced verbatim;
1053/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
1054/// problem, not a publish result — collapses to the transient
1055/// [`ts_control::SetDnsError::NetworkError`]. Factored out of [`Runtime::set_dns`] so the mapping is
1056/// unit-testable without standing up an actor.
1057fn flatten_set_dns_send_err<M>(
1058    e: kameo::error::SendError<M, ts_control::SetDnsError>,
1059) -> ts_control::SetDnsError {
1060    match e {
1061        kameo::error::SendError::HandlerError(err) => err,
1062        _ => ts_control::SetDnsError::NetworkError,
1063    }
1064}
1065
1066/// Flatten a kameo `SendError` from the `GetCertificate` ask into a [`ts_control::CertError`].
1067///
1068/// A `HandlerError` carries the real `CertError` produced by the ACME issuance and is surfaced
1069/// verbatim. `CertError` has no transient-network variant, so any other send failure (actor not
1070/// running / stopped, mailbox full, send timeout) — a delivery problem rather than an issuance
1071/// result — collapses to a [`ts_control::CertError::Io`]. Factored out of
1072/// [`Runtime::get_certificate`] so this mapping is unit-testable without standing up an actor.
1073#[cfg(feature = "acme")]
1074fn flatten_cert_send_err<M>(
1075    e: kameo::error::SendError<M, ts_control::CertError>,
1076) -> ts_control::CertError {
1077    match e {
1078        kameo::error::SendError::HandlerError(err) => err,
1079        _ => ts_control::CertError::Io(std::io::Error::other(
1080            "control runner unavailable for certificate issuance",
1081        )),
1082    }
1083}
1084
1085#[cfg(test)]
1086mod tests {
1087    use super::*;
1088
1089    /// `None` must leave the netstack's own default TCP window in place (the 256 KiB throughput
1090    /// default), and must not silently coerce to some other value.
1091    #[test]
1092    fn netstack_config_none_uses_netstack_default() {
1093        let default = netstack::netcore::Config::default();
1094        let built = netstack_config_from(None);
1095        assert_eq!(
1096            built.tcp_buffer_size, default.tcp_buffer_size,
1097            "None must inherit the netstack default TCP buffer size"
1098        );
1099    }
1100
1101    /// `Some(n)` must override the TCP window (the memory-vs-throughput knob exit-node operators
1102    /// reach for), reaching the config that both netstacks are built from.
1103    #[test]
1104    fn netstack_config_some_overrides_buffer() {
1105        let built = netstack_config_from(Some(64 * 1024));
1106        assert_eq!(
1107            built.tcp_buffer_size,
1108            64 * 1024,
1109            "Some(n) must override the TCP buffer size that both netstacks use"
1110        );
1111    }
1112
1113    /// `set_advertise_routes` must feed the wire and the forwarder the IDENTICAL filtered set:
1114    /// IPv4-only (IPv6 dropped under the IPv6-off posture), deduplicated, order preserved.
1115    #[test]
1116    fn filter_advertise_routes_keeps_v4_dedups_drops_v6() {
1117        let v4a: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
1118        let v4b: ipnet::IpNet = "192.168.1.0/24".parse().unwrap();
1119        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1120
1121        // Mixed input with a duplicate v4 and a v6 prefix.
1122        let out = filter_advertise_routes(vec![v4a, v6, v4b, v4a]);
1123
1124        assert_eq!(
1125            out,
1126            vec![v4a, v4b],
1127            "v6 dropped, duplicate v4 collapsed, first-occurrence order preserved"
1128        );
1129    }
1130
1131    /// An all-IPv6 request filters to empty (we never advertise a route we won't forward) rather
1132    /// than erroring — clearing the advertised set is a legitimate outcome.
1133    #[test]
1134    fn filter_advertise_routes_all_v6_is_empty() {
1135        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1136        assert!(filter_advertise_routes(vec![v6]).is_empty());
1137    }
1138
1139    /// `compose_advertised_routes` folds the exit-node `0.0.0.0/0` onto the filtered subnet routes
1140    /// when (and only when) the exit-node flag is set — so `set_advertise_routes` and
1141    /// `set_advertise_exit_node` compose. The two preferences are independent.
1142    #[test]
1143    fn compose_advertised_routes_folds_exit_node() {
1144        let subnet: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
1145        let default_v4: ipnet::IpNet = "0.0.0.0/0".parse().unwrap();
1146
1147        // Exit node off: just the (filtered) subnet routes.
1148        assert_eq!(
1149            compose_advertised_routes(vec![subnet], false),
1150            vec![subnet],
1151            "exit-node off ⇒ no default route"
1152        );
1153        // Exit node on: subnet routes PLUS 0.0.0.0/0.
1154        assert_eq!(
1155            compose_advertised_routes(vec![subnet], true),
1156            vec![subnet, default_v4],
1157            "exit-node on ⇒ 0.0.0.0/0 appended"
1158        );
1159        // Exit node on with NO subnet routes: just the default route.
1160        assert_eq!(
1161            compose_advertised_routes(vec![], true),
1162            vec![default_v4],
1163            "exit-node alone advertises only 0.0.0.0/0"
1164        );
1165        // Idempotent: an explicit 0.0.0.0/0 already in the routes isn't duplicated by the fold.
1166        assert_eq!(
1167            compose_advertised_routes(vec![default_v4], true),
1168            vec![default_v4],
1169            "the exit-node fold dedups against an explicit default route"
1170        );
1171    }
1172
1173    /// A `HandlerError` carries the real `IdTokenError` from the RPC handler and must pass through
1174    /// verbatim, not be flattened to a generic network error. Using an `Internal(_)` payload (not
1175    /// `NetworkError`) makes the passthrough observable: a buggy flatten that always returned
1176    /// `NetworkError` would fail this assertion.
1177    #[test]
1178    fn flatten_send_err_handler_error_passes_through() {
1179        // Build an `Internal(_)` payload via the public `From<Utf8Error>` conversion (no extra
1180        // deps): it is distinct from the `_ => NetworkError` fallback, so a buggy flatten that
1181        // always returned `NetworkError` would fail this assertion.
1182        // Route the invalid bytes through a runtime Vec so the `invalid_from_utf8` lint (which only
1183        // fires on compile-time-known literals) doesn't flag this intentional bad input.
1184        let bytes = vec![0xffu8, 0xfe];
1185        let utf8_err = core::str::from_utf8(&bytes).unwrap_err();
1186        let inner = ts_control::IdTokenError::from(utf8_err);
1187        assert!(matches!(inner, ts_control::IdTokenError::Internal(_)));
1188        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1189            kameo::error::SendError::HandlerError(inner.clone());
1190        assert_eq!(flatten_send_err(e), inner);
1191    }
1192
1193    /// A non-handler send failure (actor stopped) is a delivery problem, not an RPC result, so it
1194    /// must collapse to a transient `NetworkError`.
1195    #[test]
1196    fn flatten_send_err_actor_stopped_is_network_error() {
1197        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1198            kameo::error::SendError::ActorStopped;
1199        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1200    }
1201
1202    /// `ActorNotRunning` (the message bounces back undelivered) is likewise a delivery failure and
1203    /// must map to a transient `NetworkError`.
1204    #[test]
1205    fn flatten_send_err_actor_not_running_is_network_error() {
1206        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1207            kameo::error::SendError::ActorNotRunning(control_runner::FetchIdToken {
1208                audience: "sts.amazonaws.com".to_string(),
1209            });
1210        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1211    }
1212
1213    /// A `HandlerError` from the logout RPC carries the real `LogoutError` and must pass through
1214    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1215    /// passthrough observable.
1216    #[test]
1217    fn flatten_logout_send_err_handler_error_passes_through() {
1218        let inner = ts_control::LogoutError::Internal(ts_control::LogoutInternalErrorKind::Http);
1219        assert!(matches!(inner, ts_control::LogoutError::Internal(_)));
1220        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1221            kameo::error::SendError::HandlerError(inner.clone());
1222        assert_eq!(flatten_logout_send_err(e), inner);
1223    }
1224
1225    /// A non-handler send failure (actor stopped) is a delivery problem, not a logout result, and
1226    /// collapses to a transient `NetworkError` (logout is idempotent, so a retry is safe).
1227    #[test]
1228    fn flatten_logout_send_err_actor_stopped_is_network_error() {
1229        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1230            kameo::error::SendError::ActorStopped;
1231        assert_eq!(
1232            flatten_logout_send_err(e),
1233            ts_control::LogoutError::NetworkError
1234        );
1235    }
1236
1237    /// A `HandlerError` from the set-dns RPC carries the real `SetDnsError` and must pass through
1238    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1239    /// passthrough observable.
1240    #[test]
1241    fn flatten_set_dns_send_err_handler_error_passes_through() {
1242        let inner = ts_control::SetDnsError::Internal(ts_control::SetDnsInternalErrorKind::Http);
1243        assert!(matches!(inner, ts_control::SetDnsError::Internal(_)));
1244        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
1245            kameo::error::SendError::HandlerError(inner.clone());
1246        assert_eq!(flatten_set_dns_send_err(e), inner);
1247    }
1248
1249    /// A non-handler send failure (actor stopped) is a delivery problem, not a publish result, and
1250    /// collapses to a transient `NetworkError`.
1251    #[test]
1252    fn flatten_set_dns_send_err_actor_stopped_is_network_error() {
1253        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
1254            kameo::error::SendError::ActorStopped;
1255        assert_eq!(
1256            flatten_set_dns_send_err(e),
1257            ts_control::SetDnsError::NetworkError
1258        );
1259    }
1260}