Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
2059 lines (1907 loc) · 104 KB
/
Copy pathlib.rs
File metadata and controls
2059 lines (1907 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![doc = include_str!("../README.md")]
extern crate ts_netstack_smoltcp as netstack;
use core::time::Duration;
use std::sync::Arc;
use kameo::{
actor::{ActorRef, Spawn, WeakActorRef},
mailbox::Signal,
};
use netstack::netcore::Channel;
use tokio::sync::watch;
use crate::{
control_runner::ControlRunner, dataplane::DataplaneActor, direct::DirectManager,
forwarder_actor::ForwarderActor, multiderp::Multiderp, netstack_actor::NetstackActor,
};
/// Pcap stream framer for debug packet capture (`CapturePcap`).
pub mod capture;
/// Control runner.
pub mod control_runner;
mod dataplane;
mod derp_latency;
/// Device connection-state tracking ([`DeviceState`]) and typed registration outcome
/// ([`RegistrationError`]).
pub mod device_state;
mod direct;
/// DNS over TCP for the MagicDNS service IP: the transport a stub resolver retries on when a UDP
/// answer comes back truncated. Only the TUN application data path serves it today, so it is
/// compiled with `tun`.
#[cfg(feature = "tun")]
mod dns_over_tcp;
mod env;
mod error;
/// Exit-node suggestion algorithm (the classic DERP-region-latency path, Go
/// `suggestExitNodeUsingDERP`) and its result/error types.
pub mod exit_node_suggest;
/// Fallback TCP handler registry (`tsnet.Server.RegisterFallbackTCPHandler` parity).
pub mod fallback_tcp;
mod forwarder_actor;
/// Client-side Funnel ingress termination (`tsnet`'s `ListenFunnel` data path).
pub mod funnel;
/// Unified IPN notification bus ([`Notify`] / [`watch_ipn_bus`](Runtime::watch_ipn_bus)), mirroring
/// Go `ipn` `LocalBackend.WatchNotifications` / the `WatchIPNBus` LocalAPI.
pub mod ipn_bus;
mod magic_dns;
pub use magic_dns::DnsQueryResult;
mod multiderp;
/// OS network-link-change supervisor (opt-in `network-monitor` feature): re-binds + re-probes
/// connectivity on a link change. Compiled out entirely when the feature is off.
#[cfg(feature = "network-monitor")]
mod netmon;
mod netstack_actor;
mod packetfilter;
pub mod peer_tracker;
mod peerapi;
mod peerapi_doh;
#[cfg(feature = "portmapper")]
mod portmap;
mod route_updater;
mod security;
/// Stored Serve config + accept-loop runtime (`tsnet`'s `Get/SetServeConfig` + serving runtime).
pub mod serve;
mod src_filter;
/// Netmap status snapshot, WhoIs, and watcher types.
pub mod status;
/// Taildrop peer-to-peer file transfer store.
pub mod taildrop;
pub mod taildrop_send;
/// Tailnet-Lock (TKA) chain-sync orchestration: bootstrap + offer/send driver (the runtime layer
/// that bridges the `ts_control` sync RPCs and the `ts_tka` chain logic).
mod tka_sync;
#[cfg(feature = "tun")]
mod tun_actor;
pub use device_state::{DeviceState, RegistrationError};
pub(crate) use env::Env;
pub use error::{Error, ErrorKind};
pub use exit_node_suggest::{ExitNodeSuggestion, SuggestExitNodeError};
pub use ipn_bus::{IpnBusWatcher, Notify, NotifyWatchOpt};
pub use status::{FileTarget, NetcheckReport, RegionLatency, Status, StatusNode, WhoIs};
pub use tka_sync::TkaLogEntry;
pub use ts_control::{PortMapFacets, StunFacts};
pub use ts_dataplane::{CaptureHook, CapturePath};
use crate::peer_tracker::PeerTracker;
/// The runtime for a tailscale device.
pub struct Runtime {
/// Reference to the control actor.
pub control: ActorRef<ControlRunner>,
dataplane: ActorRef<DataplaneActor>,
/// Reference to the direct (disco/UDP underlay) manager, retained so [`Runtime::rebind`] can
/// ask it to re-bind the underlay socket on a network/link change.
direct: ActorRef<DirectManager>,
/// Reference to the application netstack actor. `None` in TUN transport mode, where there is
/// no userspace application netstack (the application data path is a real kernel TUN device).
netstack: Option<WeakActorRef<NetstackActor>>,
/// Reference to the peer tracker for peer lookups.
pub peer_tracker: WeakActorRef<PeerTracker>,
/// Fallback TCP handler registry, bound to the application netstack. `None` in TUN transport
/// mode (no application netstack exists to attach it to).
fallback_tcp: Option<fallback_tcp::FallbackTcpManager>,
/// Reference to the MagicDNS responder, retained so [`Runtime::query_dns`] can run a query
/// through the live `100.100.100.100` forward path. `None` in TUN transport mode (no
/// `MagicDnsActor` is spawned there — TUN-mode MagicDNS is an in-packet intercept, not an actor).
magic_dns: Option<ActorRef<magic_dns::MagicDnsActor>>,
/// Reference to the forwarder actor, retained so [`Runtime::set_advertise_routes`] can push a
/// new accept/dial route table onto the running forwarder (the local half of advertising
/// routes). Without this the strong ref would drop after the startup `GetChannel` and the
/// forwarder would be reachable only via the message bus.
forwarder: ActorRef<ForwarderActor>,
/// Reference to the multiderp manager, retained so [`Runtime::status`] can resolve each
/// relayed peer's DERP region id to its region **code** (`ipnstate.PeerStatus.Relay`). Without
/// this the strong ref would drop after startup (it is cloned into the direct manager + route
/// updater) and the region-code map would be unreachable.
multiderp: ActorRef<Multiderp>,
env: Env,
shutdown: watch::Sender<bool>,
_security: security::SecurityGuard,
/// Sender side of the exit-node selector `watch` cell. Held privately here (not on the cloned
/// `Env`, which keeps only the read side) so that only `Runtime::set_exit_node` can mutate the
/// selection; the route updater and source filter re-read it via [`Env::exit_node`].
exit_node_tx: watch::Sender<Option<ts_control::ExitNodeSelector>>,
/// Sender side of the accept-routes preference `watch` cell. Held privately here (same rationale
/// as [`exit_node_tx`](Self::exit_node_tx)) so that only [`Runtime::set_accept_routes`] can
/// toggle it; the route updater and source filter re-read it via [`Env::accept_routes`].
accept_routes_tx: watch::Sender<bool>,
/// Sender side of the accept-dns preference `watch` cell. Held privately here (same rationale as
/// [`accept_routes_tx`](Self::accept_routes_tx)) so that only [`Runtime::set_accept_dns`] can
/// toggle it; the MagicDNS responder re-reads it via [`Env::accept_dns`] when it rebuilds its
/// view (the republish that `set_accept_dns` triggers).
accept_dns_tx: watch::Sender<bool>,
/// Receiver mirroring the *active* (resolved + fail-closed) exit node's stable id, fed by the
/// route updater. Read by [`Runtime::status`] / [`Runtime::active_exit_node`] to report which
/// exit node traffic is actually egressing through (vs. the merely-configured selector).
active_exit_rx: watch::Receiver<Option<ts_control::StableNodeId>>,
/// Receiver for the device connection-state cell, fed by the control runner. Read by
/// [`Runtime::watch_state`] and [`Runtime::wait_until_running`].
state_rx: watch::Receiver<DeviceState>,
/// Receiver for the retained peer-capability grants, fed by the packet-filter updater. Read by
/// [`Runtime::whois`] to resolve the flow-scoped cap map (Go `apitype.WhoIsResponse.CapMap`).
cap_grants_rx: watch::Receiver<packetfilter::CapGrants>,
/// Receiver for the invalid-packet-filter health flag, fed by the packet-filter updater. Read by
/// [`Runtime::status`] to fill [`Status::health`].
invalid_filter_rx: packetfilter::InvalidPacketFilterRx,
/// Live advertised-route preference (explicit subnet routes + the exit-node flag), seeded from
/// the startup config. [`Runtime::set_advertise_routes`] and [`set_advertise_exit_node`] each
/// mutate their part under this lock then re-send the composed set, so the two compose.
advertise: std::sync::Mutex<AdvertiseState>,
/// The most recent exit-node suggestion's stable id (Go `LocalBackend.lastSuggestedExitNode`),
/// remembered across calls so [`Runtime::suggest_exit_node`] can apply *stickiness* — if the
/// previously-suggested node is still an eligible candidate in the winning region it is kept, to
/// avoid the suggestion flapping between equally-good ties on each call. `None` until the first
/// suggestion. Held behind a `Mutex` (same rationale as [`advertise`](Self::advertise): a
/// cheap, infrequently-touched bit of mutable runtime state, not worth an actor round-trip).
prev_suggestion: std::sync::Mutex<Option<ts_control::StableNodeId>>,
/// Background task that periodically reaps abandoned taildrop `.partial` files (Go
/// `feature/taildrop/delete.go` `fileDeleter`). `None` when no taildrop store is configured.
/// Aborted on [`Drop`] so it cannot outlive the runtime (the `reauth_bridge` pattern).
taildrop_reaper: Option<tokio::task::JoinHandle<()>>,
/// The opt-in OS network-link-change supervisor (`network-monitor` feature + the
/// `Config::network_monitor` flag). Retained so the actor — and thus the
/// `LinkMonitorHandle` it holds, which aborts the monitor's watcher task on drop — lives for the
/// device's life and is torn down when the runtime drops. `None` when the flag is off. Only
/// present when built with the `network-monitor` feature.
#[cfg(feature = "network-monitor")]
#[allow(dead_code)]
netmon_supervisor: Option<ActorRef<netmon::NetmonSupervisor>>,
/// The NAT port mapper's client, when it runs, behind its release guard:
/// [`graceful_shutdown`](Self::graceful_shutdown) closes it (bounded, deletes acknowledged),
/// and dropping the guard, which every drop of the runtime does, sends one unacknowledged
/// delete per rule with no runtime needed (a no-op after the close).
#[cfg(feature = "portmapper")]
portmap: portmap::PortmapRelease,
}
/// The port mapper's state, for status lines (Go's netcheck `portmap=` plus the mapping).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortMapStatus {
/// The NetInfo facets as sent to control.
pub facets: ts_control::PortMapFacets,
/// The current mapping's external address, if one is held (advertised or not).
pub external: Option<core::net::SocketAddrV4>,
/// The protocol holding it (`"pmp"` or `"pcp"`).
pub proto: Option<&'static str>,
/// Whether the mapping is offered to peers.
pub advertised: bool,
}
impl PortMapStatus {
/// Go's `portmap=` summary, e.g. `active-_MC`.
pub fn summary(&self) -> String {
self.facets.summary()
}
}
/// How long [`Runtime::graceful_shutdown`] gives the port mapper to release its router rules, at
/// most (always within the caller's timeout).
#[cfg(feature = "portmapper")]
const PORTMAP_RELEASE_BUDGET: Duration = Duration::from_secs(1);
/// The port mapper's share of a shutdown with `timeout`: at most [`PORTMAP_RELEASE_BUDGET`], never
/// more than `timeout`.
#[cfg(feature = "portmapper")]
fn portmap_budget(timeout: Option<Duration>) -> Duration {
timeout.map_or(PORTMAP_RELEASE_BUDGET, |t| t.min(PORTMAP_RELEASE_BUDGET))
}
/// The first step of [`Runtime::graceful_shutdown`]: close the port mapper within its budget.
#[cfg(feature = "portmapper")]
async fn close_portmap(pm: Option<&Arc<dyn ts_portmapper::PortMapper>>, timeout: Option<Duration>) {
if let Some(pm) = pm {
pm.close(portmap_budget(timeout)).await;
}
}
impl Runtime {
/// Spawn a new runtime with the given parameters for connecting to a tailnet.
pub async fn spawn(
config: ts_control::Config,
auth_key: Option<String>,
keys: ts_keys::NodeState,
) -> Result<Self, Error> {
let (shutdown_tx, shutdown_rx) = watch::channel(false);
// The exit-node selector, accept-routes, and accept-dns preferences are live `watch` cells so
// `Device::set_exit_node` / `set_accept_routes` / `set_accept_dns` can change them at runtime.
// `new_with_runtime_txs` returns each `Sender` (mutation capability) grouped in `pref_cells`
// so they are retained privately on the `Runtime`, while only the `Receiver`s (the readers'
// contract) live on the cloned `Env`. Initial values come from `ForwarderConfig`.
// Environment knobs are read once, here (Go caches its `envknob`s too).
let mut forwarding = env::ForwarderConfig::from_control_config(&config);
forwarding.apply_env_knobs(|k| std::env::var(k).ok());
let (env, pref_cells) = Env::new_with_runtime_txs(keys, shutdown_rx, forwarding);
let mut security = security::SecurityGuard::new(shutdown_tx.clone());
security.watch(&env.bus);
security.ready(&env.bus).await?;
// Both userspace netstacks (application + forwarder) share one netstack config. Honor the
// per-deployment TCP buffer knob, and set the netstack MTU to the overlay/tunnel MTU so the
// advertised MSS fits the tunnel — leaving it at the netstack's generic 1500 default would
// emit over-1280 segments into the WireGuard path. The MTU comes from a `Tun` transport's
// `TunConfig` when one is configured (so the netstack and the TUN agree), else the 1280
// overlay default (the `Netstack` userspace mode — the common case — has no per-OS MTU knob,
// but the tailnet overlay MTU is still 1280).
let configured_mtu = match &config.transport_mode {
ts_control::TransportMode::Tun(tun_cfg) => tun_cfg.mtu,
ts_control::TransportMode::Netstack => None,
};
let netstack_config = netstack_config_from(config.tcp_buffer_size, configured_mtu);
let dataplane = DataplaneActor::spawn(env.clone());
security.watch(&dataplane);
security.ready(&dataplane).await?;
security.packet_pump(dataplane.ask(dataplane::PacketPumpAbortHandle).await?);
let (netstack_id, netstack_up, netstack_down) =
dataplane.ask(dataplane::NewOverlayTransport).await?;
// A second overlay transport feeds the dedicated any-IP forwarder netstack. Inbound packets
// for advertised subnet routes / the exit-node default route are routed here (see
// `route_updater`), keeping forwarded flows off the application netstack.
let (forwarder_id, forwarder_up, forwarder_down) =
dataplane.ask(dataplane::NewOverlayTransport).await?;
// The selected DERP home region (Go `report.PreferredDERP`): the control runner is the sole
// writer (it applies the netcheck `bestRecent` + hysteresis smoothing), and `Multiderp`
// reads it to drive the local home relay — so the relay follows the SAME smoothed home the
// runner advertises to control, instead of picking it from the raw per-cycle latency minimum
// (which flapped on jitter and could disagree with the advertised home). Created here so it
// outlives both actors; `None` until the first home is chosen.
let (home_region_tx, home_region_rx) = watch::channel::<Option<ts_derp::RegionId>>(None);
let multiderp = Multiderp::spawn((env.clone(), dataplane.clone(), home_region_rx));
security.watch(&multiderp);
security.ready(&multiderp).await?;
// Spawn the direct (disco) underlay manager before the route updater. Its `on_start`
// binds the UDP socket and registers its transport synchronously, so by the time the
// route updater asks it for the direct transport id it is guaranteed to be available.
let direct = DirectManager::spawn((env.clone(), dataplane.clone(), multiderp.clone()));
security.watch(&direct);
security.ready(&direct).await?;
#[cfg(feature = "portmapper")]
let portmap = portmap::PortmapRelease::new(direct.ask(direct::PortmapClient).await?);
// Spawn the forwarder before the route updater. Its `on_start` builds the forwarder
// netstack, enables any-IP acceptance, and starts the per-port accept loops synchronously,
// so by the time the route updater begins delivering advertised prefixes to
// `forwarder_id` the netstack is already draining its transport.
let forwarder = ForwarderActor::spawn((
env.clone(),
netstack_config.clone(),
forwarder_up,
forwarder_down,
));
security.watch(&forwarder);
security.ready(&forwarder).await?;
// Force `on_start` to finish (any-IP enabled, accept loops live) before the route updater
// can route the first inbound flow to `forwarder_id`: an `ask` blocks until the actor has
// started.
//
// The forwarder netstack's overlay `Channel` is reused by the TUN application path for
// recursive / exit-node-DoH MagicDNS forwarding (TUN mode has no application netstack of its
// own, but the forwarder netstack runs in both modes and egresses over the overlay — the
// anti-leak property `forward_query`/`forward_doh` require). Only the `tun` Tun arm consumes
// it, so it is unused when the `tun` feature is off — allow that without warn-as-error.
#[cfg_attr(not(feature = "tun"), allow(unused_variables))]
let (forwarder_channel,) = forwarder.ask(forwarder_actor::GetChannel).await?;
// The route updater is the single authoritative resolver of the active (resolved,
// fail-closed) exit node; it publishes the resolved stable id into this watch cell so
// `Runtime::status` can report which exit is actually engaged (not just configured).
let (active_exit_tx, active_exit_rx) = watch::channel(None);
let route_updater = route_updater::RouteUpdater::spawn((
multiderp.clone(),
direct.clone(),
env.clone(),
netstack_id,
forwarder_id,
active_exit_tx,
));
security.watch(&route_updater);
security.ready(&route_updater).await?;
// The packet-filter updater also surfaces the retained cap-grants (for flow-scoped WhoIs)
// through a `watch` cell whose receiver the `Runtime` holds — the bus has no replay, so a
// `watch` is how `Runtime::whois` reads the current grants on demand.
let (cap_grants_tx, cap_grants_rx) = watch::channel(Default::default());
// The live compiled filter for the peerAPI DoH source gate. Created here — before either
// actor spawns — so the updater (sole writer) and the MagicDNS responder (reader, which
// hands the receiver to its peerAPI server task) share one cell no matter which `on_start`
// runs first. The gate is fail-closed, so a filter that never reaches it means refusing
// peers control's ACL admits. The bus has no replay for late readers (see
// `packetfilter::LiveFilterRx`).
let (live_filter_tx, live_filter_rx) = watch::channel(None);
let (invalid_filter_tx, invalid_filter_rx) = watch::channel(false);
let packetfilter = packetfilter::PacketfilterUpdater::spawn((
env.clone(),
cap_grants_tx,
live_filter_tx,
invalid_filter_tx,
));
security.watch(&packetfilter);
security.ready(&packetfilter).await?;
let source_filter = src_filter::SourceFilterUpdater::spawn(env.clone());
security.watch(&source_filter);
security.ready(&source_filter).await?;
// TKA enforcement-authority cell (Go `tkaFilterNetmapLocked`). Created here — before both
// actors spawn — so the control runner (sole writer, `Sender`) and the peer tracker (reader,
// `Receiver`) share one `watch` cell. A `watch` (not a bus message) is the transport for this
// security-critical state: last-write-wins, never dropped under load, ordered by the control
// runner's writes, so a disable (`None`) can never be reordered behind or dropped before a
// stale `Some`. `None` = no lock synced / disabled (admit all).
let (tka_authority_tx, tka_authority_rx) =
watch::channel::<Option<std::sync::Arc<ts_tka::Authority>>>(None);
let peer_tracker = PeerTracker::spawn((env.clone(), tka_authority_rx));
security.watch(&peer_tracker);
security.ready(&peer_tracker).await?;
// Select the application data path from the transport mode. The forwarder/egress path
// above is UNCHANGED in both modes — TUN mode only swaps the application data path, never
// the forwarder. `config` is moved into `ControlRunner::spawn` below, so branch on a
// borrow and clone the small `TunConfig` where needed before the move.
//
// - Netstack (the default, and the only reachable arm when the `tun` feature is off):
// spawn the application netstack + MagicDNS responder + fallback-TCP registry, all on
// the `netstack_up`/`netstack_down` overlay seam.
// - Tun: spawn `TunActor` on that same overlay seam instead; no application netstack and
// no MagicDNS responder exist, and `netstack`/`fallback_tcp` are `None`.
// - Tun requested but built without the `tun` feature: hard-error (a config/build
// mismatch knowable at spawn time). NEVER silently fall back to netstack.
let (netstack, fallback_tcp, magic_dns) = match &config.transport_mode {
ts_control::TransportMode::Netstack => {
let netstack = NetstackActor::spawn((
env.clone(),
netstack_config,
netstack_up,
netstack_down,
));
security.watch(&netstack);
security.ready(&netstack).await?;
// Fetch the netstack channel while we still hold the strong ActorRef, then spawn
// the MagicDNS responder on it. Its ActorRef is retained on `Runtime` so
// `query_dns` can drive the live forward path; the serve loop itself is owned by the
// actor's internal JoinSet.
let (channel,) = netstack.ask(netstack_actor::GetChannel).await?;
// The fallback-TCP registry attaches to the application netstack — the same one
// that carries the embedder's explicit `Device::tcp_listen` sockets — so a
// fallback handler sees exactly the inbound flows no explicit listener matched.
let fallback_tcp = fallback_tcp::FallbackTcpManager::new(channel.clone());
let magic_dns =
magic_dns::MagicDnsActor::spawn((env.clone(), channel, live_filter_rx));
security.watch(&magic_dns);
security.ready(&magic_dns).await?;
(
Some(netstack.downgrade()),
Some(fallback_tcp),
Some(magic_dns),
)
}
#[cfg(feature = "tun")]
ts_control::TransportMode::Tun(tun_cfg) => {
// Reuse the same `netstack_up`/`netstack_down` overlay-transport pair that would
// have fed the netstack — it is just the application-side overlay seam (the name
// is historical). No NetstackActor / MagicDnsActor is spawned.
let tun = tun_actor::TunActor::spawn((
env.clone(),
tun_cfg.clone(),
netstack_up,
netstack_down,
// Reuse the forwarder netstack's overlay `Channel` for recursive / exit-node-DoH
// MagicDNS forwarding in the TUN datapath (TUN mode has no application netstack
// Channel of its own). Egresses over the overlay — anti-leak preserved.
//
// Host-route gating (subnet routes gated on `--accept-routes`, the host `/0` from
// the selected exit peer) is no longer snapshotted here: `TunActor` reads the live
// `Env` cells (`accept_routes`/`exit_node`) on every host-FIB apply — both the
// device-build path and the `PeerState` re-apply path — and folds the union of
// peers' AllowedIPs (see `tun_actor::host_routes_from_node`). A runtime
// `set_accept_routes` / `set_exit_node` toggle re-broadcasts the peer state, so the
// host routing table is re-steered live (no device rebuild needed).
forwarder_channel.clone(),
));
security.watch(&tun);
security.ready(&tun).await?;
(None, None, None)
}
#[cfg(not(feature = "tun"))]
ts_control::TransportMode::Tun(_) => {
return Err(Error {
kind: ErrorKind::TunUnavailable,
target_actor: None,
message_ty: None,
});
}
};
// Device connection-state cell. Created here (not inside the actor) so the control runner's
// `on_start` can publish `Failed`/`NeedsLogin` and still return `Err` without the sender
// being tied to a `Self` that never gets constructed on a hard registration failure.
let (state_tx, state_rx) = watch::channel(DeviceState::Connecting);
// Seed the live advertised-route preference from the startup config before `config` moves
// into the control runner, so the runtime setters compose against the configured baseline.
let advertise = std::sync::Mutex::new(AdvertiseState {
routes: config.advertise_routes.clone(),
exit_node: config.advertise_exit_node,
});
// This telemetry subscriber also has a bounded mailbox and multiple subscriptions.
// Starting it after control publishes could deadlock its second Register behind
// delivery to its first subscription while on_start cannot drain its mailbox.
let latency = derp_latency::DerpLatencyMeasurer::spawn(env.clone());
security.watch(&latency);
security.ready(&latency).await?;
// Every security subscriber is now registered. Control on_start may replay a cached
// map immediately; spawning it earlier would lose state even with guaranteed delivery.
// Control self-messages (stream pump and TKA sync results), so keep its mailbox
// unbounded too. Publishers never wait for broker handling or subscriber capacity.
// A stalled handler can accumulate inputs; supervision covers death, not stalls.
let control = ControlRunner::spawn_with_mailbox(
control_runner::Params {
config,
auth_key,
env: env.clone(),
state_tx,
tka_authority: tka_authority_tx,
home_region: home_region_tx,
},
kameo::mailbox::unbounded(),
);
security.watch(&control);
// Spawn the taildrop partial-reaper if a store is configured; it sweeps abandoned `.partial`
// files every `DELETE_DELAY` and exits on shutdown (the handle is aborted in `Drop`).
let taildrop_reaper = env.taildrop_store.as_ref().map(|store| {
crate::taildrop::spawn_partial_reaper(store.clone(), shutdown_tx.subscribe())
});
// Opt-in OS network-link monitor (`Config::network_monitor`, default off). When enabled it
// spawns a `NetmonSupervisor` that, on a coalesced link change, asks the direct manager to
// rebind + re-probe and republishes `MeasureNow` for a re-netcheck — the auto-recovery a
// real `tailscaled` performs and the engine otherwise leaves to the embedder. When the flag
// is off this is a complete no-op: zero extra threads/sockets, byte-for-byte today's
// behavior. The manual `Device::rebind` path is unchanged either way.
//
// Feature gating is strict and never silent: with the `network-monitor` feature ON the
// supervisor (and its `ts_netmon` dep) compile in and spawn when the flag is set; with the
// feature OFF, setting the flag is a HARD error at spawn (mirrors the `TransportMode::Tun`
// without-`tun`-feature error above), so a build that cannot honor the request fails loudly
// rather than booting a node that silently won't auto-recover.
#[cfg(feature = "network-monitor")]
let netmon_supervisor = if env.network_monitor {
// Slice (a): no OS event-source backend is wired yet (the Linux netlink / macOS
// PF_ROUTE backends are later slices), so the supervisor runs against a `NoopLinkMonitor`
// — it is live and correctly shaped (it will react the moment a real backend feeds it),
// it just never sees a synthetic/OS event in this build. Production end-to-end reaction
// is proven in the integration test via a `ManualLinkMonitor`.
let monitor: std::sync::Arc<dyn ts_netmon::LinkMonitor> =
std::sync::Arc::new(ts_netmon::NoopLinkMonitor);
Some(netmon::NetmonSupervisor::spawn(
netmon::NetmonSupervisorArgs {
monitor,
direct: direct.clone(),
env: env.clone(),
},
))
} else {
None
};
#[cfg(not(feature = "network-monitor"))]
if env.network_monitor {
// The flag is set but this build cannot honor it. Fail loudly (never a silent no-op).
return Err(Error {
kind: ErrorKind::NetworkMonitorUnavailable,
target_actor: None,
message_ty: None,
});
}
Ok(Self {
control,
dataplane,
direct,
peer_tracker: peer_tracker.downgrade(),
fallback_tcp,
magic_dns,
forwarder,
multiderp,
netstack,
env,
shutdown: shutdown_tx,
_security: security,
exit_node_tx: pref_cells.exit_node,
accept_routes_tx: pref_cells.accept_routes,
accept_dns_tx: pref_cells.accept_dns,
active_exit_rx,
state_rx,
cap_grants_rx,
invalid_filter_rx,
advertise,
prev_suggestion: std::sync::Mutex::new(None),
taildrop_reaper,
#[cfg(feature = "network-monitor")]
netmon_supervisor,
#[cfg(feature = "portmapper")]
portmap,
})
}
/// The port mapper's state, or `None` when it does not run (disabled, or a build without the
/// `portmapper` feature).
pub fn port_map_status(&self) -> Option<PortMapStatus> {
#[cfg(feature = "portmapper")]
{
let pm = self.portmap.get()?;
let state = pm.subscribe().borrow().clone();
Some(PortMapStatus {
facets: portmap::facets(&state),
external: state.mapping.map(|m| m.external),
proto: state.mapping.map(|m| match m.proto {
ts_portmapper::oneshot::Proto::Pmp => "pmp",
ts_portmapper::oneshot::Proto::Pcp => "pcp",
}),
advertised: state.advertised().is_some(),
})
}
#[cfg(not(feature = "portmapper"))]
None
}
/// Register a fallback TCP handler consulted for every inbound TCP flow that matches no
/// explicit listener (`tsnet.Server.RegisterFallbackTCPHandler` parity).
///
/// The returned [`fallback_tcp::FallbackTcpHandle`] deregisters the handler when dropped. See
/// [`fallback_tcp`] for the dispatch contract and anti-leak guarantees.
///
/// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
/// application netstack to attach a fallback handler to.
pub fn register_fallback_tcp_handler(
&self,
cb: Arc<
dyn Fn(core::net::SocketAddr, core::net::SocketAddr) -> fallback_tcp::FallbackDecision
+ Send
+ Sync,
>,
) -> Result<fallback_tcp::FallbackTcpHandle, Error> {
Ok(self
.fallback_tcp
.as_ref()
.ok_or(Error {
kind: ErrorKind::UnsupportedInTunMode,
target_actor: None,
message_ty: None,
})?
.register(cb))
}
/// Get a channel to send commands to the netstack.
///
/// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where there is no
/// application netstack.
pub async fn channel(&self) -> Result<Channel, Error> {
let (channel,) = self
.netstack
.as_ref()
.ok_or(Error {
kind: ErrorKind::UnsupportedInTunMode,
target_actor: None,
message_ty: None,
})?
.upgrade()
.ok_or(Error {
kind: ErrorKind::ActorGone,
target_actor: None,
message_ty: None,
})?
.ask(netstack_actor::GetChannel)
.await?;
Ok(channel)
}
/// Resolve `name` for `qtype` through the live MagicDNS responder (the `100.100.100.100`
/// forward path), returning the raw DNS response, its RCODE, and the upstream resolver(s)
/// consulted (analogue of Go `LocalClient.QueryDNS`).
///
/// This drives the *real* responder — the same `decide`/forward logic an on-the-wire query
/// hits — so the answer and its anti-leak posture (a tailnet-suffix name never egresses; a
/// recursive forward delegates to the active exit node's DoH; only IPv4 upstreams are dialed)
/// match exactly what a tailnet client observes. `qtype` is the raw RFC 1035 TYPE (`1`=A,
/// `28`=AAAA, `12`=PTR, or any other).
///
/// Returns [`ErrorKind::UnsupportedInTunMode`] in TUN transport mode, where MagicDNS is an
/// in-packet intercept on the host's own resolver rather than an actor that can be queried, and
/// [`ErrorKind::ActorGone`] if the responder has shut down.
pub async fn query_dns(
&self,
name: &str,
qtype: u16,
) -> Result<magic_dns::DnsQueryResult, Error> {
let result = self
.magic_dns
.as_ref()
.ok_or(Error {
kind: ErrorKind::UnsupportedInTunMode,
target_actor: None,
message_ty: None,
})?
.ask(magic_dns::Query {
name: name.to_owned(),
qtype,
})
.await?;
Ok(result)
}
/// The Taildrop file store, if Taildrop is enabled (`taildrop_dir` configured and the store
/// initialized). `None` when disabled — fail-closed. Shared with the peerAPI Taildrop server so
/// the embedder's read APIs and the receive path see the same on-disk store.
pub fn taildrop_store(&self) -> Option<Arc<crate::taildrop::TaildropStore>> {
self.env.taildrop_store.clone()
}
/// The shared Funnel ingress slot the peerAPI `/v0/ingress` route reads per connection.
///
/// `Device::listen_funnel` installs a [`FunnelManager`](crate::funnel::FunnelManager)'s sink here
/// to make the route live (the peerAPI server is already running from startup). Returns a clone of
/// the runtime-lifetime `Arc` so the device can write the slot without restarting the server. See
/// [`crate::funnel`] for the ingress data path.
pub fn funnel_ingress_slot(&self) -> crate::funnel::FunnelIngressSlot {
self.env.funnel_ingress.clone()
}
/// The shared "Funnel ingress listener active" flag (the same `Arc` the control session reads to
/// set `HostInfo.IngressEnabled`). `Device::listen_funnel` flips it `true` while a funnel listener
/// is up so control routes Funnel traffic to this node; clearing it advertises no live endpoint.
pub fn ingress_active_flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
self.env.ingress_active.clone()
}
/// Install (`Some`) or clear (`None`) the debug packet-capture hook on the running dataplane.
/// `Some(hook)` tees every plaintext packet crossing the datapath to `hook` until it is cleared;
/// `None` stops capture. Mirrors Go `tstun.Wrapper.InstallCaptureHook` / `ClearCaptureSink`.
pub async fn install_capture(
&self,
hook: Option<ts_dataplane::CaptureHook>,
) -> Result<(), Error> {
self.dataplane
.ask(dataplane::InstallCapture { hook })
.await
.map_err(Into::into)
}
/// Re-bind the underlay UDP socket after a network/link change (Wi-Fi switch, sleep/wake). The
/// embedder's own link monitor calls this (the engine owns the socket re-bind; the embedder owns
/// OS netmon). Re-binds the socket (same-port-preferred, IPv4-only invariant preserved) and
/// resets the now-stale local NAT mapping — clearing learned reflexive addresses and every
/// confirmed direct path while keeping candidate endpoints, so peers re-probe over the new socket
/// and relay over DERP (never a direct host dial) until a path re-confirms. Peers, control, the
/// netmap, disco state, and DERP are untouched. A no-op when the underlay is inert (bind failed
/// at startup, DERP-only). Mirrors Go magicsock `Conn.Rebind` + `resetEndpointStates`.
pub async fn rebind(&self) -> Result<(), Error> {
self.direct.ask(direct::Rebind).await.map_err(Error::from)
}
/// Force an immediate STUN / endpoint re-probe **without** rebinding the underlay socket —
/// Go magicsock's `Conn.ReSTUN`. Asks the `DirectManager` to run one STUN sweep now (re-learn
/// our reflexive/public address) while leaving the socket, its NAT mapping, learned paths, peers,
/// control, and DERP untouched. Lighter than [`rebind`](Self::rebind): no socket swap, no
/// re-ping. A no-op when the underlay is inert (bind failed at startup, DERP-only). No control
/// round-trip.
pub async fn re_stun(&self) -> Result<(), Error> {
self.direct.ask(direct::ReStun).await.map_err(Error::from)
}
/// A snapshot of the local netmap: this node plus every known peer.
///
/// Combines the self node held by the control runner with the peer set held by the peer
/// tracker. Mirrors tsnet's `LocalClient::Status`.
///
/// `self_node` is `None` until the first netmap update has been received from control. Peer
/// entries carry no online/user/capability data (see the [`status`] module docs for that gap).
pub async fn status(&self) -> Result<Status, Error> {
let self_node_domain = self.control.ask(control_runner::SelfNode).await?;
// The MagicDNS suffix is the self node's FQDN minus its host label — already split into
// `Node.tailnet` at decode time (Go derives it the same way in `NetworkMap.MagicDNSSuffix`).
// Capture it before the domain `Node` is mapped away into a `StatusNode`.
let magic_dns_suffix = self_node_domain.as_ref().and_then(|n| n.tailnet.clone());
let self_node = self_node_domain.as_ref().map(StatusNode::from_node);
let peers_with_ids = self
.peer_tracker
.upgrade()
.ok_or(Error {
kind: ErrorKind::ActorGone,
target_actor: None,
message_ty: None,
})?
.ask(peer_tracker::GetStatus)
.await?;
// Join per-peer connectivity (Go `PeerStatus.CurAddr`): one batched query to the direct
// manager for every peer's current trusted direct endpoint, then fill `cur_addr` on each
// `StatusNode`. A peer absent from the map is relayed via DERP (`cur_addr = None`). This is a
// live snapshot — the direct path can expire/re-confirm between calls (matches Go's snapshot
// semantics). The `watch_netmap` stream intentionally carries no connectivity (it is a netmap
// watch, not a path-state watch, and does not re-fire on direct↔relay flips).
let ids: Vec<ts_transport::PeerId> = peers_with_ids.iter().map(|(id, _)| *id).collect();
let best_addrs = self
.direct
.ask(direct::BestAddrs { ids: ids.clone() })
.await
.unwrap_or_default();
// For the peers with NO direct path (relayed via DERP), resolve the region CODE they relay
// through (Go `PeerStatus.Relay`). One batched ask to multiderp; `cur_addr` and `relay` are
// mutually exclusive for a routed peer, mirroring Go's empty-vs-set strings.
let relay_ids: Vec<ts_transport::PeerId> = ids
.into_iter()
.filter(|id| !best_addrs.contains_key(id))
.collect();
let relay_codes = if relay_ids.is_empty() {
Default::default()
} else {
self.multiderp
.ask(multiderp::RelayCodesForPeers { ids: relay_ids })
.await
.unwrap_or_default()
};
let peers = peers_with_ids
.into_iter()
.map(|(id, mut node)| match best_addrs.get(&id).copied() {
Some(addr) => {
node.cur_addr = Some(addr);
node
}
None => {
node.relay = relay_codes.get(&id).cloned();
node
}
})
.collect();
let control_connected = self.control.ask(control_runner::ControlConnected).await?;
Ok(Status {
self_node,
peers,
active_exit_node: self.active_exit_node(),
magic_dns_suffix,
health: status::health_warnings(*self.invalid_filter_rx.borrow(), control_connected),
})
}
/// Suggest a reasonably good exit node to use, from the current netmap + recent DERP latency
/// (Go `LocalBackend.SuggestExitNode`). The Phase-1 classic DERP-region-latency path; see the
/// [`exit_node_suggest`] module for the algorithm, scope, and the IPv4-only parity deviation.
///
/// Gathers the inputs the way [`status`](Self::status) and [`file_targets`](Self::file_targets)
/// do — from the control runner, the latest [`NetcheckReport`]'s preferred DERP region plus the
/// recent per-region latencies (both immediate, non-blocking borrows), and every peer
/// [`Node`](ts_control::Node) from the peer tracker — then runs the pure algorithm with the
/// production uniform-random selectors (`random_region` / `random_node`). The returned
/// suggestion's id is remembered in the runtime's `prev_suggestion` cell so the next call is
/// *sticky* (Go `lastSuggestedExitNode`).
///
/// Returns `Ok(None)` when no peer is an eligible candidate (Go's empty response), and
/// `Err(`[`SuggestExitNodeError::NoPreferredDerp`]`)` when there is no netcheck report yet (Go's
/// `ErrNoPreferredDERP`, "try again later").
pub async fn suggest_exit_node(
&self,
) -> Result<Result<Option<ExitNodeSuggestion>, SuggestExitNodeError>, Error> {
use ts_control::NODE_ATTR_SUGGEST_EXIT_NODE;
// The two netcheck inputs Go's `suggestExitNode` takes. First the preferred DERP region from
// the latest report (Go `MagicConn().GetLastNetcheckReport().PreferredDERP`): an immediate
// borrow of the control runner's published measurement (the value `Device::netcheck`
// surfaces), used only as the "have we netchecked at all yet" precondition.
let report = self.control.ask(control_runner::Netcheck).await?;
// Then the *ranking* input: the lowest latency seen per region over the retained measurement
// history (Go `netcheck.Client.RecentRegionLatency()`). Deliberately NOT the latest report's
// own latency list — every measurement this fork makes is partial (`complete_threshold`), so
// ranking on one report leaves a distant candidate's region unmeasured and collapses the
// suggestion to a uniform random pick. See `exit_node_suggest`'s module docs.
let region_latency = self
.control
.ask(control_runner::RecentRegionLatency)
.await?;
// Every known peer (Go reads the netmap peers via `AppendMatchingPeers`); the domain `Node`
// retains the cap map, home DERP region, online state, and accepted routes the predicate
// needs.
let peers = self
.peer_tracker
.upgrade()
.ok_or(Error {
kind: ErrorKind::ActorGone,
target_actor: None,
message_ty: None,
})?
.ask(peer_tracker::AllPeers)
.await?;
// Project each peer into the algorithm's candidate inputs. The eligibility predicate runs
// inside the pure function, so every peer is passed (self is naturally absent from the peer
// set). `derp_region`/`online`/`cap_map`/`accepted_routes` map straight off the domain node;
// the exit-route check is the fork's family-agnostic `prefix_len == 0` (IPv4-only parity —
// see `exit_node_suggest::suggest_exit_node`).
let candidates: Vec<exit_node_suggest::ExitNodeCandidate> = peers
.iter()
.map(|peer| exit_node_suggest::ExitNodeCandidate {
stable_id: peer.stable_id.clone(),
name: peer
.fqdn_opt(false)
.unwrap_or_else(|| peer.hostname.clone()),
derp_region: peer.derp_region,
online: peer.online,
advertises_exit_route: peer
.accepted_routes
.iter()
.any(|route| route.prefix_len() == 0),
has_suggest_cap: peer.has_node_attr(NODE_ATTR_SUGGEST_EXIT_NODE),
})
.collect();
// Read the sticky previous suggestion, run the pure algorithm with the production
// uniform-random selectors, then update the sticky value to the new result. This mirrors Go
// `suggestExitNodeLocked` (`ipn/ipnlocal/local.go`), which assigns `b.lastSuggestedExitNode =
// res.ID` on **every** no-error return — INCLUDING the empty/no-candidate result, where it
// clears the sticky id to "". So a successful suggestion sets stickiness, an empty result
// CLEARS it (a peer that dropped out of candidacy stops being preferred), and only an `Err`
// (`NoPreferredDerp` — no netcheck yet) returns before the assignment and leaves it untouched.
let prev = self.prev_suggestion.lock().unwrap().clone();
let outcome = exit_node_suggest::suggest_exit_node(
report.preferred_derp,
®ion_latency,
&candidates,
prev.as_ref(),
&exit_node_suggest::random_region,
&exit_node_suggest::random_node,
);
*self.prev_suggestion.lock().unwrap() = exit_node_suggest::next_sticky(prev, &outcome);
Ok(outcome)
}
/// List the tailnet peers this node can Taildrop a file *to* (Go LocalAPI `FileTargets`).
///
/// Mirrors the upstream send-path filter (`feature/taildrop` `Extension::FileTargets`): a peer
/// qualifies when it advertises a reachable peerAPI **and** is either owned by the same user as
/// this node **or** explicitly granted the file-sharing-target capability. The whole list is
/// gated on this node holding the file-sharing capability (control sets it when the admin enables
/// Taildrop) — absent that, an empty list (fail-closed, not an error, matching how the receive
/// store returns empty when disabled). Results are sorted by the peer's MagicDNS name.
///
/// Targets are listed regardless of current online state (upstream's `FileTargets` does not gate
/// on online either; an offline target's send will simply time out). The self node is never
/// included. Returns empty before the first netmap.
///
/// Divergence from Go: the upstream filter also excludes `tvOS` peers, which this fork cannot
/// reproduce (the domain node carries no OS string); the impact is negligible — the actual send
/// fail-closes if such a peer refused the transfer.
pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
// Node-level gate: this node must hold the file-sharing capability (Taildrop enabled by the
// admin). Read it off the self node's cap map, like Go's `hasCapFileSharing()`.
let self_node = self.control.ask(control_runner::SelfNode).await?;
let Some(self_node) = self_node else {
return Ok(Vec::new()); // no netmap yet
};
if !self_node.can_share_files() {
return Ok(Vec::new()); // Taildrop not enabled for the tailnet — fail-closed
}
let self_user_id = self_node.user_id;
let peers = self
.peer_tracker
.upgrade()
.ok_or(Error {
kind: ErrorKind::ActorGone,
target_actor: None,
message_ty: None,
})?
.ask(peer_tracker::AllPeers)
.await?;
// Eligibility + ordering live in `build_file_targets` (pure, unit-tested in `status`).
Ok(status::build_file_targets(peers, self_user_id))
}
/// The stable id of the exit node traffic is currently egressing through, or `None` if none is
/// engaged. This is the route updater's resolved + fail-closed answer (see
/// [`Status::active_exit_node`](crate::status::Status::active_exit_node)): it differs from the
/// configured [`exit_node`](Self::exit_node) selector, which may name a peer that is absent or
/// no longer advertising a default route (in which case egress is dropped and this returns
/// `None`).
pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
self.active_exit_rx.borrow().clone()
}
/// Request an OIDC ID token from control scoped to `audience` (workload-identity federation).
///
/// Returns the signed JWT, or the token RPC's own [`ts_control::IdTokenError`]. The kameo
/// delegated-reply send error is flattened: a handler error carries the real `IdTokenError`,
/// any other send failure (actor shutdown / mailbox closed) is surfaced as
/// [`ts_control::IdTokenError::NetworkError`].
pub async fn fetch_id_token(
&self,
audience: String,
) -> Result<String, ts_control::IdTokenError> {
self.control
.ask(control_runner::FetchIdToken { audience })
.await
.map_err(flatten_send_err)
}
/// Log this node out of the tailnet: deregister it by expiring its current node key.
///
/// Forwards to the control runner, which re-POSTs `/machine/register` with a past expiry over a
/// fresh Noise channel. This is a control-plane state change only — it does NOT shut the runtime
/// down (the caller follows with [`graceful_shutdown`](Self::graceful_shutdown)) and does not
/// touch the on-disk node key. The kameo delegated-reply send error is flattened the same way as
/// `fetch_id_token`: a handler error carries the real
/// [`ts_control::LogoutError`]; any other send failure (actor shutdown / mailbox closed) is
/// surfaced as [`ts_control::LogoutError::NetworkError`].
pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
self.control
.ask(control_runner::Logout)
.await
.map_err(flatten_logout_send_err)
}
/// Publish a `TXT` DNS record for this node via control's `/machine/set-dns` (Go
/// `LocalClient.SetDNS`).
///
/// Forwards to the control runner, which POSTs the record over a fresh Noise channel. The kameo
/// delegated-reply send error is flattened the same way as `fetch_id_token`:
/// a handler error carries the real [`ts_control::SetDnsError`]; any other send failure (actor
/// shutdown / mailbox closed) is surfaced as [`ts_control::SetDnsError::NetworkError`].
pub async fn set_dns(
&self,
name: String,
value: String,
) -> Result<(), ts_control::SetDnsError> {
self.control
.ask(control_runner::SetDns { name, value })
.await