Skip to main content

ts_control/
config.rs

1use core::fmt::Debug;
2use std::net::SocketAddr;
3
4use url::Url;
5
6lazy_static::lazy_static! {
7    /// The default [`Url`] of the control plane server (aka "coordination server").
8    pub static ref DEFAULT_CONTROL_SERVER: Url = Url::parse("https://controlplane.tailscale.com/").unwrap();
9}
10
11/// Upstream-proxy wire protocol for [`ExitProxyConfig`]. Mirrors `ts_forwarder::ProxyScheme`;
12/// kept as a separate type here because `ts_control` must not depend on `ts_forwarder` (the
13/// runtime converts between them at the boundary).
14#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
15pub enum ExitProxyScheme {
16    /// SOCKS5 (RFC 1928), with optional username/password auth (RFC 1929).
17    Socks5,
18    /// HTTP `CONNECT` tunnelling, with optional `Proxy-Authorization: Basic` auth.
19    HttpConnect,
20}
21
22/// Transport-only description of an upstream proxy that exit-node egress is routed through, so a
23/// cloud exit node egresses via the proxy's (e.g. residential) IP rather than its own origin IP.
24///
25/// This is **not** read inside `ts_control`; like the other dataplane fields on [`Config`] it is
26/// carried for transport only and converted to a `ts_forwarder::ProxyConfig` by the runtime. It is
27/// only consulted when [`Config::forward_exit_egress`] is `true` (the anti-leak opt-in); on its own
28/// it changes nothing. See the proxy-egress docs in the repo's `AGENTS.md`/`CLAUDE.md`.
29#[derive(Clone, serde::Serialize, serde::Deserialize)]
30pub struct ExitProxyConfig {
31    /// Address of the upstream proxy to connect to.
32    pub addr: SocketAddr,
33    /// Wire protocol to speak to the proxy.
34    pub scheme: ExitProxyScheme,
35    /// Optional `(username, password)` credentials for proxy auth.
36    pub auth: Option<(String, String)>,
37}
38
39// Manual Debug that NEVER prints the proxy credentials, mirroring `ts_forwarder::ProxyConfig`. A
40// stray `tracing!(?cfg)` or `{:?}` must not leak the residential-proxy username/password.
41impl Debug for ExitProxyConfig {
42    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
43        f.debug_struct("ExitProxyConfig")
44            .field("addr", &self.addr)
45            .field("scheme", &self.scheme)
46            .field("auth", &self.auth.as_ref().map(|_| "<redacted>"))
47            .finish()
48    }
49}
50
51/// How the node's **application** overlay data path is realized.
52///
53/// Defaults to [`Netstack`](TransportMode::Netstack), the userspace smoltcp netstack that needs no
54/// privileges and is the right choice for the fork's primary deployment (a privacy proxy / cloud
55/// exit node running unprivileged in a container). [`Tun`](TransportMode::Tun) instead hands the
56/// node's overlay packets to a real kernel TUN interface, for embedders that want the host OS
57/// networking stack (routes, sockets, DNS) to see the tailnet directly — closer to `tailscaled`'s
58/// model than to Go `tsnet`'s in-process netstack.
59///
60/// Like the other dataplane fields this is **not read inside `ts_control`**: it is carried for
61/// transport only and converted to a `ts_transport_tun` config by the runtime at the `ts_runtime`
62/// boundary (`ts_control` must not depend on `ts_transport_tun`). The mode governs only the
63/// application data path; it never changes the exit-node / forwarder egress path, which stays its
64/// own IPv4-only userspace netstack regardless.
65#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
66#[serde(rename_all = "snake_case")]
67pub enum TransportMode {
68    /// Userspace smoltcp netstack (default). No privileges required.
69    #[default]
70    Netstack,
71    /// Real kernel TUN interface. Requires privileges (root / `CAP_NET_ADMIN` on Linux) and a
72    /// platform that supports TUN (Linux `/dev/net/tun`, macOS `utun`).
73    Tun(TunConfig),
74}
75
76/// Transport-only parameters for [`TransportMode::Tun`].
77///
78/// The node's tailnet *prefix* is deliberately absent: it is assigned by control and only known at
79/// runtime, so the runtime supplies it when it builds the real `ts_transport_tun::Config`. Only the
80/// user-choosable knobs live here.
81#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
82pub struct TunConfig {
83    /// Desired interface name (e.g. `tailscale0`). `None` lets the OS pick (e.g. `utunN` on macOS).
84    #[serde(default)]
85    pub name: Option<String>,
86
87    /// Interface MTU. `None` uses the transport's default. Tailscale's overlay MTU is 1280.
88    #[serde(default)]
89    pub mtu: Option<u16>,
90}
91
92/// Default for [`Config::ephemeral`]: `true`, matching the historical behavior of this client.
93fn default_ephemeral() -> bool {
94    true
95}
96
97/// Default WireGuard persistent-keepalive interval: 25s.
98///
99/// Matches Tailscale, which sets `PersistentKeepalive = 25` on a peer when control marks it
100/// `KeepAlive=true`. 25s sits just under the ~30s lower bound for UDP NAT/firewall mapping
101/// timeouts, so the mapping (and any DERP relay path) is refreshed before it can expire.
102pub const DEFAULT_PERSISTENT_KEEPALIVE: std::time::Duration = std::time::Duration::from_secs(25);
103
104/// Default for [`Config::persistent_keepalive_interval`]: `Some(25s)`
105/// ([`DEFAULT_PERSISTENT_KEEPALIVE`]). On by default so a relayed, idle session keeps its path warm
106/// and doesn't wedge the next dial.
107fn default_persistent_keepalive() -> Option<std::time::Duration> {
108    Some(DEFAULT_PERSISTENT_KEEPALIVE)
109}
110
111/// Configuration for the control server.
112#[derive(Clone, serde::Serialize, serde::Deserialize)]
113pub struct Config {
114    /// The URL of the control server to connect to.
115    pub server_url: Url,
116
117    /// The hostname of the current node.
118    pub hostname: Option<String>,
119
120    /// A name for this type of client.
121    ///
122    /// This will be reported to the control server in the `HostInfo.App` field.
123    pub client_name: Option<String>,
124
125    /// Tags to request from the control server (`--advertise-tags` / `AdvertiseTags` in the Go
126    /// client).
127    ///
128    /// Sent as `HostInfo.RequestTags` on registration and on every map request, so a
129    /// tag-keyed control ACL (e.g. a self-hosted control plane's route auto-approver) can match this node. Each
130    /// entry is a full tag string including the `tag:` prefix (e.g. `tag:exit`). Defaults to
131    /// empty (claim no tags); an empty set omits the wire field entirely.
132    #[serde(default)]
133    pub tags: Vec<String>,
134
135    /// Whether this node registers as *ephemeral* (`--ephemeral` / `Ephemeral` in the Go client).
136    ///
137    /// An ephemeral node is garbage-collected by the control server shortly after it
138    /// disconnects. That is the right default for short-lived clients, but a persistent exit node
139    /// or subnet router must set this to `false` or it will be GC'd out of the tailnet while
140    /// briefly offline. Defaults to `true` to match the historical behavior of this client.
141    #[serde(default = "default_ephemeral")]
142    pub ephemeral: bool,
143
144    /// Whether to accept subnet routes advertised by peers (`--accept-routes` / `RouteAll` in the
145    /// Go client).
146    ///
147    /// When `false` (the default, matching the Go client on Linux/server platforms and our
148    /// fail-closed posture), only each peer's own tailnet addresses are routed; larger advertised
149    /// subnet routes are ignored. When `true`, traffic destined for an accepted subnet egresses
150    /// via the advertising peer.
151    ///
152    /// This is a client-side preference and is not read inside `ts_control`: control always sends
153    /// the full set of advertised routes, and the runtime trims them. It is carried here only to
154    /// be threaded through to the runtime's route filter.
155    #[serde(default)]
156    pub accept_routes: bool,
157
158    /// Which peer (if any) to use as an exit node (`--exit-node` / `ExitNodeID` in the Go client).
159    ///
160    /// The selector may name the peer by stable id, tailnet IP, or MagicDNS name (see
161    /// [`ExitNodeSelector`](crate::ExitNodeSelector)); it is resolved against the live peer set on
162    /// every route rebuild, so an IP/name selection follows the peer across netmap changes. When
163    /// set and resolvable, the selected peer's advertised default route (`0.0.0.0/0` / `::/0`) is
164    /// installed so internet-bound traffic egresses through it. When `None` (the default) or
165    /// unresolvable, no peer receives a default route and internet-bound traffic is dropped
166    /// (fail-closed).
167    ///
168    /// Like [`accept_routes`](Config::accept_routes), this is a client-side preference not read
169    /// inside `ts_control`; it is carried here only to be threaded through to the runtime's route
170    /// filter.
171    ///
172    /// **Full-tunnel exit vs. just reaching a peer's port — leave this `None` unless you mean
173    /// full-tunnel.** Set `exit_node` *only* to route **all** internet-bound traffic through a peer
174    /// that advertises a default route (`advertise_exit_node`). To merely **reach a specific peer's
175    /// service over the tailnet** — e.g. `Device::tcp_connect` to its `100.x.y.z:1080` — you do
176    /// **not** set `exit_node` at all; direct peer dials need no exit node. Setting `exit_node` to a
177    /// peer that is only a selective CONNECT proxy (advertises no `0.0.0.0/0`) leaves egress
178    /// fail-closed and logs a warning that internet-bound traffic is dropped — which looks like a
179    /// failure but is just "that peer isn't a full-tunnel exit." If you saw that warning while only
180    /// trying to dial a peer's port, the fix is to unset `exit_node`.
181    #[serde(default)]
182    pub exit_node: Option<crate::ExitNodeSelector>,
183
184    /// Subnet routes to advertise to the control server (`--advertise-routes` / `RoutableIPs` in
185    /// the Go client).
186    ///
187    /// Unlike [`accept_routes`](Config::accept_routes)/[`exit_node`](Config::exit_node), this field
188    /// *is* read inside `ts_control`: it populates `HostInfo.RoutableIPs` on every map request so
189    /// the control server can grant this node as a subnet router. Defaults to empty (advertise
190    /// nothing — fail-closed). Only IPv4 prefixes are advertised; IPv6 prefixes are dropped to
191    /// uphold the IPv6-off posture (advertising a route we won't forward would be a black hole).
192    #[serde(default)]
193    pub advertise_routes: Vec<ipnet::IpNet>,
194
195    /// Whether to advertise this node as an exit node (`--advertise-exit-node` in the Go client).
196    ///
197    /// When `true`, the default route `0.0.0.0/0` is added to the advertised
198    /// [`routable_ips`](Config::advertise_routes) so the control server can grant this node as an
199    /// exit node, after which other peers may egress internet-bound traffic through our real IP.
200    /// Defaults to `false` (fail-closed): being an exit node means *other* peers' traffic leaves
201    /// via our real origin IP, so it must be explicit opt-in. IPv6 (`::/0`) is never advertised,
202    /// per the IPv6-off posture.
203    #[serde(default)]
204    pub advertise_exit_node: bool,
205
206    /// TCP ports the inbound forwarder accepts and splices to real OS sockets for every advertised
207    /// route (`advertise_routes` / `advertise_exit_node`).
208    ///
209    /// smoltcp has no all-port accept mode (see the `ts_forwarder` crate docs), so the forwarder
210    /// forwards a configured set of ports rather than the full 1–65535 range. Defaults to empty: a
211    /// node that advertises routes but configures no forward ports accepts inbound flows into its
212    /// dedicated forwarder netstack but forwards none of them (fail-closed — nothing is dialed).
213    #[serde(default)]
214    pub forward_tcp_ports: Vec<u16>,
215
216    /// UDP ports the inbound forwarder accepts and splices to real OS sockets for every advertised
217    /// route. See [`forward_tcp_ports`](Config::forward_tcp_ports); defaults to empty.
218    #[serde(default)]
219    pub forward_udp_ports: Vec<u16>,
220
221    /// Forward **all** TCP/UDP ports (1–65535) on every advertised route, like a Go subnet router
222    /// (`tailscale up --advertise-routes` forwards all ports), instead of the explicit
223    /// [`forward_tcp_ports`](Config::forward_tcp_ports) /
224    /// [`forward_udp_ports`](Config::forward_udp_ports) sets.
225    ///
226    /// smoltcp cannot wildcard-port-accept, so all-port mode is implemented with an on-demand
227    /// per-port listener manager driven by a raw-socket port observer on the dedicated forwarder
228    /// netstack (see the `ts_forwarder` crate docs). When `true`, the explicit port sets are
229    /// ignored. Anti-leak is unchanged: every flow still routes through the same
230    /// `RouteTable`→dialer chokepoint, so [`forward_exit_egress`](Config::forward_exit_egress) still
231    /// governs exit-node egress. Defaults to `false`.
232    #[serde(default)]
233    pub forward_all_ports: bool,
234
235    /// Whether exit-node (`0.0.0.0/0`) inbound flows are actually egressed via **this host's real
236    /// origin IP**.
237    ///
238    /// This is the anti-leak opt-in, kept separate from
239    /// [`advertise_exit_node`](Config::advertise_exit_node): advertising the default route only
240    /// makes control *offer* this node as an exit; it does not by itself egress a peer's traffic.
241    /// When `false` (the default, fail-closed), the forwarder uses a dialer that **structurally
242    /// refuses** exit-node egress — a `0.0.0.0/0` flow is dropped at dial time, never leaked out our
243    /// real IP. Set to `true` only on a node whose real IP *is* the intended egress (e.g. a
244    /// residential exit), never on a node whose host IP must stay hidden (e.g. a cloud VPS). Subnet
245    /// routes are dialed identically regardless of this flag.
246    #[serde(default)]
247    pub forward_exit_egress: bool,
248
249    /// Shields-up (Go `ipn` prefs `ShieldsUp`): when `true`, refuse all **inbound** connections from
250    /// peers that terminate on this node — the packet filter drops inbound packets aimed at this
251    /// node's own addresses. Replies to connections this node itself initiated, and forwarded
252    /// subnet/exit transit, are unaffected (the deny is scoped to self-destined packets; see
253    /// `ts_packetfilter::ShieldsUpFilter`). Transport-only client preference — `ts_control` never
254    /// reads it; the runtime's packet-filter updater consumes it. Defaults to `false`.
255    #[serde(default)]
256    pub block_incoming: bool,
257
258    /// Optional upstream proxy that exit-node egress is routed through, so the node egresses via
259    /// the proxy's IP rather than its own origin IP.
260    ///
261    /// Only consulted when [`forward_exit_egress`](Config::forward_exit_egress) is `true`. When
262    /// set, the runtime wires the forwarder with a proxy dialer (SOCKS5 / HTTP `CONNECT`) that
263    /// **fails closed** — any proxy connect or handshake failure drops the flow rather than falling
264    /// back to a direct host-IP dial, so the real origin IP never leaks. When `None` (the default)
265    /// and exit egress is enabled, egress uses this host's real IP (`HostExitDialer`).
266    ///
267    /// Like the other dataplane fields, this is a client-side preference not read inside
268    /// `ts_control`; it is carried here only to be threaded through to the runtime's dialer
269    /// selection. This is a product capability (residential-proxy egress) beyond strict tsnet
270    /// parity — see the repo's `AGENTS.md`/`CLAUDE.md`.
271    #[serde(default)]
272    pub exit_proxy: Option<ExitProxyConfig>,
273
274    /// The IPv4 peerAPI port this node binds to serve exit-node DoH (DNS-over-HTTPS) proxying for
275    /// peers that select it as their exit node (`peerapi4` + `peerapi-dns-proxy` services).
276    ///
277    /// When `Some(port)`, the runtime binds a peerAPI DoH server on this host's overlay IPv4
278    /// address at `port`, and registration / map requests advertise both the `peerapi4` service
279    /// (at `port`) and the `peerapi-dns-proxy` service (Go quirk: its advertised port is always
280    /// `1`) so peers know they can delegate DNS to us. When `None` (the default, fail-closed), no
281    /// peerAPI is run and no services are advertised — this node never offers DNS proxying.
282    ///
283    /// The DoH server always answers authoritative/overlay records (MagicDNS peer names,
284    /// `ExtraRecords`, PTR); *recursive* resolution to real upstream resolvers is gated separately
285    /// behind [`forward_exit_egress`](Config::forward_exit_egress), so a cloud exit node can serve
286    /// overlay DNS without ever exposing its real origin IP via a recursive lookup.
287    #[serde(default)]
288    pub peerapi_port: Option<u16>,
289
290    /// Filesystem directory that received Taildrop files land in, or `None` to disable Taildrop
291    /// (the default, fail-closed).
292    ///
293    /// When `Some(dir)` **and** [`peerapi_port`](Config::peerapi_port) is also set, the runtime
294    /// serves the Taildrop peerAPI route `PUT /v0/put/<name>` on the shared peerAPI listener, and
295    /// incoming files are written under `dir` (created if absent). When `None`, no Taildrop server
296    /// is run — a peer's `PUT` is refused. This is a pure on-disk destination: like the other
297    /// dataplane fields it is not read inside `ts_control`; it is carried here only to be threaded
298    /// into the runtime, which constructs the file store from it.
299    ///
300    /// Independently of the network server, the embedder consumes received files via the
301    /// `Device::taildrop_*` methods (Go exposes these over LocalAPI; this fork exposes them on the
302    /// device). With no `peerapi_port`, the store still exists for those read APIs but no peer can
303    /// deliver to it.
304    #[serde(default)]
305    pub taildrop_dir: Option<std::path::PathBuf>,
306
307    /// Per-direction TCP send/receive buffer size (bytes) for the userspace netstack, or `None` to
308    /// use the netstack default (256 KiB per direction, ~512 KiB per socket).
309    ///
310    /// smoltcp has no window auto-tuning, so this is the hard cap on a single flow's
311    /// bandwidth-delay product; raising it helps large model-API responses on high-RTT links, at
312    /// the cost of more memory per concurrent socket (each socket allocates this size for both rx
313    /// and tx). Like the other dataplane fields, this is a client-side preference not read inside
314    /// `ts_control`; it is carried here only to be threaded into the runtime's netstack
315    /// configuration.
316    #[serde(default)]
317    pub tcp_buffer_size: Option<usize>,
318
319    /// Whether IPv6 is enabled on the tailnet overlay. Defaults to `false` (IPv4-only).
320    ///
321    /// Like the other dataplane fields, this is a client-side preference not read inside
322    /// `ts_control`; it is carried here only to be threaded into the runtime's underlay socket,
323    /// disco candidate filter, netstack address assignment, and MagicDNS AAAA handling. It governs
324    /// only the overlay and never the exit-node / forwarder egress path, which stays IPv4-only
325    /// regardless to uphold the real-origin-IP isolation invariant.
326    #[serde(default)]
327    pub enable_ipv6: bool,
328
329    /// WireGuard persistent-keepalive interval applied to every peer, or `None` to disable persistent
330    /// keepalives (`PersistentKeepalive`; Tailscale uses 25s).
331    ///
332    /// When `Some(interval)`, each peer emits an empty authenticated keepalive every `interval` of
333    /// outbound silence, holding the (typically DERP-relayed) path/NAT mapping warm so an idle
334    /// session doesn't age past expiry and wedge the next dial — the failure this fork's primary
335    /// userspace-netstack deployment hits, where the relay is the only path to a peer. Unlike the
336    /// reactive WireGuard §6.5 keepalive (armed only by inbound traffic), this re-arms unconditionally
337    /// and fires on a fully idle tunnel; the empty packet does not advance the session's
338    /// rotation/expiry timers, so a genuinely dead peer is still detected. Defaults to `Some(25s)`
339    /// ([`DEFAULT_PERSISTENT_KEEPALIVE`]). Like the other dataplane fields it is not read inside
340    /// `ts_control`; it is carried here only to be threaded into the runtime's dataplane actor.
341    #[serde(default = "default_persistent_keepalive")]
342    pub persistent_keepalive_interval: Option<std::time::Duration>,
343
344    /// How the application overlay data path is realized: userspace netstack (default) or a real
345    /// kernel TUN interface. See [`TransportMode`].
346    ///
347    /// Like the other dataplane fields, this is a client-side preference not read inside
348    /// `ts_control`; it is carried here only to be threaded into the runtime, which builds either a
349    /// netstack actor or a TUN transport from it. `ts_control` must not depend on `ts_transport_tun`.
350    #[serde(default)]
351    pub transport_mode: TransportMode,
352
353    /// Whether to ask control to wire this node up server-side for Tailscale Funnel
354    /// (`HostInfo.WireIngress`, the capver-113 client→control Funnel signal), even when no Funnel
355    /// endpoint is currently active.
356    ///
357    /// Unlike the dataplane fields above, this one *is* read inside `ts_control`: it sets
358    /// `HostInfo.WireIngress` on registration and the streaming map request, asking control to
359    /// provision the DNS / ingress records a Funnel node needs so a later `serve`/funnel session
360    /// works immediately. It mirrors Go `tsnet`'s "would like to be wired up for Funnel" signal.
361    ///
362    /// This fork cannot yet *terminate* public Funnel ingress — [`crate::listen_funnel`] is
363    /// fail-closed (no client-side ACME engine, and a self-hosted control plane provides no public
364    /// ingress relay). So `HostInfo.IngressEnabled` (Funnel endpoints actually live) is never set;
365    /// only `WireIngress` is, and only when this flag is `true`. Defaults to `false` (fail-closed):
366    /// a node requests Funnel wiring only when explicitly opted in.
367    #[serde(default)]
368    pub wire_ingress: bool,
369
370    /// Live signal that this node currently has an active Funnel ingress listener
371    /// (`Device::listen_funnel` was called and its listener is up), driving `HostInfo.IngressEnabled`
372    /// on the streaming map request.
373    ///
374    /// Unlike [`wire_ingress`](Self::wire_ingress) (a static "please provision Funnel records" hint),
375    /// this is a *dynamic* flag: the runtime flips it `true` when a funnel listener starts serving and
376    /// back to `false` when it stops, so the next map request advertises `IngressEnabled` accordingly
377    /// (Go sets `HostInfo.IngressEnabled` only while Funnel endpoints are actually live, and
378    /// `IngressEnabled` implies `WireIngress`). Shared (`Arc`) with the runtime so the device can flip
379    /// it without rebuilding the config. Defaults to a fresh `false` (fail-closed: no live endpoint).
380    /// Not serialized — it is process-local runtime state, not persisted configuration.
381    #[serde(skip, default)]
382    pub ingress_active: std::sync::Arc<std::sync::atomic::AtomicBool>,
383
384    /// VIP services this node advertises that it **hosts** (`svc:<dns-label>` names), the
385    /// advertise side of Tailscale VIP services (Go `tsnet`'s `Hostinfo.ServicesHash` +
386    /// c2n `GET /vip-services`).
387    ///
388    /// Each entry is a full `svc:`-prefixed service name. This field *is* read inside `ts_control`:
389    /// the valid names ([`validate_service_name`](crate::validate_service_name) is applied
390    /// fail-closed; malformed names are dropped and logged) are hashed into `HostInfo.ServicesHash`
391    /// on every map request, and answered when control fetches the list via the c2n
392    /// `/vip-services` endpoint. Defaults to empty: with no entries the hash is `""` and behavior is
393    /// byte-for-byte the historical non-advertising path. Hosting a service additionally requires
394    /// control to assign it a VIP and the node to be tagged (the *consume* side, unchanged here).
395    #[serde(default)]
396    pub advertise_services: Vec<String>,
397
398    /// Allow fetching the control server's machine public key (`GET /key`) over plain **http** when
399    /// the [`server_url`](Config::server_url) is itself `http://`.
400    ///
401    /// By default (`false`) the `/key` fetch is always upgraded to `https`, even when the control
402    /// URL is `http://` — matching Tailscale's posture that the unauthenticated key bootstrap must
403    /// be TLS-protected. That upgrade makes registration **fail** against a control plane that only
404    /// serves plain http (e.g. a self-hosted Headscale exposed over a `http://host:port` LAN
405    /// endpoint / NodePort with no TLS), even though the rest of the control connection already
406    /// honors the `http` scheme. Set this to `true` for such a deployment to fetch `/key` over the
407    /// same `http` scheme as the control URL.
408    ///
409    /// Security: only enable this when you control both ends and the control plane is reachable
410    /// over a trusted network path — an on-path attacker could otherwise substitute the control
411    /// key. It has no effect when `server_url` is `https://` (the fetch stays https regardless).
412    /// Fail-closed default is `false`.
413    #[serde(default)]
414    pub allow_http_key_fetch: bool,
415}
416
417impl Config {
418    /// Get the full client name as a string.
419    ///
420    /// This takes the form `tailscale-rs ({client_name})`, where the parenthetical is only
421    /// provided if self.client_name is set.
422    pub fn format_client_name(&self) -> String {
423        let mut full_name = "tailscale-rs".to_owned();
424        if let Some(client_name) = &self.client_name {
425            full_name.push_str(&format!(" ({client_name})"));
426        }
427
428        full_name
429    }
430
431    /// Compute the set of IP prefixes to advertise in `HostInfo.RoutableIPs`, combining
432    /// [`advertise_routes`](Config::advertise_routes) with the exit-node default route when
433    /// [`advertise_exit_node`](Config::advertise_exit_node) is set.
434    ///
435    /// IPv6 prefixes are filtered out (IPv6-off posture): we never forward IPv6, so advertising an
436    /// IPv6 route would create a black hole. The exit-node default route is therefore `0.0.0.0/0`
437    /// only, never `::/0`. The result is deduplicated and order-preserving; an empty result means
438    /// "advertise nothing", and callers omit the wire field entirely.
439    pub fn advertised_routes(&self) -> Vec<ipnet::IpNet> {
440        let mut routes: Vec<ipnet::IpNet> = Vec::new();
441        let mut push_unique = |net: ipnet::IpNet| {
442            if !routes.contains(&net) {
443                routes.push(net);
444            }
445        };
446
447        for net in &self.advertise_routes {
448            // IPv6-off: drop v6 prefixes so we never advertise a route we won't forward.
449            if matches!(net, ipnet::IpNet::V4(_)) {
450                push_unique(*net);
451            } else {
452                tracing::warn!(prefix = %net, "dropping IPv6 advertise_routes prefix (IPv6-off posture)");
453            }
454        }
455
456        if self.advertise_exit_node {
457            let default_v4 = ipnet::IpNet::V4(
458                ipnet::Ipv4Net::new(core::net::Ipv4Addr::UNSPECIFIED, 0)
459                    .expect("0.0.0.0/0 is a valid prefix"),
460            );
461            push_unique(default_v4);
462        }
463
464        routes
465    }
466
467    /// The services to advertise in `HostInfo.Services`, derived from
468    /// [`peerapi_port`](Config::peerapi_port).
469    ///
470    /// When a peerAPI port is configured, we advertise the `peerapi4` service at that port plus the
471    /// `peerapi-dns-proxy` service (whose advertised port is always `1`, matching the Go client's
472    /// quirk) so peers learn they can delegate exit-node DNS to us. When `None`, the result is empty
473    /// and callers omit the `HostInfo.Services` wire field entirely (advertise no services). IPv6
474    /// peerAPI (`peerapi6`) is never advertised, per the IPv6-off posture.
475    pub fn advertised_services(&self) -> Vec<ts_control_serde::Service<'static>> {
476        use ts_control_serde::{Service, ServiceProto};
477
478        let Some(port) = self.peerapi_port else {
479            return Vec::new();
480        };
481
482        vec![
483            Service {
484                proto: ServiceProto::PeerApi4,
485                port,
486                description: "tailscale-rs",
487            },
488            Service {
489                // Go quirk: the peerapi-dns-proxy service always advertises port 1.
490                proto: ServiceProto::PeerApiDnsProxy,
491                port: 1,
492                description: "tailscale-rs",
493            },
494        ]
495    }
496
497    /// The validated set of VIP services this node advertises that it hosts, derived from
498    /// [`advertise_services`](Config::advertise_services).
499    ///
500    /// Each configured name is validated with
501    /// [`validate_service_name`](crate::validate_service_name) (fail-closed: a name that is not a
502    /// well-formed `svc:<dns-label>` is dropped with a warning, never advertised). Each surviving
503    /// service is advertised on **all ports** (a single `0/0..=65535`
504    /// [`ProtoPortRange`](ts_control_serde::ProtoPortRange), matching
505    /// Go's default `ServicePortRange()` when no explicit ports are configured) and marked active.
506    /// The result is the canonical input to both [`services_hash`] and the c2n `/vip-services`
507    /// response. An empty config yields an empty `Vec` (advertise nothing — the hash is `""`).
508    pub fn advertised_vip_services(&self) -> Vec<ts_control_serde::VipServiceOwned> {
509        use ts_control_serde::{ProtoPortRange, VipServiceOwned};
510
511        self.advertise_services
512            .iter()
513            .filter_map(|name| {
514                if crate::validate_service_name(name).is_none() {
515                    tracing::warn!(
516                        service = %name,
517                        "dropping invalid advertise_services name (expected svc:<dns-label>)"
518                    );
519                    return None;
520                }
521                Some(VipServiceOwned {
522                    name: name.clone(),
523                    // All ports: proto 0 (all protocols), full 0..=65535 span — Go's default
524                    // ServicePortRange() for a service with no explicit port restriction.
525                    ports: vec![ProtoPortRange {
526                        proto: 0,
527                        first: 0,
528                        last: 65535,
529                    }],
530                    active: true,
531                })
532            })
533            .collect()
534    }
535}
536
537/// Compute the `HostInfo.ServicesHash` for a node's advertised VIP services, mirroring Go's
538/// `vipServiceHash`.
539///
540/// The services are sorted by name, serialized to canonical (whitespace-free) JSON as a
541/// [`ts_control_serde::VipServiceOwned`] list, SHA-256'd, and hex-encoded. An empty list hashes to
542/// the empty string `""` (the "no services advertised" sentinel, which omits/clears the wire
543/// field). The hash is byte-stable and order-independent: the same set in any input order yields the
544/// same value, so control reliably refetches only on a genuine change.
545///
546/// Uses `ring`'s SHA-256 (the same crypto backend the rest of the stack links — no aws-lc-rs /
547/// openssl is introduced).
548pub fn services_hash(services: &[ts_control_serde::VipServiceOwned]) -> String {
549    if services.is_empty() {
550        return String::new();
551    }
552
553    let mut sorted = services.to_vec();
554    sorted.sort_by(|a, b| a.name.cmp(&b.name));
555
556    // Canonical, whitespace-free JSON so the digest is byte-stable across builds.
557    let json = serde_json::to_vec(&sorted).expect("VipServiceOwned list always serializes");
558    let digest = ring::digest::digest(&ring::digest::SHA256, &json);
559
560    let mut hex = String::with_capacity(digest.as_ref().len() * 2);
561    for byte in digest.as_ref() {
562        hex.push_str(&format!("{byte:02x}"));
563    }
564    hex
565}
566
567impl Debug for Config {
568    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
569        f.debug_struct("Config")
570            .field("hostname", &self.hostname)
571            .field("server_url", &self.server_url.as_str())
572            .field("client_name", &self.client_name)
573            .finish()
574    }
575}
576
577impl Default for Config {
578    fn default() -> Self {
579        Self {
580            server_url: DEFAULT_CONTROL_SERVER.clone(),
581            hostname: gethostname::gethostname().into_string().ok(),
582            client_name: None,
583            tags: Default::default(),
584            ephemeral: default_ephemeral(),
585            accept_routes: false,
586            exit_node: None,
587            advertise_routes: Vec::new(),
588            advertise_exit_node: false,
589            forward_tcp_ports: Vec::new(),
590            forward_udp_ports: Vec::new(),
591            forward_all_ports: false,
592            forward_exit_egress: false,
593            block_incoming: false,
594            exit_proxy: None,
595            peerapi_port: None,
596            taildrop_dir: None,
597            tcp_buffer_size: None,
598            enable_ipv6: false,
599            persistent_keepalive_interval: default_persistent_keepalive(),
600            transport_mode: TransportMode::default(),
601            wire_ingress: false,
602            ingress_active: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
603            advertise_services: Vec::new(),
604            allow_http_key_fetch: false,
605        }
606    }
607}
608
609#[cfg(test)]
610mod tests {
611    use super::*;
612
613    fn v4(s: &str) -> ipnet::IpNet {
614        ipnet::IpNet::V4(s.parse().unwrap())
615    }
616
617    fn v6(s: &str) -> ipnet::IpNet {
618        ipnet::IpNet::V6(s.parse().unwrap())
619    }
620
621    #[test]
622    fn default_advertises_nothing() {
623        let cfg = Config::default();
624        assert!(cfg.advertised_routes().is_empty());
625    }
626
627    #[test]
628    fn advertises_v4_subnet_routes() {
629        let cfg = Config {
630            advertise_routes: vec![v4("10.0.0.0/24"), v4("192.168.1.0/24")],
631            ..Default::default()
632        };
633        assert_eq!(
634            cfg.advertised_routes(),
635            vec![v4("10.0.0.0/24"), v4("192.168.1.0/24")]
636        );
637    }
638
639    #[test]
640    fn exit_node_adds_default_v4_route() {
641        let cfg = Config {
642            advertise_exit_node: true,
643            ..Default::default()
644        };
645        assert_eq!(cfg.advertised_routes(), vec![v4("0.0.0.0/0")]);
646    }
647
648    #[test]
649    fn v6_prefixes_are_dropped() {
650        let cfg = Config {
651            advertise_routes: vec![v4("10.0.0.0/24"), v6("fd00::/64")],
652            ..Default::default()
653        };
654        // IPv6-off: only the v4 prefix survives.
655        assert_eq!(cfg.advertised_routes(), vec![v4("10.0.0.0/24")]);
656    }
657
658    #[test]
659    fn exit_node_never_advertises_v6_default() {
660        let cfg = Config {
661            advertise_routes: vec![v6("::/0")],
662            advertise_exit_node: true,
663            ..Default::default()
664        };
665        // ::/0 is dropped; only the v4 default route is advertised.
666        assert_eq!(cfg.advertised_routes(), vec![v4("0.0.0.0/0")]);
667    }
668
669    #[test]
670    fn default_is_ephemeral() {
671        // Preserves the historical hardcoded behavior; persistent nodes must opt out explicitly.
672        assert!(Config::default().ephemeral);
673    }
674
675    #[test]
676    fn ephemeral_deserializes_default_true_when_absent() {
677        // A config that predates the field still registers ephemeral.
678        let cfg: Config = serde_json::from_str(r#"{"server_url":"https://example.com/"}"#).unwrap();
679        assert!(cfg.ephemeral);
680    }
681
682    #[test]
683    fn ephemeral_can_be_disabled_for_persistent_nodes() {
684        let cfg: Config =
685            serde_json::from_str(r#"{"server_url":"https://example.com/","ephemeral":false}"#)
686                .unwrap();
687        assert!(!cfg.ephemeral);
688    }
689
690    #[test]
691    fn tags_default_empty_and_deserialize() {
692        let cfg: Config =
693            serde_json::from_str(r#"{"server_url":"https://example.com/","tags":["tag:exit"]}"#)
694                .unwrap();
695        assert_eq!(cfg.tags, vec!["tag:exit".to_owned()]);
696        assert!(Config::default().tags.is_empty());
697    }
698
699    #[test]
700    fn advertises_no_services_without_peerapi_port() {
701        // Fail-closed default: no peerAPI port means no services advertised.
702        assert!(Config::default().advertised_services().is_empty());
703    }
704
705    #[test]
706    fn advertises_peerapi4_and_dns_proxy_when_port_set() {
707        use ts_control_serde::ServiceProto;
708
709        let cfg = Config {
710            peerapi_port: Some(8080),
711            ..Default::default()
712        };
713        let services = cfg.advertised_services();
714        assert_eq!(services.len(), 2);
715
716        // peerapi4 carries the real bind port.
717        assert_eq!(services[0].proto, ServiceProto::PeerApi4);
718        assert_eq!(services[0].port, 8080);
719
720        // peerapi-dns-proxy always advertises port 1 (Go quirk).
721        assert_eq!(services[1].proto, ServiceProto::PeerApiDnsProxy);
722        assert_eq!(services[1].port, 1);
723    }
724
725    #[test]
726    fn peerapi_port_deserializes_default_none() {
727        let cfg: Config = serde_json::from_str(r#"{"server_url":"https://example.com/"}"#).unwrap();
728        assert_eq!(cfg.peerapi_port, None);
729    }
730
731    #[test]
732    fn advertise_services_default_empty() {
733        assert!(Config::default().advertise_services.is_empty());
734        assert!(Config::default().advertised_vip_services().is_empty());
735    }
736
737    #[test]
738    fn advertise_services_deserializes() {
739        let cfg: Config = serde_json::from_str(
740            r#"{"server_url":"https://example.com/","advertise_services":["svc:samba"]}"#,
741        )
742        .unwrap();
743        assert_eq!(cfg.advertise_services, vec!["svc:samba".to_owned()]);
744    }
745
746    #[test]
747    fn advertised_vip_services_validates_and_drops_bad_names() {
748        let cfg = Config {
749            advertise_services: vec![
750                "svc:good".to_owned(),
751                "bad-no-prefix".to_owned(),
752                "svc:-bad-label".to_owned(),
753            ],
754            ..Default::default()
755        };
756        let svcs = cfg.advertised_vip_services();
757        assert_eq!(svcs.len(), 1);
758        assert_eq!(svcs[0].name, "svc:good");
759        // All-ports default range, active.
760        assert_eq!(svcs[0].ports.len(), 1);
761        assert_eq!(svcs[0].ports[0].first, 0);
762        assert_eq!(svcs[0].ports[0].last, 65535);
763        assert!(svcs[0].active);
764    }
765
766    #[test]
767    fn services_hash_empty_is_empty_string() {
768        assert_eq!(services_hash(&[]), "");
769    }
770
771    #[test]
772    fn services_hash_is_order_independent() {
773        let a = Config {
774            advertise_services: vec!["svc:a".to_owned(), "svc:b".to_owned()],
775            ..Default::default()
776        };
777        let b = Config {
778            advertise_services: vec!["svc:b".to_owned(), "svc:a".to_owned()],
779            ..Default::default()
780        };
781        let ha = services_hash(&a.advertised_vip_services());
782        let hb = services_hash(&b.advertised_vip_services());
783        assert_eq!(ha, hb);
784        assert!(!ha.is_empty());
785    }
786
787    #[test]
788    fn services_hash_changes_with_set() {
789        let one = Config {
790            advertise_services: vec!["svc:a".to_owned()],
791            ..Default::default()
792        };
793        let two = Config {
794            advertise_services: vec!["svc:a".to_owned(), "svc:b".to_owned()],
795            ..Default::default()
796        };
797        assert_ne!(
798            services_hash(&one.advertised_vip_services()),
799            services_hash(&two.advertised_vip_services())
800        );
801    }
802
803    #[test]
804    fn services_hash_known_answer() {
805        // KAT: pin the hash of a single all-ports `svc:samba` so a future serialization change
806        // (field order, whitespace) that would silently break control's change-detection fails
807        // this test. Computed once from this very implementation.
808        let cfg = Config {
809            advertise_services: vec!["svc:samba".to_owned()],
810            ..Default::default()
811        };
812        let hash = services_hash(&cfg.advertised_vip_services());
813        // 64 hex chars = SHA-256.
814        assert_eq!(hash.len(), 64);
815        assert!(hash.bytes().all(|b| b.is_ascii_hexdigit()));
816        assert_eq!(
817            hash,
818            "f96574bfe9f637164f5d7fff37ea169b3aa86b12e25d98f5c3b7fd049839f4e9"
819        );
820    }
821
822    #[test]
823    fn deduplicates_routes() {
824        let cfg = Config {
825            advertise_routes: vec![v4("0.0.0.0/0"), v4("10.0.0.0/24")],
826            advertise_exit_node: true,
827            ..Default::default()
828        };
829        // Explicit 0.0.0.0/0 plus the exit-node default route collapse to one entry.
830        assert_eq!(
831            cfg.advertised_routes(),
832            vec![v4("0.0.0.0/0"), v4("10.0.0.0/24")]
833        );
834    }
835}