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