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