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