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    env: Env,
84    shutdown: watch::Sender<bool>,
85    /// Sender side of the exit-node selector `watch` cell. Held privately here (not on the cloned
86    /// `Env`, which keeps only the read side) so that only `Runtime::set_exit_node` can mutate the
87    /// selection; the route updater and source filter re-read it via [`Env::exit_node`].
88    exit_node_tx: watch::Sender<Option<ts_control::ExitNodeSelector>>,
89    /// Receiver mirroring the *active* (resolved + fail-closed) exit node's stable id, fed by the
90    /// route updater. Read by [`Runtime::status`] / [`Runtime::active_exit_node`] to report which
91    /// exit node traffic is actually egressing through (vs. the merely-configured selector).
92    active_exit_rx: watch::Receiver<Option<ts_control::StableNodeId>>,
93    /// Receiver for the device connection-state cell, fed by the control runner. Read by
94    /// [`Runtime::watch_state`] and [`Runtime::wait_until_running`].
95    state_rx: watch::Receiver<DeviceState>,
96}
97
98impl Runtime {
99    /// Spawn a new runtime with the given parameters for connecting to a tailnet.
100    pub async fn spawn(
101        config: ts_control::Config,
102        auth_key: Option<String>,
103        keys: ts_keys::NodeState,
104    ) -> Result<Self, Error> {
105        let (shutdown_tx, shutdown_rx) = watch::channel(false);
106
107        // The exit-node selector is a live `watch` cell so `Device::set_exit_node` can change it at
108        // runtime. `new_with_exit_tx` returns the `Sender` (mutation capability) separately so it is
109        // retained privately on the `Runtime`, while only the `Receiver` (the readers' contract)
110        // lives on the cloned `Env`. The initial value comes from `ForwarderConfig.exit_node`.
111        let (env, exit_node_tx) = Env::new_with_exit_tx(
112            keys,
113            shutdown_rx,
114            env::ForwarderConfig::from_control_config(&config),
115        );
116
117        // Both userspace netstacks (application + forwarder) share one netstack config. Honor the
118        // per-deployment TCP buffer knob when set, otherwise fall back to the netstack default.
119        let netstack_config = netstack_config_from(config.tcp_buffer_size);
120
121        let dataplane = DataplaneActor::spawn(env.clone());
122
123        let (netstack_id, netstack_up, netstack_down) =
124            dataplane.ask(dataplane::NewOverlayTransport).await?;
125
126        // A second overlay transport feeds the dedicated any-IP forwarder netstack. Inbound packets
127        // for advertised subnet routes / the exit-node default route are routed here (see
128        // `route_updater`), keeping forwarded flows off the application netstack.
129        let (forwarder_id, forwarder_up, forwarder_down) =
130            dataplane.ask(dataplane::NewOverlayTransport).await?;
131
132        let multiderp = Multiderp::spawn((env.clone(), dataplane.clone()));
133
134        // Spawn the direct (disco) underlay manager before the route updater. Its `on_start`
135        // binds the UDP socket and registers its transport synchronously, so by the time the
136        // route updater asks it for the direct transport id it is guaranteed to be available.
137        let direct = DirectManager::spawn((env.clone(), dataplane.clone(), multiderp.clone()));
138
139        // Spawn the forwarder before the route updater. Its `on_start` builds the forwarder
140        // netstack, enables any-IP acceptance, and starts the per-port accept loops synchronously,
141        // so by the time the route updater begins delivering advertised prefixes to
142        // `forwarder_id` the netstack is already draining its transport.
143        let forwarder = ForwarderActor::spawn((
144            env.clone(),
145            netstack_config.clone(),
146            forwarder_up,
147            forwarder_down,
148        ));
149        // Force `on_start` to finish (any-IP enabled, accept loops live) before the route updater
150        // can route the first inbound flow to `forwarder_id`: an `ask` blocks until the actor has
151        // started.
152        //
153        // The forwarder netstack's overlay `Channel` is reused by the TUN application path for
154        // recursive / exit-node-DoH MagicDNS forwarding (TUN mode has no application netstack of its
155        // own, but the forwarder netstack runs in both modes and egresses over the overlay — the
156        // anti-leak property `forward_query`/`forward_doh` require). Only the `tun` Tun arm consumes
157        // it, so it is unused when the `tun` feature is off — allow that without warn-as-error.
158        #[cfg_attr(not(feature = "tun"), allow(unused_variables))]
159        let (forwarder_channel,) = forwarder.ask(forwarder_actor::GetChannel).await?;
160
161        // The route updater is the single authoritative resolver of the active (resolved,
162        // fail-closed) exit node; it publishes the resolved stable id into this watch cell so
163        // `Runtime::status` can report which exit is actually engaged (not just configured).
164        let (active_exit_tx, active_exit_rx) = watch::channel(None);
165        route_updater::RouteUpdater::spawn((
166            multiderp.clone(),
167            direct.clone(),
168            env.clone(),
169            netstack_id,
170            forwarder_id,
171            active_exit_tx,
172        ));
173        packetfilter::PacketfilterUpdater::spawn(env.clone());
174        src_filter::SourceFilterUpdater::spawn(env.clone());
175        let peer_tracker = PeerTracker::spawn(env.clone()).downgrade();
176
177        // Select the application data path from the transport mode. The forwarder/egress path
178        // above is UNCHANGED in both modes — TUN mode only swaps the application data path, never
179        // the forwarder. `config` is moved into `ControlRunner::spawn` below, so branch on a
180        // borrow and clone the small `TunConfig` where needed before the move.
181        //
182        // - Netstack (the default, and the only reachable arm when the `tun` feature is off):
183        //   spawn the application netstack + MagicDNS responder + fallback-TCP registry, all on
184        //   the `netstack_up`/`netstack_down` overlay seam.
185        // - Tun: spawn `TunActor` on that same overlay seam instead; no application netstack and
186        //   no MagicDNS responder exist, and `netstack`/`fallback_tcp` are `None`.
187        // - Tun requested but built without the `tun` feature: hard-error (a config/build
188        //   mismatch knowable at spawn time). NEVER silently fall back to netstack.
189        let (netstack, fallback_tcp) = match &config.transport_mode {
190            ts_control::TransportMode::Netstack => {
191                let netstack = NetstackActor::spawn((
192                    env.clone(),
193                    netstack_config,
194                    netstack_up,
195                    netstack_down,
196                ));
197
198                // Fetch the netstack channel while we still hold the strong ActorRef, then spawn
199                // the MagicDNS responder on it. Fire-and-forget: like src_filter/route_updater,
200                // it's owned by the message bus and isn't stored on `Runtime`.
201                let (channel,) = netstack.ask(netstack_actor::GetChannel).await?;
202                // The fallback-TCP registry attaches to the application netstack — the same one
203                // that carries the embedder's explicit `Device::tcp_listen` sockets — so a
204                // fallback handler sees exactly the inbound flows no explicit listener matched.
205                let fallback_tcp = fallback_tcp::FallbackTcpManager::new(channel.clone());
206                magic_dns::MagicDnsActor::spawn((env.clone(), channel));
207
208                (Some(netstack.downgrade()), Some(fallback_tcp))
209            }
210
211            #[cfg(feature = "tun")]
212            ts_control::TransportMode::Tun(tun_cfg) => {
213                // Reuse the same `netstack_up`/`netstack_down` overlay-transport pair that would
214                // have fed the netstack — it is just the application-side overlay seam (the name
215                // is historical). No NetstackActor / MagicDnsActor is spawned.
216                tun_actor::TunActor::spawn((
217                    env.clone(),
218                    tun_cfg.clone(),
219                    netstack_up,
220                    netstack_down,
221                    // Host-route gating inputs derived from `Env`: subnet routes are only steered
222                    // into the TUN when `--accept-routes` is set, and the host `/0` only when the
223                    // embedder configured an exit node. See `tun_actor::host_routes_from_node`.
224                    tun_actor::HostRouteGating {
225                        accept_routes: env.accept_routes,
226                        exit_node_configured: env.exit_node().is_some(),
227                    },
228                    // Reuse the forwarder netstack's overlay `Channel` for recursive / exit-node-DoH
229                    // MagicDNS forwarding in the TUN datapath (TUN mode has no application netstack
230                    // Channel of its own). Egresses over the overlay — anti-leak preserved.
231                    forwarder_channel.clone(),
232                ));
233
234                (None, None)
235            }
236
237            #[cfg(not(feature = "tun"))]
238            ts_control::TransportMode::Tun(_) => {
239                return Err(Error {
240                    kind: ErrorKind::TunUnavailable,
241                    target_actor: None,
242                    message_ty: None,
243                });
244            }
245        };
246
247        // Device connection-state cell. Created here (not inside the actor) so the control runner's
248        // `on_start` can publish `Failed`/`NeedsLogin` and still return `Err` without the sender
249        // being tied to a `Self` that never gets constructed on a hard registration failure.
250        let (state_tx, state_rx) = watch::channel(DeviceState::Connecting);
251
252        let control = ControlRunner::spawn(control_runner::Params {
253            config,
254            auth_key,
255            env: env.clone(),
256            state_tx,
257        });
258
259        Ok(Self {
260            control,
261            dataplane,
262            direct,
263            peer_tracker,
264            fallback_tcp,
265            netstack,
266            env,
267            shutdown: shutdown_tx,
268            exit_node_tx,
269            active_exit_rx,
270            state_rx,
271        })
272    }
273
274    /// Register a fallback TCP handler consulted for every inbound TCP flow that matches no
275    /// explicit listener (`tsnet.Server.RegisterFallbackTCPHandler` parity).
276    ///
277    /// The returned [`fallback_tcp::FallbackTcpHandle`] deregisters the handler when dropped. See
278    /// [`fallback_tcp`] for the dispatch contract and anti-leak guarantees.
279    ///
280    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
281    /// application netstack to attach a fallback handler to.
282    pub fn register_fallback_tcp_handler(
283        &self,
284        cb: Arc<
285            dyn Fn(core::net::SocketAddr, core::net::SocketAddr) -> fallback_tcp::FallbackDecision
286                + Send
287                + Sync,
288        >,
289    ) -> Result<fallback_tcp::FallbackTcpHandle, Error> {
290        Ok(self
291            .fallback_tcp
292            .as_ref()
293            .ok_or(Error {
294                kind: ErrorKind::UnsupportedInTunMode,
295                target_actor: None,
296                message_ty: None,
297            })?
298            .register(cb))
299    }
300
301    /// Get a channel to send commands to the netstack.
302    ///
303    /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
304    /// application netstack.
305    pub async fn channel(&self) -> Result<Channel, Error> {
306        let (channel,) = self
307            .netstack
308            .as_ref()
309            .ok_or(Error {
310                kind: ErrorKind::UnsupportedInTunMode,
311                target_actor: None,
312                message_ty: None,
313            })?
314            .upgrade()
315            .ok_or(Error {
316                kind: ErrorKind::ActorGone,
317                target_actor: None,
318                message_ty: None,
319            })?
320            .ask(netstack_actor::GetChannel)
321            .await?;
322
323        Ok(channel)
324    }
325
326    /// The Taildrop file store, if Taildrop is enabled (`taildrop_dir` configured and the store
327    /// initialized). `None` when disabled — fail-closed. Shared with the peerAPI Taildrop server so
328    /// the embedder's read APIs and the receive path see the same on-disk store.
329    pub fn taildrop_store(&self) -> Option<Arc<crate::taildrop::TaildropStore>> {
330        self.env.taildrop_store.clone()
331    }
332
333    /// The shared Funnel ingress slot the peerAPI `/v0/ingress` route reads per connection.
334    ///
335    /// `Device::listen_funnel` installs a [`FunnelManager`](crate::funnel::FunnelManager)'s sink here
336    /// to make the route live (the peerAPI server is already running from startup). Returns a clone of
337    /// the runtime-lifetime `Arc` so the device can write the slot without restarting the server. See
338    /// [`crate::funnel`] for the ingress data path.
339    pub fn funnel_ingress_slot(&self) -> crate::funnel::FunnelIngressSlot {
340        self.env.funnel_ingress.clone()
341    }
342
343    /// The shared "Funnel ingress listener active" flag (the same `Arc` the control session reads to
344    /// set `HostInfo.IngressEnabled`). `Device::listen_funnel` flips it `true` while a funnel listener
345    /// is up so control routes Funnel traffic to this node; clearing it advertises no live endpoint.
346    pub fn ingress_active_flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
347        self.env.ingress_active.clone()
348    }
349
350    /// Install (`Some`) or clear (`None`) the debug packet-capture hook on the running dataplane.
351    /// `Some(hook)` tees every plaintext packet crossing the datapath to `hook` until it is cleared;
352    /// `None` stops capture. Mirrors Go `tstun.Wrapper.InstallCaptureHook` / `ClearCaptureSink`.
353    pub async fn install_capture(
354        &self,
355        hook: Option<ts_dataplane::CaptureHook>,
356    ) -> Result<(), Error> {
357        self.dataplane
358            .ask(dataplane::InstallCapture { hook })
359            .await
360            .map_err(Into::into)
361    }
362
363    /// Re-bind the underlay UDP socket after a network/link change (Wi-Fi switch, sleep/wake). The
364    /// embedder's own link monitor calls this (the engine owns the socket re-bind; the embedder owns
365    /// OS netmon). Re-binds the socket (same-port-preferred, IPv4-only invariant preserved) and
366    /// resets the now-stale local NAT mapping — clearing learned reflexive addresses and every
367    /// confirmed direct path while keeping candidate endpoints, so peers re-probe over the new socket
368    /// and relay over DERP (never a direct host dial) until a path re-confirms. Peers, control, the
369    /// netmap, disco state, and DERP are untouched. A no-op when the underlay is inert (bind failed
370    /// at startup, DERP-only). Mirrors Go magicsock `Conn.Rebind` + `resetEndpointStates`.
371    pub async fn rebind(&self) -> Result<(), Error> {
372        self.direct.ask(direct::Rebind).await.map_err(Error::from)
373    }
374
375    /// A snapshot of the local netmap: this node plus every known peer.
376    ///
377    /// Combines the self node held by the control runner with the peer set held by the peer
378    /// tracker. Mirrors tsnet's `LocalClient::Status`.
379    ///
380    /// `self_node` is `None` until the first netmap update has been received from control. Peer
381    /// entries carry no online/user/capability data (see the [`status`] module docs for that gap).
382    pub async fn status(&self) -> Result<Status, Error> {
383        let self_node_domain = self.control.ask(control_runner::SelfNode).await?;
384        // The MagicDNS suffix is the self node's FQDN minus its host label — already split into
385        // `Node.tailnet` at decode time (Go derives it the same way in `NetworkMap.MagicDNSSuffix`).
386        // Capture it before the domain `Node` is mapped away into a `StatusNode`.
387        let magic_dns_suffix = self_node_domain.as_ref().and_then(|n| n.tailnet.clone());
388        let self_node = self_node_domain.as_ref().map(StatusNode::from_node);
389
390        let peers = self
391            .peer_tracker
392            .upgrade()
393            .ok_or(Error {
394                kind: ErrorKind::ActorGone,
395                target_actor: None,
396                message_ty: None,
397            })?
398            .ask(peer_tracker::GetStatus)
399            .await?;
400
401        Ok(Status {
402            self_node,
403            peers,
404            active_exit_node: self.active_exit_node(),
405            magic_dns_suffix,
406        })
407    }
408
409    /// List the tailnet peers this node can Taildrop a file *to* (Go LocalAPI `FileTargets`).
410    ///
411    /// Mirrors the upstream send-path filter (`feature/taildrop` `Extension::FileTargets`): a peer
412    /// qualifies when it advertises a reachable peerAPI **and** is either owned by the same user as
413    /// this node **or** explicitly granted the file-sharing-target capability. The whole list is
414    /// gated on this node holding the file-sharing capability (control sets it when the admin enables
415    /// Taildrop) — absent that, an empty list (fail-closed, not an error, matching how the receive
416    /// store returns empty when disabled). Results are sorted by the peer's MagicDNS name.
417    ///
418    /// Targets are listed regardless of current online state (upstream's `FileTargets` does not gate
419    /// on online either; an offline target's send will simply time out). The self node is never
420    /// included. Returns empty before the first netmap.
421    ///
422    /// Divergence from Go: the upstream filter also excludes `tvOS` peers, which this fork cannot
423    /// reproduce (the domain node carries no OS string); the impact is negligible — the actual send
424    /// fail-closes if such a peer refused the transfer.
425    pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
426        // Node-level gate: this node must hold the file-sharing capability (Taildrop enabled by the
427        // admin). Read it off the self node's cap map, like Go's `hasCapFileSharing()`.
428        let self_node = self.control.ask(control_runner::SelfNode).await?;
429        let Some(self_node) = self_node else {
430            return Ok(Vec::new()); // no netmap yet
431        };
432        if !self_node.can_share_files() {
433            return Ok(Vec::new()); // Taildrop not enabled for the tailnet — fail-closed
434        }
435        let self_user_id = self_node.user_id;
436
437        let peers = self
438            .peer_tracker
439            .upgrade()
440            .ok_or(Error {
441                kind: ErrorKind::ActorGone,
442                target_actor: None,
443                message_ty: None,
444            })?
445            .ask(peer_tracker::AllPeers)
446            .await?;
447
448        // Eligibility + ordering live in `build_file_targets` (pure, unit-tested in `status`).
449        Ok(status::build_file_targets(peers, self_user_id))
450    }
451
452    /// The stable id of the exit node traffic is currently egressing through, or `None` if none is
453    /// engaged. This is the route updater's resolved + fail-closed answer (see
454    /// [`Status::active_exit_node`](crate::status::Status::active_exit_node)): it differs from the
455    /// configured [`exit_node`](Self::exit_node) selector, which may name a peer that is absent or
456    /// no longer advertising a default route (in which case egress is dropped and this returns
457    /// `None`).
458    pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
459        self.active_exit_rx.borrow().clone()
460    }
461
462    /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
463    ///
464    /// Returns the signed JWT, or the token RPC's own [`ts_control::IdTokenError`]. The kameo
465    /// delegated-reply send error is flattened: a handler error carries the real `IdTokenError`,
466    /// any other send failure (actor shutdown / mailbox closed) is surfaced as
467    /// [`ts_control::IdTokenError::NetworkError`].
468    pub async fn fetch_id_token(
469        &self,
470        audience: String,
471    ) -> Result<String, ts_control::IdTokenError> {
472        self.control
473            .ask(control_runner::FetchIdToken { audience })
474            .await
475            .map_err(flatten_send_err)
476    }
477
478    /// Log this node out of the tailnet: deregister it by expiring its current node key.
479    ///
480    /// Forwards to the control runner, which re-POSTs `/machine/register` with a past expiry over a
481    /// fresh Noise channel. This is a control-plane state change only — it does NOT shut the runtime
482    /// down (the caller follows with [`graceful_shutdown`](Self::graceful_shutdown)) and does not
483    /// touch the on-disk node key. The kameo delegated-reply send error is flattened the same way as
484    /// [`fetch_id_token`](Self::fetch_id_token): a handler error carries the real
485    /// [`ts_control::LogoutError`]; any other send failure (actor shutdown / mailbox closed) is
486    /// surfaced as [`ts_control::LogoutError::NetworkError`].
487    pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
488        self.control
489            .ask(control_runner::Logout)
490            .await
491            .map_err(flatten_logout_send_err)
492    }
493
494    /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` (`acme` feature).
495    ///
496    /// Mirrors [`fetch_id_token`](Self::fetch_id_token): forwards to the control runner, which runs
497    /// the client-side ACME DNS-01 flow on a spawned task and publishes the challenge TXT via the
498    /// node's set-dns RPC. The kameo delegated-reply send error is flattened — a handler error
499    /// carries the real [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox
500    /// closed) is surfaced as a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control
501    /// plane 501s on set-dns.
502    #[cfg(feature = "acme")]
503    pub async fn get_certificate(
504        &self,
505        name: String,
506    ) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
507        self.control
508            .ask(control_runner::GetCertificate { name })
509            .await
510            .map_err(flatten_cert_send_err)
511    }
512
513    /// Resolve which node owns a tailnet source address.
514    ///
515    /// Maps the source IP of `addr` to its owning node. Mirrors tsnet's `LocalClient::WhoIs`.
516    /// Returns `None` if no peer holds that tailnet IP. The returned [`WhoIs`] carries no
517    /// user/login or capability data in this fork (see the [`status`] module docs).
518    pub async fn whois(&self, addr: core::net::SocketAddr) -> Result<Option<WhoIs>, Error> {
519        self.peer_tracker
520            .upgrade()
521            .ok_or(Error {
522                kind: ErrorKind::ActorGone,
523                target_actor: None,
524                message_ty: None,
525            })?
526            .ask(peer_tracker::Whois { addr })
527            .await
528            .map_err(Into::into)
529    }
530
531    /// Change the selected exit node at runtime (the equivalent of Go `tsnet`'s
532    /// `LocalClient.EditPrefs(ExitNodeID/ExitNodeIP)`), without recreating the device.
533    ///
534    /// Updates the live exit-node selector, then asks the peer tracker to re-broadcast the current
535    /// peer set so the route updater and source filter re-resolve the new selector immediately.
536    /// `None` clears the exit node (internet-bound traffic is then dropped, fail-closed, unless this
537    /// node egresses directly). The selection is re-resolved against the live peer set, so passing a
538    /// selector for a peer not yet in the netmap simply takes effect once that peer appears.
539    pub async fn set_exit_node(
540        &self,
541        selector: Option<ts_control::ExitNodeSelector>,
542    ) -> Result<(), Error> {
543        // Update the live cell every reader borrows from. `send_replace` keeps the value current
544        // even with no active receivers (none can have dropped while the runtime is up, but it is
545        // the right non-failing primitive here).
546        self.exit_node_tx.send_replace(selector);
547
548        // Trigger an immediate re-resolution: the route updater (outbound routes + DoH delegation)
549        // and the source filter (inbound validation) both recompute on an `Arc<PeerState>`, so a
550        // re-broadcast applies the new exit without waiting for the next netmap update.
551        self.peer_tracker
552            .upgrade()
553            .ok_or(Error {
554                kind: ErrorKind::ActorGone,
555                target_actor: None,
556                message_ty: None,
557            })?
558            .ask(peer_tracker::RepublishState)
559            .await
560            .map_err(Into::into)
561    }
562
563    /// The currently-selected exit node, or `None` if none is selected.
564    pub fn exit_node(&self) -> Option<ts_control::ExitNodeSelector> {
565        self.env.exit_node()
566    }
567
568    /// Subscribe to netmap peer-change events.
569    ///
570    /// Returns a [`watch::Receiver`] whose value is the current set of peer [`StatusNode`]s,
571    /// updated on every netmap state update from control. Mirrors tsnet's `WatchIPNBus`. Await
572    /// [`watch::Receiver::changed`](tokio::sync::watch::Receiver::changed) to react to peers
573    /// joining, leaving, or changing.
574    pub async fn watch_netmap(&self) -> Result<watch::Receiver<Vec<StatusNode>>, Error> {
575        self.peer_tracker
576            .upgrade()
577            .ok_or(Error {
578                kind: ErrorKind::ActorGone,
579                target_actor: None,
580                message_ty: None,
581            })?
582            .ask(peer_tracker::WatchNetmap)
583            .await
584            .map_err(Into::into)
585    }
586
587    /// The current device connection-[`DeviceState`].
588    pub fn device_state(&self) -> DeviceState {
589        self.state_rx.borrow().clone()
590    }
591
592    /// Watch the device connection-[`DeviceState`] (`Connecting` → `Running` / `NeedsLogin` /
593    /// `Expired` / `Failed`).
594    ///
595    /// Returns a [`watch::Receiver`]; await
596    /// [`changed`](tokio::sync::watch::Receiver::changed) to react push-style to control connection
597    /// transitions instead of polling [`status`](Self::status). The initial value is the current
598    /// state. Note: a transient per-reconnect dip back to `Connecting` is **not** currently
599    /// emitted (control transparently reconnects below this layer); the state reflects registration
600    /// outcome and node-key expiry.
601    pub fn watch_state(&self) -> watch::Receiver<DeviceState> {
602        self.state_rx.clone()
603    }
604
605    /// Wait until the device finishes registering, returning a typed outcome.
606    ///
607    /// Resolves `Ok(())` once the device reaches [`DeviceState::Running`]. Returns a typed
608    /// [`RegistrationError`] otherwise — the actionable distinction between "retry", "re-pair", and
609    /// "drive interactive login" that replaces polling [`ipv4_addr`](Self::ipv4_addr) in a loop:
610    /// - `AuthRejected` — bad/expired/unknown auth key. **Permanent** (re-pair).
611    /// - `NeedsLogin(url)` — interactive authorization required (no usable auth key). **Not
612    ///   permanent**: the runtime keeps retrying and will reach `Running` once the user authorizes
613    ///   the URL. An **auth-key** caller should treat this as a failure; an **interactive** caller
614    ///   should ignore this return and instead drive the flow via [`watch_state`](Self::watch_state)
615    ///   (this method returns the URL eagerly rather than blocking for the whole login).
616    /// - `NetworkUnreachable` — control unreachable. **Transient** (retry).
617    /// - `Timeout` — no settled state within `timeout`.
618    ///
619    /// `KeyExpired` is not produced by this initial wait (a node key expires only *after* it has
620    /// come up); observe post-registration expiry via [`watch_state`](Self::watch_state).
621    /// `timeout` of `None` waits indefinitely for a settled state.
622    pub async fn wait_until_running(
623        &self,
624        timeout: Option<Duration>,
625    ) -> Result<(), RegistrationError> {
626        device_state::wait_for_running(self.state_rx.clone(), timeout).await
627    }
628
629    /// Attempt to shut down the runtime gracefully.
630    ///
631    /// Returns false if the shutdown timed out. It is still shut down if it timed out, just
632    /// more violently and with possible resource leaks.
633    pub async fn graceful_shutdown(self, timeout: Option<Duration>) -> bool {
634        self.shutdown.send_replace(true);
635
636        async fn _shutdown_all(runtime: Runtime) {
637            // See the note in `Drop` for why we only need to stop these actors to bring down the
638            // whole runtime.
639
640            let _ignore = runtime.control.stop_gracefully().await;
641            let _ignore = runtime.dataplane.stop_gracefully().await;
642            let _ignore = runtime.env.bus.stop_gracefully().await;
643
644            tokio::join![
645                runtime.control.wait_for_shutdown(),
646                runtime.dataplane.wait_for_shutdown(),
647                runtime.env.bus.wait_for_shutdown(),
648            ];
649        }
650
651        let fut = _shutdown_all(self);
652
653        match timeout {
654            Some(timeout) => tokio::time::timeout(timeout, fut).await.is_ok(),
655            None => {
656                fut.await;
657                true
658            }
659        }
660    }
661}
662
663impl Drop for Runtime {
664    fn drop(&mut self) {
665        // We must have already run `graceful_shutdown`: on the happy path, this does nothing, but
666        // if it timed out, we need to make sure the actors are dead so we don't leak them and their
667        // dependents.
668        if *self.shutdown.borrow() {
669            self.control.kill();
670            self.dataplane.kill();
671            self.env.bus.kill();
672            return;
673        }
674
675        self.shutdown.send_replace(true);
676
677        // Actors shut down when the last ActorRef to them is dropped (as nothing can send them
678        // messages anymore). If we don't hold an ActorRef in Runtime, in general the only thing
679        // that has one is the MessageBus, which each actor subscribes to for a subset of messages.
680        // Hence, if we shut down the bus, most actors die as well.
681
682        // First shut down the actors we have an ActorRef to:
683        try_shutdown(&self.control);
684        try_shutdown(&self.dataplane);
685
686        // Then shutdown the message bus, stopping the rest of the actors:
687        try_shutdown(&self.env.bus);
688    }
689}
690
691fn try_shutdown(a: &ActorRef<impl kameo::Actor>) {
692    if let Err(e) = a.mailbox_sender().try_send(Signal::Stop) {
693        tracing::error!(error = %e, "graceful shutdown failed, killing actor");
694        a.kill();
695    }
696}
697
698/// Build the netstack config shared by both userspace netstacks (application + forwarder) from the
699/// per-deployment `tcp_buffer_size` knob.
700///
701/// `None` keeps the netstack default (256 KiB/direction); `Some(n)` overrides it (e.g. a smaller
702/// window on a memory-constrained exit node forwarding many concurrent flows — see
703/// [`netstack::netcore::Config::tcp_buffer_size`]). Factored out of [`Runtime::spawn`] so the
704/// None-default / Some-override mapping is unit-testable without standing up the actor system.
705fn netstack_config_from(tcp_buffer_size: Option<usize>) -> netstack::netcore::Config {
706    let mut c = netstack::netcore::Config::default();
707    if let Some(tcp_buffer_size) = tcp_buffer_size {
708        c.tcp_buffer_size = tcp_buffer_size;
709    }
710    c
711}
712
713/// Flatten a kameo delegated-reply [`SendError`] for the id-token RPC into the RPC's own
714/// [`ts_control::IdTokenError`].
715///
716/// A [`SendError::HandlerError`](kameo::error::SendError::HandlerError) carries the real
717/// `IdTokenError` produced by the handler and is surfaced verbatim. Any other send failure (actor
718/// not running / stopped, mailbox full, send timeout) is a delivery problem rather than an RPC
719/// result, so it collapses to a transient [`ts_control::IdTokenError::NetworkError`]. Factored out
720/// of [`Runtime::fetch_id_token`] so this mapping is unit-testable without standing up an actor.
721fn flatten_send_err<M>(
722    e: kameo::error::SendError<M, ts_control::IdTokenError>,
723) -> ts_control::IdTokenError {
724    match e {
725        kameo::error::SendError::HandlerError(err) => err,
726        _ => ts_control::IdTokenError::NetworkError,
727    }
728}
729
730/// Flatten a kameo `SendError` from the `Logout` ask into a [`ts_control::LogoutError`].
731///
732/// A `HandlerError` carries the real `LogoutError` from the control RPC and is surfaced verbatim;
733/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
734/// problem, not a logout result — collapses to the transient [`ts_control::LogoutError::NetworkError`]
735/// (logout is idempotent, so a retry after a delivery failure is safe). Factored out of
736/// [`Runtime::logout`] so the mapping is unit-testable without standing up an actor.
737fn flatten_logout_send_err<M>(
738    e: kameo::error::SendError<M, ts_control::LogoutError>,
739) -> ts_control::LogoutError {
740    match e {
741        kameo::error::SendError::HandlerError(err) => err,
742        _ => ts_control::LogoutError::NetworkError,
743    }
744}
745
746/// Flatten a kameo `SendError` from the `GetCertificate` ask into a [`ts_control::CertError`].
747///
748/// A `HandlerError` carries the real `CertError` produced by the ACME issuance and is surfaced
749/// verbatim. `CertError` has no transient-network variant, so any other send failure (actor not
750/// running / stopped, mailbox full, send timeout) — a delivery problem rather than an issuance
751/// result — collapses to a [`ts_control::CertError::Io`]. Factored out of
752/// [`Runtime::get_certificate`] so this mapping is unit-testable without standing up an actor.
753#[cfg(feature = "acme")]
754fn flatten_cert_send_err<M>(
755    e: kameo::error::SendError<M, ts_control::CertError>,
756) -> ts_control::CertError {
757    match e {
758        kameo::error::SendError::HandlerError(err) => err,
759        _ => ts_control::CertError::Io(std::io::Error::other(
760            "control runner unavailable for certificate issuance",
761        )),
762    }
763}
764
765#[cfg(test)]
766mod tests {
767    use super::*;
768
769    /// `None` must leave the netstack's own default TCP window in place (the 256 KiB throughput
770    /// default), and must not silently coerce to some other value.
771    #[test]
772    fn netstack_config_none_uses_netstack_default() {
773        let default = netstack::netcore::Config::default();
774        let built = netstack_config_from(None);
775        assert_eq!(
776            built.tcp_buffer_size, default.tcp_buffer_size,
777            "None must inherit the netstack default TCP buffer size"
778        );
779    }
780
781    /// `Some(n)` must override the TCP window (the memory-vs-throughput knob exit-node operators
782    /// reach for), reaching the config that both netstacks are built from.
783    #[test]
784    fn netstack_config_some_overrides_buffer() {
785        let built = netstack_config_from(Some(64 * 1024));
786        assert_eq!(
787            built.tcp_buffer_size,
788            64 * 1024,
789            "Some(n) must override the TCP buffer size that both netstacks use"
790        );
791    }
792
793    /// A `HandlerError` carries the real `IdTokenError` from the RPC handler and must pass through
794    /// verbatim, not be flattened to a generic network error. Using an `Internal(_)` payload (not
795    /// `NetworkError`) makes the passthrough observable: a buggy flatten that always returned
796    /// `NetworkError` would fail this assertion.
797    #[test]
798    fn flatten_send_err_handler_error_passes_through() {
799        // Build an `Internal(_)` payload via the public `From<Utf8Error>` conversion (no extra
800        // deps): it is distinct from the `_ => NetworkError` fallback, so a buggy flatten that
801        // always returned `NetworkError` would fail this assertion.
802        // Route the invalid bytes through a runtime Vec so the `invalid_from_utf8` lint (which only
803        // fires on compile-time-known literals) doesn't flag this intentional bad input.
804        let bytes = vec![0xffu8, 0xfe];
805        let utf8_err = core::str::from_utf8(&bytes).unwrap_err();
806        let inner = ts_control::IdTokenError::from(utf8_err);
807        assert!(matches!(inner, ts_control::IdTokenError::Internal(_)));
808        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
809            kameo::error::SendError::HandlerError(inner.clone());
810        assert_eq!(flatten_send_err(e), inner);
811    }
812
813    /// A non-handler send failure (actor stopped) is a delivery problem, not an RPC result, so it
814    /// must collapse to a transient `NetworkError`.
815    #[test]
816    fn flatten_send_err_actor_stopped_is_network_error() {
817        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
818            kameo::error::SendError::ActorStopped;
819        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
820    }
821
822    /// `ActorNotRunning` (the message bounces back undelivered) is likewise a delivery failure and
823    /// must map to a transient `NetworkError`.
824    #[test]
825    fn flatten_send_err_actor_not_running_is_network_error() {
826        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
827            kameo::error::SendError::ActorNotRunning(control_runner::FetchIdToken {
828                audience: "sts.amazonaws.com".to_string(),
829            });
830        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
831    }
832
833    /// A `HandlerError` from the logout RPC carries the real `LogoutError` and must pass through
834    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
835    /// passthrough observable.
836    #[test]
837    fn flatten_logout_send_err_handler_error_passes_through() {
838        let inner = ts_control::LogoutError::Internal(ts_control::LogoutInternalErrorKind::Http);
839        assert!(matches!(inner, ts_control::LogoutError::Internal(_)));
840        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
841            kameo::error::SendError::HandlerError(inner.clone());
842        assert_eq!(flatten_logout_send_err(e), inner);
843    }
844
845    /// A non-handler send failure (actor stopped) is a delivery problem, not a logout result, and
846    /// collapses to a transient `NetworkError` (logout is idempotent, so a retry is safe).
847    #[test]
848    fn flatten_logout_send_err_actor_stopped_is_network_error() {
849        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
850            kameo::error::SendError::ActorStopped;
851        assert_eq!(
852            flatten_logout_send_err(e),
853            ts_control::LogoutError::NetworkError
854        );
855    }
856}