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 = 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        Ok(Status {
408            self_node,
409            peers,
410            active_exit_node: self.active_exit_node(),
411            magic_dns_suffix,
412        })
413    }
414
415    /// List the tailnet peers this node can Taildrop a file *to* (Go LocalAPI `FileTargets`).
416    ///
417    /// Mirrors the upstream send-path filter (`feature/taildrop` `Extension::FileTargets`): a peer
418    /// qualifies when it advertises a reachable peerAPI **and** is either owned by the same user as
419    /// this node **or** explicitly granted the file-sharing-target capability. The whole list is
420    /// gated on this node holding the file-sharing capability (control sets it when the admin enables
421    /// Taildrop) — absent that, an empty list (fail-closed, not an error, matching how the receive
422    /// store returns empty when disabled). Results are sorted by the peer's MagicDNS name.
423    ///
424    /// Targets are listed regardless of current online state (upstream's `FileTargets` does not gate
425    /// on online either; an offline target's send will simply time out). The self node is never
426    /// included. Returns empty before the first netmap.
427    ///
428    /// Divergence from Go: the upstream filter also excludes `tvOS` peers, which this fork cannot
429    /// reproduce (the domain node carries no OS string); the impact is negligible — the actual send
430    /// fail-closes if such a peer refused the transfer.
431    pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
432        // Node-level gate: this node must hold the file-sharing capability (Taildrop enabled by the
433        // admin). Read it off the self node's cap map, like Go's `hasCapFileSharing()`.
434        let self_node = self.control.ask(control_runner::SelfNode).await?;
435        let Some(self_node) = self_node else {
436            return Ok(Vec::new()); // no netmap yet
437        };
438        if !self_node.can_share_files() {
439            return Ok(Vec::new()); // Taildrop not enabled for the tailnet — fail-closed
440        }
441        let self_user_id = self_node.user_id;
442
443        let peers = self
444            .peer_tracker
445            .upgrade()
446            .ok_or(Error {
447                kind: ErrorKind::ActorGone,
448                target_actor: None,
449                message_ty: None,
450            })?
451            .ask(peer_tracker::AllPeers)
452            .await?;
453
454        // Eligibility + ordering live in `build_file_targets` (pure, unit-tested in `status`).
455        Ok(status::build_file_targets(peers, self_user_id))
456    }
457
458    /// The stable id of the exit node traffic is currently egressing through, or `None` if none is
459    /// engaged. This is the route updater's resolved + fail-closed answer (see
460    /// [`Status::active_exit_node`](crate::status::Status::active_exit_node)): it differs from the
461    /// configured [`exit_node`](Self::exit_node) selector, which may name a peer that is absent or
462    /// no longer advertising a default route (in which case egress is dropped and this returns
463    /// `None`).
464    pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
465        self.active_exit_rx.borrow().clone()
466    }
467
468    /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
469    ///
470    /// Returns the signed JWT, or the token RPC's own [`ts_control::IdTokenError`]. The kameo
471    /// delegated-reply send error is flattened: a handler error carries the real `IdTokenError`,
472    /// any other send failure (actor shutdown / mailbox closed) is surfaced as
473    /// [`ts_control::IdTokenError::NetworkError`].
474    pub async fn fetch_id_token(
475        &self,
476        audience: String,
477    ) -> Result<String, ts_control::IdTokenError> {
478        self.control
479            .ask(control_runner::FetchIdToken { audience })
480            .await
481            .map_err(flatten_send_err)
482    }
483
484    /// Log this node out of the tailnet: deregister it by expiring its current node key.
485    ///
486    /// Forwards to the control runner, which re-POSTs `/machine/register` with a past expiry over a
487    /// fresh Noise channel. This is a control-plane state change only — it does NOT shut the runtime
488    /// down (the caller follows with [`graceful_shutdown`](Self::graceful_shutdown)) and does not
489    /// touch the on-disk node key. The kameo delegated-reply send error is flattened the same way as
490    /// [`fetch_id_token`](Self::fetch_id_token): a handler error carries the real
491    /// [`ts_control::LogoutError`]; any other send failure (actor shutdown / mailbox closed) is
492    /// surfaced as [`ts_control::LogoutError::NetworkError`].
493    pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
494        self.control
495            .ask(control_runner::Logout)
496            .await
497            .map_err(flatten_logout_send_err)
498    }
499
500    /// Publish a `TXT` DNS record for this node via control's `/machine/set-dns` (Go
501    /// `LocalClient.SetDNS`).
502    ///
503    /// Forwards to the control runner, which POSTs the record over a fresh Noise channel. The kameo
504    /// delegated-reply send error is flattened the same way as [`fetch_id_token`](Self::fetch_id_token):
505    /// a handler error carries the real [`ts_control::SetDnsError`]; any other send failure (actor
506    /// shutdown / mailbox closed) is surfaced as [`ts_control::SetDnsError::NetworkError`].
507    pub async fn set_dns(
508        &self,
509        name: String,
510        value: String,
511    ) -> Result<(), ts_control::SetDnsError> {
512        self.control
513            .ask(control_runner::SetDns { name, value })
514            .await
515            .map_err(flatten_set_dns_send_err)
516    }
517
518    /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` (`acme` feature).
519    ///
520    /// Mirrors [`fetch_id_token`](Self::fetch_id_token): forwards to the control runner, which runs
521    /// the client-side ACME DNS-01 flow on a spawned task and publishes the challenge TXT via the
522    /// node's set-dns RPC. The kameo delegated-reply send error is flattened — a handler error
523    /// carries the real [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox
524    /// closed) is surfaced as a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control
525    /// plane 501s on set-dns.
526    #[cfg(feature = "acme")]
527    pub async fn get_certificate(
528        &self,
529        name: String,
530    ) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
531        self.control
532            .ask(control_runner::GetCertificate { name })
533            .await
534            .map_err(flatten_cert_send_err)
535    }
536
537    /// Resolve which node owns a tailnet source address.
538    ///
539    /// Maps the source IP of `addr` to its owning node. Mirrors tsnet's `LocalClient::WhoIs`.
540    /// Returns `None` if no peer holds that tailnet IP. The returned [`WhoIs`] carries no
541    /// user/login or capability data in this fork (see the [`status`] module docs).
542    pub async fn whois(&self, addr: core::net::SocketAddr) -> Result<Option<WhoIs>, Error> {
543        self.peer_tracker
544            .upgrade()
545            .ok_or(Error {
546                kind: ErrorKind::ActorGone,
547                target_actor: None,
548                message_ty: None,
549            })?
550            .ask(peer_tracker::Whois { addr })
551            .await
552            .map_err(Into::into)
553    }
554
555    /// Change the selected exit node at runtime (the equivalent of Go `tsnet`'s
556    /// `LocalClient.EditPrefs(ExitNodeID/ExitNodeIP)`), without recreating the device.
557    ///
558    /// Updates the live exit-node selector, then asks the peer tracker to re-broadcast the current
559    /// peer set so the route updater and source filter re-resolve the new selector immediately.
560    /// `None` clears the exit node (internet-bound traffic is then dropped, fail-closed, unless this
561    /// node egresses directly). The selection is re-resolved against the live peer set, so passing a
562    /// selector for a peer not yet in the netmap simply takes effect once that peer appears.
563    pub async fn set_exit_node(
564        &self,
565        selector: Option<ts_control::ExitNodeSelector>,
566    ) -> Result<(), Error> {
567        // Update the live cell every reader borrows from. `send_replace` keeps the value current
568        // even with no active receivers (none can have dropped while the runtime is up, but it is
569        // the right non-failing primitive here).
570        self.exit_node_tx.send_replace(selector);
571
572        // Trigger an immediate re-resolution: the route updater (outbound routes + DoH delegation)
573        // and the source filter (inbound validation) both recompute on an `Arc<PeerState>`, so a
574        // re-broadcast applies the new exit without waiting for the next netmap update.
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::RepublishState)
583            .await
584            .map_err(Into::into)
585    }
586
587    /// The currently-selected exit node, or `None` if none is selected.
588    pub fn exit_node(&self) -> Option<ts_control::ExitNodeSelector> {
589        self.env.exit_node()
590    }
591
592    /// Change the set of subnet routes this node advertises at runtime (Go `tailscale set
593    /// --advertise-routes`). Applies BOTH halves together so the wire and the data path agree:
594    ///
595    /// 1. **Wire** — re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
596    ///    (so control grants the node the subnet-router role for exactly these prefixes).
597    /// 2. **Local** — swap the forwarder's accept/dial route table (so the node actually forwards the
598    ///    prefixes it advertises). New flows see the new set; in-flight flows keep their routing.
599    ///
600    /// `routes` is filtered to the IPv4-only, deduplicated set this fork can honor (IPv6 prefixes are
601    /// dropped under the IPv6-off posture — we never advertise a route we won't forward), so the wire
602    /// and forwarder are fed the identical final set. This sets the explicit subnet prefixes only; it
603    /// does NOT touch the exit-node `0.0.0.0/0` advertisement (a separate concern).
604    pub async fn set_advertise_routes(&self, routes: Vec<ipnet::IpNet>) -> Result<(), Error> {
605        // IPv4-only + dedup, mirroring `ts_control::Config::advertised_routes` so the wire grant and
606        // the forwarder accept set never disagree.
607        let filtered = filter_advertise_routes(routes);
608
609        // Local half first: start forwarding the prefixes before control grants them, so there is no
610        // window where control has granted a route the node black-holes. (The reverse order would
611        // briefly advertise a route we don't yet forward.) New flows pick up the table immediately.
612        self.forwarder
613            .ask(forwarder_actor::UpdateRoutes {
614                routes: filtered.clone(),
615            })
616            .await?;
617
618        // Wire half: re-advertise to control on the live map-poll connection.
619        self.control
620            .ask(control_runner::SetAdvertiseRoutes { routes: filtered })
621            .await
622            .map_err(Into::into)
623    }
624
625    /// Subscribe to netmap peer-change events.
626    ///
627    /// Returns a [`watch::Receiver`] whose value is the current set of peer [`StatusNode`]s,
628    /// updated on every netmap state update from control. Mirrors tsnet's `WatchIPNBus`. Await
629    /// [`watch::Receiver::changed`](tokio::sync::watch::Receiver::changed) to react to peers
630    /// joining, leaving, or changing.
631    pub async fn watch_netmap(&self) -> Result<watch::Receiver<Vec<StatusNode>>, Error> {
632        self.peer_tracker
633            .upgrade()
634            .ok_or(Error {
635                kind: ErrorKind::ActorGone,
636                target_actor: None,
637                message_ty: None,
638            })?
639            .ask(peer_tracker::WatchNetmap)
640            .await
641            .map_err(Into::into)
642    }
643
644    /// The current device connection-[`DeviceState`].
645    pub fn device_state(&self) -> DeviceState {
646        self.state_rx.borrow().clone()
647    }
648
649    /// Watch the device connection-[`DeviceState`] (`Connecting` → `Running` / `NeedsLogin` /
650    /// `Expired` / `Failed`).
651    ///
652    /// Returns a [`watch::Receiver`]; await
653    /// [`changed`](tokio::sync::watch::Receiver::changed) to react push-style to control connection
654    /// transitions instead of polling [`status`](Self::status). The initial value is the current
655    /// state. Note: a transient per-reconnect dip back to `Connecting` is **not** currently
656    /// emitted (control transparently reconnects below this layer); the state reflects registration
657    /// outcome and node-key expiry.
658    pub fn watch_state(&self) -> watch::Receiver<DeviceState> {
659        self.state_rx.clone()
660    }
661
662    /// Wait until the device finishes registering, returning a typed outcome.
663    ///
664    /// Resolves `Ok(())` once the device reaches [`DeviceState::Running`]. Returns a typed
665    /// [`RegistrationError`] otherwise — the actionable distinction between "retry", "re-pair", and
666    /// "drive interactive login" that replaces polling [`ipv4_addr`](Self::ipv4_addr) in a loop:
667    /// - `AuthRejected` — bad/expired/unknown auth key. **Permanent** (re-pair).
668    /// - `NeedsLogin(url)` — interactive authorization required (no usable auth key). **Not
669    ///   permanent**: the runtime keeps retrying and will reach `Running` once the user authorizes
670    ///   the URL. An **auth-key** caller should treat this as a failure; an **interactive** caller
671    ///   should ignore this return and instead drive the flow via [`watch_state`](Self::watch_state)
672    ///   (this method returns the URL eagerly rather than blocking for the whole login).
673    /// - `NetworkUnreachable` — control unreachable. **Transient** (retry).
674    /// - `Timeout` — no settled state within `timeout`.
675    ///
676    /// `KeyExpired` is not produced by this initial wait (a node key expires only *after* it has
677    /// come up); observe post-registration expiry via [`watch_state`](Self::watch_state).
678    /// `timeout` of `None` waits indefinitely for a settled state.
679    pub async fn wait_until_running(
680        &self,
681        timeout: Option<Duration>,
682    ) -> Result<(), RegistrationError> {
683        device_state::wait_for_running(self.state_rx.clone(), timeout).await
684    }
685
686    /// Attempt to shut down the runtime gracefully.
687    ///
688    /// Returns false if the shutdown timed out. It is still shut down if it timed out, just
689    /// more violently and with possible resource leaks.
690    pub async fn graceful_shutdown(self, timeout: Option<Duration>) -> bool {
691        self.shutdown.send_replace(true);
692
693        async fn _shutdown_all(runtime: Runtime) {
694            // See the note in `Drop` for why we only need to stop these actors to bring down the
695            // whole runtime.
696
697            let _ignore = runtime.control.stop_gracefully().await;
698            let _ignore = runtime.dataplane.stop_gracefully().await;
699            let _ignore = runtime.env.bus.stop_gracefully().await;
700
701            tokio::join![
702                runtime.control.wait_for_shutdown(),
703                runtime.dataplane.wait_for_shutdown(),
704                runtime.env.bus.wait_for_shutdown(),
705            ];
706        }
707
708        let fut = _shutdown_all(self);
709
710        match timeout {
711            Some(timeout) => tokio::time::timeout(timeout, fut).await.is_ok(),
712            None => {
713                fut.await;
714                true
715            }
716        }
717    }
718}
719
720impl Drop for Runtime {
721    fn drop(&mut self) {
722        // We must have already run `graceful_shutdown`: on the happy path, this does nothing, but
723        // if it timed out, we need to make sure the actors are dead so we don't leak them and their
724        // dependents.
725        if *self.shutdown.borrow() {
726            self.control.kill();
727            self.dataplane.kill();
728            self.env.bus.kill();
729            return;
730        }
731
732        self.shutdown.send_replace(true);
733
734        // Actors shut down when the last ActorRef to them is dropped (as nothing can send them
735        // messages anymore). If we don't hold an ActorRef in Runtime, in general the only thing
736        // that has one is the MessageBus, which each actor subscribes to for a subset of messages.
737        // Hence, if we shut down the bus, most actors die as well.
738
739        // First shut down the actors we have an ActorRef to:
740        try_shutdown(&self.control);
741        try_shutdown(&self.dataplane);
742
743        // Then shutdown the message bus, stopping the rest of the actors:
744        try_shutdown(&self.env.bus);
745    }
746}
747
748fn try_shutdown(a: &ActorRef<impl kameo::Actor>) {
749    if let Err(e) = a.mailbox_sender().try_send(Signal::Stop) {
750        tracing::error!(error = %e, "graceful shutdown failed, killing actor");
751        a.kill();
752    }
753}
754
755/// Build the netstack config shared by both userspace netstacks (application + forwarder) from the
756/// per-deployment `tcp_buffer_size` knob.
757///
758/// `None` keeps the netstack default (256 KiB/direction); `Some(n)` overrides it (e.g. a smaller
759/// window on a memory-constrained exit node forwarding many concurrent flows — see
760/// [`netstack::netcore::Config::tcp_buffer_size`]). Factored out of [`Runtime::spawn`] so the
761/// None-default / Some-override mapping is unit-testable without standing up the actor system.
762fn netstack_config_from(tcp_buffer_size: Option<usize>) -> netstack::netcore::Config {
763    let mut c = netstack::netcore::Config::default();
764    if let Some(tcp_buffer_size) = tcp_buffer_size {
765        c.tcp_buffer_size = tcp_buffer_size;
766    }
767    c
768}
769
770/// Filter a requested advertise-route set to the IPv4-only, deduplicated set this fork can honor,
771/// mirroring [`ts_control::Config::advertised_routes`] so a runtime `set_advertise_routes` feeds the
772/// wire (control grant) and the forwarder (accept/dial table) the identical final set. IPv6 prefixes
773/// are dropped under the IPv6-off posture — we never advertise a route we won't forward. Order is
774/// preserved (first occurrence wins). Factored out so the filter is unit-testable without an actor.
775fn filter_advertise_routes(routes: Vec<ipnet::IpNet>) -> Vec<ipnet::IpNet> {
776    let mut filtered: Vec<ipnet::IpNet> = Vec::new();
777    for net in routes {
778        if matches!(net, ipnet::IpNet::V4(_)) {
779            if !filtered.contains(&net) {
780                filtered.push(net);
781            }
782        } else {
783            tracing::warn!(prefix = %net, "dropping IPv6 advertise route (IPv6-off posture)");
784        }
785    }
786    filtered
787}
788
789/// Flatten a kameo delegated-reply [`SendError`] for the id-token RPC into the RPC's own
790/// [`ts_control::IdTokenError`].
791///
792/// A [`SendError::HandlerError`](kameo::error::SendError::HandlerError) carries the real
793/// `IdTokenError` produced by the handler and is surfaced verbatim. Any other send failure (actor
794/// not running / stopped, mailbox full, send timeout) is a delivery problem rather than an RPC
795/// result, so it collapses to a transient [`ts_control::IdTokenError::NetworkError`]. Factored out
796/// of [`Runtime::fetch_id_token`] so this mapping is unit-testable without standing up an actor.
797fn flatten_send_err<M>(
798    e: kameo::error::SendError<M, ts_control::IdTokenError>,
799) -> ts_control::IdTokenError {
800    match e {
801        kameo::error::SendError::HandlerError(err) => err,
802        _ => ts_control::IdTokenError::NetworkError,
803    }
804}
805
806/// Flatten a kameo `SendError` from the `Logout` ask into a [`ts_control::LogoutError`].
807///
808/// A `HandlerError` carries the real `LogoutError` from the control RPC and is surfaced verbatim;
809/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
810/// problem, not a logout result — collapses to the transient [`ts_control::LogoutError::NetworkError`]
811/// (logout is idempotent, so a retry after a delivery failure is safe). Factored out of
812/// [`Runtime::logout`] so the mapping is unit-testable without standing up an actor.
813fn flatten_logout_send_err<M>(
814    e: kameo::error::SendError<M, ts_control::LogoutError>,
815) -> ts_control::LogoutError {
816    match e {
817        kameo::error::SendError::HandlerError(err) => err,
818        _ => ts_control::LogoutError::NetworkError,
819    }
820}
821
822/// Flatten a kameo `SendError` from the `SetDns` ask into a [`ts_control::SetDnsError`].
823///
824/// A `HandlerError` carries the real `SetDnsError` from the set-dns RPC and is surfaced verbatim;
825/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
826/// problem, not a publish result — collapses to the transient
827/// [`ts_control::SetDnsError::NetworkError`]. Factored out of [`Runtime::set_dns`] so the mapping is
828/// unit-testable without standing up an actor.
829fn flatten_set_dns_send_err<M>(
830    e: kameo::error::SendError<M, ts_control::SetDnsError>,
831) -> ts_control::SetDnsError {
832    match e {
833        kameo::error::SendError::HandlerError(err) => err,
834        _ => ts_control::SetDnsError::NetworkError,
835    }
836}
837
838/// Flatten a kameo `SendError` from the `GetCertificate` ask into a [`ts_control::CertError`].
839///
840/// A `HandlerError` carries the real `CertError` produced by the ACME issuance and is surfaced
841/// verbatim. `CertError` has no transient-network variant, so any other send failure (actor not
842/// running / stopped, mailbox full, send timeout) — a delivery problem rather than an issuance
843/// result — collapses to a [`ts_control::CertError::Io`]. Factored out of
844/// [`Runtime::get_certificate`] so this mapping is unit-testable without standing up an actor.
845#[cfg(feature = "acme")]
846fn flatten_cert_send_err<M>(
847    e: kameo::error::SendError<M, ts_control::CertError>,
848) -> ts_control::CertError {
849    match e {
850        kameo::error::SendError::HandlerError(err) => err,
851        _ => ts_control::CertError::Io(std::io::Error::other(
852            "control runner unavailable for certificate issuance",
853        )),
854    }
855}
856
857#[cfg(test)]
858mod tests {
859    use super::*;
860
861    /// `None` must leave the netstack's own default TCP window in place (the 256 KiB throughput
862    /// default), and must not silently coerce to some other value.
863    #[test]
864    fn netstack_config_none_uses_netstack_default() {
865        let default = netstack::netcore::Config::default();
866        let built = netstack_config_from(None);
867        assert_eq!(
868            built.tcp_buffer_size, default.tcp_buffer_size,
869            "None must inherit the netstack default TCP buffer size"
870        );
871    }
872
873    /// `Some(n)` must override the TCP window (the memory-vs-throughput knob exit-node operators
874    /// reach for), reaching the config that both netstacks are built from.
875    #[test]
876    fn netstack_config_some_overrides_buffer() {
877        let built = netstack_config_from(Some(64 * 1024));
878        assert_eq!(
879            built.tcp_buffer_size,
880            64 * 1024,
881            "Some(n) must override the TCP buffer size that both netstacks use"
882        );
883    }
884
885    /// `set_advertise_routes` must feed the wire and the forwarder the IDENTICAL filtered set:
886    /// IPv4-only (IPv6 dropped under the IPv6-off posture), deduplicated, order preserved.
887    #[test]
888    fn filter_advertise_routes_keeps_v4_dedups_drops_v6() {
889        let v4a: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
890        let v4b: ipnet::IpNet = "192.168.1.0/24".parse().unwrap();
891        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
892
893        // Mixed input with a duplicate v4 and a v6 prefix.
894        let out = filter_advertise_routes(vec![v4a, v6, v4b, v4a]);
895
896        assert_eq!(
897            out,
898            vec![v4a, v4b],
899            "v6 dropped, duplicate v4 collapsed, first-occurrence order preserved"
900        );
901    }
902
903    /// An all-IPv6 request filters to empty (we never advertise a route we won't forward) rather
904    /// than erroring — clearing the advertised set is a legitimate outcome.
905    #[test]
906    fn filter_advertise_routes_all_v6_is_empty() {
907        let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
908        assert!(filter_advertise_routes(vec![v6]).is_empty());
909    }
910
911    /// A `HandlerError` carries the real `IdTokenError` from the RPC handler and must pass through
912    /// verbatim, not be flattened to a generic network error. Using an `Internal(_)` payload (not
913    /// `NetworkError`) makes the passthrough observable: a buggy flatten that always returned
914    /// `NetworkError` would fail this assertion.
915    #[test]
916    fn flatten_send_err_handler_error_passes_through() {
917        // Build an `Internal(_)` payload via the public `From<Utf8Error>` conversion (no extra
918        // deps): it is distinct from the `_ => NetworkError` fallback, so a buggy flatten that
919        // always returned `NetworkError` would fail this assertion.
920        // Route the invalid bytes through a runtime Vec so the `invalid_from_utf8` lint (which only
921        // fires on compile-time-known literals) doesn't flag this intentional bad input.
922        let bytes = vec![0xffu8, 0xfe];
923        let utf8_err = core::str::from_utf8(&bytes).unwrap_err();
924        let inner = ts_control::IdTokenError::from(utf8_err);
925        assert!(matches!(inner, ts_control::IdTokenError::Internal(_)));
926        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
927            kameo::error::SendError::HandlerError(inner.clone());
928        assert_eq!(flatten_send_err(e), inner);
929    }
930
931    /// A non-handler send failure (actor stopped) is a delivery problem, not an RPC result, so it
932    /// must collapse to a transient `NetworkError`.
933    #[test]
934    fn flatten_send_err_actor_stopped_is_network_error() {
935        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
936            kameo::error::SendError::ActorStopped;
937        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
938    }
939
940    /// `ActorNotRunning` (the message bounces back undelivered) is likewise a delivery failure and
941    /// must map to a transient `NetworkError`.
942    #[test]
943    fn flatten_send_err_actor_not_running_is_network_error() {
944        let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
945            kameo::error::SendError::ActorNotRunning(control_runner::FetchIdToken {
946                audience: "sts.amazonaws.com".to_string(),
947            });
948        assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
949    }
950
951    /// A `HandlerError` from the logout RPC carries the real `LogoutError` and must pass through
952    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
953    /// passthrough observable.
954    #[test]
955    fn flatten_logout_send_err_handler_error_passes_through() {
956        let inner = ts_control::LogoutError::Internal(ts_control::LogoutInternalErrorKind::Http);
957        assert!(matches!(inner, ts_control::LogoutError::Internal(_)));
958        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
959            kameo::error::SendError::HandlerError(inner.clone());
960        assert_eq!(flatten_logout_send_err(e), inner);
961    }
962
963    /// A non-handler send failure (actor stopped) is a delivery problem, not a logout result, and
964    /// collapses to a transient `NetworkError` (logout is idempotent, so a retry is safe).
965    #[test]
966    fn flatten_logout_send_err_actor_stopped_is_network_error() {
967        let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
968            kameo::error::SendError::ActorStopped;
969        assert_eq!(
970            flatten_logout_send_err(e),
971            ts_control::LogoutError::NetworkError
972        );
973    }
974
975    /// A `HandlerError` from the set-dns RPC carries the real `SetDnsError` and must pass through
976    /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
977    /// passthrough observable.
978    #[test]
979    fn flatten_set_dns_send_err_handler_error_passes_through() {
980        let inner = ts_control::SetDnsError::Internal(ts_control::SetDnsInternalErrorKind::Http);
981        assert!(matches!(inner, ts_control::SetDnsError::Internal(_)));
982        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
983            kameo::error::SendError::HandlerError(inner.clone());
984        assert_eq!(flatten_set_dns_send_err(e), inner);
985    }
986
987    /// A non-handler send failure (actor stopped) is a delivery problem, not a publish result, and
988    /// collapses to a transient `NetworkError`.
989    #[test]
990    fn flatten_set_dns_send_err_actor_stopped_is_network_error() {
991        let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
992            kameo::error::SendError::ActorStopped;
993        assert_eq!(
994            flatten_set_dns_send_err(e),
995            ts_control::SetDnsError::NetworkError
996        );
997    }
998}