tailscale/lib.rs
1//! A work-in-progress [Tailscale](https://tailscale.com/blog/how-tailscale-works) library.
2//!
3//! `tailscale` allows Rust programs to connect to a tailnet and exchange traffic with peers over
4//! TCP and UDP. It can communicate with other `tailscale`-based peers, `tailscaled` (the Tailscale
5//! Go client), `tsnet`, and `libtailscale` via public DERP servers.
6//!
7//! <div class="warning">
8//! `tailscale` is unstable and insecure.
9//!
10//! We welcome enthusiasm and interest, but please **do not** build production software using these
11//! libraries or rely on it for data privacy until we have a chance to batten down some hatches and
12//! complete a third-party audit.
13//!
14//! See the [Caveats section](#caveats) for more details.
15//! </div>
16//!
17//! For language bindings, see the following crates:
18//!
19//! - C: [ts_ffi](https://docs.rs/ts_ffi)
20//! - Python: [ts_python](https://docs.rs/ts_python)
21//! - Elixir: [ts_elixir](https://docs.rs/ts_elixir)
22//!
23//! For instructions on how to run tests, lints, etc., see [CONTRIBUTING.md]. For the high-level
24//! architecture and repository layout, see [ARCHITECTURE.md].
25//!
26//! ## Code Sample
27//!
28//! A simple UDP client that periodically sends messages to a tailnet peer at `100.64.0.1:5678`:
29//!
30//! ```no_run
31//! # use std::{
32//! # time::Duration,
33//! # net::Ipv4Addr,
34//! # error::Error,
35//! # };
36//! #
37//! # #[tokio::main]
38//! # async fn main() -> Result<(), Box<dyn Error>> {
39//! // Open a new connection to the tailnet
40//! let dev = tailscale::Device::new(
41//! &tailscale::Config::default_with_key_file("tsrs_keys.json").await?,
42//! Some("YOUR_AUTH_KEY_HERE".to_owned()),
43//! ).await?;
44//!
45//! // Bind a UDP socket on our tailnet IP, port 1234
46//! let sock = dev.udp_bind((dev.ipv4_addr().await?, 1234).into()).await?;
47//!
48//! // Send a packet containing "hello, world!" to 100.64.0.1:5678 once per second
49//! loop {
50//! sock.send_to((Ipv4Addr::new(100, 64, 0, 1), 5678).into(), b"hello, world!").await?;
51//! tokio::time::sleep(Duration::from_secs(1)).await;
52//! }
53//! # }
54//! ```
55//!
56//! Additional examples of using the `tailscale` crate can be found in the [`examples/`] directory.
57//!
58//! ## Using `tailscale`
59//!
60//! To use this crate or the language bindings, you will need to set the `TS_RS_EXPERIMENT` env var
61//! to `this_is_unstable_software`. We'll remove this requirement after a third-party code/cryptography
62//! audit and any necessary fixes.
63//!
64//! Under the hood, we use Tokio for our async runtime. You must also use Tokio, any kind and most
65//! configurations of Tokio runtimes should work, but there must be one available when you call any
66//! async API functions. The easiest way to do this is to use `#[tokio::main]`, see the
67//! [Tokio docs](https://docs.rs/tokio) for more information. In the future, we would like to limit
68//! our reliance on Tokio so that there are alternatives for users of other async runtimes.
69//!
70//! ## Caveats
71//!
72//! This software is still a work-in-progress! We are providing it in the open at this stage out of
73//! a belief in open-source and to see where the community runs with it, but please be aware of a
74//! few important considerations:
75//!
76//! - This implementation contains unaudited cryptography and hasn't undergone a comprehensive
77//! security analysis. Conservatively, assume there could be a critical security hole meaning
78//! anything you send or receive could be in the clear on the public Internet.
79//! - There are no compatibility guarantees at the moment. This is early-days software - we may
80//! break dependent code in order to get things right.
81//! - Direct peer-to-peer connections via NAT traversal are implemented (STUN-discovered endpoints
82//! and Disco, with `CallMeMaybe` hole-punching over DERP), with DERP relays as the fallback when
83//! no direct path is available. Hard/symmetric NATs get the same single fixed-local-port candidate
84//! (`EndpointSTUN4LocalPort`) Go Tailscale uses; behind a NAT with no static port mapping a flow
85//! may still stay relayed through DERP, which caps its throughput. (Upstream Go does **not** do a
86//! "256-port birthday-paradox spray" — that is a common misconception; the single-candidate guess
87//! is the actual behavior, and this fork matches it.)
88//!
89//! ## Feature Flags
90//!
91//! - `axum`: enables the `axum` module, which enables you to run an `axum` HTTP server on top
92//! of a [`netstack::TcpListener`].
93//!
94//! ## Platform Support
95//!
96//! `tailscale` currently supports the following platforms:
97//!
98//! - Linux (x86_64 and ARM64)
99//! - macOS (ARM64)
100//!
101//! ## Component crates
102//!
103//! The following crates are part of the tailscale-rs project and are dependencies of this one. For
104//! many tasks, just this crate should be sufficient and these other crates are an implementation detail.
105//! There are other crates too, see [ARCHITECTURE.md]
106//! or the [GitHub repo](https://github.com/tailscale/tailscale-rs).
107//!
108//! - [ts_runtime](https://docs.rs/ts_runtime): for each API-level `Device`, the runtime uses an actor
109//! architecture to manage the lifecycle of the control client, data plane components, netstack, etc.
110//! A message bus passes updates and communications between these top-level actors.
111//! - [ts_netcheck](https://docs.rs/ts_netcheck): checks network availability and reports latency to
112//! DERP servers in different regions.
113//! - [ts_netstack_smoltcp](https://docs.rs/ts_netstack_smoltcp): a [smoltcp](https://docs.rs/smoltcp)-based
114//! network stack that processes Layer 3+ packets to/from the overlay network.
115//! - [ts_control](https://docs.rs/ts_control): control plane client that handles registration,
116//! authorization/authentication, configuration, and streaming updates.
117//! - [ts_dataplane](https://docs.rs/ts_dataplane): wires all the individual data plane functions together,
118//! flowing inbound and outbound packets through the components in the correct order.
119//! - [ts_tunnel](https://docs.rs/ts_tunnel): a partial implementation of the WireGuard specification
120//! that protects all data plane traffic, and is interoperable with other WireGuard clients, including Tailscale clients.
121//! - [ts_cli_util](https://docs.rs/ts_cli_util): helpers for writing command line tools and initializing
122//! logging, used in examples.
123//! - [ts_disco_protocol](https://docs.rs/ts_disco_protocol): incomplete implementation of Tailscale's
124//! discovery protocol (disco).
125//!
126//! [ARCHITECTURE.md]: https://github.com/tailscale/tailscale-rs/blob/main/ARCHITECTURE.md
127//! [CONTRIBUTING.md]: https://github.com/tailscale/tailscale-rs/blob/main/CONTRIBUTING.md
128//! [`examples/`]: https://github.com/tailscale/tailscale-rs/blob/main/examples/README.md
129//! [open an issue]: https://github.com/tailscale/tailscale-rs/issues
130//! [`axum` HTTP server]: https://docs.rs/axum/latest/axum/
131
132use std::{
133 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
134 time::Duration,
135};
136
137#[doc(inline)]
138pub use config::Config;
139#[doc(inline)]
140pub use error::{Error, InternalErrorKind};
141// Re-exported so a downstream crate depending only on `tailscale` can name the auth-key secret type
142// for [`Device::new_with_secret`] without taking a separate, version-pinned dependency on `secrecy`
143// (which would risk a `SecretString`-type mismatch if the two `secrecy` majors diverged). Callers
144// pass `tailscale::SecretString`; `secrecy` is a pure-Rust wrapper (no aws-lc/openssl/ring).
145pub use secrecy::SecretString;
146#[doc(inline)]
147pub use ts_control::ExitNodeSelector;
148#[doc(inline)]
149pub use ts_control::Node as NodeInfo;
150#[doc(inline)]
151pub use ts_control::tls::{CertifiedKey, TlsAcceptor, TlsStream};
152#[doc(inline)]
153pub use ts_control::{CertError, MISSING_CERT_RPC, ServeConfig, ServeState, ServeTarget};
154/// The netmap DNS configuration returned by [`Device::dns_config`] (Go `netmap.NetworkMap.DNS`).
155#[doc(inline)]
156pub use ts_control::{DnsConfig, DnsResolver, ExtraRecord};
157#[doc(inline)]
158pub use ts_control::{ExitProxyConfig, ExitProxyScheme};
159pub use ts_control::{
160 IdTokenError, LogoutError, ServiceError, ServiceMode, SshAccept, SshAction, SshConnIdentity,
161 SshDecision, SshDenyReason, SshPolicy, SshPrincipal, SshRule, StableNodeId,
162};
163// Re-exported so the application data-path transport can be selected through the `tailscale`
164// facade alone: `Config::transport_mode` is `TransportMode` (default `Netstack`; `Tun(TunConfig {
165// name, mtu })` for a real kernel TUN interface). Both are `pub` in `ts_control` but were not
166// reachable through this facade, forcing downstream crates to depend on `ts_control` directly just
167// to name them.
168pub use ts_control::{TransportMode, TunConfig};
169#[doc(inline)]
170pub use ts_netstack_smoltcp::PingError;
171use ts_netstack_smoltcp::{CreateSocket, netcore::Channel};
172#[doc(inline)]
173pub use ts_runtime::fallback_tcp::{
174 FallbackConnFuture, FallbackConnHandler, FallbackDecision, FallbackTcpHandle,
175};
176#[doc(inline)]
177pub use ts_runtime::taildrop::WaitingFile;
178#[doc(inline)]
179pub use ts_runtime::{
180 DeviceState, FileTarget, NetcheckReport, RegionLatency, RegistrationError, Status, StatusNode,
181 WhoIs,
182};
183
184#[cfg(feature = "axum")]
185pub mod axum;
186pub mod config;
187mod dial;
188mod error;
189mod loopback;
190#[cfg(feature = "ssh")]
191pub mod ssh;
192
193#[doc(inline)]
194pub use dial::{ConnectedUdpSocket, DialConn};
195#[doc(inline)]
196pub use loopback::LoopbackHandle;
197
198/// How a program connects to a tailnet and communicates with peers.
199///
200/// The `Device` connects to the control plane, registers itself with the tailnet, and communicates
201/// with tailnet peers. Its tailnet identity is determined by the key state provided at
202/// construction-time.
203pub struct Device {
204 runtime: ts_runtime::Runtime,
205 /// Command channel to the application netstack. `None` in TUN transport mode, where there is
206 /// no userspace application netstack; the channel-driven socket APIs ([`Device::udp_bind`],
207 /// [`Device::tcp_listen`], [`Device::tcp_connect`], [`Device::ping`]) are unsupported there.
208 channel: Option<Channel>,
209 /// Whether IPv6 is enabled on the tailnet overlay (the `Config::enable_ipv6` gate, default
210 /// `false`). Captured at construction; used by [`Device::listen_service`] to decide whether an
211 /// IPv6 VIP-service address is bindable (the netstack only accepts IPv6 overlay addresses when
212 /// this is set).
213 enable_ipv6: bool,
214 /// The stored Serve config + its live per-port accept loops (`tsnet`'s `Get/SetServeConfig` +
215 /// serving runtime). Built lazily on the first [`Device::set_serve_config`] (it needs this
216 /// node's overlay IPv4, only known after registration). Held here so its accept loops abort when
217 /// the `Device` drops; `None` (empty config) until the first `set`.
218 serve: std::sync::Mutex<Option<ts_runtime::serve::ServeManager>>,
219 /// The live Funnel ingress manager (`tsnet`'s `ListenFunnel` data path), built on
220 /// [`Device::listen_funnel`](crate::Device::listen_funnel). Held here so its TLS-termination pump and the installed peerAPI
221 /// ingress sink stay alive for the device's life (and tear down when a new `listen_funnel`
222 /// replaces it, or the `Device` drops). `None` until the first `listen_funnel`.
223 funnel: std::sync::Mutex<Option<ts_runtime::funnel::FunnelManager>>,
224}
225
226/// Map a [`ts_runtime::taildrop::TaildropError`] to the device-facing [`Error`]. `Error` is a
227/// `Copy` enum with no payload, so the I/O detail string is dropped, but the *kind* is preserved so
228/// a caller can still distinguish the actionable cases: an invalid name →
229/// [`InternalErrorKind::BadRequest`], an in-progress conflict → [`InternalErrorKind::AlreadyExists`],
230/// a missing file → [`InternalErrorKind::NotFound`], and any other filesystem failure →
231/// [`InternalErrorKind::Io`].
232fn taildrop_err(e: ts_runtime::taildrop::TaildropError) -> Error {
233 use ts_runtime::taildrop::TaildropError;
234 match e {
235 TaildropError::InvalidFileName => Error::Internal(InternalErrorKind::BadRequest),
236 TaildropError::FileExists => Error::Internal(InternalErrorKind::AlreadyExists),
237 TaildropError::Io(io) if io.kind() == std::io::ErrorKind::NotFound => {
238 Error::Internal(InternalErrorKind::NotFound)
239 }
240 TaildropError::Io(_) => Error::Internal(InternalErrorKind::Io),
241 }
242}
243
244/// Map a [`ts_runtime::taildrop_send::TaildropSendError`] (the Taildrop *sender*) to the
245/// device-facing [`Error`]. The send-side conflict/forbidden/unexpected-status cases all reduce to
246/// `BadRequest` (the peer refused the transfer for a request-level reason), a dial failure or
247/// timeout to `Timeout`, an invalid name to `BadRequest`, and any stream I/O failure to `Io`.
248fn taildrop_send_err(e: ts_runtime::taildrop_send::TaildropSendError) -> Error {
249 use ts_runtime::taildrop_send::TaildropSendError;
250 match e {
251 TaildropSendError::Connect | TaildropSendError::Timeout => Error::Timeout,
252 TaildropSendError::InvalidName
253 | TaildropSendError::Forbidden
254 | TaildropSendError::Conflict
255 | TaildropSendError::UnexpectedStatus(_) => Error::Internal(InternalErrorKind::BadRequest),
256 TaildropSendError::Io => Error::Internal(InternalErrorKind::Io),
257 }
258}
259
260/// Resolve the effective registration auth key from `auth_key` plus the config's
261/// workload-identity-federation (WIF) / OAuth-client fields.
262///
263/// With the `identity-federation` feature enabled, an OAuth client secret (`tskey-client-…`) or a
264/// `client_id` + (`id_token` | `audience`) is exchanged for a Tailscale auth key against the SaaS
265/// admin API before registration (Go `tsnet.Server`'s `resolveAuthKey`). Without the feature this is
266/// a pure pass-through: `auth_key` is returned unchanged and the WIF config fields are ignored, so
267/// the default build is byte-identical to before.
268#[cfg(feature = "identity-federation")]
269async fn resolve_auth_key(
270 config: &Config,
271 auth_key: Option<String>,
272) -> Result<Option<String>, Error> {
273 let wif = ts_control::WifConfig {
274 auth_key,
275 client_id: config.client_id.clone(),
276 client_secret: config.client_secret.clone(),
277 id_token: config.id_token.clone(),
278 audience: config.audience.clone(),
279 tags: config.requested_tags.clone(),
280 };
281 ts_control::resolve_auth_key(&wif, &config.control_server_url)
282 .await
283 .map_err(|e| {
284 tracing::error!(error = %e, "resolving auth key via workload-identity federation");
285 Error::Internal(InternalErrorKind::BadRequest)
286 })
287}
288
289/// Pass-through when the `identity-federation` feature is disabled: the auth key is used as-is and
290/// the WIF config fields have no effect (matching Go, where the federation path is compiled out
291/// unless its optional feature is linked).
292#[cfg(not(feature = "identity-federation"))]
293async fn resolve_auth_key(
294 _config: &Config,
295 auth_key: Option<String>,
296) -> Result<Option<String>, Error> {
297 Ok(auth_key)
298}
299
300impl Device {
301 /// Create a device from the given [`Config`] and auth key.
302 ///
303 /// Internally, this will spawn multiple asynchronous actors onto a Tokio runtime.
304 ///
305 /// # Example
306 ///
307 /// ```rust,no_run
308 /// # #[tokio::main]
309 /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
310 /// # use tailscale::*;
311 /// let dev = Device::new(
312 /// &Config::default_with_key_file("tsrs_keys.json").await?,
313 /// Some("MY_AUTH_KEY".to_string()),
314 /// ).await?;
315 /// # Ok(()) }
316 /// ```
317 pub async fn new(config: &Config, auth_key: Option<String>) -> Result<Self, Error> {
318 check_magic_env()?;
319
320 // Resolve the effective registration auth key. The explicit `auth_key` argument wins; if it
321 // is `None`, fall back to `config.auth_key` (Go `tsnet.Server.AuthKey`). When the
322 // `identity-federation` feature is enabled, the resolved key is further passed through the
323 // WIF / OAuth-client bootstrap, which exchanges an OAuth client secret (`tskey-client-…`) or
324 // an IdP-issued OIDC token for a Tailscale auth key before registration (SaaS-only).
325 let auth_key = auth_key.or_else(|| config.auth_key.clone());
326 let auth_key = resolve_auth_key(config, auth_key).await?;
327
328 let rt =
329 ts_runtime::Runtime::spawn(config.into(), auth_key, (&config.key_state).into()).await?;
330 // In TUN transport mode there is no application netstack, so the runtime has no command
331 // channel: that surfaces as `UnsupportedInTunMode`, which we map to a `None` channel rather
332 // than an error (the device is still usable for control-plane and peer-lookup APIs).
333 let channel = match rt.channel().await {
334 Ok(c) => Some(c),
335 Err(e) if e.kind == ts_runtime::ErrorKind::UnsupportedInTunMode => None,
336 Err(e) => return Err(e.into()),
337 };
338
339 Ok(Self {
340 runtime: rt,
341 channel,
342 enable_ipv6: config.enable_ipv6,
343 serve: std::sync::Mutex::new(None),
344 funnel: std::sync::Mutex::new(None),
345 })
346 }
347
348 /// Create a device from the given [`Config`] and a [`SecretString`] auth key.
349 ///
350 /// This is a back-compat-preserving convenience over [`new`](Self::new) for callers that already
351 /// hold the registration auth key as a [`secrecy::SecretString`] (e.g. a daemon that keeps the
352 /// pre-auth key wrapped end-to-end). It lets the caller avoid materializing a plain `String` at
353 /// the engine boundary: the secret is exposed only on the last inch, immediately before being
354 /// handed to [`new`](Self::new).
355 ///
356 /// # Honesty about the plaintext window
357 ///
358 /// This closes the *caller's* boundary, **not** the engine's internal handling. The engine still
359 /// resolves the auth key to a plain `String` internally for registration (the plaintext `String`
360 /// window inside the engine is identical to calling [`new`](Self::new) directly) — this method
361 /// does not make the engine itself secret-clean. If you call [`new`](Self::new) you create that
362 /// `String` yourself; if you call this you do not, but the engine creates one either way.
363 ///
364 /// Passing `None` is equivalent to `new(config, None)` (falls back to `config.auth_key`).
365 ///
366 /// # Example
367 ///
368 /// ```rust,no_run
369 /// # #[tokio::main]
370 /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
371 /// # use tailscale::*;
372 /// let dev = Device::new_with_secret(
373 /// &Config::default_with_key_file("tsrs_keys.json").await?,
374 /// Some(SecretString::from("MY_AUTH_KEY")),
375 /// ).await?;
376 /// # Ok(()) }
377 /// ```
378 pub async fn new_with_secret(
379 config: &Config,
380 auth_key: Option<SecretString>,
381 ) -> Result<Self, Error> {
382 use secrecy::ExposeSecret as _;
383
384 // Expose the secret on the last inch and delegate to `new`, so the spawn/registration path
385 // is shared verbatim (no duplicated runtime-spawn logic) and the engine-internal plaintext
386 // window is byte-for-byte identical to a direct `new` call.
387 let plain = auth_key.map(|s| s.expose_secret().to_string());
388 Self::new(config, plain).await
389 }
390
391 /// The application netstack command channel, or an error in TUN transport mode (no application
392 /// netstack exists).
393 fn channel(&self) -> Result<&Channel, Error> {
394 self.channel
395 .as_ref()
396 .ok_or(Error::Internal(InternalErrorKind::UnsupportedInTunMode))
397 }
398
399 /// Get this [`Device`]'s IPv4 tailnet address.
400 pub async fn ipv4_addr(&self) -> Result<Ipv4Addr, Error> {
401 self.runtime
402 .control
403 .ask(ts_runtime::control_runner::Ipv4)
404 .await
405 .map_err(ts_runtime::Error::from)?
406 .ok_or(Error::Internal(InternalErrorKind::Actor))
407 }
408
409 /// Get this [`Device`]'s IPv6 tailnet address.
410 pub async fn ipv6_addr(&self) -> Result<Ipv6Addr, Error> {
411 self.runtime
412 .control
413 .ask(ts_runtime::control_runner::Ipv6)
414 .await
415 .map_err(ts_runtime::Error::from)?
416 .ok_or(Error::Internal(InternalErrorKind::Actor))
417 }
418
419 /// This node's tailnet IPv4 and (when provisioned) IPv6 addresses as a pair — the Rust analog of
420 /// Go `tsnet.Server.TailscaleIPs() (ip4, ip6 netip.Addr)`.
421 ///
422 /// Reads the self node's assigned addresses (the same source Go splits by family). The tailnet
423 /// is IPv4-only unless [`Config::enable_ipv6`](crate::config::Config) is set, so the IPv6 half is
424 /// `None` when no v6 address is assigned — the Rust shape for Go returning the zero `netip.Addr`
425 /// in that case (Go's IPv6-absent sentinel). Errors until the first netmap is received (no self
426 /// node yet), matching Go returning invalid addresses before the node has joined.
427 pub async fn tailscale_ips(&self) -> Result<(Ipv4Addr, Option<Ipv6Addr>), Error> {
428 let me = self.self_node().await?;
429 let v4 = me.tailnet_address.ipv4.addr();
430 let v6 = me.tailnet_address.ipv6.addr();
431 // The decoder synthesizes the unspecified `::` placeholder on an IPv4-only tailnet; surface
432 // a real v6 only when IPv6 is enabled AND a non-placeholder address was assigned.
433 let v6 = (self.enable_ipv6 && !v6.is_unspecified()).then_some(v6);
434 Ok((v4, v6))
435 }
436
437 /// Bind a UDP socket to the specified [`SocketAddr`].
438 ///
439 /// Returns an error in TUN transport mode (there is no application netstack to bind on).
440 pub async fn udp_bind(&self, socket_addr: SocketAddr) -> Result<netstack::UdpSocket, Error> {
441 self.channel()?
442 .udp_bind(socket_addr)
443 .await
444 .map_err(Into::into)
445 }
446
447 /// Bind a TCP listener to the specified [`SocketAddr`].
448 ///
449 /// Returns an error in TUN transport mode (there is no application netstack to listen on).
450 pub async fn tcp_listen(
451 &self,
452 socket_addr: SocketAddr,
453 ) -> Result<netstack::TcpListener, Error> {
454 self.channel()?
455 .tcp_listen(socket_addr)
456 .await
457 .map_err(Into::into)
458 }
459
460 /// Register a fallback TCP handler (like `tsnet`'s `RegisterFallbackTCPHandler`).
461 ///
462 /// The callback is consulted for every inbound TCP flow that matches **no** explicit
463 /// [`Device::tcp_listen`] listener, with the flow's `(src, dst)` addresses. It returns
464 /// `(handler, intercept)`:
465 /// - `(_, false)` — decline; the next registered callback is tried.
466 /// - `(Some(h), true)` — claim the flow; `h` is handed the accepted [`netstack::TcpStream`].
467 /// - `(None, true)` — claim and reject the flow (the connection is closed).
468 ///
469 /// Multiple handlers may be registered; they are consulted in registration order and the first
470 /// to intercept wins. The returned [`FallbackTcpHandle`] deregisters the handler when dropped.
471 ///
472 /// Handlers serve flows over the overlay netstack only — never a host socket — and a flow no
473 /// handler claims is closed (fail-closed), never direct-dialed.
474 ///
475 /// Returns an error in TUN transport mode (there is no application netstack to attach to).
476 pub fn register_fallback_tcp_handler<F>(&self, cb: F) -> Result<FallbackTcpHandle, Error>
477 where
478 F: Fn(SocketAddr, SocketAddr) -> FallbackDecision + Send + Sync + 'static,
479 {
480 self.runtime
481 .register_fallback_tcp_handler(std::sync::Arc::new(cb))
482 .map_err(Into::into)
483 }
484
485 /// Resolve a tailnet peer (or this node) by MagicDNS name to its tailnet IPv4 address.
486 ///
487 /// This is an in-process lookup against the netmap we already hold — like `tsnet`'s in-memory
488 /// `dnsMap`, it does not query any DNS server (there is no `100.100.100.100` resolver). The
489 /// `name` may be a bare hostname or a fully-qualified MagicDNS name, with or without a trailing
490 /// dot, in any case (matching is case-insensitive). Returns `Ok(None)` if no tailnet node has
491 /// that name.
492 ///
493 /// Only MagicDNS names are resolved; names outside the tailnet are not looked up here, so the
494 /// caller's system resolver remains responsible for them. IPv6 is intentionally not resolved —
495 /// this fork operates IPv4-only on the tailnet.
496 pub async fn resolve(&self, name: &str) -> Result<Option<Ipv4Addr>, Error> {
497 if let Some(peer) = self.peer_by_name(name).await? {
498 return Ok(Some(peer.tailnet_address.ipv4.addr()));
499 }
500
501 // tsnet's dnsMap also resolves our own name; fall back to self when no peer matches.
502 let me = self.self_node().await?;
503 if me.matches_name(name) {
504 return Ok(Some(me.tailnet_address.ipv4.addr()));
505 }
506
507 Ok(None)
508 }
509
510 /// Connect to a tailnet peer by MagicDNS name and port over TCP.
511 ///
512 /// Resolves `name` via [`Device::resolve`] (an in-process netmap lookup, no DNS server), then
513 /// dials the resulting tailnet IPv4 address. Returns [`InternalErrorKind::BadRequest`] if the
514 /// name does not resolve to a tailnet node.
515 pub async fn connect_by_name(
516 &self,
517 name: &str,
518 port: u16,
519 ) -> Result<netstack::TcpStream, Error> {
520 let addr = self
521 .resolve(name)
522 .await?
523 .ok_or(Error::Internal(InternalErrorKind::BadRequest))?;
524
525 self.tcp_connect((addr, port).into()).await
526 }
527
528 /// Resolve a `host:port` string to a tailnet [`SocketAddr`], honoring the family forced by a
529 /// `network` suffix. The host may be an IP literal (parsed directly) or a MagicDNS name
530 /// (resolved via [`Device::resolve`], which yields a tailnet IPv4). Shared by [`Device::dial`]
531 /// and [`Device::dial_tcp`]. The IPv4-only invariant is enforced here: a `…6` network, or any v6
532 /// destination, requires `Config::enable_ipv6` and otherwise returns
533 /// [`InternalErrorKind::BadRequest`] (a clean typed error rather than a downstream actor error).
534 async fn resolve_dial_addr(
535 &self,
536 network: dial::Network,
537 addr: &str,
538 ) -> Result<SocketAddr, Error> {
539 let (host, port) = dial::split_host_port(addr)?;
540
541 // An IP literal is used directly; otherwise resolve the MagicDNS name (IPv4 only).
542 let ip: IpAddr = if let Ok(ip) = host.parse::<IpAddr>() {
543 ip
544 } else {
545 self.resolve(host)
546 .await?
547 .ok_or(Error::Internal(InternalErrorKind::BadRequest))?
548 .into()
549 };
550
551 dial::check_family(network.family, ip)?;
552
553 // IPv4-only invariant: a v6 destination is only reachable when IPv6 is provisioned.
554 if ip.is_ipv6() && !self.enable_ipv6 {
555 return Err(Error::Internal(InternalErrorKind::BadRequest));
556 }
557
558 Ok((ip, port).into())
559 }
560
561 /// Connect to a tailnet address over TCP or UDP, the Rust analog of Go
562 /// `tsnet.Server.Dial(ctx, network, address)`.
563 ///
564 /// `network` is one of `"tcp"`, `"tcp4"`, `"tcp6"`, `"udp"`, `"udp4"`, `"udp6"`; `addr` is a
565 /// `host:port` string where `host` is a MagicDNS name, an IPv4 literal, or a bracketed IPv6
566 /// literal (`[2001:db8::1]:443`). The host is resolved in-process via [`Device::resolve`] (no DNS
567 /// server). Returns a [`DialConn`] whose arm matches the transport — use [`Device::dial_tcp`]
568 /// when you want the TCP stream directly.
569 ///
570 /// Differences from Go (documented for parity): ports must be **numeric** (Go's `LookupPort`
571 /// also resolves named ports like `"http"`; this fork avoids a services-file dependency), and
572 /// `…6`/v6 destinations require `Config::enable_ipv6` (the tailnet is IPv4-only by default).
573 ///
574 /// # Errors
575 /// [`InternalErrorKind::BadRequest`] for an unsupported `network`, a malformed/portless `addr`,
576 /// an unresolvable name, or a v6 destination while IPv6 is disabled; otherwise the transport's
577 /// own connect error.
578 pub async fn dial(&self, network: &str, addr: &str) -> Result<DialConn, Error> {
579 let net = dial::parse_network(network)?;
580 let remote = self.resolve_dial_addr(net, addr).await?;
581
582 match net.transport {
583 dial::Transport::Tcp => Ok(DialConn::Tcp(self.tcp_connect(remote).await?)),
584 dial::Transport::Udp => {
585 // Bind an ephemeral local UDP socket on this node's tailnet address of the SAME
586 // family as the remote, then connect it (Go's `Dial("udp", …)` returns a connected
587 // UDP `net.Conn`, with the local source picked by `IfElse(dst.Is6(), v6, v4)`). A v4
588 // local socket cannot send to a v6 peer, so the family must match `remote`. (TCP gets
589 // this for free: `tcp_connect` already picks the source family from `remote`.)
590 let local_ip: IpAddr = if remote.is_ipv6() {
591 self.ipv6_addr().await?.into()
592 } else {
593 self.ipv4_addr().await?.into()
594 };
595 let sock = self.udp_bind((local_ip, 0).into()).await?;
596 Ok(DialConn::Udp(ConnectedUdpSocket::new(sock, remote)))
597 }
598 }
599 }
600
601 /// Connect to a tailnet address over TCP, returning the stream directly — the common case of
602 /// [`Device::dial`] for `"tcp"`. `addr` is a `host:port` string (MagicDNS name or IP literal).
603 /// This is the building block for HTTP-over-tailnet: an embedder's `hyper`/`reqwest` client can
604 /// route requests by calling `dial_tcp(&format!("{host}:{port}"))` from its connector, mirroring
605 /// how Go `tsnet.Server.HTTPClient` sets `http.Transport.DialContext = Server.Dial`.
606 ///
607 /// # Errors
608 /// As [`Device::dial`] for the `"tcp"` network.
609 pub async fn dial_tcp(&self, addr: &str) -> Result<netstack::TcpStream, Error> {
610 let remote = self
611 .resolve_dial_addr(
612 dial::Network {
613 transport: dial::Transport::Tcp,
614 family: dial::Family::Any,
615 },
616 addr,
617 )
618 .await?;
619 self.tcp_connect(remote).await
620 }
621
622 /// Bind a UDP socket from a `host:port` string, the Rust analog of Go
623 /// `tsnet.Server.ListenPacket(network, addr)`.
624 ///
625 /// `network` is one of `"udp"`, `"udp4"`, `"udp6"`; `addr` must be a **valid IP literal**
626 /// `host:port` (Go's `ListenPacket` rejects a name or empty host — unlike `Listen`). An
627 /// unspecified host (`0.0.0.0`/`[::]`) binds on this node's tailnet address. Returns the
628 /// unconnected [`netstack::UdpSocket`] (a `net.PacketConn`).
629 ///
630 /// # Errors
631 /// [`InternalErrorKind::BadRequest`] for a non-UDP/unsupported `network`, a malformed addr, a
632 /// non-IP host, a family mismatch, or a v6 bind while IPv6 is disabled.
633 pub async fn listen_packet(
634 &self,
635 network: &str,
636 addr: &str,
637 ) -> Result<netstack::UdpSocket, Error> {
638 let net = dial::parse_network(network)?;
639 if net.transport != dial::Transport::Udp {
640 return Err(Error::Internal(InternalErrorKind::BadRequest));
641 }
642 let (host, port) = dial::split_host_port(addr)?;
643
644 // ListenPacket requires a valid IP host (Go rejects a name here).
645 let ip: IpAddr = host
646 .parse()
647 .map_err(|_| Error::Internal(InternalErrorKind::BadRequest))?;
648 dial::check_family(net.family, ip)?;
649
650 // A v6 bind (whether an explicit literal or an unspecified `[::]`) requires IPv6 to be
651 // provisioned — enforce the gate for BOTH cases (the unspecified `[::]` path used to skip it).
652 if ip.is_ipv6() && !self.enable_ipv6 {
653 return Err(Error::Internal(InternalErrorKind::BadRequest));
654 }
655
656 // An unspecified bind host (`0.0.0.0` / `[::]`) means "this node's tailnet address" — of the
657 // SAME family as the requested address, so a `udp6` `[::]:0` binds a v6 socket (it used to
658 // fall through to the v4 address regardless, silently yielding an IPv4 socket for a v6 listen).
659 let bind_ip: IpAddr = if ip.is_unspecified() {
660 if ip.is_ipv6() {
661 self.ipv6_addr().await?.into()
662 } else {
663 self.ipv4_addr().await?.into()
664 }
665 } else {
666 ip
667 };
668
669 self.udp_bind((bind_ip, port).into()).await
670 }
671
672 /// Connect to a TCP socket at the remote address.
673 ///
674 /// Returns an error in TUN transport mode (there is no application netstack to dial from).
675 pub async fn tcp_connect(&self, remote: SocketAddr) -> Result<netstack::TcpStream, Error> {
676 let channel = self.channel()?;
677
678 let ip: IpAddr = match remote.is_ipv4() {
679 true => self.ipv4_addr().await?.into(),
680 false => self.ipv6_addr().await?.into(),
681 };
682
683 // TODO(npry): collision checking
684 let ephemeral_port = rand::random_range(49152..=u16::MAX);
685
686 channel
687 .tcp_connect((ip, ephemeral_port).into(), remote)
688 .await
689 .map_err(Into::into)
690 }
691
692 /// Start a SOCKS5 proxy on a host loopback address that dials into the tailnet (Go
693 /// `tsnet.Server.Loopback`, SOCKS5 half).
694 ///
695 /// Binds a TCP listener on `127.0.0.1:0` (host loopback only — never an external interface) and
696 /// serves SOCKS5 (RFC 1928) with required username/password auth (RFC 1929): username `tsnet`,
697 /// password = the returned `proxy_cred`. Each `CONNECT` is dialed INTO the overlay via
698 /// [`Device::connect_by_name`] / [`Device::tcp_connect`] and spliced to the accepted host socket, so
699 /// a non-Rust host process can reach tailnet peers through the proxy. Returns the bound address, the
700 /// proxy credential, and a [`LoopbackHandle`] whose drop stops the listener.
701 ///
702 /// Anti-leak: the listener is loopback-only and every connection egresses over the overlay, never a
703 /// host socket — the host's real origin IP is never used to reach the destination. Unlike Go, the
704 /// LocalAPI HTTP surface is not served (this fork exposes status/whois/id-token natively on
705 /// `Device`); only the SOCKS5 proxy is provided.
706 ///
707 /// Returns an error in TUN transport mode (no application netstack to dial from).
708 pub async fn loopback(&self) -> Result<(std::net::SocketAddr, String, LoopbackHandle), Error> {
709 // Capture only cloneable pieces — never `&self` — for the spawned accept loop: a clone of the
710 // netstack command channel, this device's own overlay IPv4 (fetched once), and a boxed
711 // resolver closure over clones of the control + peer-tracker actor refs. The resolver
712 // replicates `Device::resolve` (peer-by-name, falling back to this node's own name).
713 let channel = self.channel()?.clone();
714 let self_ipv4 = self.ipv4_addr().await?;
715
716 let control = self.runtime.control.clone();
717 let peer_tracker = self.runtime.peer_tracker.clone();
718 let resolve: loopback::Resolver = std::sync::Arc::new(move |name: String| {
719 let control = control.clone();
720 let peer_tracker = peer_tracker.clone();
721 Box::pin(async move {
722 let pt = peer_tracker
723 .upgrade()
724 .ok_or(Error::Internal(InternalErrorKind::Actor))?;
725 let peer = pt
726 .ask(ts_runtime::peer_tracker::PeerByName { name: name.clone() })
727 .await
728 .map_err(ts_runtime::Error::from)?;
729 if let Some(peer) = peer {
730 return Ok(Some(peer.tailnet_address.ipv4.addr()));
731 }
732 // tsnet's dnsMap also resolves our own name; fall back to self.
733 let me = control
734 .ask(ts_runtime::control_runner::SelfNode)
735 .await
736 .map_err(ts_runtime::Error::from)?
737 .ok_or(Error::Internal(InternalErrorKind::Actor))?;
738 if me.matches_name(&name) {
739 Ok(Some(me.tailnet_address.ipv4.addr()))
740 } else {
741 Ok(None)
742 }
743 }) as std::pin::Pin<Box<dyn std::future::Future<Output = _> + Send>>
744 });
745
746 let dialer = loopback::OverlayDialer::new(channel, self_ipv4, resolve);
747 loopback::start(dialer).await
748 }
749
750 /// Get our node info.
751 pub async fn self_node(&self) -> Result<NodeInfo, Error> {
752 self.runtime
753 .control
754 .ask(ts_runtime::control_runner::SelfNode)
755 .await
756 .map_err(ts_runtime::Error::from)?
757 .ok_or(Error::Internal(InternalErrorKind::Actor))
758 }
759
760 /// The DNS names this node can obtain TLS certificates for — Go `tsnet.Server.CertDomains()`.
761 ///
762 /// These are the `CertDomains` control pushed in the netmap DNS config: the names a TLS-serving
763 /// consumer (e.g. a `ListenTLS`/`GetCertificate`-style caller) should request a cert for. Returns
764 /// an empty `Vec` before the first netmap, or when control granted none — mirroring Go returning a
765 /// clone of `nm.DNS.CertDomains` (empty/`nil` when absent).
766 pub async fn cert_domains(&self) -> Result<Vec<String>, Error> {
767 self.runtime
768 .control
769 .ask(ts_runtime::control_runner::CertDomains)
770 .await
771 .map_err(ts_runtime::Error::from)
772 .map_err(Into::into)
773 }
774
775 /// The DNS configuration control pushed in the latest netmap — Go `tsnet`'s view of
776 /// `netmap.NetworkMap.DNS` (what `tailscale dns status` reports).
777 ///
778 /// Returns the full [`DnsConfig`] — MagicDNS on/off, search domains, global + fallback resolvers,
779 /// split-DNS routes, extra records, cert domains — or `None` before the first netmap / when
780 /// control has sent no DNS config. A superset of [`cert_domains`](Device::cert_domains), which
781 /// remains a separate narrower accessor for the TLS-cert use. Mirrors Go reading a clone of
782 /// `nm.DNS` (absent ⇒ `None`).
783 pub async fn dns_config(&self) -> Result<Option<DnsConfig>, Error> {
784 self.runtime
785 .control
786 .ask(ts_runtime::control_runner::DnsConfig)
787 .await
788 .map_err(ts_runtime::Error::from)
789 .map_err(Into::into)
790 }
791
792 /// This node's latest network-conditions report — the Rust analog of Go's `netcheck.Report` as
793 /// `tailscale netcheck` surfaces it.
794 ///
795 /// Returns the [`NetcheckReport`]: the preferred (lowest-latency) DERP region and the per-region
796 /// latency map this node last measured. Empty (default) before the first measurement. This fork's
797 /// net-report path measures only DERP-region latency, so the report carries that subset rather
798 /// than fabricating the UDP/port-mapping fields Go also reports (see [`NetcheckReport`]).
799 pub async fn netcheck(&self) -> Result<NetcheckReport, Error> {
800 self.runtime
801 .control
802 .ask(ts_runtime::control_runner::Netcheck)
803 .await
804 .map_err(ts_runtime::Error::from)
805 .map_err(Into::into)
806 }
807
808 /// This node's key-expiry instant as Unix seconds (`Node.KeyExpiry` in Go), or `Ok(None)` if
809 /// the key never expires.
810 ///
811 /// Like Go, this fork is **reactive** about key expiry — it reports it rather than rotating the
812 /// node key in the background. A caller can schedule re-authentication around this time; on
813 /// expiry, re-create the [`Device`] (which re-registers), supplying a fresh node key + the prior
814 /// `old_node_key` to rotate, or the same key to refresh.
815 pub async fn self_key_expiry_unix(&self) -> Result<Option<i64>, Error> {
816 Ok(self.self_node().await?.key_expiry_unix())
817 }
818
819 /// Whether this node's key has expired as of now (`!KeyExpiry.IsZero() && KeyExpiry.Before(now)`
820 /// in Go). A key with no expiry is never expired. See [`Device::self_key_expiry_unix`] for the
821 /// reactive-rotation note.
822 pub async fn self_key_expired(&self) -> Result<bool, Error> {
823 let now = std::time::SystemTime::now()
824 .duration_since(std::time::UNIX_EPOCH)
825 .map(|d| d.as_secs() as i64)
826 // An unreadable clock (pre-epoch) is treated as the far future so a time-limited key
827 // looks expired — fail-safe toward prompting re-auth rather than trusting a stale key.
828 .unwrap_or(i64::MAX);
829 Ok(self.self_node().await?.key_expired_at_unix(now))
830 }
831
832 /// Fetch the current Tailscale SSH policy pushed by control, if any.
833 ///
834 /// Returns `Ok(None)` when control has not sent an SSH policy. The SSH server treats an absent
835 /// or empty policy as **deny-all** (fail-closed). Used by the SSH auth path
836 /// ([`SshPolicy::evaluate`][ts_control::SshPolicy::evaluate]) to authorize incoming
837 /// connections.
838 pub async fn ssh_policy(&self) -> Result<Option<ts_control::SshPolicy>, Error> {
839 self.runtime
840 .control
841 .ask(ts_runtime::control_runner::CurrentSshPolicy)
842 .await
843 .map_err(ts_runtime::Error::from)
844 .map_err(Into::into)
845 }
846
847 /// Look up a peer by name.
848 pub async fn peer_by_name(&self, name: &str) -> Result<Option<NodeInfo>, Error> {
849 let pt = self
850 .runtime
851 .peer_tracker
852 .upgrade()
853 .ok_or(Error::Internal(InternalErrorKind::Actor))?;
854
855 pt.ask(ts_runtime::peer_tracker::PeerByName {
856 name: name.to_string(),
857 })
858 .await
859 .map_err(ts_runtime::Error::from)
860 .map_err(Into::into)
861 }
862
863 /// Look up a peer by ip.
864 pub async fn peer_by_tailnet_ip(&self, ip: IpAddr) -> Result<Option<NodeInfo>, Error> {
865 let pt = self
866 .runtime
867 .peer_tracker
868 .upgrade()
869 .ok_or(Error::Internal(InternalErrorKind::Actor))?;
870
871 pt.ask(ts_runtime::peer_tracker::PeerByTailnetIp { ip })
872 .await
873 .map_err(ts_runtime::Error::from)
874 .map_err(Into::into)
875 }
876
877 /// Look up the peer(s) with the most-specific route matches for `ip`.
878 ///
879 /// This reports which peers *advertise* a route covering `ip`, independent of this device's
880 /// `accept_routes` setting — analogous to the Go client's informational `PrimaryRoutes`. It is
881 /// not a reachability oracle: with `accept_routes` off, the dataplane will not actually route
882 /// to (or accept return traffic from) advertised subnet routes even if this returns a peer.
883 pub async fn peers_with_route(&self, ip: IpAddr) -> Result<Vec<NodeInfo>, Error> {
884 let pt = self
885 .runtime
886 .peer_tracker
887 .upgrade()
888 .ok_or(Error::Internal(InternalErrorKind::Actor))?;
889
890 pt.ask(ts_runtime::peer_tracker::PeerByAcceptedRoute { ip })
891 .await
892 .map_err(ts_runtime::Error::from)
893 .map_err(Into::into)
894 }
895
896 /// List the Taildrop files this device has fully received and not yet consumed (Go LocalAPI
897 /// `WaitingFiles`).
898 ///
899 /// Returns the files waiting under the configured `taildrop_dir`, sorted by name. Returns an
900 /// empty list when Taildrop is disabled (`Config::taildrop_dir` unset) — fail-closed, never an
901 /// error for the disabled case. A filesystem error while listing surfaces as
902 /// [`InternalErrorKind::Actor`].
903 pub fn taildrop_waiting_files(&self) -> Result<Vec<WaitingFile>, Error> {
904 let Some(store) = self.runtime.taildrop_store() else {
905 return Ok(Vec::new());
906 };
907 store
908 .waiting_files()
909 .map_err(|_| Error::Internal(InternalErrorKind::Actor))
910 }
911
912 /// Open a received Taildrop file by name for reading, returning the handle and its size (Go
913 /// LocalAPI `OpenFile`).
914 ///
915 /// The `name` is validated (path-traversal-safe) inside the store before any path is built.
916 /// Returns [`InternalErrorKind::BadRequest`] when Taildrop is disabled or the name is invalid,
917 /// and [`InternalErrorKind::Actor`] for a filesystem error (e.g. the file does not exist).
918 pub fn taildrop_open_file(&self, name: &str) -> Result<(std::fs::File, u64), Error> {
919 let store = self
920 .runtime
921 .taildrop_store()
922 .ok_or(Error::Internal(InternalErrorKind::BadRequest))?;
923 store.open_file(name).map_err(taildrop_err)
924 }
925
926 /// Delete a received Taildrop file by name (Go LocalAPI `DeleteFile`).
927 ///
928 /// The `name` is validated (path-traversal-safe) inside the store before any path is built.
929 /// Returns [`InternalErrorKind::BadRequest`] when Taildrop is disabled or the name is invalid,
930 /// and [`InternalErrorKind::Actor`] for a filesystem error (e.g. the file does not exist).
931 pub fn taildrop_delete_file(&self, name: &str) -> Result<(), Error> {
932 let store = self
933 .runtime
934 .taildrop_store()
935 .ok_or(Error::Internal(InternalErrorKind::BadRequest))?;
936 store.delete_file(name).map_err(taildrop_err)
937 }
938
939 /// Send a local file to a tailnet `peer` via Taildrop (Go `PushFile` / `tailscale file cp`).
940 ///
941 /// Pushes `content_length` bytes from `reader` to the peer's peerAPI as
942 /// `PUT /v0/put/<name>` over the overlay netstack — the sending counterpart to the receive store
943 /// surfaced by [`Device::taildrop_waiting_files`]. The transfer rides the encrypted WireGuard
944 /// overlay, never a host socket. The body is streamed from offset 0 (no resume).
945 ///
946 /// The destination is derived **solely from `peer`'s own node record**
947 /// ([`NodeInfo::peerapi_addr`][ts_control::Node::peerapi_addr]): its advertised tailnet IPv4 and
948 /// `peerapi4` port. The caller obtains `peer` from [`Device::peer_by_name`] /
949 /// [`Device::peer_by_tailnet_ip`], so it is always a current netmap peer — a raw control-supplied
950 /// or attacker-chosen address can never be targeted. As defense in depth, the resolved address is
951 /// additionally asserted to be a Tailscale CGNAT IP before dialing.
952 ///
953 /// Returns [`InternalErrorKind::BadRequest`] when the peer advertises no IPv4 peerAPI (so it
954 /// cannot receive files), when the name is invalid, or when the peer refuses the transfer
955 /// (`403`/`409`/unexpected status); [`Error::Timeout`] on a dial failure or timeout; and
956 /// [`InternalErrorKind::Io`] on a mid-transfer stream error.
957 pub async fn send_file<R>(
958 &self,
959 peer: &NodeInfo,
960 name: &str,
961 content_length: u64,
962 reader: R,
963 ) -> Result<(), Error>
964 where
965 R: tokio::io::AsyncRead + Unpin,
966 {
967 let channel = self.channel()?;
968
969 // Destination comes only from the peer's own node record — never an arbitrary address.
970 let dst = peer
971 .peerapi_addr()
972 .ok_or(Error::Internal(InternalErrorKind::BadRequest))?;
973 // Defense in depth: refuse to dial anything outside the Tailscale CGNAT range, so a
974 // malformed node record can't steer the PUT at a non-tailnet host.
975 if !ts_control::is_tailscale_ip(dst.ip()) {
976 return Err(Error::Internal(InternalErrorKind::BadRequest));
977 }
978
979 let self_ipv4 = self.ipv4_addr().await?;
980
981 ts_runtime::taildrop_send::send_file(channel, self_ipv4, dst, name, content_length, reader)
982 .await
983 .map_err(taildrop_send_err)
984 }
985
986 /// List the tailnet peers this node can Taildrop a file *to* — the Rust analog of Go's LocalAPI
987 /// `FileTargets`.
988 ///
989 /// Each [`FileTarget`] pairs a peer's node record with the `http://ip:port` base of its peerAPI;
990 /// pass `target.node` straight to [`Device::send_file`]. A peer qualifies when it advertises a
991 /// reachable IPv4 peerAPI **and** is either owned by the same user as this node **or** explicitly
992 /// granted the file-sharing-target capability — mirroring upstream's send-path filter. The list is
993 /// gated on this node holding the file-sharing capability (control grants it when the admin
994 /// enables Taildrop); absent that, the result is empty (fail-closed, not an error). Sorted by the
995 /// peer's MagicDNS name. Targets are listed regardless of online state (matching upstream — an
996 /// offline target's [`send_file`](Device::send_file) simply times out). Empty before the first
997 /// netmap.
998 pub async fn file_targets(&self) -> Result<Vec<FileTarget>, Error> {
999 self.runtime.file_targets().await.map_err(Into::into)
1000 }
1001
1002 /// Begin a debug packet capture, streaming a pcap of every packet crossing the dataplane to
1003 /// `writer` (Go `tsnet.Server.CapturePcap`).
1004 ///
1005 /// Installs a capture hook on the running dataplane: from now until [`Device::stop_capture`] is
1006 /// called (or another capture replaces this one), a copy of every plaintext IP packet on the
1007 /// datapath — outbound (pre-encrypt) and inbound (post-decrypt) — is framed and written to
1008 /// `writer`. The 24-byte pcap global header is written immediately on success.
1009 ///
1010 /// The format is byte-faithful classic pcap with Tailscale's `LINKTYPE_USER0` + 4-byte path
1011 /// preamble per record (see [`ts_runtime::capture`]); a resulting file opens in Wireshark, and
1012 /// with Tailscale's `ts-dissector.lua` the direction/path of each packet decodes.
1013 ///
1014 /// The hook runs **inline on the single-threaded dataplane step**, so `writer` must not block for
1015 /// long — a slow writer back-pressures the datapath. Records are **not** flushed per packet (that
1016 /// would be a syscall on every packet on the dataplane thread); buffered bytes are flushed when
1017 /// the writer is dropped on [`Device::stop_capture`]. Wrap `writer` in a [`std::io::BufWriter`] if
1018 /// you want buffering. A write error is swallowed per-packet (the capture silently drops that
1019 /// record) rather than tearing down the datapath; call [`Device::stop_capture`] to end it. Returns
1020 /// an error only if the dataplane actor is unreachable or the initial global-header write fails.
1021 pub async fn capture_pcap<W>(&self, writer: W) -> Result<(), Error>
1022 where
1023 W: std::io::Write + Send + 'static,
1024 {
1025 let sink = std::sync::Arc::new(std::sync::Mutex::new(
1026 ts_runtime::capture::PcapSink::new(writer)
1027 .map_err(|_| Error::Internal(InternalErrorKind::Io))?,
1028 ));
1029 let hook: ts_runtime::CaptureHook = std::sync::Arc::new(move |path, pkt: &[u8]| {
1030 if let Ok(mut sink) = sink.lock() {
1031 // A per-packet write failure (e.g. a closed pipe) silently drops that record rather
1032 // than tearing down the datapath; the caller ends capture via `stop_capture`.
1033 drop(sink.log_packet(path.code(), pkt));
1034 }
1035 });
1036 self.runtime.install_capture(Some(hook)).await?;
1037 Ok(())
1038 }
1039
1040 /// Stop a debug packet capture started by [`Device::capture_pcap`] (Go `ClearCaptureSink`).
1041 ///
1042 /// Clears the dataplane capture hook; the writer is dropped (its remaining buffered bytes are
1043 /// flushed by its own `Drop`). Idempotent — clearing when no capture is installed is a no-op.
1044 /// Returns an error only if the dataplane actor is unreachable.
1045 pub async fn stop_capture(&self) -> Result<(), Error> {
1046 self.runtime.install_capture(None).await?;
1047 Ok(())
1048 }
1049
1050 /// Snapshot of this device and its tailnet peers (like `tailscale status`).
1051 ///
1052 /// Combines this node's self info with the current peer set: each [`StatusNode`] reports the
1053 /// stable id, display name, tailnet IPs, advertised routes, and exit-node flag. (Per-peer
1054 /// `online`/user/capabilities are honestly `None`/empty in this fork — the domain node model
1055 /// does not yet carry the wire-level liveness/login fields; see `ts_runtime::status` docs.)
1056 pub async fn status(&self) -> Result<Status, Error> {
1057 self.runtime.status().await.map_err(Into::into)
1058 }
1059
1060 /// Fetch the current Tailnet Lock (TKA) status pushed by control, if any.
1061 ///
1062 /// Returns `Ok(None)` when control has sent no `TKAInfo` (tailnet lock not in use, or no change
1063 /// observed yet). The returned [`TkaStatus`][ts_control::TkaStatus] carries the authority head
1064 /// (a base32 `AUMHash`, decode with [`tka::AumHash::from_base32`][ts_tka::AumHash::from_base32])
1065 /// and the disablement signal. Signature verification of a peer's node-key signature against the
1066 /// authority is performed with the [`tka`] module's [`tka::Authority`][ts_tka::Authority].
1067 pub async fn tka_status(&self) -> Result<Option<ts_control::TkaStatus>, Error> {
1068 self.runtime
1069 .control
1070 .ask(ts_runtime::control_runner::CurrentTkaStatus)
1071 .await
1072 .map_err(ts_runtime::Error::from)
1073 .map_err(Into::into)
1074 }
1075
1076 /// Request an OIDC **ID token** from control for this node, scoped to `audience` (workload-
1077 /// identity federation, like `tailscale`'s `id-token` LocalAPI).
1078 ///
1079 /// Returns a signed JWT whose `sub` claim is this node's MagicDNS name and whose `aud` claim is
1080 /// `audience`, suitable for presenting to a third-party relying party (e.g. AWS/GCP
1081 /// workload-identity federation). The node is the token *subject*, not the authenticator — this
1082 /// is token issuance over the Noise transport (`POST /machine/id-token`), not a login path.
1083 /// Requires the control plane to support capability version ≥ 30.
1084 pub async fn fetch_id_token(&self, audience: &str) -> Result<String, ts_control::IdTokenError> {
1085 self.runtime.fetch_id_token(audience.to_string()).await
1086 }
1087
1088 /// Log this node out of the tailnet — deregister it from the control plane (the equivalent of
1089 /// Go `tsnet`'s `LocalClient.Logout`).
1090 ///
1091 /// Re-`POST`s `/machine/register` with this node's current node key and a past expiry, which the
1092 /// control plane honors by **expiring the node now**: it drops out of every peer's netmap and
1093 /// must re-register (re-authenticate) to rejoin.
1094 ///
1095 /// This is primarily for **non-ephemeral** nodes. An ephemeral node is garbage-collected by
1096 /// control shortly after it disconnects, but a persistent node lingers in the tailnet
1097 /// (visible to peers, counting against the machine limit) for up to ~24h after the process exits
1098 /// unless explicitly logged out. Call this before [`shutdown`](Self::shutdown) to deregister
1099 /// immediately. Calling it on an ephemeral node simply brings the GC forward; it is idempotent,
1100 /// so logging out an already-gone node is not an error.
1101 ///
1102 /// This is a **control-plane state change only**: it does not tear down the local datapath (do
1103 /// that via [`shutdown`](Self::shutdown)), and it does not delete or rotate the on-disk node key
1104 /// — re-registering with the same key (a fresh [`Device::new`]) is the re-login path.
1105 pub async fn logout(&self) -> Result<(), ts_control::LogoutError> {
1106 self.runtime.logout().await
1107 }
1108
1109 /// Snapshot this node's client metrics in Prometheus text exposition format.
1110 ///
1111 /// Mirrors Go Tailscale's `clientmetric` registry: process-global counters/gauges incremented
1112 /// on the datapath hot loops (e.g. `magicsock_send_udp`, `magicsock_recv_data_bytes_udp`),
1113 /// rendered as `# TYPE <name> <kind>\n<name> <value>\n` per metric, sorted by name. (Go `tsnet`
1114 /// exposes no metrics method of its own, so this is the fork's clean public surface.) The
1115 /// registry is process-global, so the output covers every `Device` in the process.
1116 pub fn metrics(&self) -> String {
1117 ts_metrics::write_prometheus()
1118 }
1119
1120 /// Map a tailnet source `addr` to the node that owns its IP (like `tsnet`'s `WhoIs`).
1121 ///
1122 /// Only the IP of `addr` is used; the port is ignored. Returns `Ok(None)` if no tailnet node
1123 /// owns that address.
1124 pub async fn whois(&self, addr: SocketAddr) -> Result<Option<WhoIs>, Error> {
1125 self.runtime.whois(addr).await.map_err(Into::into)
1126 }
1127
1128 /// Change the selected exit node at runtime, without recreating the [`Device`] — the equivalent
1129 /// of Go `tsnet`'s `LocalClient.EditPrefs(ExitNodeID/ExitNodeIP)`.
1130 ///
1131 /// The peer may be named by stable node ID, tailnet IP, or MagicDNS name via
1132 /// [`ExitNodeSelector`] (a bare IP or name parses with `selector.parse()`); this is the same
1133 /// selector type as [`Config::exit_node`](crate::Config::exit_node), so the construction-time
1134 /// and runtime paths are identical. Passing `None` clears the exit node — internet-bound traffic
1135 /// is then dropped (fail-closed) unless this node egresses directly.
1136 ///
1137 /// The change is applied immediately: the new selector is re-resolved against the live peer set
1138 /// and the outbound route + inbound source filter are recomputed at once. A selector for a peer
1139 /// not yet in the netmap simply takes effect once that peer appears.
1140 ///
1141 /// Only NEW flows use the changed exit; in-flight connections are not torn down and continue
1142 /// egressing via the previously-selected exit until they close.
1143 pub async fn set_exit_node(&self, exit_node: Option<ExitNodeSelector>) -> Result<(), Error> {
1144 self.runtime
1145 .set_exit_node(exit_node)
1146 .await
1147 .map_err(Into::into)
1148 }
1149
1150 /// The currently-selected exit node, or `None` if none is selected.
1151 pub fn exit_node(&self) -> Option<ExitNodeSelector> {
1152 self.runtime.exit_node()
1153 }
1154
1155 /// Re-bind the underlay UDP socket after a **network/link change** — Wi-Fi switch, sleep/wake,
1156 /// or any event that invalidates the device's local address/NAT mapping. This is the Rust
1157 /// analog of Go magicsock's `Conn.Rebind()`.
1158 ///
1159 /// The embedder owns deciding *when* to call this (it watches the OS for link changes — there is
1160 /// no built-in network monitor); `rebind` is the engine half that does the socket work:
1161 /// - Re-binds the underlay UDP socket, preferring the same local port (so the advertised
1162 /// endpoint stays stable) and falling back to an ephemeral port. The IPv4-only-by-default
1163 /// invariant is preserved.
1164 /// - Invalidates the now-stale local mapping: learned reflexive (STUN) addresses and every
1165 /// peer's *confirmed* direct path are cleared, while candidate endpoints are kept — so peers
1166 /// are re-probed over the new socket and **relay over DERP (never a direct host dial) until a
1167 /// path re-confirms**. Endpoint discovery re-runs on its normal cadence.
1168 /// - Leaves peers, control, the netmap, disco keys, and DERP connections untouched; existing
1169 /// WireGuard sessions survive (they ride whatever underlay carries them).
1170 ///
1171 /// A no-op if the underlay socket failed to bind at startup (the device is DERP-only). Existing
1172 /// connectivity is preserved on a re-bind error (the old socket is kept; the error is returned).
1173 pub async fn rebind(&self) -> Result<(), Error> {
1174 self.runtime.rebind().await.map_err(Into::into)
1175 }
1176
1177 /// The stable id of the exit node traffic is **currently** egressing through, or `None` if none
1178 /// is engaged (the equivalent of Go `tsnet`'s `Status.ExitNodeStatus.ID`).
1179 ///
1180 /// This differs from [`exit_node`](Self::exit_node), which returns the *configured* selector:
1181 /// the active exit node is the route updater's resolved, fail-closed answer. It is `None` when
1182 /// no exit node is configured, the configured selector matches no current peer, or the matched
1183 /// peer no longer advertises a default route (egress is then dropped, fail-closed). Match the id
1184 /// against [`Status::peers`](crate::Status::peers) (via [`status`](Self::status)) for details.
1185 pub fn active_exit_node(&self) -> Option<ts_control::StableNodeId> {
1186 self.runtime.active_exit_node()
1187 }
1188
1189 /// Watch for netmap changes: the returned receiver's value is the current set of peer
1190 /// [`StatusNode`]s and updates on every netmap change (like subscribing to `ipn` notifications).
1191 pub async fn watch_netmap(
1192 &self,
1193 ) -> Result<tokio::sync::watch::Receiver<Vec<StatusNode>>, Error> {
1194 self.runtime.watch_netmap().await.map_err(Into::into)
1195 }
1196
1197 /// The current device connection-[`DeviceState`] (`Connecting` / `Running` / `NeedsLogin` /
1198 /// `Expired` / `Failed`).
1199 pub fn device_state(&self) -> DeviceState {
1200 self.runtime.device_state()
1201 }
1202
1203 /// Watch the device connection-[`DeviceState`], reacting push-style to control connection
1204 /// transitions instead of polling [`status`](Self::status).
1205 ///
1206 /// Returns a [`tokio::sync::watch::Receiver`]; await its
1207 /// [`changed`](tokio::sync::watch::Receiver::changed) to be woken on each transition. The
1208 /// initial value is the current state.
1209 pub fn watch_state(&self) -> tokio::sync::watch::Receiver<DeviceState> {
1210 self.runtime.watch_state()
1211 }
1212
1213 /// Wait until the device finishes registering, returning a typed outcome — the clean
1214 /// replacement for polling [`ipv4_addr`](Self::ipv4_addr) in a loop.
1215 ///
1216 /// Resolves `Ok(())` once the device is [`DeviceState::Running`]. On a non-running outcome it
1217 /// returns a typed [`RegistrationError`]:
1218 /// - [`AuthRejected`](RegistrationError::AuthRejected) — bad/expired/unknown auth key;
1219 /// **permanent** (re-pair).
1220 /// - [`NeedsLogin`](RegistrationError::NeedsLogin) — interactive authorization required;
1221 /// **not permanent** (the runtime keeps retrying and reaches `Running` once the user
1222 /// authorizes). Auth-key callers treat this as failure; interactive callers should ignore it
1223 /// and drive the flow via [`watch_state`](Self::watch_state).
1224 /// - [`NetworkUnreachable`](RegistrationError::NetworkUnreachable) — **transient** (retry).
1225 /// - [`Timeout`](RegistrationError::Timeout) — no settled state within `timeout` (`None` waits
1226 /// indefinitely).
1227 ///
1228 /// [`KeyExpired`](RegistrationError::KeyExpired) is not produced here (a key expires only after
1229 /// the node is up); observe it via [`watch_state`](Self::watch_state). Use
1230 /// [`RegistrationError::is_permanent`] to branch "re-pair" vs. "retry / drive login".
1231 pub async fn wait_until_running(
1232 &self,
1233 timeout: Option<Duration>,
1234 ) -> Result<(), RegistrationError> {
1235 self.runtime.wait_until_running(timeout).await
1236 }
1237
1238 /// Ping a tailnet peer over the overlay with an ICMPv4 echo, returning the round-trip time
1239 /// (like `tailscale ping`).
1240 ///
1241 /// The echo is sent from this device's own tailnet IPv4 over the overlay netstack — never a
1242 /// host socket. IPv6 destinations return [`PingError::Ipv6Unsupported`] (this fork is
1243 /// IPv4-only on the tailnet). A peer answers from its own OS stack; this netstack does not
1244 /// auto-reply to echo requests.
1245 ///
1246 /// In TUN transport mode there is no application netstack to ping from; this surfaces as
1247 /// [`PingError::Timeout`] (the same error this method already uses for an unavailable source
1248 /// address — `PingError` carries no dedicated "unsupported" variant).
1249 pub async fn ping(&self, dst: IpAddr, timeout: Duration) -> Result<Duration, PingError> {
1250 let channel = self.channel().map_err(|_| PingError::Timeout)?;
1251 let src = self.ipv4_addr().await.map_err(|_| PingError::Timeout)?;
1252 ts_netstack_smoltcp::ping(channel, src, dst, timeout).await
1253 }
1254
1255 /// Obtain a TLS certificate for a node's MagicDNS `name` (like `tsnet`'s `GetCertificate`).
1256 ///
1257 /// **Fail-closed without the `acme` feature.** By default this fork has no client-side ACME
1258 /// engine wired in, so this returns [`ts_control::CertError::Unimplemented`] (after a
1259 /// tailnet-name check) — it NEVER self-signs and NEVER returns a placeholder certificate
1260 /// ([`ts_control::MISSING_CERT_RPC`] names what is missing).
1261 ///
1262 /// **With the `acme` feature** this instead drives the client-side ACME DNS-01 engine to issue a
1263 /// real Let's Encrypt certificate for `name`, publishing the challenge TXT via the node's
1264 /// `POST /machine/set-dns` RPC (routed through the control runner). SaaS-only: a self-hosted
1265 /// control plane may 501 on set-dns, surfaced as [`ts_control::CertError::Acme`].
1266 #[cfg(not(feature = "acme"))]
1267 pub async fn get_certificate(&self, name: &str) -> Result<CertifiedKey, ts_control::CertError> {
1268 ts_control::get_certificate(name).await
1269 }
1270
1271 /// See the no-`acme` variant for the contract; with `acme` this issues a real cert via the
1272 /// runtime's ACME engine (`Device → Runtime → ControlRunner → issue_certificate_via_setdns`).
1273 #[cfg(feature = "acme")]
1274 pub async fn get_certificate(&self, name: &str) -> Result<CertifiedKey, ts_control::CertError> {
1275 self.runtime.get_certificate(name.to_string()).await
1276 }
1277
1278 /// Build a [`TlsAcceptor`] terminating TLS for `cfg.name` on the overlay (like `tsnet`'s
1279 /// `ListenTLS`).
1280 ///
1281 /// Obtains the certificate via [`Device::get_certificate`] — so with the `acme` feature this
1282 /// issues a real Let's Encrypt cert (when the control plane answers `set-dns`), and without it
1283 /// (or when issuance is unavailable) it surfaces the same fail-closed
1284 /// [`ts_control::CertError`] rather than ever serving a self-signed cert or downgrading to
1285 /// plaintext. Terminate accepted overlay streams with [`ts_control::accept_tls`].
1286 pub async fn listen_tls(
1287 &self,
1288 cfg: &ts_control::ServeConfig,
1289 ) -> Result<TlsAcceptor, ts_control::CertError> {
1290 // Route through Device::get_certificate (the acme-aware issuance path) rather than
1291 // ts_control::listen_tls, which only knows the non-acme stub. Validate the serve config
1292 // first (same fail-closed checks ts_control::listen_tls applies), then assemble the acceptor.
1293 cfg.validate()?;
1294 let cert = self.get_certificate(&cfg.name).await?;
1295 ts_control::tls_acceptor(cert)
1296 }
1297
1298 /// The currently-stored Serve config (like `tsnet`'s `GetServeConfig`).
1299 ///
1300 /// Returns the config last passed to [`Device::set_serve_config`], or an empty
1301 /// [`ts_control::ServeState`] (no ports) if none was ever set. Pure read — does not touch the
1302 /// network.
1303 pub fn get_serve_config(&self) -> ts_control::ServeState {
1304 match &*self.serve.lock().unwrap_or_else(|e| e.into_inner()) {
1305 Some(mgr) => mgr.get(),
1306 None => ts_control::ServeState::default(),
1307 }
1308 }
1309
1310 /// Replace this node's Serve config and (re)bind its tailnet ports (like `tsnet`'s
1311 /// `SetServeConfig`, REPLACE semantics).
1312 ///
1313 /// `state` becomes the **whole** config (full-replace reconcile: every previously-bound serve
1314 /// port's accept loop is torn down and the new config's ports are bound from scratch). For each
1315 /// configured port the manager binds an overlay listener on this node's tailnet IPv4 and
1316 /// dispatches per [`ts_control::ServeTarget`]:
1317 /// - [`Accept`](ts_control::ServeTarget::Accept) — the TLS-terminated stream is handed back over
1318 /// the returned [`ServeAcceptedReceiver`](ts_runtime::serve::ServeAcceptedReceiver) (the
1319 /// in-process stand-in for `ListenTLS`'s `net.Listener`).
1320 /// - [`Proxy`](ts_control::ServeTarget::Proxy) — reverse-proxy the decrypted stream to a local
1321 /// host backend.
1322 /// - [`Text`](ts_control::ServeTarget::Text) — write a fixed body and close.
1323 /// - [`TcpForward`](ts_control::ServeTarget::TcpForward) — forward the **raw** (non-TLS) stream
1324 /// to a local host backend.
1325 ///
1326 /// **Fail-closed.** `state.validate()` runs first. Every TLS-terminating port's acceptor is
1327 /// obtained up-front via [`Device::listen_tls`] (the ACME-aware cert path); if any cert cannot be
1328 /// issued the whole call fails with that [`ts_control::CertError`] and **nothing is bound** — a
1329 /// TLS port never downgrades to plaintext.
1330 ///
1331 /// **Anti-leak.** Listeners bind the overlay netstack only (never a host socket). The
1332 /// `Proxy`/`TcpForward` backend dial is a local host socket to the embedder's own backend (like
1333 /// Go's reverse-proxy to `127.0.0.1`), intentionally NOT routed through the exit-egress
1334 /// forwarder. A backend dial failure drops that connection; it never falls back.
1335 ///
1336 /// Returns an error in TUN transport mode (there is no application netstack to bind on). The
1337 /// previous config's accept loops (and any earlier `ServeAcceptedReceiver`) stop when this
1338 /// returns; the new receiver delivers every `Accept`-port connection.
1339 pub async fn set_serve_config(
1340 &self,
1341 state: ts_control::ServeState,
1342 ) -> Result<ts_runtime::serve::ServeAcceptedReceiver, Error> {
1343 state
1344 .validate()
1345 .map_err(|_| Error::Internal(InternalErrorKind::BadRequest))?;
1346
1347 // Fail-closed: build every TLS-terminating port's acceptor up-front via the ACME-aware cert
1348 // path. If any cert can't be issued, return before binding anything (no plaintext downgrade).
1349 let mut resolved = std::collections::BTreeMap::new();
1350 for (port, target) in &state.ports {
1351 let acceptor = if target.terminates_tls() {
1352 let cfg = ts_control::ServeConfig {
1353 name: state.name.clone(),
1354 port: *port,
1355 target: target.clone(),
1356 };
1357 Some(self.listen_tls(&cfg).await.map_err(|_| {
1358 // Cert issuance is fail-closed in this fork; surface as a request error rather
1359 // than ever binding a plaintext TLS port.
1360 Error::Internal(InternalErrorKind::BadRequest)
1361 })?)
1362 } else {
1363 None
1364 };
1365 resolved.insert(
1366 *port,
1367 ts_runtime::serve::ResolvedPort {
1368 target: target.clone(),
1369 acceptor,
1370 },
1371 );
1372 }
1373
1374 // The manager binds the OVERLAY netstack on this node's own tailnet IPv4.
1375 let self_ipv4 = self.ipv4_addr().await?;
1376 let channel = self.channel()?.clone();
1377
1378 let mut slot = self.serve.lock().unwrap_or_else(|e| e.into_inner());
1379 let mgr =
1380 slot.get_or_insert_with(|| ts_runtime::serve::ServeManager::new(channel, self_ipv4));
1381 Ok(mgr.set(state, resolved))
1382 }
1383
1384 /// Expose a tailnet TLS service to the public internet via Tailscale Funnel (like `tsnet`'s
1385 /// `ListenFunnel`), returning a [`FunnelAcceptedReceiver`](ts_runtime::funnel::FunnelAcceptedReceiver)
1386 /// that delivers each TLS-terminated public connection.
1387 ///
1388 /// **Two fail-closed gates, then the live ingress listener.** First the node-attribute gate is
1389 /// fully enforced from this node's own capability map (mirroring Go `ipn.NodeCanFunnel` +
1390 /// `ipn.CheckFunnelPort`): the tailnet admin must have enabled HTTPS and granted the `funnel`
1391 /// node attribute, and `cfg.port` must be in the set the `funnel-ports` capability allows —
1392 /// otherwise this returns [`ts_control::FunnelError::NotAllowed`] /
1393 /// [`ts_control::FunnelError::PortNotAllowed`] before touching any cert or network. Then the
1394 /// node's `*.ts.net` certificate is obtained via the ACME-aware [`Device::get_certificate`] (the
1395 /// Funnel hostname *is* the node's MagicDNS name, so its DNS-01 cert matches); fail-closed on
1396 /// [`ts_control::FunnelError::Cert`] — no self-signed or plaintext fallback.
1397 ///
1398 /// On success a [`FunnelManager`](ts_runtime::funnel::FunnelManager) is registered: its ingress
1399 /// sink is installed into the runtime's peerAPI `/v0/ingress` slot (making that route live without
1400 /// restarting the peerAPI server), and the `HostInfo.IngressEnabled` map-request signal is set so
1401 /// control routes Funnel traffic to this node. Public Funnel bytes arrive as a relay POST to
1402 /// `/v0/ingress`, are membership-gated + `101`-hijacked into a raw stream, TLS-terminated by the
1403 /// manager, and delivered over the returned receiver.
1404 ///
1405 /// **Where the relay comes from.** The public ingress **relay + DNS mapping** that feed
1406 /// `/v0/ingress` are Tailscale infrastructure ([`ts_control::MISSING_FUNNEL_RELAY`]), provisioned
1407 /// automatically against real Tailscale SaaS with a Funnel-enabled ACL; against a self-hosted
1408 /// control plane no relay exists, so the listener is correct but never fed.
1409 ///
1410 /// Anti-leak: Funnel TLS terminates only on the overlay netstack (the hijacked ingress stream
1411 /// arrives on the overlay peerAPI listener), never a host socket; there is no self-signed or
1412 /// plaintext fallback. A new `listen_funnel` replaces the previous manager (its pump + sink tear
1413 /// down); dropping the `Device` tears it down too.
1414 pub async fn listen_funnel(
1415 &self,
1416 cfg: &ts_control::ServeConfig,
1417 opts: ts_control::FunnelOptions,
1418 ) -> Result<ts_runtime::funnel::FunnelAcceptedReceiver, ts_control::FunnelError> {
1419 // Gate 1 (fail-closed, no network): node-attribute + funnel-port access from our cap map.
1420 let me = self
1421 .self_node()
1422 .await
1423 .map_err(|_| ts_control::FunnelError::NotAllowed)?;
1424 cfg.validate()?;
1425 ts_control::funnel_access(&me, cfg.port)?;
1426
1427 // Gate 2 (fail-closed): obtain the node's `*.ts.net` cert via the ACME-aware path and build
1428 // the TLS acceptor. A cert failure surfaces as FunnelError::Cert — never a plaintext listener.
1429 let cert = self
1430 .get_certificate(&cfg.name)
1431 .await
1432 .map_err(ts_control::FunnelError::Cert)?;
1433 let acceptor = ts_control::tls_acceptor(cert).map_err(ts_control::FunnelError::Cert)?;
1434
1435 // `opts.funnel_only` (reject tailnet-internal connections) is accepted for surface stability;
1436 // the ingress data path only ever carries relay-delivered public traffic, so there is no
1437 // tailnet-internal leg on this listener to reject. Documented as a no-op here for now.
1438 let _ = opts;
1439
1440 // Build the funnel manager + its ingress sink + the hand-back receiver, install the sink into
1441 // the runtime's shared peerAPI `/v0/ingress` slot (making the route live), and flip the
1442 // IngressEnabled map signal. Hold the manager on the device so its pump/sink live as long as
1443 // the listener; replacing a prior manager tears the old one down on drop at end of scope.
1444 let (manager, sink, receiver) = ts_runtime::funnel::FunnelManager::new(acceptor);
1445 {
1446 let slot = self.runtime.funnel_ingress_slot();
1447 *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(sink);
1448 }
1449 self.runtime
1450 .ingress_active_flag()
1451 .store(true, std::sync::atomic::Ordering::Relaxed);
1452
1453 let old = {
1454 let mut held = self.funnel.lock().unwrap_or_else(|e| e.into_inner());
1455 held.replace(manager)
1456 };
1457 drop(old);
1458
1459 Ok(receiver)
1460 }
1461
1462 /// Host a Tailscale **VIP service** (`svc:<label>`) by binding an overlay listener on the
1463 /// service's control-assigned virtual IP (like `tsnet`'s `ListenService`).
1464 ///
1465 /// **Fail-closed.** Mirrors Go `tsnet.Server.ListenService`'s preconditions, enforced from this
1466 /// node's own netmap state ([`ts_control::resolve_service_listen`]): the `name` must be a valid
1467 /// `svc:<dns-label>`, this node must be **tagged** (Go `ErrUntaggedServiceHost`), and control
1468 /// must have assigned the service a VIP address on this node (delivered via the `service-host`
1469 /// node-capability — see [`ts_control::Node::service_addresses`]). Any unmet precondition
1470 /// returns a typed [`ts_control::ServiceError`] before binding anything.
1471 ///
1472 /// When all hold, this binds a [`tcp_listen`][Device::tcp_listen] on the service VIP and the
1473 /// configured `mode` port over the **overlay netstack** (never a host socket) and returns the
1474 /// listener. The netstack already accepts packets for control-assigned VIPs (they are injected
1475 /// alongside the node's own tailnet address), so the listener is reachable by tailnet peers.
1476 ///
1477 /// The `Tun`/L3 service mode is unsupported (a TODO in upstream tsnet); only TCP/HTTP modes
1478 /// (which bind the same VIP:port at the listen layer) are offered. Returns an error in TUN
1479 /// transport mode (there is no application netstack to bind on).
1480 pub async fn listen_service(
1481 &self,
1482 name: &str,
1483 mode: ts_control::ServiceMode,
1484 ) -> Result<netstack::TcpListener, ts_control::ServiceError> {
1485 let me = self
1486 .self_node()
1487 .await
1488 .map_err(|e| ts_control::ServiceError::Listen(e.to_string()))?;
1489 let listen_addr = ts_control::resolve_service_listen(&me, name, mode, self.enable_ipv6)?;
1490 self.tcp_listen(listen_addr)
1491 .await
1492 .map_err(|e| ts_control::ServiceError::Listen(e.to_string()))
1493 }
1494
1495 /// Attempt to gracefully shut down this device's runtime.
1496 ///
1497 /// Reports whether the device was fully shut down before the timeout. It is still shut
1498 /// down if it timed out, just more violently and with potential resource leaks.
1499 ///
1500 /// If `timeout` is `None`, then shutdown will never time-out.
1501 pub async fn shutdown(self, timeout: Option<Duration>) -> bool {
1502 self.runtime.graceful_shutdown(timeout).await
1503 }
1504}
1505
1506/// Command-channel-driven userspace network stack.
1507///
1508/// This is an opinionated wrapper around [smoltcp](https://docs.rs/smoltcp) that provides an
1509/// easier-to-integrate, more-portable API.
1510pub mod netstack {
1511 #[doc(inline)]
1512 pub use ts_netstack_smoltcp::netcore::Error;
1513 #[doc(inline)]
1514 pub use ts_netstack_smoltcp::netcore::InternalErrorKind;
1515 #[doc(inline)]
1516 pub use ts_netstack_smoltcp::netsock::{TcpListener, TcpStream, UdpSocket};
1517}
1518
1519/// Geneve (RFC 8926) framing for Tailscale **peer-relay** traffic. A peer that advertises
1520/// [`NodeInfo::is_peer_relay`] runs a UDP relay server; relayed disco + WireGuard frames are
1521/// Geneve-encapsulated with a VNI. This module exposes the header codec so the framing is
1522/// recognizable. NOTE: the active relay *data path* (the relay-allocation handshake +
1523/// magicsock integration) is **not yet implemented** in this fork — this is the wire-aware slice.
1524pub mod geneve {
1525 #[doc(inline)]
1526 pub use ts_packet::geneve::{
1527 GENEVE_FIXED_HEADER_LEN, GENEVE_PROTOCOL_DISCO, GENEVE_PROTOCOL_WIREGUARD, GeneveError,
1528 GeneveHeader,
1529 };
1530}
1531
1532/// Tailnet Lock (TKA) verification: the [`tka::Authority`] checks a peer's node-key signature
1533/// against the trusted-key state, mirroring Go's `tka` package. Pair with [`Device::tka_status`]
1534/// (the control-pushed head/disablement signal).
1535pub mod tka {
1536 #[doc(inline)]
1537 pub use ts_tka::{
1538 AumHash, AumKind, Authority, Key, KeyKind, NodeKeySignature, SigKind, State, TkaError,
1539 aum_hash,
1540 };
1541}
1542
1543/// Tailscale cryptographic key types.
1544pub mod keys {
1545 #[doc(inline)]
1546 pub use ts_keys::{
1547 DiscoKeyPair, DiscoPrivateKey, DiscoPublicKey, MachineKeyPair, MachinePrivateKey,
1548 MachinePublicKey, NetworkLockKeyPair, NetworkLockPrivateKey, NetworkLockPublicKey,
1549 NodeKeyPair, NodePrivateKey, NodePublicKey, NodeState, PersistState,
1550 };
1551}
1552
1553const ENV_MAGIC_VAR: &str = "TS_RS_EXPERIMENT";
1554const ENV_MAGIC_VALUE: &str = "this_is_unstable_software";
1555
1556fn check_magic_env() -> Result<(), Error> {
1557 if std::env::var(ENV_MAGIC_VAR).as_deref() != Ok(ENV_MAGIC_VALUE) {
1558 let warning = format!(
1559 "
1560check failed: set {ENV_MAGIC_VAR}={ENV_MAGIC_VALUE} to acknowledge that tailscale-rs is early-days
1561experimental software containing bugs, unvalidated cryptography, and no stability or compatibility
1562guarantees.
1563 "
1564 );
1565
1566 eprintln!("{}", warning.trim());
1567
1568 return Err(Error::UnstableEnvVar);
1569 };
1570
1571 Ok(())
1572}
1573
1574#[cfg(test)]
1575mod tests {
1576 use secrecy::ExposeSecret as _;
1577
1578 use super::*;
1579
1580 // `Device::new`/`new_with_secret` cannot be unit-tested end-to-end without a live control
1581 // server (registration). The only behavioral difference `new_with_secret` introduces over `new`
1582 // is exposing the `SecretString` to a plain `String` on the last inch; everything after is the
1583 // shared `new` path. So we assert that equivalence at the auth-key-resolution level: the secret
1584 // path must resolve to the exact same key the plain path feeds into `resolve_auth_key`.
1585 const SAMPLE_KEY: &str = "tskey-auth-koCgSLP5R811CNTRL-EXAMPLEEXAMPLEEXAMPLEEXAMPLE";
1586
1587 // The mapping `new_with_secret` applies (`Option<SecretString>` -> `Option<String>`) must be a
1588 // byte-for-byte round-trip, so the spawn arg is identical to a direct `new(config, Some(..))`.
1589 #[test]
1590 fn secret_exposes_to_identical_string() {
1591 let plain = Some(SAMPLE_KEY.to_string());
1592 let from_secret =
1593 Some(SecretString::from(SAMPLE_KEY)).map(|s| s.expose_secret().to_string());
1594 assert_eq!(from_secret, plain);
1595
1596 // `None` must pass through unchanged (so it falls back to `config.auth_key` exactly as `new`).
1597 let none_secret: Option<SecretString> = None;
1598 assert_eq!(
1599 none_secret.map(|s| s.expose_secret().to_string()),
1600 None::<String>
1601 );
1602 }
1603
1604 // End-to-end equivalence at the resolve layer: feeding the exposed secret through
1605 // `resolve_auth_key` yields the same `Option<String>` as feeding the plain string — i.e. both
1606 // constructors reach the same spawn argument, without registering against a control server.
1607 #[tokio::test]
1608 async fn new_with_secret_resolves_same_as_new() {
1609 let config = Config::default();
1610
1611 let via_plain = resolve_auth_key(&config, Some(SAMPLE_KEY.to_string()))
1612 .await
1613 .expect("plain auth key resolves");
1614
1615 let exposed = Some(SecretString::from(SAMPLE_KEY)).map(|s| s.expose_secret().to_string());
1616 let via_secret = resolve_auth_key(&config, exposed)
1617 .await
1618 .expect("secret-derived auth key resolves");
1619
1620 assert_eq!(via_plain, via_secret);
1621 // Without the `identity-federation` feature `resolve_auth_key` is a pass-through, so the
1622 // resolved key is the input verbatim; assert that too to pin the default-build behavior.
1623 #[cfg(not(feature = "identity-federation"))]
1624 assert_eq!(via_secret, Some(SAMPLE_KEY.to_string()));
1625 }
1626}