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