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;
30/// DNS over TCP for the MagicDNS service IP: the transport a stub resolver retries on when a UDP
31/// answer comes back truncated. Only the TUN application data path serves it today, so it is
32/// compiled with `tun`.
33#[cfg(feature = "tun")]
34mod dns_over_tcp;
35mod env;
36mod error;
37/// Exit-node suggestion algorithm (the classic DERP-region-latency path, Go
38/// `suggestExitNodeUsingDERP`) and its result/error types.
39pub mod exit_node_suggest;
40/// Fallback TCP handler registry (`tsnet.Server.RegisterFallbackTCPHandler` parity).
41pub mod fallback_tcp;
42mod forwarder_actor;
43/// Client-side Funnel ingress termination (`tsnet`'s `ListenFunnel` data path).
44pub mod funnel;
45/// Unified IPN notification bus ([`Notify`] / [`watch_ipn_bus`](Runtime::watch_ipn_bus)), mirroring
46/// Go `ipn` `LocalBackend.WatchNotifications` / the `WatchIPNBus` LocalAPI.
47pub mod ipn_bus;
48mod magic_dns;
49pub use magic_dns::DnsQueryResult;
50mod multiderp;
51/// OS network-link-change supervisor (opt-in `network-monitor` feature): re-binds + re-probes
52/// connectivity on a link change. Compiled out entirely when the feature is off.
53#[cfg(feature = "network-monitor")]
54mod netmon;
55mod netstack_actor;
56mod packetfilter;
57pub mod peer_tracker;
58mod peerapi;
59mod peerapi_doh;
60mod route_updater;
61/// Stored Serve config + accept-loop runtime (`tsnet`'s `Get/SetServeConfig` + serving runtime).
62pub mod serve;
63mod src_filter;
64/// Netmap status snapshot, WhoIs, and watcher types.
65pub mod status;
66/// Taildrop peer-to-peer file transfer store.
67pub mod taildrop;
68pub mod taildrop_send;
69/// Tailnet-Lock (TKA) chain-sync orchestration: bootstrap + offer/send driver (the runtime layer
70/// that bridges the `ts_control` sync RPCs and the `ts_tka` chain logic).
71mod tka_sync;
72#[cfg(feature = "tun")]
73mod tun_actor;
74
75pub use device_state::{DeviceState, RegistrationError};
76pub(crate) use env::Env;
77pub use error::{Error, ErrorKind};
78pub use exit_node_suggest::{ExitNodeSuggestion, SuggestExitNodeError};
79pub use ipn_bus::{IpnBusWatcher, Notify, NotifyWatchOpt};
80pub use status::{FileTarget, NetcheckReport, RegionLatency, Status, StatusNode, WhoIs};
81pub use tka_sync::TkaLogEntry;
82pub use ts_dataplane::{CaptureHook, CapturePath};
83
84use crate::peer_tracker::PeerTracker;
85
86/// The runtime for a tailscale device.
87pub struct Runtime {
88 /// Reference to the control actor.
89 pub control: ActorRef<ControlRunner>,
90 dataplane: ActorRef<DataplaneActor>,
91 /// Reference to the direct (disco/UDP underlay) manager, retained so [`Runtime::rebind`] can
92 /// ask it to re-bind the underlay socket on a network/link change.
93 direct: ActorRef<DirectManager>,
94 /// Reference to the application netstack actor. `None` in TUN transport mode, where there is
95 /// no userspace application netstack (the application data path is a real kernel TUN device).
96 netstack: Option<WeakActorRef<NetstackActor>>,
97 /// Reference to the peer tracker for peer lookups.
98 pub peer_tracker: WeakActorRef<PeerTracker>,
99 /// Fallback TCP handler registry, bound to the application netstack. `None` in TUN transport
100 /// mode (no application netstack exists to attach it to).
101 fallback_tcp: Option<fallback_tcp::FallbackTcpManager>,
102 /// Reference to the MagicDNS responder, retained so [`Runtime::query_dns`] can run a query
103 /// through the live `100.100.100.100` forward path. `None` in TUN transport mode (no
104 /// `MagicDnsActor` is spawned there — TUN-mode MagicDNS is an in-packet intercept, not an actor).
105 magic_dns: Option<ActorRef<magic_dns::MagicDnsActor>>,
106 /// Reference to the forwarder actor, retained so [`Runtime::set_advertise_routes`] can push a
107 /// new accept/dial route table onto the running forwarder (the local half of advertising
108 /// routes). Without this the strong ref would drop after the startup `GetChannel` and the
109 /// forwarder would be reachable only via the message bus.
110 forwarder: ActorRef<ForwarderActor>,
111 /// Reference to the multiderp manager, retained so [`Runtime::status`] can resolve each
112 /// relayed peer's DERP region id to its region **code** (`ipnstate.PeerStatus.Relay`). Without
113 /// this the strong ref would drop after startup (it is cloned into the direct manager + route
114 /// updater) and the region-code map would be unreachable.
115 multiderp: ActorRef<Multiderp>,
116 env: Env,
117 shutdown: watch::Sender<bool>,
118 /// Sender side of the exit-node selector `watch` cell. Held privately here (not on the cloned
119 /// `Env`, which keeps only the read side) so that only `Runtime::set_exit_node` can mutate the
120 /// selection; the route updater and source filter re-read it via [`Env::exit_node`].
121 exit_node_tx: watch::Sender<Option<ts_control::ExitNodeSelector>>,
122 /// Sender side of the accept-routes preference `watch` cell. Held privately here (same rationale
123 /// as [`exit_node_tx`](Self::exit_node_tx)) so that only [`Runtime::set_accept_routes`] can
124 /// toggle it; the route updater and source filter re-read it via [`Env::accept_routes`].
125 accept_routes_tx: watch::Sender<bool>,
126 /// Sender side of the accept-dns preference `watch` cell. Held privately here (same rationale as
127 /// [`accept_routes_tx`](Self::accept_routes_tx)) so that only [`Runtime::set_accept_dns`] can
128 /// toggle it; the MagicDNS responder re-reads it via [`Env::accept_dns`] when it rebuilds its
129 /// view (the republish that `set_accept_dns` triggers).
130 accept_dns_tx: watch::Sender<bool>,
131 /// Receiver mirroring the *active* (resolved + fail-closed) exit node's stable id, fed by the
132 /// route updater. Read by [`Runtime::status`] / [`Runtime::active_exit_node`] to report which
133 /// exit node traffic is actually egressing through (vs. the merely-configured selector).
134 active_exit_rx: watch::Receiver<Option<ts_control::StableNodeId>>,
135 /// Receiver for the device connection-state cell, fed by the control runner. Read by
136 /// [`Runtime::watch_state`] and [`Runtime::wait_until_running`].
137 state_rx: watch::Receiver<DeviceState>,
138 /// Receiver for the retained peer-capability grants, fed by the packet-filter updater. Read by
139 /// [`Runtime::whois`] to resolve the flow-scoped cap map (Go `apitype.WhoIsResponse.CapMap`).
140 cap_grants_rx: watch::Receiver<packetfilter::CapGrants>,
141 /// Live advertised-route preference (explicit subnet routes + the exit-node flag), seeded from
142 /// the startup config. [`Runtime::set_advertise_routes`] and [`set_advertise_exit_node`] each
143 /// mutate their part under this lock then re-send the composed set, so the two compose.
144 advertise: std::sync::Mutex<AdvertiseState>,
145 /// The most recent exit-node suggestion's stable id (Go `LocalBackend.lastSuggestedExitNode`),
146 /// remembered across calls so [`Runtime::suggest_exit_node`] can apply *stickiness* — if the
147 /// previously-suggested node is still an eligible candidate in the winning region it is kept, to
148 /// avoid the suggestion flapping between equally-good ties on each call. `None` until the first
149 /// suggestion. Held behind a `Mutex` (same rationale as [`advertise`](Self::advertise): a
150 /// cheap, infrequently-touched bit of mutable runtime state, not worth an actor round-trip).
151 prev_suggestion: std::sync::Mutex<Option<ts_control::StableNodeId>>,
152 /// Background task that periodically reaps abandoned taildrop `.partial` files (Go
153 /// `feature/taildrop/delete.go` `fileDeleter`). `None` when no taildrop store is configured.
154 /// Aborted on [`Drop`] so it cannot outlive the runtime (the `reauth_bridge` pattern).
155 taildrop_reaper: Option<tokio::task::JoinHandle<()>>,
156 /// The opt-in OS network-link-change supervisor (`network-monitor` feature + the
157 /// `Config::network_monitor` flag). Retained so the actor — and thus the
158 /// `LinkMonitorHandle` it holds, which aborts the monitor's watcher task on drop — lives for the
159 /// device's life and is torn down when the runtime drops. `None` when the flag is off. Only
160 /// present when built with the `network-monitor` feature.
161 #[cfg(feature = "network-monitor")]
162 #[allow(dead_code)]
163 netmon_supervisor: Option<ActorRef<netmon::NetmonSupervisor>>,
164}
165
166impl Runtime {
167 /// Spawn a new runtime with the given parameters for connecting to a tailnet.
168 pub async fn spawn(
169 config: ts_control::Config,
170 auth_key: Option<String>,
171 keys: ts_keys::NodeState,
172 ) -> Result<Self, Error> {
173 let (shutdown_tx, shutdown_rx) = watch::channel(false);
174
175 // The exit-node selector, accept-routes, and accept-dns preferences are live `watch` cells so
176 // `Device::set_exit_node` / `set_accept_routes` / `set_accept_dns` can change them at runtime.
177 // `new_with_runtime_txs` returns each `Sender` (mutation capability) grouped in `pref_cells`
178 // so they are retained privately on the `Runtime`, while only the `Receiver`s (the readers'
179 // contract) live on the cloned `Env`. Initial values come from `ForwarderConfig`.
180 let (env, pref_cells) = Env::new_with_runtime_txs(
181 keys,
182 shutdown_rx,
183 env::ForwarderConfig::from_control_config(&config),
184 );
185
186 // Both userspace netstacks (application + forwarder) share one netstack config. Honor the
187 // per-deployment TCP buffer knob, and set the netstack MTU to the overlay/tunnel MTU so the
188 // advertised MSS fits the tunnel — leaving it at the netstack's generic 1500 default would
189 // emit over-1280 segments into the WireGuard path. The MTU comes from a `Tun` transport's
190 // `TunConfig` when one is configured (so the netstack and the TUN agree), else the 1280
191 // overlay default (the `Netstack` userspace mode — the common case — has no per-OS MTU knob,
192 // but the tailnet overlay MTU is still 1280).
193 let configured_mtu = match &config.transport_mode {
194 ts_control::TransportMode::Tun(tun_cfg) => tun_cfg.mtu,
195 ts_control::TransportMode::Netstack => None,
196 };
197 let netstack_config = netstack_config_from(config.tcp_buffer_size, configured_mtu);
198
199 let dataplane = DataplaneActor::spawn(env.clone());
200
201 let (netstack_id, netstack_up, netstack_down) =
202 dataplane.ask(dataplane::NewOverlayTransport).await?;
203
204 // A second overlay transport feeds the dedicated any-IP forwarder netstack. Inbound packets
205 // for advertised subnet routes / the exit-node default route are routed here (see
206 // `route_updater`), keeping forwarded flows off the application netstack.
207 let (forwarder_id, forwarder_up, forwarder_down) =
208 dataplane.ask(dataplane::NewOverlayTransport).await?;
209
210 // The selected DERP home region (Go `report.PreferredDERP`): the control runner is the sole
211 // writer (it applies the netcheck `bestRecent` + hysteresis smoothing), and `Multiderp`
212 // reads it to drive the local home relay — so the relay follows the SAME smoothed home the
213 // runner advertises to control, instead of picking it from the raw per-cycle latency minimum
214 // (which flapped on jitter and could disagree with the advertised home). Created here so it
215 // outlives both actors; `None` until the first home is chosen.
216 let (home_region_tx, home_region_rx) = watch::channel::<Option<ts_derp::RegionId>>(None);
217
218 let multiderp = Multiderp::spawn((env.clone(), dataplane.clone(), home_region_rx));
219
220 // Spawn the direct (disco) underlay manager before the route updater. Its `on_start`
221 // binds the UDP socket and registers its transport synchronously, so by the time the
222 // route updater asks it for the direct transport id it is guaranteed to be available.
223 let direct = DirectManager::spawn((env.clone(), dataplane.clone(), multiderp.clone()));
224
225 // Spawn the forwarder before the route updater. Its `on_start` builds the forwarder
226 // netstack, enables any-IP acceptance, and starts the per-port accept loops synchronously,
227 // so by the time the route updater begins delivering advertised prefixes to
228 // `forwarder_id` the netstack is already draining its transport.
229 let forwarder = ForwarderActor::spawn((
230 env.clone(),
231 netstack_config.clone(),
232 forwarder_up,
233 forwarder_down,
234 ));
235 // Force `on_start` to finish (any-IP enabled, accept loops live) before the route updater
236 // can route the first inbound flow to `forwarder_id`: an `ask` blocks until the actor has
237 // started.
238 //
239 // The forwarder netstack's overlay `Channel` is reused by the TUN application path for
240 // recursive / exit-node-DoH MagicDNS forwarding (TUN mode has no application netstack of its
241 // own, but the forwarder netstack runs in both modes and egresses over the overlay — the
242 // anti-leak property `forward_query`/`forward_doh` require). Only the `tun` Tun arm consumes
243 // it, so it is unused when the `tun` feature is off — allow that without warn-as-error.
244 #[cfg_attr(not(feature = "tun"), allow(unused_variables))]
245 let (forwarder_channel,) = forwarder.ask(forwarder_actor::GetChannel).await?;
246
247 // The route updater is the single authoritative resolver of the active (resolved,
248 // fail-closed) exit node; it publishes the resolved stable id into this watch cell so
249 // `Runtime::status` can report which exit is actually engaged (not just configured).
250 let (active_exit_tx, active_exit_rx) = watch::channel(None);
251 route_updater::RouteUpdater::spawn((
252 multiderp.clone(),
253 direct.clone(),
254 env.clone(),
255 netstack_id,
256 forwarder_id,
257 active_exit_tx,
258 ));
259 // The packet-filter updater also surfaces the retained cap-grants (for flow-scoped WhoIs)
260 // through a `watch` cell whose receiver the `Runtime` holds — the bus has no replay, so a
261 // `watch` is how `Runtime::whois` reads the current grants on demand.
262 let (cap_grants_tx, cap_grants_rx) = watch::channel(Default::default());
263 packetfilter::PacketfilterUpdater::spawn((env.clone(), cap_grants_tx));
264 src_filter::SourceFilterUpdater::spawn(env.clone());
265 // TKA enforcement-authority cell (Go `tkaFilterNetmapLocked`). Created here — before both
266 // actors spawn — so the control runner (sole writer, `Sender`) and the peer tracker (reader,
267 // `Receiver`) share one `watch` cell. A `watch` (not a bus message) is the transport for this
268 // security-critical state: last-write-wins, never dropped under load, ordered by the control
269 // runner's writes, so a disable (`None`) can never be reordered behind or dropped before a
270 // stale `Some`. `None` = no lock synced / disabled (admit all).
271 let (tka_authority_tx, tka_authority_rx) =
272 watch::channel::<Option<std::sync::Arc<ts_tka::Authority>>>(None);
273 let peer_tracker = PeerTracker::spawn((env.clone(), tka_authority_rx)).downgrade();
274
275 // Select the application data path from the transport mode. The forwarder/egress path
276 // above is UNCHANGED in both modes — TUN mode only swaps the application data path, never
277 // the forwarder. `config` is moved into `ControlRunner::spawn` below, so branch on a
278 // borrow and clone the small `TunConfig` where needed before the move.
279 //
280 // - Netstack (the default, and the only reachable arm when the `tun` feature is off):
281 // spawn the application netstack + MagicDNS responder + fallback-TCP registry, all on
282 // the `netstack_up`/`netstack_down` overlay seam.
283 // - Tun: spawn `TunActor` on that same overlay seam instead; no application netstack and
284 // no MagicDNS responder exist, and `netstack`/`fallback_tcp` are `None`.
285 // - Tun requested but built without the `tun` feature: hard-error (a config/build
286 // mismatch knowable at spawn time). NEVER silently fall back to netstack.
287 let (netstack, fallback_tcp, magic_dns) = match &config.transport_mode {
288 ts_control::TransportMode::Netstack => {
289 let netstack = NetstackActor::spawn((
290 env.clone(),
291 netstack_config,
292 netstack_up,
293 netstack_down,
294 ));
295
296 // Fetch the netstack channel while we still hold the strong ActorRef, then spawn
297 // the MagicDNS responder on it. Its ActorRef is retained on `Runtime` so
298 // `query_dns` can drive the live forward path; the serve loop itself is owned by the
299 // actor's internal JoinSet.
300 let (channel,) = netstack.ask(netstack_actor::GetChannel).await?;
301 // The fallback-TCP registry attaches to the application netstack — the same one
302 // that carries the embedder's explicit `Device::tcp_listen` sockets — so a
303 // fallback handler sees exactly the inbound flows no explicit listener matched.
304 let fallback_tcp = fallback_tcp::FallbackTcpManager::new(channel.clone());
305 let magic_dns = magic_dns::MagicDnsActor::spawn((env.clone(), channel));
306
307 (
308 Some(netstack.downgrade()),
309 Some(fallback_tcp),
310 Some(magic_dns),
311 )
312 }
313
314 #[cfg(feature = "tun")]
315 ts_control::TransportMode::Tun(tun_cfg) => {
316 // Reuse the same `netstack_up`/`netstack_down` overlay-transport pair that would
317 // have fed the netstack — it is just the application-side overlay seam (the name
318 // is historical). No NetstackActor / MagicDnsActor is spawned.
319 tun_actor::TunActor::spawn((
320 env.clone(),
321 tun_cfg.clone(),
322 netstack_up,
323 netstack_down,
324 // Reuse the forwarder netstack's overlay `Channel` for recursive / exit-node-DoH
325 // MagicDNS forwarding in the TUN datapath (TUN mode has no application netstack
326 // Channel of its own). Egresses over the overlay — anti-leak preserved.
327 //
328 // Host-route gating (subnet routes gated on `--accept-routes`, the host `/0` from
329 // the selected exit peer) is no longer snapshotted here: `TunActor` reads the live
330 // `Env` cells (`accept_routes`/`exit_node`) on every host-FIB apply — both the
331 // device-build path and the `PeerState` re-apply path — and folds the union of
332 // peers' AllowedIPs (see `tun_actor::host_routes_from_node`). A runtime
333 // `set_accept_routes` / `set_exit_node` toggle re-broadcasts the peer state, so the
334 // host routing table is re-steered live (no device rebuild needed).
335 forwarder_channel.clone(),
336 ));
337
338 (None, None, None)
339 }
340
341 #[cfg(not(feature = "tun"))]
342 ts_control::TransportMode::Tun(_) => {
343 return Err(Error {
344 kind: ErrorKind::TunUnavailable,
345 target_actor: None,
346 message_ty: None,
347 });
348 }
349 };
350
351 // Device connection-state cell. Created here (not inside the actor) so the control runner's
352 // `on_start` can publish `Failed`/`NeedsLogin` and still return `Err` without the sender
353 // being tied to a `Self` that never gets constructed on a hard registration failure.
354 let (state_tx, state_rx) = watch::channel(DeviceState::Connecting);
355
356 // Seed the live advertised-route preference from the startup config before `config` moves
357 // into the control runner, so the runtime setters compose against the configured baseline.
358 let advertise = std::sync::Mutex::new(AdvertiseState {
359 routes: config.advertise_routes.clone(),
360 exit_node: config.advertise_exit_node,
361 });
362
363 // Unbounded mailbox (not the default bounded-64): the control runner SELF-messages — a
364 // spawned TKA sync task delivers its result back via `self_ref.tell(TkaSynced)`, and the
365 // netmap stream pump tells `StreamMessage::Next` onto the same mailbox. The stall path: the
366 // netmap handler ends by parking on `env.publish().await` into the bounded-64 *bus* (a slow
367 // bus subscriber, e.g. a busy TKA-enforcing peer tracker, holds the bus full); while it is
368 // parked, a concurrently-finishing sync task's `TkaSynced` self-tell queues behind a full
369 // *ControlRunner* mailbox and blocks waiting for capacity, delaying the verified-authority
370 // (or lock-disable) write to the enforcement cell — i.e. stale TKA enforcement under churn.
371 // kameo gates its self-tell deadlock warning on `is_current()`, which is false for the
372 // detached sync task, so the stall is silent. An unbounded mailbox lets the self-tell and the
373 // stream pump enqueue without ever awaiting capacity (kameo's documented choice for a
374 // self-messaging actor); the runner's inputs are control-paced (the netmap stream + a few RPC
375 // replies; the bus delivers best-effort and never backpressures this mailbox), not an attacker
376 // flood, so unbounded growth is not a practical exposure.
377 let control = ControlRunner::spawn_with_mailbox(
378 control_runner::Params {
379 config,
380 auth_key,
381 env: env.clone(),
382 state_tx,
383 tka_authority: tka_authority_tx,
384 home_region: home_region_tx,
385 },
386 kameo::mailbox::unbounded(),
387 );
388
389 // Spawn the taildrop partial-reaper if a store is configured; it sweeps abandoned `.partial`
390 // files every `DELETE_DELAY` and exits on shutdown (the handle is aborted in `Drop`).
391 let taildrop_reaper = env.taildrop_store.as_ref().map(|store| {
392 crate::taildrop::spawn_partial_reaper(store.clone(), shutdown_tx.subscribe())
393 });
394
395 // Opt-in OS network-link monitor (`Config::network_monitor`, default off). When enabled it
396 // spawns a `NetmonSupervisor` that, on a coalesced link change, asks the direct manager to
397 // rebind + re-probe and republishes `MeasureNow` for a re-netcheck — the auto-recovery a
398 // real `tailscaled` performs and the engine otherwise leaves to the embedder. When the flag
399 // is off this is a complete no-op: zero extra threads/sockets, byte-for-byte today's
400 // behavior. The manual `Device::rebind` path is unchanged either way.
401 //
402 // Feature gating is strict and never silent: with the `network-monitor` feature ON the
403 // supervisor (and its `ts_netmon` dep) compile in and spawn when the flag is set; with the
404 // feature OFF, setting the flag is a HARD error at spawn (mirrors the `TransportMode::Tun`
405 // without-`tun`-feature error above), so a build that cannot honor the request fails loudly
406 // rather than booting a node that silently won't auto-recover.
407 #[cfg(feature = "network-monitor")]
408 let netmon_supervisor = if env.network_monitor {
409 // Slice (a): no OS event-source backend is wired yet (the Linux netlink / macOS
410 // PF_ROUTE backends are later slices), so the supervisor runs against a `NoopLinkMonitor`
411 // — it is live and correctly shaped (it will react the moment a real backend feeds it),
412 // it just never sees a synthetic/OS event in this build. Production end-to-end reaction
413 // is proven in the integration test via a `ManualLinkMonitor`.
414 let monitor: std::sync::Arc<dyn ts_netmon::LinkMonitor> =
415 std::sync::Arc::new(ts_netmon::NoopLinkMonitor);
416 Some(netmon::NetmonSupervisor::spawn(
417 netmon::NetmonSupervisorArgs {
418 monitor,
419 direct: direct.clone(),
420 env: env.clone(),
421 },
422 ))
423 } else {
424 None
425 };
426
427 #[cfg(not(feature = "network-monitor"))]
428 if env.network_monitor {
429 // The flag is set but this build cannot honor it. Fail loudly (never a silent no-op).
430 return Err(Error {
431 kind: ErrorKind::NetworkMonitorUnavailable,
432 target_actor: None,
433 message_ty: None,
434 });
435 }
436
437 Ok(Self {
438 control,
439 dataplane,
440 direct,
441 peer_tracker,
442 fallback_tcp,
443 magic_dns,
444 forwarder,
445 multiderp,
446 netstack,
447 env,
448 shutdown: shutdown_tx,
449 exit_node_tx: pref_cells.exit_node,
450 accept_routes_tx: pref_cells.accept_routes,
451 accept_dns_tx: pref_cells.accept_dns,
452 active_exit_rx,
453 state_rx,
454 cap_grants_rx,
455 advertise,
456 prev_suggestion: std::sync::Mutex::new(None),
457 taildrop_reaper,
458 #[cfg(feature = "network-monitor")]
459 netmon_supervisor,
460 })
461 }
462
463 /// Register a fallback TCP handler consulted for every inbound TCP flow that matches no
464 /// explicit listener (`tsnet.Server.RegisterFallbackTCPHandler` parity).
465 ///
466 /// The returned [`fallback_tcp::FallbackTcpHandle`] deregisters the handler when dropped. See
467 /// [`fallback_tcp`] for the dispatch contract and anti-leak guarantees.
468 ///
469 /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
470 /// application netstack to attach a fallback handler to.
471 pub fn register_fallback_tcp_handler(
472 &self,
473 cb: Arc<
474 dyn Fn(core::net::SocketAddr, core::net::SocketAddr) -> fallback_tcp::FallbackDecision
475 + Send
476 + Sync,
477 >,
478 ) -> Result<fallback_tcp::FallbackTcpHandle, Error> {
479 Ok(self
480 .fallback_tcp
481 .as_ref()
482 .ok_or(Error {
483 kind: ErrorKind::UnsupportedInTunMode,
484 target_actor: None,
485 message_ty: None,
486 })?
487 .register(cb))
488 }
489
490 /// Get a channel to send commands to the netstack.
491 ///
492 /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
493 /// application netstack.
494 pub async fn channel(&self) -> Result<Channel, Error> {
495 let (channel,) = self
496 .netstack
497 .as_ref()
498 .ok_or(Error {
499 kind: ErrorKind::UnsupportedInTunMode,
500 target_actor: None,
501 message_ty: None,
502 })?
503 .upgrade()
504 .ok_or(Error {
505 kind: ErrorKind::ActorGone,
506 target_actor: None,
507 message_ty: None,
508 })?
509 .ask(netstack_actor::GetChannel)
510 .await?;
511
512 Ok(channel)
513 }
514
515 /// Resolve `name` for `qtype` through the live MagicDNS responder (the `100.100.100.100`
516 /// forward path), returning the raw DNS response, its RCODE, and the upstream resolver(s)
517 /// consulted (analogue of Go `LocalClient.QueryDNS`).
518 ///
519 /// This drives the *real* responder — the same `decide`/forward logic an on-the-wire query
520 /// hits — so the answer and its anti-leak posture (a tailnet-suffix name never egresses; a
521 /// recursive forward delegates to the active exit node's DoH; only IPv4 upstreams are dialed)
522 /// match exactly what a tailnet client observes. `qtype` is the raw RFC 1035 TYPE (`1`=A,
523 /// `28`=AAAA, `12`=PTR, or any other).
524 ///
525 /// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where MagicDNS is an
526 /// in-packet intercept on the host's own resolver rather than an actor that can be queried, and
527 /// [`ErrorKind::ActorGone`] if the responder has shut down.
528 pub async fn query_dns(
529 &self,
530 name: &str,
531 qtype: u16,
532 ) -> Result<magic_dns::DnsQueryResult, Error> {
533 let result = self
534 .magic_dns
535 .as_ref()
536 .ok_or(Error {
537 kind: ErrorKind::UnsupportedInTunMode,
538 target_actor: None,
539 message_ty: None,
540 })?
541 .ask(magic_dns::Query {
542 name: name.to_owned(),
543 qtype,
544 })
545 .await?;
546
547 Ok(result)
548 }
549
550 /// The Taildrop file store, if Taildrop is enabled (`taildrop_dir` configured and the store
551 /// initialized). `None` when disabled — fail-closed. Shared with the peerAPI Taildrop server so
552 /// the embedder's read APIs and the receive path see the same on-disk store.
553 pub fn taildrop_store(&self) -> Option<Arc<crate::taildrop::TaildropStore>> {
554 self.env.taildrop_store.clone()
555 }
556
557 /// The shared Funnel ingress slot the peerAPI `/v0/ingress` route reads per connection.
558 ///
559 /// `Device::listen_funnel` installs a [`FunnelManager`](crate::funnel::FunnelManager)'s sink here
560 /// to make the route live (the peerAPI server is already running from startup). Returns a clone of
561 /// the runtime-lifetime `Arc` so the device can write the slot without restarting the server. See
562 /// [`crate::funnel`] for the ingress data path.
563 pub fn funnel_ingress_slot(&self) -> crate::funnel::FunnelIngressSlot {
564 self.env.funnel_ingress.clone()
565 }
566
567 /// The shared "Funnel ingress listener active" flag (the same `Arc` the control session reads to
568 /// set `HostInfo.IngressEnabled`). `Device::listen_funnel` flips it `true` while a funnel listener
569 /// is up so control routes Funnel traffic to this node; clearing it advertises no live endpoint.
570 pub fn ingress_active_flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
571 self.env.ingress_active.clone()
572 }
573
574 /// Install (`Some`) or clear (`None`) the debug packet-capture hook on the running dataplane.
575 /// `Some(hook)` tees every plaintext packet crossing the datapath to `hook` until it is cleared;
576 /// `None` stops capture. Mirrors Go `tstun.Wrapper.InstallCaptureHook` / `ClearCaptureSink`.
577 pub async fn install_capture(
578 &self,
579 hook: Option<ts_dataplane::CaptureHook>,
580 ) -> Result<(), Error> {
581 self.dataplane
582 .ask(dataplane::InstallCapture { hook })
583 .await
584 .map_err(Into::into)
585 }
586
587 /// Re-bind the underlay UDP socket after a network/link change (Wi-Fi switch, sleep/wake). The
588 /// embedder's own link monitor calls this (the engine owns the socket re-bind; the embedder owns
589 /// OS netmon). Re-binds the socket (same-port-preferred, IPv4-only invariant preserved) and
590 /// resets the now-stale local NAT mapping — clearing learned reflexive addresses and every
591 /// confirmed direct path while keeping candidate endpoints, so peers re-probe over the new socket
592 /// and relay over DERP (never a direct host dial) until a path re-confirms. Peers, control, the
593 /// netmap, disco state, and DERP are untouched. A no-op when the underlay is inert (bind failed
594 /// at startup, DERP-only). Mirrors Go magicsock `Conn.Rebind` + `resetEndpointStates`.
595 pub async fn rebind(&self) -> Result<(), Error> {
596 self.direct.ask(direct::Rebind).await.map_err(Error::from)
597 }
598
599 /// Force an immediate STUN / endpoint re-probe **without** rebinding the underlay socket —
600 /// Go magicsock's `Conn.ReSTUN`. Asks the `DirectManager` to run one STUN sweep now (re-learn
601 /// our reflexive/public address) while leaving the socket, its NAT mapping, learned paths, peers,
602 /// control, and DERP untouched. Lighter than [`rebind`](Self::rebind): no socket swap, no
603 /// re-ping. A no-op when the underlay is inert (bind failed at startup, DERP-only). No control
604 /// round-trip.
605 pub async fn re_stun(&self) -> Result<(), Error> {
606 self.direct.ask(direct::ReStun).await.map_err(Error::from)
607 }
608
609 /// A snapshot of the local netmap: this node plus every known peer.
610 ///
611 /// Combines the self node held by the control runner with the peer set held by the peer
612 /// tracker. Mirrors tsnet's `LocalClient::Status`.
613 ///
614 /// `self_node` is `None` until the first netmap update has been received from control. Peer
615 /// entries carry no online/user/capability data (see the [`status`] module docs for that gap).
616 pub async fn status(&self) -> Result<Status, Error> {
617 let self_node_domain = self.control.ask(control_runner::SelfNode).await?;
618 // The MagicDNS suffix is the self node's FQDN minus its host label — already split into
619 // `Node.tailnet` at decode time (Go derives it the same way in `NetworkMap.MagicDNSSuffix`).
620 // Capture it before the domain `Node` is mapped away into a `StatusNode`.
621 let magic_dns_suffix = self_node_domain.as_ref().and_then(|n| n.tailnet.clone());
622 let self_node = self_node_domain.as_ref().map(StatusNode::from_node);
623
624 let peers_with_ids = self
625 .peer_tracker
626 .upgrade()
627 .ok_or(Error {
628 kind: ErrorKind::ActorGone,
629 target_actor: None,
630 message_ty: None,
631 })?
632 .ask(peer_tracker::GetStatus)
633 .await?;
634
635 // Join per-peer connectivity (Go `PeerStatus.CurAddr`): one batched query to the direct
636 // manager for every peer's current trusted direct endpoint, then fill `cur_addr` on each
637 // `StatusNode`. A peer absent from the map is relayed via DERP (`cur_addr = None`). This is a
638 // live snapshot — the direct path can expire/re-confirm between calls (matches Go's snapshot
639 // semantics). The `watch_netmap` stream intentionally carries no connectivity (it is a netmap
640 // watch, not a path-state watch, and does not re-fire on direct↔relay flips).
641 let ids: Vec<ts_transport::PeerId> = peers_with_ids.iter().map(|(id, _)| *id).collect();
642 let best_addrs = self
643 .direct
644 .ask(direct::BestAddrs { ids: ids.clone() })
645 .await
646 .unwrap_or_default();
647
648 // For the peers with NO direct path (relayed via DERP), resolve the region CODE they relay
649 // through (Go `PeerStatus.Relay`). One batched ask to multiderp; `cur_addr` and `relay` are
650 // mutually exclusive for a routed peer, mirroring Go's empty-vs-set strings.
651 let relay_ids: Vec<ts_transport::PeerId> = ids
652 .into_iter()
653 .filter(|id| !best_addrs.contains_key(id))
654 .collect();
655 let relay_codes = if relay_ids.is_empty() {
656 Default::default()
657 } else {
658 self.multiderp
659 .ask(multiderp::RelayCodesForPeers { ids: relay_ids })
660 .await
661 .unwrap_or_default()
662 };
663
664 let peers = peers_with_ids
665 .into_iter()
666 .map(|(id, mut node)| match best_addrs.get(&id).copied() {
667 Some(addr) => {
668 node.cur_addr = Some(addr);
669 node
670 }
671 None => {
672 node.relay = relay_codes.get(&id).cloned();
673 node
674 }
675 })
676 .collect();
677
678 Ok(Status {
679 self_node,
680 peers,
681 active_exit_node: self.active_exit_node(),
682 magic_dns_suffix,
683 })
684 }
685
686 /// Suggest a reasonably good exit node to use, from the current netmap + recent DERP latency
687 /// (Go `LocalBackend.SuggestExitNode`). The Phase-1 classic DERP-region-latency path; see the
688 /// [`exit_node_suggest`] module for the algorithm, scope, and the IPv4-only parity deviation.
689 ///
690 /// Gathers the inputs the way [`status`](Self::status) and [`file_targets`](Self::file_targets)
691 /// do — from the control runner, the latest [`NetcheckReport`]'s preferred DERP region plus the
692 /// recent per-region latencies (both immediate, non-blocking borrows), and every peer
693 /// [`Node`](ts_control::Node) from the peer tracker — then runs the pure algorithm with the
694 /// production uniform-random selectors (`random_region` / `random_node`). The returned
695 /// suggestion's id is remembered in the runtime's `prev_suggestion` cell so the next call is
696 /// *sticky* (Go `lastSuggestedExitNode`).
697 ///
698 /// Returns `Ok(None)` when no peer is an eligible candidate (Go's empty response), and
699 /// `Err(`[`SuggestExitNodeError::NoPreferredDerp`]`)` when there is no netcheck report yet (Go's
700 /// `ErrNoPreferredDERP`, "try again later").
701 pub async fn suggest_exit_node(
702 &self,
703 ) -> Result<Result<Option<ExitNodeSuggestion>, SuggestExitNodeError>, Error> {
704 use ts_control::NODE_ATTR_SUGGEST_EXIT_NODE;
705
706 // The two netcheck inputs Go's `suggestExitNode` takes. First the preferred DERP region from
707 // the latest report (Go `MagicConn().GetLastNetcheckReport().PreferredDERP`): an immediate
708 // borrow of the control runner's published measurement (the value `Device::netcheck`
709 // surfaces), used only as the "have we netchecked at all yet" precondition.
710 let report = self.control.ask(control_runner::Netcheck).await?;
711
712 // Then the *ranking* input: the lowest latency seen per region over the retained measurement
713 // history (Go `netcheck.Client.RecentRegionLatency()`). Deliberately NOT the latest report's
714 // own latency list — every measurement this fork makes is partial (`complete_threshold`), so
715 // ranking on one report leaves a distant candidate's region unmeasured and collapses the
716 // suggestion to a uniform random pick. See `exit_node_suggest`'s module docs.
717 let region_latency = self
718 .control
719 .ask(control_runner::RecentRegionLatency)
720 .await?;
721
722 // Every known peer (Go reads the netmap peers via `AppendMatchingPeers`); the domain `Node`
723 // retains the cap map, home DERP region, online state, and accepted routes the predicate
724 // needs.
725 let peers = self
726 .peer_tracker
727 .upgrade()
728 .ok_or(Error {
729 kind: ErrorKind::ActorGone,
730 target_actor: None,
731 message_ty: None,
732 })?
733 .ask(peer_tracker::AllPeers)
734 .await?;
735
736 // Project each peer into the algorithm's candidate inputs. The eligibility predicate runs
737 // inside the pure function, so every peer is passed (self is naturally absent from the peer
738 // set). `derp_region`/`online`/`cap_map`/`accepted_routes` map straight off the domain node;
739 // the exit-route check is the fork's family-agnostic `prefix_len == 0` (IPv4-only parity —
740 // see `exit_node_suggest::suggest_exit_node`).
741 let candidates: Vec<exit_node_suggest::ExitNodeCandidate> = peers
742 .iter()
743 .map(|peer| exit_node_suggest::ExitNodeCandidate {
744 stable_id: peer.stable_id.clone(),
745 name: peer
746 .fqdn_opt(false)
747 .unwrap_or_else(|| peer.hostname.clone()),
748 derp_region: peer.derp_region,
749 online: peer.online,
750 advertises_exit_route: peer
751 .accepted_routes
752 .iter()
753 .any(|route| route.prefix_len() == 0),
754 has_suggest_cap: peer.has_node_attr(NODE_ATTR_SUGGEST_EXIT_NODE),
755 })
756 .collect();
757
758 // Read the sticky previous suggestion, run the pure algorithm with the production
759 // uniform-random selectors, then update the sticky value to the new result. This mirrors Go
760 // `suggestExitNodeLocked` (`ipn/ipnlocal/local.go`), which assigns `b.lastSuggestedExitNode =
761 // res.ID` on **every** no-error return — INCLUDING the empty/no-candidate result, where it
762 // clears the sticky id to "". So a successful suggestion sets stickiness, an empty result
763 // CLEARS it (a peer that dropped out of candidacy stops being preferred), and only an `Err`
764 // (`NoPreferredDerp` — no netcheck yet) returns before the assignment and leaves it untouched.
765 let prev = self.prev_suggestion.lock().unwrap().clone();
766 let outcome = exit_node_suggest::suggest_exit_node(
767 report.preferred_derp,
768 ®ion_latency,
769 &candidates,
770 prev.as_ref(),
771 &exit_node_suggest::random_region,
772 &exit_node_suggest::random_node,
773 );
774 *self.prev_suggestion.lock().unwrap() = exit_node_suggest::next_sticky(prev, &outcome);
775 Ok(outcome)
776 }
777
778 /// List the tailnet peers this node can Taildrop a file *to* (Go LocalAPI `FileTargets`).
779 ///
780 /// Mirrors the upstream send-path filter (`feature/taildrop` `Extension::FileTargets`): a peer
781 /// qualifies when it advertises a reachable peerAPI **and** is either owned by the same user as
782 /// this node **or** explicitly granted the file-sharing-target capability. The whole list is
783 /// gated on this node holding the file-sharing capability (control sets it when the admin enables
784 /// Taildrop) — absent that, an empty list (fail-closed, not an error, matching how the receive
785 /// store returns empty when disabled). Results are sorted by the peer's MagicDNS name.
786 ///
787 /// Targets are listed regardless of current online state (upstream's `FileTargets` does not gate
788 /// on online either; an offline target's send will simply time out). The self node is never
789 /// included. Returns empty before the first netmap.
790 ///
791 /// Divergence from Go: the upstream filter also excludes `tvOS` peers, which this fork cannot
792 /// reproduce (the domain node carries no OS string); the impact is negligible — the actual send
793 /// fail-closes if such a peer refused the transfer.
794 pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
795 // Node-level gate: this node must hold the file-sharing capability (Taildrop enabled by the
796 // admin). Read it off the self node's cap map, like Go's `hasCapFileSharing()`.
797 let self_node = self.control.ask(control_runner::SelfNode).await?;
798 let Some(self_node) = self_node else {
799 return Ok(Vec::new()); // no netmap yet
800 };
801 if !self_node.can_share_files() {
802 return Ok(Vec::new()); // Taildrop not enabled for the tailnet — fail-closed
803 }
804 let self_user_id = self_node.user_id;
805
806 let peers = self
807 .peer_tracker
808 .upgrade()
809 .ok_or(Error {
810 kind: ErrorKind::ActorGone,
811 target_actor: None,
812 message_ty: None,
813 })?
814 .ask(peer_tracker::AllPeers)
815 .await?;
816
817 // Eligibility + ordering live in `build_file_targets` (pure, unit-tested in `status`).
818 Ok(status::build_file_targets(peers, self_user_id))
819 }
820
821 /// The stable id of the exit node traffic is currently egressing through, or `None` if none is
822 /// engaged. This is the route updater's resolved + fail-closed answer (see
823 /// [`Status::active_exit_node`](crate::status::Status::active_exit_node)): it differs from the
824 /// configured [`exit_node`](Self::exit_node) selector, which may name a peer that is absent or
825 /// no longer advertising a default route (in which case egress is dropped and this returns
826 /// `None`).
827 pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
828 self.active_exit_rx.borrow().clone()
829 }
830
831 /// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
832 ///
833 /// Returns the signed JWT, or the token RPC's own [`ts_control::IdTokenError`]. The kameo
834 /// delegated-reply send error is flattened: a handler error carries the real `IdTokenError`,
835 /// any other send failure (actor shutdown / mailbox closed) is surfaced as
836 /// [`ts_control::IdTokenError::NetworkError`].
837 pub async fn fetch_id_token(
838 &self,
839 audience: String,
840 ) -> Result<String, ts_control::IdTokenError> {
841 self.control
842 .ask(control_runner::FetchIdToken { audience })
843 .await
844 .map_err(flatten_send_err)
845 }
846
847 /// Log this node out of the tailnet: deregister it by expiring its current node key.
848 ///
849 /// Forwards to the control runner, which re-POSTs `/machine/register` with a past expiry over a
850 /// fresh Noise channel. This is a control-plane state change only — it does NOT shut the runtime
851 /// down (the caller follows with [`graceful_shutdown`](Self::graceful_shutdown)) and does not
852 /// touch the on-disk node key. The kameo delegated-reply send error is flattened the same way as
853 /// `fetch_id_token`: a handler error carries the real
854 /// [`ts_control::LogoutError`]; any other send failure (actor shutdown / mailbox closed) is
855 /// surfaced as [`ts_control::LogoutError::NetworkError`].
856 pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
857 self.control
858 .ask(control_runner::Logout)
859 .await
860 .map_err(flatten_logout_send_err)
861 }
862
863 /// Publish a `TXT` DNS record for this node via control's `/machine/set-dns` (Go
864 /// `LocalClient.SetDNS`).
865 ///
866 /// Forwards to the control runner, which POSTs the record over a fresh Noise channel. The kameo
867 /// delegated-reply send error is flattened the same way as `fetch_id_token`:
868 /// a handler error carries the real [`ts_control::SetDnsError`]; any other send failure (actor
869 /// shutdown / mailbox closed) is surfaced as [`ts_control::SetDnsError::NetworkError`].
870 pub async fn set_dns(
871 &self,
872 name: String,
873 value: String,
874 ) -> Result<(), ts_control::SetDnsError> {
875 self.control
876 .ask(control_runner::SetDns { name, value })
877 .await
878 .map_err(flatten_set_dns_send_err)
879 }
880
881 /// Sign `node_key` with this node's network-lock key and submit the signature to control
882 /// (Go `tka.sign` Direct case → `/machine/tka/sign`).
883 ///
884 /// Submits only — the local [`Authority`](ts_tka::Authority) is **not** mutated here; it advances
885 /// via the existing verified-sync path. A handler error carries the real [`ts_control::TkaSyncError`];
886 /// any other send failure (actor shutdown / mailbox closed) is surfaced as
887 /// [`ts_control::TkaSyncError::NetworkError`].
888 pub async fn tka_sign(&self, node_key: [u8; 32]) -> Result<(), ts_control::TkaSyncError> {
889 self.control
890 .ask(control_runner::TkaSign { node_key })
891 .await
892 .map_err(flatten_tka_send_err)
893 }
894
895 /// Disable Tailnet Lock by presenting the `disablement_secret` to control (Go `tka.disable` →
896 /// `/machine/tka/disable`), targeting the current authority head.
897 ///
898 /// Submits only — the local [`Authority`](ts_tka::Authority) is **not** mutated here. A handler
899 /// error carries the real [`ts_control::TkaSyncError`] (incl.
900 /// [`Unsupported`](ts_control::TkaSyncError::Unsupported) when there is no known TKA head to
901 /// disable); any other send failure collapses to
902 /// [`NetworkError`](ts_control::TkaSyncError::NetworkError).
903 pub async fn tka_disable(
904 &self,
905 disablement_secret: Vec<u8>,
906 ) -> Result<(), ts_control::TkaSyncError> {
907 self.control
908 .ask(control_runner::TkaDisable { disablement_secret })
909 .await
910 .map_err(flatten_tka_send_err)
911 }
912
913 /// Initialize Tailnet Lock with this node as the sole initial trusted key, gated by
914 /// `disablement_secret` (Go `tka` init → `/machine/tka/init/{begin,finish}`).
915 ///
916 /// Submits only — does not seed the local [`Authority`](ts_tka::Authority); the node picks up the
917 /// new lock via the existing verified netmap-sync. A handler error carries the real
918 /// [`ts_control::TkaSyncError`] ([`Unsupported`](ts_control::TkaSyncError::Unsupported) if
919 /// control needs other nodes re-signed — the single-node "lock yourself in" subset only); any
920 /// other send failure collapses to [`NetworkError`](ts_control::TkaSyncError::NetworkError).
921 pub async fn tka_init(
922 &self,
923 disablement_secret: Vec<u8>,
924 ) -> Result<(), ts_control::TkaSyncError> {
925 self.control
926 .ask(control_runner::TkaInit { disablement_secret })
927 .await
928 .map_err(flatten_tka_send_err)
929 }
930
931 /// Read up to `limit` entries of the Tailnet-Lock update-chain log, head-first (Go
932 /// `NetworkLockLog`). A **pure local read** of the synced AUM chain — no control round-trip — so
933 /// the only failure is a kameo send error (actor gone / mailbox), surfaced as a coarse [`Error`]
934 /// like the other local-read paths (`status`/`tka_status`), not a [`ts_control::TkaSyncError`].
935 /// Returns an empty `Vec` when no lock is synced.
936 pub async fn tka_log(&self, limit: usize) -> Result<Vec<TkaLogEntry>, Error> {
937 self.control
938 .ask(control_runner::TkaLog { limit })
939 .await
940 .map_err(Error::from)
941 }
942
943 /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` (`acme` feature).
944 ///
945 /// Mirrors `fetch_id_token`: forwards to the control runner, which runs
946 /// the client-side ACME DNS-01 flow on a spawned task and publishes the challenge TXT via the
947 /// node's set-dns RPC. The kameo delegated-reply send error is flattened — a handler error
948 /// carries the real [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox
949 /// closed) is surfaced as a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control
950 /// plane 501s on set-dns.
951 #[cfg(feature = "acme")]
952 pub async fn get_certificate(
953 &self,
954 name: String,
955 ) -> Result<ts_control::tls::CertifiedKey, ts_control::CertError> {
956 self.control
957 .ask(control_runner::GetCertificate { name })
958 .await
959 .map_err(flatten_cert_send_err)
960 }
961
962 /// Issue a real Let's Encrypt certificate for this node's MagicDNS `name` and return the
963 /// **PEM pair** `(cert_chain_pem, key_pem)` — the analog of Go's
964 /// `LocalClient.CertPairWithValidity`, for writing the daemon's on-disk `.crt` + `.key`
965 /// (`tnet cert`). `acme` feature.
966 ///
967 /// Same issuance as [`get_certificate`](Self::get_certificate) (one client-side ACME DNS-01
968 /// order, challenge published via the node's set-dns RPC) — only the result shape differs: this
969 /// returns the leaf+chain PEM and the leaf-key PEM instead of the opaque
970 /// [`CertifiedKey`](ts_control::tls::CertifiedKey). The second element is the **leaf private
971 /// key** PEM; it is never logged anywhere on this path.
972 ///
973 /// **`min_validity` (honest "always fresh").** Go's `CertPairWithValidity` reuses a cached cert
974 /// when it has at least `min_validity` of its lifetime left, and re-issues otherwise. This fork
975 /// has **no cert cache** — every call performs a fresh issuance — so `min_validity` is accepted
976 /// for signature compatibility but does not change behavior: a freshly issued cert (full
977 /// lifetime) trivially satisfies any `min_validity`. A reuse cache is separate future work; this
978 /// does NOT fake one.
979 ///
980 /// Mirrors [`get_certificate`](Self::get_certificate)'s error handling: the kameo
981 /// delegated-reply send error is flattened — a handler error carries the real
982 /// [`ts_control::CertError`]; any other send failure (actor shutdown / mailbox closed) collapses
983 /// to a [`ts_control::CertError::Io`]. SaaS-only: a self-hosted control plane 501s on set-dns.
984 #[cfg(feature = "acme")]
985 pub async fn cert_pair(
986 &self,
987 name: String,
988 min_validity: Option<Duration>,
989 ) -> Result<(String, String), ts_control::CertError> {
990 // No cert cache exists in this fork (every issuance is fresh), so `min_validity` is honored
991 // trivially by always issuing a full-lifetime cert. Bound (unused beyond this contract) so
992 // the parameter is explicitly accounted for rather than silently ignored.
993 let _ = min_validity;
994 self.control
995 .ask(control_runner::GetCertPair { name })
996 .await
997 .map_err(flatten_cert_send_err)
998 }
999
1000 /// Resolve which node owns a tailnet source address.
1001 ///
1002 /// Maps the destination IP of `addr` to its owning node. Mirrors tsnet's `LocalClient::WhoIs`.
1003 /// Returns `None` if no peer holds that tailnet IP.
1004 ///
1005 /// The returned [`WhoIs`] additionally carries the **flow-scoped** peer-capability grants
1006 /// ([`WhoIs::cap_map`], Go `apitype.WhoIsResponse.CapMap`): the caps control's packet-filter
1007 /// application rules authorize for traffic from THIS node (the flow source) to `addr` (the
1008 /// destination). Empty when no grant matches. (The node-level cap map rides
1009 /// [`WhoIs::capabilities`].)
1010 pub async fn whois(&self, addr: core::net::SocketAddr) -> Result<Option<WhoIs>, Error> {
1011 let whois = self
1012 .peer_tracker
1013 .upgrade()
1014 .ok_or(Error {
1015 kind: ErrorKind::ActorGone,
1016 target_actor: None,
1017 message_ty: None,
1018 })?
1019 .ask(peer_tracker::Whois { addr })
1020 .await?;
1021
1022 let Some(mut whois) = whois else {
1023 return Ok(None);
1024 };
1025
1026 // Fill the flow-scoped cap map: src = this node's own tailnet IP (of the dst's family),
1027 // dst = the queried address. A grant applies when its source matches the flow source — `src`
1028 // ∈ its src prefixes OR this node holds one of its source node-caps — AND `dst` ∈ its dst
1029 // prefixes (Go `Filter.CapsWithValues`). Resolve our own IP + cap map from the self node; if
1030 // it isn't known yet, leave the map empty (no grants resolvable without a source).
1031 let dst = addr.ip();
1032 if let Some(self_node) = self.control.ask(control_runner::SelfNode).await? {
1033 let src: core::net::IpAddr = if dst.is_ipv6() {
1034 self_node.tailnet_address.ipv6.addr().into()
1035 } else {
1036 self_node.tailnet_address.ipv4.addr().into()
1037 };
1038 let grants = self.cap_grants_rx.borrow();
1039 whois.cap_map = ts_packetfilter_state::caps_for(&grants, src, dst, |cap| {
1040 self_node.has_node_attr(cap)
1041 });
1042 }
1043
1044 Ok(Some(whois))
1045 }
1046
1047 /// The current direct-path status to the peer holding tailnet IP `dst`: its confirmed direct UDP
1048 /// endpoint and that path's last-measured RTT, or `None` when there is no direct path right now
1049 /// (the peer is relayed via DERP, is unknown, or has no disco key).
1050 ///
1051 /// The latency is the RTT of the most recent disco ping/pong that confirmed the path — a live
1052 /// snapshot up to one probe interval stale, NOT a fresh on-demand round-trip (that is a separate,
1053 /// heavier capability). Mirrors the direct-path latency Go surfaces for `ipnstate.PeerStatus`.
1054 pub async fn direct_path(
1055 &self,
1056 dst: core::net::IpAddr,
1057 ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
1058 let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
1059 kind: ErrorKind::ActorGone,
1060 target_actor: None,
1061 message_ty: None,
1062 })?;
1063
1064 // Resolve the tailnet IP to its node, then to its disco key. No node / no disco key ⇒ no
1065 // direct path is possible (a peer with no disco key can only be reached via DERP).
1066 let Some(node) = peer_tracker
1067 .ask(peer_tracker::PeerByTailnetIp { ip: dst })
1068 .await?
1069 else {
1070 return Ok(None);
1071 };
1072 let Some(disco) = node.disco_key else {
1073 return Ok(None);
1074 };
1075
1076 self.direct
1077 .ask(direct::DirectPathLatency { disco })
1078 .await
1079 .map_err(Into::into)
1080 }
1081
1082 /// Send a disco ping to the peer holding tailnet IP `dst` **now** and await the pong, returning
1083 /// the fresh round-trip latency and the endpoint that answered, or `None` if no pong arrives
1084 /// within `timeout` (or the peer is unknown / has no disco key / no candidate path). This is the
1085 /// true on-demand `PingType::Disco` (Go `tailscale ping`), as opposed to
1086 /// [`direct_path`](Self::direct_path) which reports the last periodic probe's RTT.
1087 ///
1088 /// The ping round-trip is awaited OFF the direct manager's mailbox (we take a `MagicSock` handle
1089 /// and await on it directly), so a slow/timing-out ping never blocks the actor.
1090 pub async fn ping_disco(
1091 &self,
1092 dst: core::net::IpAddr,
1093 timeout: Duration,
1094 ) -> Result<Option<(core::net::SocketAddr, Duration)>, Error> {
1095 let peer_tracker = self.peer_tracker.upgrade().ok_or(Error {
1096 kind: ErrorKind::ActorGone,
1097 target_actor: None,
1098 message_ty: None,
1099 })?;
1100
1101 let Some(node) = peer_tracker
1102 .ask(peer_tracker::PeerByTailnetIp { ip: dst })
1103 .await?
1104 else {
1105 return Ok(None);
1106 };
1107 let Some(disco) = node.disco_key else {
1108 return Ok(None);
1109 };
1110
1111 // Cheap synchronous handle fetch, then await the ping OFF the actor mailbox.
1112 let Some(sock) = self.direct.ask(direct::SockHandle).await? else {
1113 return Ok(None);
1114 };
1115 // A `ping_now` error is an underlay UDP send failure (not an actor problem); surface it as a
1116 // reply-level error. A timed-out / unanswered ping is `Ok(None)`, not an error.
1117 sock.ping_now(&disco, timeout).await.map_err(|_| Error {
1118 kind: ErrorKind::ReplyErr,
1119 target_actor: None,
1120 message_ty: None,
1121 })
1122 }
1123
1124 /// Change the selected exit node at runtime (the equivalent of Go `tsnet`'s
1125 /// `LocalClient.EditPrefs(ExitNodeID/ExitNodeIP)`), without recreating the device.
1126 ///
1127 /// Updates the live exit-node selector, then asks the peer tracker to re-broadcast the current
1128 /// peer set so the route updater and source filter re-resolve the new selector immediately.
1129 /// `None` clears the exit node (internet-bound traffic is then dropped, fail-closed, unless this
1130 /// node egresses directly). The selection is re-resolved against the live peer set, so passing a
1131 /// selector for a peer not yet in the netmap simply takes effect once that peer appears.
1132 pub async fn set_exit_node(
1133 &self,
1134 selector: Option<ts_control::ExitNodeSelector>,
1135 ) -> Result<(), Error> {
1136 // Update the live cell every reader borrows from. `send_replace` keeps the value current
1137 // even with no active receivers (none can have dropped while the runtime is up, but it is
1138 // the right non-failing primitive here).
1139 self.exit_node_tx.send_replace(selector);
1140
1141 // Trigger an immediate re-resolution: the route updater (outbound routes + DoH delegation)
1142 // and the source filter (inbound validation) both recompute on an `Arc<PeerState>`, so a
1143 // re-broadcast applies the new exit without waiting for the next netmap update.
1144 self.peer_tracker
1145 .upgrade()
1146 .ok_or(Error {
1147 kind: ErrorKind::ActorGone,
1148 target_actor: None,
1149 message_ty: None,
1150 })?
1151 .ask(peer_tracker::RepublishState)
1152 .await
1153 .map_err(Into::into)
1154 }
1155
1156 /// The currently-selected exit node, or `None` if none is selected.
1157 pub fn exit_node(&self) -> Option<ts_control::ExitNodeSelector> {
1158 self.env.exit_node()
1159 }
1160
1161 /// Toggle whether this node accepts peer-advertised subnet routes at runtime (the equivalent of
1162 /// Go `tsnet`'s `LocalClient.EditPrefs(RouteAll)` / `tailscale set --accept-routes`), without
1163 /// recreating the device.
1164 ///
1165 /// `accept-routes` is a purely **local** preference — unlike advertised routes it is never
1166 /// reported to control (no `Hostinfo` / MapRequest side), so this only re-runs the local
1167 /// route/source-filter recompute, mirroring [`set_exit_node`](Self::set_exit_node) rather than
1168 /// [`set_advertise_routes`](Self::set_advertise_routes). Updates the live cell, then asks the peer
1169 /// tracker to re-broadcast the current peer set so the route updater (outbound routes) and the
1170 /// source filter (inbound validation) re-filter against the new value immediately: turning it on
1171 /// installs newly-accepted subnet routes (and widens the source filter to match); turning it off
1172 /// removes them from BOTH in lock-step (never accepting a source for a route no longer installed).
1173 /// Self routes and the exit-node default `/0` are unaffected (the latter is gated by the exit-node
1174 /// selection, not this flag).
1175 ///
1176 /// In TUN transport mode the host routing table is also re-steered live: the `RepublishState`
1177 /// kicked below re-broadcasts the peer set to the `TunActor`, whose `PeerState` handler re-reads
1178 /// `accept_routes` (and the exit selection) from `Env` and re-applies the host routes — so the
1179 /// toggle takes effect without rebuilding the device (the apply is an idempotent add-new/
1180 /// remove-gone diff). The exit-node default `/0` is still keyed on the exit selection, not this flag.
1181 pub async fn set_accept_routes(&self, accept: bool) -> Result<(), Error> {
1182 // Update the live cell every reader borrows from (same primitive/rationale as set_exit_node).
1183 self.accept_routes_tx.send_replace(accept);
1184
1185 // Trigger an immediate re-filter: the route updater and source filter both recompute on an
1186 // `Arc<PeerState>`, so a re-broadcast applies the new preference without waiting for the next
1187 // netmap update. Both re-read the same live cell, so the outbound route set and the inbound
1188 // source filter stay coupled (the anti-leak invariant).
1189 self.peer_tracker
1190 .upgrade()
1191 .ok_or(Error {
1192 kind: ErrorKind::ActorGone,
1193 target_actor: None,
1194 message_ty: None,
1195 })?
1196 .ask(peer_tracker::RepublishState)
1197 .await
1198 .map_err(Into::into)
1199 }
1200
1201 /// Whether this node currently accepts peer-advertised subnet routes (`--accept-routes`).
1202 pub fn accept_routes(&self) -> bool {
1203 self.env.accept_routes()
1204 }
1205
1206 /// Toggle whether this node accepts the tailnet's DNS configuration at runtime (the equivalent of
1207 /// Go `tsnet`'s `LocalClient.EditPrefs(CorpDNS)` / `tailscale set --accept-dns`), without
1208 /// recreating the device.
1209 ///
1210 /// Like [`set_accept_routes`](Self::set_accept_routes), `accept-dns` is a purely **local**
1211 /// preference — it is never reported to control (no `Hostinfo` / MapRequest side), so this only
1212 /// re-runs the local MagicDNS view rebuild. Updates the live cell, then asks the peer tracker to
1213 /// re-broadcast the current peer set; the resulting `PeerState` rebuild re-applies the gate on the
1214 /// MagicDNS responder (and the peerAPI DoH server that shares its view). When `false`, the
1215 /// responder ignores the control-pushed DNS config and answers every query `REFUSED`, mirroring Go
1216 /// applying an empty `dns.Config` when `CorpDNS` is off; flipping it back to `true` restores
1217 /// serving from the still-current config (the real config is never destroyed — only gated at the
1218 /// read site), so the OFF→ON restore is automatic.
1219 pub async fn set_accept_dns(&self, accept: bool) -> Result<(), Error> {
1220 // Update the live cell every reader borrows from (same primitive/rationale as set_accept_routes).
1221 self.accept_dns_tx.send_replace(accept);
1222
1223 // Trigger an immediate view rebuild: the MagicDNS responder re-reads `Env::accept_dns()` when
1224 // it handles a `PeerState`, so a re-broadcast re-applies the gate on both the netstack
1225 // responder and the peerAPI DoH server (which share the view) without waiting for the next
1226 // control/peer update. Mirrors `set_accept_routes`'s republish.
1227 self.peer_tracker
1228 .upgrade()
1229 .ok_or(Error {
1230 kind: ErrorKind::ActorGone,
1231 target_actor: None,
1232 message_ty: None,
1233 })?
1234 .ask(peer_tracker::RepublishState)
1235 .await
1236 .map_err(Into::into)
1237 }
1238
1239 /// Whether this node currently accepts the tailnet's DNS configuration (`--accept-dns` / `CorpDNS`).
1240 pub fn accept_dns(&self) -> bool {
1241 self.env.accept_dns()
1242 }
1243
1244 /// Change the set of subnet routes this node advertises at runtime (Go `tailscale set
1245 /// --advertise-routes`). Applies BOTH halves together so the wire and the data path agree:
1246 ///
1247 /// 1. **Wire** — re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
1248 /// (so control grants the node the subnet-router role for exactly these prefixes).
1249 /// 2. **Local** — swap the forwarder's accept/dial route table (so the node actually forwards the
1250 /// prefixes it advertises). New flows see the new set; in-flight flows keep their routing.
1251 ///
1252 /// `routes` is filtered to the IPv4-only, deduplicated set this fork can honor (IPv6 prefixes are
1253 /// dropped under the IPv6-off posture — we never advertise a route we won't forward), so the wire
1254 /// and forwarder are fed the identical final set. This sets the explicit subnet prefixes only; it
1255 /// does NOT touch the exit-node `0.0.0.0/0` advertisement (a separate concern).
1256 pub async fn set_advertise_routes(&self, routes: Vec<ipnet::IpNet>) -> Result<(), Error> {
1257 // Update the explicit-subnet part of the live preference, keep the exit-node flag, and
1258 // re-send the composed set. Composes with `set_advertise_exit_node` (neither clobbers the
1259 // other's contribution to `Hostinfo.RoutableIPs`).
1260 let composed = {
1261 let mut adv = self.advertise.lock().unwrap_or_else(|p| p.into_inner());
1262 adv.routes = routes;
1263 compose_advertised_routes(adv.routes.clone(), adv.exit_node)
1264 };
1265 self.apply_advertised_routes(composed).await
1266 }
1267
1268 /// Advertise (or stop advertising) this node as an **exit node** — the `0.0.0.0/0` default route
1269 /// (Go `tailscale set --advertise-exit-node`). Composes with
1270 /// [`set_advertise_routes`](Self::set_advertise_routes): toggling the exit node re-sends the
1271 /// explicit subnet routes plus (when `enable`) `0.0.0.0/0`, so the two preferences are
1272 /// independent. Like `set_advertise_routes`, this both re-advertises `Hostinfo.RoutableIPs` to
1273 /// control AND updates the forwarder's accept/dial set, applied together. Control still gates
1274 /// whether the advertised exit node is actually *usable* by peers (this only advertises it).
1275 pub async fn set_advertise_exit_node(&self, enable: bool) -> Result<(), Error> {
1276 let composed = {
1277 let mut adv = self.advertise.lock().unwrap_or_else(|p| p.into_inner());
1278 adv.exit_node = enable;
1279 compose_advertised_routes(adv.routes.clone(), adv.exit_node)
1280 };
1281 self.apply_advertised_routes(composed).await
1282 }
1283
1284 /// Push a freshly-composed advertised-route set to BOTH halves: the forwarder's accept/dial
1285 /// table (local) FIRST — so the node forwards a prefix before control grants it, never the
1286 /// reverse — then re-advertise `Hostinfo.RoutableIPs` to control on the live map-poll connection
1287 /// (wire). `composed` is already filtered + exit-node-folded by [`compose_advertised_routes`].
1288 async fn apply_advertised_routes(&self, composed: Vec<ipnet::IpNet>) -> Result<(), Error> {
1289 self.forwarder
1290 .ask(forwarder_actor::UpdateRoutes {
1291 routes: composed.clone(),
1292 })
1293 .await?;
1294 self.control
1295 .ask(control_runner::SetAdvertiseRoutes { routes: composed })
1296 .await
1297 .map_err(Into::into)
1298 }
1299
1300 /// Change this node's hostname at runtime (Go `tailscale set --hostname`), re-reporting
1301 /// `Hostinfo.Hostname` to control on the live map-poll connection. Hostname is display-only
1302 /// (control reflects it in the netmap), so there is no dataplane half. The new value is also
1303 /// what a subsequent re-registration reports, so it persists across a reconnect.
1304 pub async fn set_hostname(&self, hostname: String) -> Result<(), Error> {
1305 self.control
1306 .ask(control_runner::SetHostname { hostname })
1307 .await
1308 .map_err(Into::into)
1309 }
1310
1311 /// Subscribe to netmap peer-change events: the **narrow** peer-set view.
1312 ///
1313 /// Returns a [`watch::Receiver`] whose value is the current set of peer [`StatusNode`]s,
1314 /// updated on every netmap state update from control. Await
1315 /// [`watch::Receiver::changed`](tokio::sync::watch::Receiver::changed) to react to peers
1316 /// joining, leaving, or changing. For the unified Go-`WatchIPNBus` feed that merges this with
1317 /// device-state and the interactive-login URL, see [`watch_ipn_bus`](Self::watch_ipn_bus); this
1318 /// method is the peer-only projection of the same underlying cell.
1319 pub async fn watch_netmap(&self) -> Result<watch::Receiver<Vec<StatusNode>>, Error> {
1320 self.peer_tracker
1321 .upgrade()
1322 .ok_or(Error {
1323 kind: ErrorKind::ActorGone,
1324 target_actor: None,
1325 message_ty: None,
1326 })?
1327 .ask(peer_tracker::WatchNetmap)
1328 .await
1329 .map_err(Into::into)
1330 }
1331
1332 /// The current device connection-[`DeviceState`].
1333 pub fn device_state(&self) -> DeviceState {
1334 self.state_rx.borrow().clone()
1335 }
1336
1337 /// Watch the device connection-[`DeviceState`] (`Connecting` → `Running` / `NeedsLogin` /
1338 /// `Expired` / `Failed`).
1339 ///
1340 /// Returns a [`watch::Receiver`]; await
1341 /// [`changed`](tokio::sync::watch::Receiver::changed) to react push-style to control connection
1342 /// transitions instead of polling [`status`](Self::status). The initial value is the current
1343 /// state. Note: a transient per-reconnect dip back to `Connecting` is **not** currently
1344 /// emitted (control transparently reconnects below this layer); the state reflects registration
1345 /// outcome and node-key expiry.
1346 pub fn watch_state(&self) -> watch::Receiver<DeviceState> {
1347 self.state_rx.clone()
1348 }
1349
1350 /// Wait until the device finishes registering, returning a typed outcome.
1351 ///
1352 /// Resolves `Ok(())` once the device reaches [`DeviceState::Running`]. Returns a typed
1353 /// [`RegistrationError`] otherwise — the actionable distinction between "retry", "re-pair", and
1354 /// "drive interactive login" that replaces polling the device's `ipv4_addr` in a loop:
1355 /// - `AuthRejected` — bad/expired/unknown auth key. **Permanent** (re-pair).
1356 /// - `NeedsLogin(url)` — interactive authorization required (no usable auth key). **Not
1357 /// permanent**: the runtime keeps retrying and will reach `Running` once the user authorizes
1358 /// the URL. An **auth-key** caller should treat this as a failure; an **interactive** caller
1359 /// should ignore this return and instead drive the flow via [`watch_state`](Self::watch_state)
1360 /// (this method returns the URL eagerly rather than blocking for the whole login).
1361 /// - `NetworkUnreachable` — control unreachable. **Transient** (retry).
1362 /// - `Timeout` — no settled state within `timeout`.
1363 ///
1364 /// `KeyExpired` is not produced by this initial wait (a node key expires only *after* it has
1365 /// come up); observe post-registration expiry via [`watch_state`](Self::watch_state).
1366 /// `timeout` of `None` waits indefinitely for a settled state.
1367 pub async fn wait_until_running(
1368 &self,
1369 timeout: Option<Duration>,
1370 ) -> Result<(), RegistrationError> {
1371 device_state::wait_for_running(self.state_rx.clone(), timeout).await
1372 }
1373
1374 /// Subscribe to the unified IPN notification bus (Go `ipn` `WatchIPNBus` /
1375 /// `LocalBackend.WatchNotifications`).
1376 ///
1377 /// Returns an [`IpnBusWatcher`]; await [`next`](IpnBusWatcher::next) to receive [`Notify`]
1378 /// events that coalesce device-[`DeviceState`] changes (including the interactive-login URL as
1379 /// `browse_to_url`) and netmap peer-set changes into one feed. `mask`
1380 /// ([`NotifyWatchOpt`]) selects which current-state fields are front-loaded as an initial
1381 /// snapshot on subscribe (`INITIAL_STATE` / `INITIAL_NETMAP`), exactly like Go's
1382 /// `NotifyInitialState` / `NotifyInitialNetMap`.
1383 ///
1384 /// This composes the same `watch` cells as [`watch_state`](Self::watch_state),
1385 /// [`watch_netmap`](Self::watch_netmap), and `pop_browser_url` — one source of truth, so the
1386 /// merged feed cannot diverge from those narrow views. Besides the registration-time login URL
1387 /// (carried by `NeedsLogin`), `browse_to_url` also streams the mid-session
1388 /// `MapResponse.PopBrowserURL` (re-auth / consent on an already-running node). Delivery is
1389 /// best-effort/lossy (a bounded per-watcher buffer; a notification is dropped rather than
1390 /// blocking the runtime if a slow consumer's buffer fills), matching Go's bus. The stream ends
1391 /// (`next` returns `None`) on runtime shutdown or when the watcher is dropped.
1392 pub async fn watch_ipn_bus(&self, mask: NotifyWatchOpt) -> Result<IpnBusWatcher, Error> {
1393 // The peer-set cell lives on the peer-tracker actor; obtain a receiver the same way
1394 // `watch_netmap` does. State + shutdown cells are held here.
1395 let peer_rx = self
1396 .peer_tracker
1397 .upgrade()
1398 .ok_or(Error {
1399 kind: ErrorKind::ActorGone,
1400 target_actor: None,
1401 message_ty: None,
1402 })?
1403 .ask(peer_tracker::WatchNetmap)
1404 .await?;
1405 // The running-node consent-URL cell lives on the control runner; obtain its receiver the
1406 // same way (the control actor ref is strong, so no upgrade needed).
1407 let browser_rx = self.control.ask(control_runner::WatchBrowserUrl).await?;
1408 Ok(ipn_bus::spawn_watcher(
1409 mask,
1410 self.state_rx.clone(),
1411 peer_rx,
1412 browser_rx,
1413 self.shutdown.subscribe(),
1414 ))
1415 }
1416
1417 /// Attempt to shut down the runtime gracefully.
1418 ///
1419 /// Returns false if the shutdown timed out. It is still shut down if it timed out, just
1420 /// more violently and with possible resource leaks.
1421 pub async fn graceful_shutdown(self, timeout: Option<Duration>) -> bool {
1422 self.shutdown.send_replace(true);
1423
1424 async fn _shutdown_all(runtime: Runtime) {
1425 // See the note in `Drop` for why we only need to stop these actors to bring down the
1426 // whole runtime.
1427
1428 let _ignore = runtime.control.stop_gracefully().await;
1429 let _ignore = runtime.dataplane.stop_gracefully().await;
1430 let _ignore = runtime.env.bus.stop_gracefully().await;
1431
1432 tokio::join![
1433 runtime.control.wait_for_shutdown(),
1434 runtime.dataplane.wait_for_shutdown(),
1435 runtime.env.bus.wait_for_shutdown(),
1436 ];
1437 }
1438
1439 let fut = _shutdown_all(self);
1440
1441 match timeout {
1442 Some(timeout) => tokio::time::timeout(timeout, fut).await.is_ok(),
1443 None => {
1444 fut.await;
1445 true
1446 }
1447 }
1448 }
1449}
1450
1451impl Drop for Runtime {
1452 fn drop(&mut self) {
1453 // Stop the taildrop reaper so it cannot outlive the runtime (the `reauth_bridge` pattern). It
1454 // also self-exits when `shutdown` flips below, but aborting is immediate and covers the
1455 // already-shutdown early-return path too.
1456 if let Some(reaper) = self.taildrop_reaper.take() {
1457 reaper.abort();
1458 }
1459
1460 // We must have already run `graceful_shutdown`: on the happy path, this does nothing, but
1461 // if it timed out, we need to make sure the actors are dead so we don't leak them and their
1462 // dependents.
1463 if *self.shutdown.borrow() {
1464 self.control.kill();
1465 self.dataplane.kill();
1466 self.env.bus.kill();
1467 return;
1468 }
1469
1470 self.shutdown.send_replace(true);
1471
1472 // Actors shut down when the last ActorRef to them is dropped (as nothing can send them
1473 // messages anymore). If we don't hold an ActorRef in Runtime, in general the only thing
1474 // that has one is the MessageBus, which each actor subscribes to for a subset of messages.
1475 // Hence, if we shut down the bus, most actors die as well.
1476
1477 // First shut down the actors we have an ActorRef to:
1478 try_shutdown(&self.control);
1479 try_shutdown(&self.dataplane);
1480
1481 // Then shutdown the message bus, stopping the rest of the actors:
1482 try_shutdown(&self.env.bus);
1483 }
1484}
1485
1486fn try_shutdown(a: &ActorRef<impl kameo::Actor>) {
1487 if let Err(e) = a.mailbox_sender().try_send(Signal::Stop) {
1488 tracing::error!(error = %e, "graceful shutdown failed, killing actor");
1489 a.kill();
1490 }
1491}
1492
1493/// Tailscale's overlay MTU. The userspace netstacks MUST advertise an MSS that fits this so they
1494/// never hand the WireGuard encrypt path an IP packet larger than the tunnel can carry (the netstack
1495/// has no PMTU discovery and nothing re-segments between it and the 1280-MTU TUN). This is the same
1496/// default the TUN device uses (`tun_config_from_control`); both are derived from this value so the
1497/// netstack and the TUN always agree.
1498///
1499/// This is the **inner** IP-packet budget. The WireGuard transport header (a 16-byte
1500/// `TransportDataHeader` + the 16-byte AEAD tag = 32 bytes) is added by `TransmitSession::encrypt`
1501/// *after* the netstack produces the inner packet, and the outer UDP/IP headers ride on top of that.
1502/// So do NOT subtract the WireGuard overhead here — that would be a double-subtraction that
1503/// under-fills the tunnel and diverges from the TUN's MTU. The assert below documents that the outer
1504/// datagram still fits a conventional 1500-byte physical path with margin (1280 + 32 WG + 8 UDP +
1505/// 20 outer-IP = 1340).
1506const DEFAULT_OVERLAY_MTU: u16 = 1280;
1507
1508const _: () = assert!(
1509 DEFAULT_OVERLAY_MTU as usize + 32 + 8 + 20 <= 1500,
1510 "inner overlay MTU + WireGuard(32) + UDP(8) + outer-IP(20) must fit a 1500-byte physical path"
1511);
1512
1513/// Build the netstack config shared by both userspace netstacks (application + forwarder) from the
1514/// per-deployment `tcp_buffer_size` and `mtu` knobs.
1515///
1516/// `tcp_buffer_size`: `None` keeps the netstack default (256 KiB/direction); `Some(n)` overrides it
1517/// (e.g. a smaller window on a memory-constrained exit node forwarding many concurrent flows — see
1518/// [`netstack::netcore::Config::tcp_buffer_size`]).
1519///
1520/// `mtu`: the overlay/tunnel MTU. `None` (and a stray `0`) falls back to [`DEFAULT_OVERLAY_MTU`]
1521/// (1280), exactly as the TUN device does, so the netstack's advertised MSS fits the tunnel. Leaving
1522/// this at the netstack's generic 1500 default (the prior behavior) made smoltcp advertise MSS ~1460
1523/// and segment to ~1500 B, which then overflowed the 1280 TUN — a PMTU black-hole / throughput cliff.
1524///
1525/// Factored out of [`Runtime::spawn`] so the mapping is unit-testable without standing up the actors.
1526fn netstack_config_from(
1527 tcp_buffer_size: Option<usize>,
1528 mtu: Option<u16>,
1529) -> netstack::netcore::Config {
1530 let mut c = netstack::netcore::Config::default();
1531 if let Some(tcp_buffer_size) = tcp_buffer_size {
1532 c.tcp_buffer_size = tcp_buffer_size;
1533 }
1534 // `0` is not a usable MTU; treat it like `None` and fall back to the overlay default, mirroring
1535 // the TUN's `and_then(NonZeroU16::new).unwrap_or(1280)`.
1536 let mtu = mtu.filter(|&m| m != 0).unwrap_or(DEFAULT_OVERLAY_MTU);
1537 c.mtu = usize::from(mtu);
1538 c
1539}
1540
1541/// Filter a requested advertise-route set to the IPv4-only, deduplicated set this fork can honor,
1542/// mirroring [`ts_control::Config::advertised_routes`] so a runtime `set_advertise_routes` feeds the
1543/// wire (control grant) and the forwarder (accept/dial table) the identical final set. IPv6 prefixes
1544/// are dropped under the IPv6-off posture — we never advertise a route we won't forward. Order is
1545/// preserved (first occurrence wins). Factored out so the filter is unit-testable without an actor.
1546fn filter_advertise_routes(routes: Vec<ipnet::IpNet>) -> Vec<ipnet::IpNet> {
1547 let mut filtered: Vec<ipnet::IpNet> = Vec::new();
1548 for net in routes {
1549 if matches!(net, ipnet::IpNet::V4(_)) {
1550 if !filtered.contains(&net) {
1551 filtered.push(net);
1552 }
1553 } else {
1554 tracing::warn!(prefix = %net, "dropping IPv6 advertise route (IPv6-off posture)");
1555 }
1556 }
1557 filtered
1558}
1559
1560/// Compose the final advertised-route set from the explicit subnet `routes` and the exit-node flag,
1561/// mirroring [`ts_control::Config::advertised_routes`]: the IPv4-only, deduplicated subnet prefixes,
1562/// plus `0.0.0.0/0` appended when `exit_node` is set. This is the single source of truth both
1563/// runtime advertise mutators (`set_advertise_routes`, `set_advertise_exit_node`) feed, so the two
1564/// compose instead of clobbering. Factored out so the composition is unit-testable without an actor.
1565fn compose_advertised_routes(routes: Vec<ipnet::IpNet>, exit_node: bool) -> Vec<ipnet::IpNet> {
1566 let mut filtered = filter_advertise_routes(routes);
1567 if exit_node {
1568 let default_v4 = ipnet::IpNet::V4(
1569 ipnet::Ipv4Net::new(core::net::Ipv4Addr::UNSPECIFIED, 0)
1570 .expect("0.0.0.0/0 is a valid prefix"),
1571 );
1572 if !filtered.contains(&default_v4) {
1573 filtered.push(default_v4);
1574 }
1575 }
1576 filtered
1577}
1578
1579/// The runtime's live advertised-route preference: the explicit subnet routes plus whether this node
1580/// advertises itself as an exit node. Held behind a `Mutex` on the [`Runtime`] so
1581/// [`Runtime::set_advertise_routes`] and [`Runtime::set_advertise_exit_node`] each mutate their own
1582/// part and re-send the composed set — they compose rather than clobber (Go `EditPrefs` keeps
1583/// `AdvertiseRoutes` and the exit-node advertisement as independent prefs that both feed
1584/// `Hostinfo.RoutableIPs`).
1585#[derive(Debug, Default, Clone)]
1586struct AdvertiseState {
1587 /// The explicit subnet prefixes (pre-filter; the last value passed to `set_advertise_routes`).
1588 routes: Vec<ipnet::IpNet>,
1589 /// Whether this node advertises the exit-node default route (`0.0.0.0/0`).
1590 exit_node: bool,
1591}
1592
1593/// Flatten a kameo delegated-reply [`SendError`] for the id-token RPC into the RPC's own
1594/// [`ts_control::IdTokenError`].
1595///
1596/// A [`SendError::HandlerError`](kameo::error::SendError::HandlerError) carries the real
1597/// `IdTokenError` produced by the handler and is surfaced verbatim. Any other send failure (actor
1598/// not running / stopped, mailbox full, send timeout) is a delivery problem rather than an RPC
1599/// result, so it collapses to a transient [`ts_control::IdTokenError::NetworkError`]. Factored out
1600/// of [`Runtime::fetch_id_token`] so this mapping is unit-testable without standing up an actor.
1601fn flatten_send_err<M>(
1602 e: kameo::error::SendError<M, ts_control::IdTokenError>,
1603) -> ts_control::IdTokenError {
1604 match e {
1605 kameo::error::SendError::HandlerError(err) => err,
1606 _ => ts_control::IdTokenError::NetworkError,
1607 }
1608}
1609
1610/// Flatten a kameo `SendError` from the `Logout` ask into a [`ts_control::LogoutError`].
1611///
1612/// A `HandlerError` carries the real `LogoutError` from the control RPC and is surfaced verbatim;
1613/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
1614/// problem, not a logout result — collapses to the transient [`ts_control::LogoutError::NetworkError`]
1615/// (logout is idempotent, so a retry after a delivery failure is safe). Factored out of
1616/// [`Runtime::logout`] so the mapping is unit-testable without standing up an actor.
1617fn flatten_logout_send_err<M>(
1618 e: kameo::error::SendError<M, ts_control::LogoutError>,
1619) -> ts_control::LogoutError {
1620 match e {
1621 kameo::error::SendError::HandlerError(err) => err,
1622 _ => ts_control::LogoutError::NetworkError,
1623 }
1624}
1625
1626/// Flatten a kameo `SendError` from the `SetDns` ask into a [`ts_control::SetDnsError`].
1627///
1628/// A `HandlerError` carries the real `SetDnsError` from the set-dns RPC and is surfaced verbatim;
1629/// any other send failure (actor not running / stopped, mailbox full, send timeout) — a delivery
1630/// problem, not a publish result — collapses to the transient
1631/// [`ts_control::SetDnsError::NetworkError`]. Factored out of [`Runtime::set_dns`] so the mapping is
1632/// unit-testable without standing up an actor.
1633fn flatten_set_dns_send_err<M>(
1634 e: kameo::error::SendError<M, ts_control::SetDnsError>,
1635) -> ts_control::SetDnsError {
1636 match e {
1637 kameo::error::SendError::HandlerError(err) => err,
1638 _ => ts_control::SetDnsError::NetworkError,
1639 }
1640}
1641
1642/// Flatten a kameo `SendError` from a TKA mutation ask (`TkaSign`/`TkaDisable`) into a
1643/// [`ts_control::TkaSyncError`]. A `HandlerError` carries the real RPC error; any other send failure
1644/// (actor shutdown / mailbox closed) is surfaced as the transient
1645/// [`ts_control::TkaSyncError::NetworkError`]. Generic over the message type so both share it.
1646fn flatten_tka_send_err<M>(
1647 e: kameo::error::SendError<M, ts_control::TkaSyncError>,
1648) -> ts_control::TkaSyncError {
1649 match e {
1650 kameo::error::SendError::HandlerError(err) => err,
1651 _ => ts_control::TkaSyncError::NetworkError,
1652 }
1653}
1654
1655/// Flatten a kameo `SendError` from the `GetCertificate` / `GetCertPair` ask into a
1656/// [`ts_control::CertError`].
1657///
1658/// A `HandlerError` carries the real `CertError` produced by the ACME issuance and is surfaced
1659/// verbatim. `CertError` has no transient-network variant, so any other send failure (actor not
1660/// running / stopped, mailbox full, send timeout) — a delivery problem rather than an issuance
1661/// result — collapses to a [`ts_control::CertError::Io`]. Generic over the message type, so it
1662/// serves both [`Runtime::get_certificate`] and [`Runtime::cert_pair`]; factored out so the mapping
1663/// is unit-testable without standing up an actor.
1664#[cfg(feature = "acme")]
1665fn flatten_cert_send_err<M>(
1666 e: kameo::error::SendError<M, ts_control::CertError>,
1667) -> ts_control::CertError {
1668 match e {
1669 kameo::error::SendError::HandlerError(err) => err,
1670 _ => ts_control::CertError::Io(std::io::Error::other(
1671 "control runner unavailable for certificate issuance",
1672 )),
1673 }
1674}
1675
1676#[cfg(test)]
1677mod tests {
1678 use super::*;
1679
1680 /// `None` must leave the netstack's own default TCP window in place (the 256 KiB throughput
1681 /// default), and must not silently coerce to some other value.
1682 #[test]
1683 fn netstack_config_none_uses_netstack_default() {
1684 let default = netstack::netcore::Config::default();
1685 let built = netstack_config_from(None, None);
1686 assert_eq!(
1687 built.tcp_buffer_size, default.tcp_buffer_size,
1688 "None must inherit the netstack default TCP buffer size"
1689 );
1690 }
1691
1692 #[test]
1693 fn netstack_config_mtu_defaults_to_overlay_not_generic_1500() {
1694 // The crux of the fix: with no explicit MTU, the netstack must use the 1280 overlay MTU, NOT
1695 // smoltcp's generic 1500 default — otherwise it advertises an MSS that overflows the tunnel.
1696 let built = netstack_config_from(None, None);
1697 assert_eq!(
1698 built.mtu,
1699 usize::from(DEFAULT_OVERLAY_MTU),
1700 "netstack MTU must default to the 1280 overlay MTU, not the 1500 netstack default"
1701 );
1702 assert_ne!(built.mtu, 1500, "must not leave the generic 1500 default");
1703 }
1704
1705 #[test]
1706 fn netstack_config_honors_explicit_mtu_and_rejects_zero() {
1707 // An explicit (control-supplied) MTU is honored verbatim.
1708 assert_eq!(netstack_config_from(None, Some(1400)).mtu, 1400);
1709 // A stray 0 is not a usable MTU; fall back to the overlay default (mirrors the TUN).
1710 assert_eq!(
1711 netstack_config_from(None, Some(0)).mtu,
1712 usize::from(DEFAULT_OVERLAY_MTU)
1713 );
1714 }
1715
1716 #[test]
1717 fn netstack_config_overlay_mtu_matches_tun_default() {
1718 // The netstack MTU default and the TUN MTU default must be the same value, or the two
1719 // netstacks and the TUN would disagree on the segment size budget.
1720 assert_eq!(
1721 DEFAULT_OVERLAY_MTU, 1280,
1722 "overlay MTU must match the TUN device default (tun_config_from_control)"
1723 );
1724 }
1725
1726 /// `Some(n)` must override the TCP window (the memory-vs-throughput knob exit-node operators
1727 /// reach for), reaching the config that both netstacks are built from.
1728 #[test]
1729 fn netstack_config_some_overrides_buffer() {
1730 let built = netstack_config_from(Some(64 * 1024), None);
1731 assert_eq!(
1732 built.tcp_buffer_size,
1733 64 * 1024,
1734 "Some(n) must override the TCP buffer size that both netstacks use"
1735 );
1736 }
1737
1738 /// `set_advertise_routes` must feed the wire and the forwarder the IDENTICAL filtered set:
1739 /// IPv4-only (IPv6 dropped under the IPv6-off posture), deduplicated, order preserved.
1740 #[test]
1741 fn filter_advertise_routes_keeps_v4_dedups_drops_v6() {
1742 let v4a: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
1743 let v4b: ipnet::IpNet = "192.168.1.0/24".parse().unwrap();
1744 let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1745
1746 // Mixed input with a duplicate v4 and a v6 prefix.
1747 let out = filter_advertise_routes(vec![v4a, v6, v4b, v4a]);
1748
1749 assert_eq!(
1750 out,
1751 vec![v4a, v4b],
1752 "v6 dropped, duplicate v4 collapsed, first-occurrence order preserved"
1753 );
1754 }
1755
1756 /// An all-IPv6 request filters to empty (we never advertise a route we won't forward) rather
1757 /// than erroring — clearing the advertised set is a legitimate outcome.
1758 #[test]
1759 fn filter_advertise_routes_all_v6_is_empty() {
1760 let v6: ipnet::IpNet = "2001:db8::/32".parse().unwrap();
1761 assert!(filter_advertise_routes(vec![v6]).is_empty());
1762 }
1763
1764 /// `compose_advertised_routes` folds the exit-node `0.0.0.0/0` onto the filtered subnet routes
1765 /// when (and only when) the exit-node flag is set — so `set_advertise_routes` and
1766 /// `set_advertise_exit_node` compose. The two preferences are independent.
1767 #[test]
1768 fn compose_advertised_routes_folds_exit_node() {
1769 let subnet: ipnet::IpNet = "10.0.0.0/24".parse().unwrap();
1770 let default_v4: ipnet::IpNet = "0.0.0.0/0".parse().unwrap();
1771
1772 // Exit node off: just the (filtered) subnet routes.
1773 assert_eq!(
1774 compose_advertised_routes(vec![subnet], false),
1775 vec![subnet],
1776 "exit-node off ⇒ no default route"
1777 );
1778 // Exit node on: subnet routes PLUS 0.0.0.0/0.
1779 assert_eq!(
1780 compose_advertised_routes(vec![subnet], true),
1781 vec![subnet, default_v4],
1782 "exit-node on ⇒ 0.0.0.0/0 appended"
1783 );
1784 // Exit node on with NO subnet routes: just the default route.
1785 assert_eq!(
1786 compose_advertised_routes(vec![], true),
1787 vec![default_v4],
1788 "exit-node alone advertises only 0.0.0.0/0"
1789 );
1790 // Idempotent: an explicit 0.0.0.0/0 already in the routes isn't duplicated by the fold.
1791 assert_eq!(
1792 compose_advertised_routes(vec![default_v4], true),
1793 vec![default_v4],
1794 "the exit-node fold dedups against an explicit default route"
1795 );
1796 }
1797
1798 /// A `HandlerError` carries the real `IdTokenError` from the RPC handler and must pass through
1799 /// verbatim, not be flattened to a generic network error. Using an `Internal(_)` payload (not
1800 /// `NetworkError`) makes the passthrough observable: a buggy flatten that always returned
1801 /// `NetworkError` would fail this assertion.
1802 #[test]
1803 fn flatten_send_err_handler_error_passes_through() {
1804 // Build an `Internal(_)` payload via the public `From<Utf8Error>` conversion (no extra
1805 // deps): it is distinct from the `_ => NetworkError` fallback, so a buggy flatten that
1806 // always returned `NetworkError` would fail this assertion.
1807 // Route the invalid bytes through a runtime Vec so the `invalid_from_utf8` lint (which only
1808 // fires on compile-time-known literals) doesn't flag this intentional bad input.
1809 let bytes = vec![0xffu8, 0xfe];
1810 let utf8_err = core::str::from_utf8(&bytes).unwrap_err();
1811 let inner = ts_control::IdTokenError::from(utf8_err);
1812 assert!(matches!(inner, ts_control::IdTokenError::Internal(_)));
1813 let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1814 kameo::error::SendError::HandlerError(inner.clone());
1815 assert_eq!(flatten_send_err(e), inner);
1816 }
1817
1818 /// A non-handler send failure (actor stopped) is a delivery problem, not an RPC result, so it
1819 /// must collapse to a transient `NetworkError`.
1820 #[test]
1821 fn flatten_send_err_actor_stopped_is_network_error() {
1822 let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1823 kameo::error::SendError::ActorStopped;
1824 assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1825 }
1826
1827 /// `ActorNotRunning` (the message bounces back undelivered) is likewise a delivery failure and
1828 /// must map to a transient `NetworkError`.
1829 #[test]
1830 fn flatten_send_err_actor_not_running_is_network_error() {
1831 let e: kameo::error::SendError<control_runner::FetchIdToken, ts_control::IdTokenError> =
1832 kameo::error::SendError::ActorNotRunning(control_runner::FetchIdToken {
1833 audience: "sts.amazonaws.com".to_string(),
1834 });
1835 assert_eq!(flatten_send_err(e), ts_control::IdTokenError::NetworkError);
1836 }
1837
1838 /// A `HandlerError` from the logout RPC carries the real `LogoutError` and must pass through
1839 /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1840 /// passthrough observable.
1841 #[test]
1842 fn flatten_logout_send_err_handler_error_passes_through() {
1843 let inner = ts_control::LogoutError::Internal(ts_control::LogoutInternalErrorKind::Http);
1844 assert!(matches!(inner, ts_control::LogoutError::Internal(_)));
1845 let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1846 kameo::error::SendError::HandlerError(inner.clone());
1847 assert_eq!(flatten_logout_send_err(e), inner);
1848 }
1849
1850 /// A non-handler send failure (actor stopped) is a delivery problem, not a logout result, and
1851 /// collapses to a transient `NetworkError` (logout is idempotent, so a retry is safe).
1852 #[test]
1853 fn flatten_logout_send_err_actor_stopped_is_network_error() {
1854 let e: kameo::error::SendError<control_runner::Logout, ts_control::LogoutError> =
1855 kameo::error::SendError::ActorStopped;
1856 assert_eq!(
1857 flatten_logout_send_err(e),
1858 ts_control::LogoutError::NetworkError
1859 );
1860 }
1861
1862 /// A `HandlerError` from the set-dns RPC carries the real `SetDnsError` and must pass through
1863 /// verbatim. An `Internal(_)` payload (distinct from the `_ => NetworkError` fallback) makes the
1864 /// passthrough observable.
1865 #[test]
1866 fn flatten_set_dns_send_err_handler_error_passes_through() {
1867 let inner = ts_control::SetDnsError::Internal(ts_control::SetDnsInternalErrorKind::Http);
1868 assert!(matches!(inner, ts_control::SetDnsError::Internal(_)));
1869 let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
1870 kameo::error::SendError::HandlerError(inner.clone());
1871 assert_eq!(flatten_set_dns_send_err(e), inner);
1872 }
1873
1874 /// A non-handler send failure (actor stopped) is a delivery problem, not a publish result, and
1875 /// collapses to a transient `NetworkError`.
1876 #[test]
1877 fn flatten_set_dns_send_err_actor_stopped_is_network_error() {
1878 let e: kameo::error::SendError<control_runner::SetDns, ts_control::SetDnsError> =
1879 kameo::error::SendError::ActorStopped;
1880 assert_eq!(
1881 flatten_set_dns_send_err(e),
1882 ts_control::SetDnsError::NetworkError
1883 );
1884 }
1885
1886 /// A `HandlerError` from a TKA mutation RPC carries the real `TkaSyncError` and must pass through
1887 /// verbatim (an `Unsupported` payload makes the passthrough observable, distinct from the
1888 /// `_ => NetworkError` fallback).
1889 #[test]
1890 fn flatten_tka_send_err_handler_error_passes_through() {
1891 let e: kameo::error::SendError<control_runner::TkaSign, ts_control::TkaSyncError> =
1892 kameo::error::SendError::HandlerError(ts_control::TkaSyncError::Unsupported);
1893 assert_eq!(
1894 flatten_tka_send_err(e),
1895 ts_control::TkaSyncError::Unsupported
1896 );
1897 }
1898
1899 /// A non-handler send failure (actor stopped) collapses to a transient `NetworkError`.
1900 #[test]
1901 fn flatten_tka_send_err_actor_stopped_is_network_error() {
1902 let e: kameo::error::SendError<control_runner::TkaSign, ts_control::TkaSyncError> =
1903 kameo::error::SendError::ActorStopped;
1904 assert_eq!(
1905 flatten_tka_send_err(e),
1906 ts_control::TkaSyncError::NetworkError
1907 );
1908 }
1909
1910 /// The same flatten works for the `TkaDisable` message type (the helper is generic over `M`).
1911 #[test]
1912 fn flatten_tka_send_err_works_for_disable() {
1913 let e: kameo::error::SendError<control_runner::TkaDisable, ts_control::TkaSyncError> =
1914 kameo::error::SendError::HandlerError(ts_control::TkaSyncError::Unsupported);
1915 assert_eq!(
1916 flatten_tka_send_err(e),
1917 ts_control::TkaSyncError::Unsupported
1918 );
1919 }
1920}