Skip to main content

ts_capabilityversion/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use core::fmt;
4
5/// Indicates the capability level of a Tailscale node. This must be kept in-sync with the
6/// CapabilityVersion constants in the Golang codebase (`tailcfg/tailcfg.go`).
7///
8/// It can be thought of as a node's simple version number; a single monotonically increasing
9/// integer, rather than the complex x.y.z-cccccc semver+hash(es) versioning scheme. Whenever a
10/// node gains a capability or wants to negotiate a change in semantics with the control plane,
11/// peers, or an official frontend (such as LocalAPI in the Golang codebase), bump this number and
12/// document what's changed.
13///
14/// The capability versions 0, 1, 2, and 35 are undefined; you cannot create a
15/// [`CapabilityVersion`] with these values.
16///
17/// Note: Prior to 2022-03-06, this value was known as the "`MapRequest` version", `mapVer`, or "map
18/// cap"; you'll still see that name used in comments throughout the Golang codebase.
19#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
20#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
21pub struct CapabilityVersion(u16);
22
23impl Default for CapabilityVersion {
24    #[inline]
25    fn default() -> Self {
26        Self::CURRENT
27    }
28}
29
30impl CapabilityVersion {
31    /// 2020-??-??: implicit compression, keep-alives
32    pub const V3: Self = Self(3);
33    /// 2020-??-??: opt-in keep-alives via KeepAlive field, opt-in compression via Compress
34    pub const V4: Self = Self(4);
35    /// 2020-10-19: implies IncludeIPv6; delta Peers/UserProfiles, supports MagicDNS
36    pub const V5: Self = Self(5);
37    /// 2020-12-07: means MapResponse.PacketFilter nil means unchanged
38    pub const V6: Self = Self(6);
39    /// 2020-12-15: FilterRule.SrcIPs accepts CIDRs+ranges, doesn't warn about 0.0.0.0/::
40    pub const V7: Self = Self(7);
41    /// 2020-12-19: client can buggily receive IPv6 addresses and routes if beta enabled server-side
42    pub const V8: Self = Self(8);
43    /// 2020-12-30: client doesn't auto-add implicit search domains from peers; only
44    /// DNSConfig.Domains
45    pub const V9: Self = Self(9);
46    /// 2021-01-17: client understands MapResponse.PeerSeenChange
47    pub const V10: Self = Self(10);
48    /// 2021-03-03: client understands IPv6; multiple default routes, and goroutine dumping
49    pub const V11: Self = Self(11);
50    /// 2021-03-04: client understands PingRequest
51    pub const V12: Self = Self(12);
52    /// 2021-03-19: client understands FilterRule.IPProto
53    pub const V13: Self = Self(13);
54    /// 2021-04-07: client understands DNSConfig.Routes and DNSConfig.Resolvers
55    pub const V14: Self = Self(14);
56    /// 2021-04-12: client treats nil MapResponse.DNSConfig as meaning unchanged
57    pub const V15: Self = Self(15);
58    /// 2021-04-15: client understands Node.Online, MapResponse.OnlineChange
59    pub const V16: Self = Self(16);
60    /// 2021-04-18: MapResponse.Domain empty means unchanged
61    pub const V17: Self = Self(17);
62    /// 2021-04-19: MapResponse.Node nil means unchanged (all fields now omitempty)
63    pub const V18: Self = Self(18);
64    /// 2021-04-21: MapResponse.Debug.SleepSeconds
65    pub const V19: Self = Self(19);
66    /// 2021-06-11: MapResponse.LastSeen used even less
67    /// (<https://github.com/tailscale/tailscale/issues/2107>)
68    pub const V20: Self = Self(20);
69    /// 2021-06-15: added MapResponse.DNSConfig.CertDomains
70    pub const V21: Self = Self(21);
71    /// 2021-06-16: added MapResponse.DNSConfig.ExtraRecords
72    pub const V22: Self = Self(22);
73    /// 2021-08-25: DNSConfig.Routes values may be empty (for ExtraRecords support in 1.14.1+)
74    pub const V23: Self = Self(23);
75    /// 2021-09-18: MapResponse.Health from control to node; node shows in "tailscale status"
76    pub const V24: Self = Self(24);
77    /// 2021-11-01: MapResponse.Debug.Exit
78    pub const V25: Self = Self(25);
79    /// 2022-01-12: (nothing, just bumping for 1.20.0)
80    pub const V26: Self = Self(26);
81    /// 2022-02-18: start of SSHPolicy being respected
82    pub const V27: Self = Self(27);
83    /// 2022-03-09: client can communicate over Noise.
84    pub const V28: Self = Self(28);
85    /// 2022-03-21: MapResponse.PopBrowserURL
86    pub const V29: Self = Self(29);
87    /// 2022-03-22: client can request id tokens.
88    pub const V30: Self = Self(30);
89    /// 2022-04-15: PingRequest & PingResponse TSMP & disco support
90    pub const V31: Self = Self(31);
91    /// 2022-04-17: client knows FilterRule.CapMatch
92    pub const V32: Self = Self(32);
93    /// 2022-07-20: added MapResponse.PeersChangedPatch (DERPRegion + Endpoints)
94    pub const V33: Self = Self(33);
95    /// 2022-08-02: client understands CapabilityFileSharingTarget
96    pub const V34: Self = Self(34);
97    /// 2022-08-02: added PeersChangedPatch.{Key,DiscoKey,Online,LastSeen,KeyExpiry,Capabilities}
98    pub const V36: Self = Self(36);
99    /// 2022-08-09: added Debug.{SetForceBackgroundSTUN,SetRandomizeClientPort}; Debug are sticky
100    pub const V37: Self = Self(37);
101    /// 2022-08-11: added PingRequest.URLIsNoise
102    pub const V38: Self = Self(38);
103    /// 2022-08-15: clients can talk Noise over arbitrary HTTPS port
104    pub const V39: Self = Self(39);
105    /// 2022-08-22: added Node.KeySignature, PeersChangedPatch.KeySignature
106    pub const V40: Self = Self(40);
107    /// 2022-08-30: uses 100.100.100.100 for route-less ExtraRecords if global nameservers is set
108    pub const V41: Self = Self(41);
109    /// 2022-09-06: NextDNS DoH support; see <https://github.com/tailscale/tailscale/pull/5556>
110    pub const V42: Self = Self(42);
111    /// 2022-09-21: clients can return usernames for SSH
112    pub const V43: Self = Self(43);
113    /// 2022-09-22: MapResponse.ControlDialPlan
114    pub const V44: Self = Self(44);
115    /// 2022-09-26: c2n /debug/{goroutines,prefs,metrics}
116    pub const V45: Self = Self(45);
117    /// 2022-10-04: c2n /debug/component-logging
118    pub const V46: Self = Self(46);
119    /// 2022-10-11: Register{Request,Response}.NodeKeySignature
120    pub const V47: Self = Self(47);
121    /// 2022-11-02: Node.UnsignedPeerAPIOnly
122    pub const V48: Self = Self(48);
123    /// 2022-11-03: Client understands EarlyNoise
124    pub const V49: Self = Self(49);
125    /// 2022-11-14: Client understands CapabilityIngress
126    pub const V50: Self = Self(50);
127    /// 2022-11-30: Client understands CapabilityTailnetLockAlpha
128    pub const V51: Self = Self(51);
129    /// 2023-01-05: client can handle c2n POST /logtail/flush
130    pub const V52: Self = Self(52);
131    /// 2023-01-18: client respects explicit Node.Expired + auto-sets based on Node.KeyExpiry
132    pub const V53: Self = Self(53);
133    /// 2023-01-19: Node.Cap added, PeersChangedPatch.Cap, uses Node.Cap for ExitDNS before
134    /// Hostinfo.Services fallback
135    pub const V54: Self = Self(54);
136    /// 2023-01-23: start of c2n GET+POST /update handler
137    pub const V55: Self = Self(55);
138    /// 2023-01-24: Client understands CapabilityDebugTSDNSResolution
139    pub const V56: Self = Self(56);
140    /// 2023-01-25: Client understands CapabilityBindToInterfaceByRoute
141    pub const V57: Self = Self(57);
142    /// 2023-03-10: Client retries lite map updates before restarting map poll.
143    pub const V58: Self = Self(58);
144    /// 2023-03-16: Client understands Peers[].SelfNodeV4MasqAddrForThisPeer
145    pub const V59: Self = Self(59);
146    /// 2023-04-06: Client understands IsWireGuardOnly
147    pub const V60: Self = Self(60);
148    /// 2023-04-18: Client understand SSHAction.SSHRecorderFailureAction
149    pub const V61: Self = Self(61);
150    /// 2023-05-05: Client can notify control over noise for SSHEventNotificationRequest recording
151    /// failure events
152    pub const V62: Self = Self(62);
153    /// 2023-06-08: Client understands SSHAction.AllowRemotePortForwarding.
154    pub const V63: Self = Self(63);
155    /// 2023-07-11: Client understands s/CapabilityTailnetLockAlpha/CapabilityTailnetLock
156    pub const V64: Self = Self(64);
157    /// 2023-07-12: Client understands DERPMap.HomeParams + incremental DERPMap updates with params
158    pub const V65: Self = Self(65);
159    /// 2023-07-23: UserProfile.Groups added (available via WhoIs) (removed in 87)
160    pub const V66: Self = Self(66);
161    /// 2023-07-25: Client understands PeerCapMap
162    pub const V67: Self = Self(67);
163    /// 2023-08-09: Client has dedicated updateRoutine; MapRequest.Stream true means ignore
164    /// Hostinfo+Endpoints
165    pub const V68: Self = Self(68);
166    /// 2023-08-16: removed Debug.LogHeap* + GoroutineDumpURL; added c2n /debug/logheap
167    pub const V69: Self = Self(69);
168    /// 2023-08-16: removed most Debug fields; added NodeAttrDisable*, NodeAttrDebug* instead
169    pub const V70: Self = Self(70);
170    /// 2023-08-17: added NodeAttrOneCGNATEnable, NodeAttrOneCGNATDisable
171    pub const V71: Self = Self(71);
172    /// 2023-08-23: TS-2023-006 UPnP issue fixed; UPnP can now be used again
173    pub const V72: Self = Self(72);
174    /// 2023-09-01: Non-Windows clients expect to receive ClientVersion
175    pub const V73: Self = Self(73);
176    /// 2023-09-18: Client understands NodeCapMap
177    pub const V74: Self = Self(74);
178    /// 2023-09-12: Client understands NodeAttrDNSForwarderDisableTCPRetries
179    pub const V75: Self = Self(75);
180    /// 2023-09-20: Client understands ExitNodeDNSResolvers for IsWireGuardOnly nodes
181    pub const V76: Self = Self(76);
182    /// 2023-10-03: Client understands Peers[].SelfNodeV6MasqAddrForThisPeer
183    pub const V77: Self = Self(77);
184    /// 2023-10-05: can handle c2n Wake-on-LAN sending
185    pub const V78: Self = Self(78);
186    /// 2023-10-05: Client understands UrgentSecurityUpdate in ClientVersion
187    pub const V79: Self = Self(79);
188    /// 2023-11-16: can handle c2n GET /tls-cert-status
189    pub const V80: Self = Self(80);
190    /// 2023-11-17: MapResponse.PacketFilters (incremental packet filter updates)
191    pub const V81: Self = Self(81);
192    /// 2023-12-01: Client understands NodeAttrLinuxMustUseIPTables, NodeAttrLinuxMustUseNfTables,
193    /// c2n /netfilter-kind
194    pub const V82: Self = Self(82);
195    /// 2023-12-18: Client understands DefaultAutoUpdate
196    pub const V83: Self = Self(83);
197    /// 2024-01-04: Client understands SeamlessKeyRenewal
198    pub const V84: Self = Self(84);
199    /// 2024-01-05: Client understands MaxKeyDuration
200    pub const V85: Self = Self(85);
201    /// 2024-01-23: Client understands NodeAttrProbeUDPLifetime
202    pub const V86: Self = Self(86);
203    /// 2024-02-11: UserProfile.Groups removed (added in 66)
204    pub const V87: Self = Self(87);
205    /// 2024-03-05: Client understands NodeAttrSuggestExitNode
206    pub const V88: Self = Self(88);
207    /// 2024-03-23: Client no longer respects deleted PeerChange.Capabilities (use CapMap)
208    pub const V89: Self = Self(89);
209    /// 2024-04-03: Client understands PeerCapabilityTaildrive.
210    pub const V90: Self = Self(90);
211    /// 2024-04-24: Client understands PeerCapabilityTaildriveSharer.
212    pub const V91: Self = Self(91);
213    /// 2024-05-06: Client understands NodeAttrUserDialUseRoutes.
214    pub const V92: Self = Self(92);
215    /// 2024-05-06: added support for stateful firewalling.
216    pub const V93: Self = Self(93);
217    /// 2024-05-06: Client understands Node.IsJailed.
218    pub const V94: Self = Self(94);
219    /// 2024-05-06: Client uses NodeAttrUserDialUseRoutes to change DNS dialing behavior.
220    pub const V95: Self = Self(95);
221    /// 2024-05-29: Client understands NodeAttrSSHBehaviorV1
222    pub const V96: Self = Self(96);
223    /// 2024-06-06: Client understands NodeAttrDisableSplitDNSWhenNoCustomResolvers
224    pub const V97: Self = Self(97);
225    /// 2024-06-13: iOS/tvOS clients may provide serial number as part of posture information
226    pub const V98: Self = Self(98);
227    /// 2024-06-14: Client understands NodeAttrDisableLocalDNSOverrideViaNRPT
228    pub const V99: Self = Self(99);
229    /// 2024-06-18: Initial support for filtertype.Match.SrcCaps - actually usable in capver 109
230    /// (issue #12542)
231    pub const V100: Self = Self(100);
232    /// 2024-07-01: Client supports SSH agent forwarding when handling connections with /bin/su
233    pub const V101: Self = Self(101);
234    /// 2024-07-12: NodeAttrDisableMagicSockCryptoRouting support
235    pub const V102: Self = Self(102);
236    /// 2024-07-24: Client supports NodeAttrDisableCaptivePortalDetection
237    pub const V103: Self = Self(103);
238    /// 2024-08-03: SelfNodeV6MasqAddrForThisPeer now works
239    pub const V104: Self = Self(104);
240    /// 2024-08-05: Fixed SSH behavior on systems that use busybox (issue #12849)
241    pub const V105: Self = Self(105);
242    /// 2024-09-03: fix panic regression from cryptokey routing change (65fe0ba7b5)
243    pub const V106: Self = Self(106);
244    /// 2024-10-30: add App Connector to conffile (PR #13942)
245    pub const V107: Self = Self(107);
246    /// 2024-11-08: Client sends ServicesHash in Hostinfo, understands c2n GET /vip-services.
247    pub const V108: Self = Self(108);
248    /// 2024-11-18: Client supports filtertype.Match.SrcCaps (issue #12542)
249    pub const V109: Self = Self(109);
250    /// 2024-12-12: removed never-before-used Tailscale SSH public key support (#14373)
251    pub const V110: Self = Self(110);
252    /// 2025-01-14: Client supports a peer having Node.HomeDERP (issue #14636)
253    pub const V111: Self = Self(111);
254    /// 2025-01-14: Client interprets AllowedIPs of nil as meaning same as Addresses
255    pub const V112: Self = Self(112);
256    /// 2025-01-20: Client communicates to control whether funnel is enabled by sending
257    /// Hostinfo.IngressEnabled (#14688)
258    pub const V113: Self = Self(113);
259    /// 2025-01-30: NodeAttrMaxKeyDuration CapMap defined, clients might use it (no tailscaled code
260    /// change) (#14829)
261    pub const V114: Self = Self(114);
262    /// 2025-03-07: Client understands DERPRegion.NoMeasureNoHome.
263    pub const V115: Self = Self(115);
264    /// 2025-05-05: Client serves MagicDNS "AAAA" if NodeAttrMagicDNSPeerAAAA set on self node
265    pub const V116: Self = Self(116);
266    /// 2025-05-28: Client understands DisplayMessages (structured health messages), but not
267    /// necessarily PrimaryAction.
268    pub const V117: Self = Self(117);
269    /// 2025-07-01: Client sends Hostinfo.StateEncrypted to report whether the state file is
270    /// encrypted at rest (#15830)
271    pub const V118: Self = Self(118);
272    /// 2025-07-10: Client uses Hostinfo.Location.Priority to prioritize one route over another.
273    pub const V119: Self = Self(119);
274    /// 2025-07-15: Client understands peer relay disco messages, and implements peer client and
275    /// relay server functions
276    pub const V120: Self = Self(120);
277    /// 2025-07-19: Client understands peer relay endpoint alloc with
278    /// `disco.AllocateUDPRelayEndpointRequest` & `disco.AllocateUDPRelayEndpointResponse`
279    pub const V121: Self = Self(121);
280    /// 2025-07-21: Client sends Hostinfo.ExitNodeID to report which exit node it has selected, if any.
281    pub const V122: Self = Self(122);
282    /// 2025-07-28: fix deadlock regression from cryptokey routing change (issue #16651)
283    pub const V123: Self = Self(123);
284    /// 2025-08-08: removed NodeAttrDisableMagicSockCryptoRouting support, crypto routing is now mandatory
285    pub const V124: Self = Self(124);
286    /// 2025-08-11: dnstype.Resolver adds UseWithExitNode field.
287    pub const V125: Self = Self(125);
288    /// 2025-09-17: Client uses seamless key renewal unless disabled by control
289    /// (tailscale/corp#31479)
290    pub const V126: Self = Self(126);
291    /// 2025-09-19: can handle C2N /debug/netmap.
292    pub const V127: Self = Self(127);
293    /// 2025-10-02: can handle C2N /debug/health.
294    pub const V128: Self = Self(128);
295    /// 2025-10-04: Fixed sleep/wake deadlock in magicsock when using peer relay (PR #17449)
296    pub const V129: Self = Self(129);
297    /// 2025-10-06: client can send key.HardwareAttestationPublic and
298    /// key.HardwareAttestationKeySignature in MapRequest
299    pub const V130: Self = Self(130);
300    /// 2025-11-25: client respects NodeAttrDefaultAutoUpdate
301    pub const V131: Self = Self(131);
302    /// 2026-02-13: client respects NodeAttrDisableHostsFileUpdates
303    pub const V132: Self = Self(132);
304    /// 2026-02-17: client understands NodeAttrForceRegisterMagicDNSIPv4Only; MagicDNS IPv6
305    /// registered w/ OS by default
306    pub const V133: Self = Self(133);
307
308    /// The capability version this node declares to control.
309    ///
310    /// **This is a claim control and peers act on, so it is pinned to what this tree actually
311    /// implements — not to the newest constant defined above.** The constants above are a
312    /// transcription of upstream's list (they document what each version *means*); this one is a
313    /// promise. Declaring a version whose behaviour is missing does not gain a feature, it just
314    /// tells control to stop sending the compatibility path for it.
315    ///
316    /// The value is bracketed from **both** sides, and both bounds are load-bearing. See
317    /// [`Self::is_relay_capable`] for the lower one.
318    ///
319    /// # Upper bound: below 126
320    ///
321    /// The declaration is held at **125** because the next three versions each name a behaviour
322    /// this tree does not have:
323    ///
324    /// - **126** — seamless key renewal. Go renews the node key ahead of expiry without breaking
325    ///   connections (`controlknobs.Knobs.SeamlessKeyRenewal`). This tree's expiry recovery is a
326    ///   node-key rotation plus a full re-register with the stored auth key
327    ///   (`ts_control::Config::reauth_on_expiry`, Go `doLogin`) — that is upstream's *non*-seamless
328    ///   path, so connections do break across a renewal.
329    /// - **127** — c2n `GET|POST /debug/netmap` (Go `handleC2NDebugNetMap`,
330    ///   `ipn/ipnlocal/c2n.go`). Needs a `netmap.NetworkMap` aggregate to marshal; this tree has
331    ///   none — the netmap arrives as a stream of deltas accumulated by the runtime's peer tracker.
332    /// - **128** — c2n `/debug/health` (Go `handleC2NDebugHealth`, `ipn/ipnlocal/c2n.go`). Needs a
333    ///   `health.Tracker`; this fork has no health subsystem.
334    ///
335    /// and **138** (c2n `/debug/tka/log`, Go `handleC2NDebugTKALog` in
336    /// `feature/tailnetlock/tailnetlock.go`) is unimplemented for the same reason: the AUM chain
337    /// lives in `ts_runtime`, and the c2n responder in `ts_control` cannot reach it. All three
338    /// paths take the responder's `400 Bad Request` / `unknown c2n path` fallthrough, which is
339    /// exactly what Go's `handleC2N` writes for an unregistered path.
340    ///
341    /// 125 is also a version a real client shipped (Tailscale `v1.88.0` declares it), which keeps
342    /// this coherent with the `IPNVersion` advertised in `ts_control::hostinfo`.
343    ///
344    /// # Lower bound: at or above 121 — and the one exception it leaves standing
345    ///
346    /// A capability version is a single integer, so declaring 125 also asserts **120** ("Client
347    /// understands peer relay disco messages, and implements peer client and relay server
348    /// functions") and **121** ("Client understands peer relay endpoint alloc with
349    /// `disco.AllocateUDPRelayEndpointRequest` & `disco.AllocateUDPRelayEndpointResponse`").
350    /// Neither is *fully* implemented here: this tree ports the peer-relay **client** half only —
351    /// it answers an inbound `CallMeMaybeVia` and brings the relayed path up (`ts_magicsock`'s
352    /// relay module) — but it never serves as a relay (Go `net/udprelay.Server`,
353    /// `feature/relayserver`) and never originates an allocation request of its own.
354    ///
355    /// That is a real overclaim, and it is deliberately **not** resolved the way 126, 127, 128 and
356    /// 138 were, because here the two directions are not symmetric:
357    ///
358    /// - **Lowering would be unconditionally destructive.** An upstream peer decides whether we may
359    ///   be offered a relay path from our declared version alone, with
360    ///   `magicsock.capVerIsRelayCapable(n.Cap())` — ported here as [`Self::is_relay_capable`]. It
361    ///   gates both `endpoint.wantUDPRelayPathDiscoveryLocked` (no discovery is started toward a
362    ///   peer below the floor) and the inbound `CallMeMaybeVia` handler (the message is ignored
363    ///   outright). Declaring 119 would mean no Go peer ever sends us a `CallMeMaybeVia`, making
364    ///   the ported client half unreachable in production. 122–125 would go with it, including
365    ///   125's `dnstype.Resolver.UseWithExitNode`, which `ts_runtime::magic_dns` *does* implement.
366    /// - **The overclaim is inert unless an operator opts in.** The half we do not implement —
367    ///   serving as a relay — is additionally gated on tailnet policy: a peer treats us as a
368    ///   relay-server candidate only if it *also* holds `peercap.RelayTarget`
369    ///   (`tailscale.com/cap/relay-target`) on us (`Conn.updateRelayServersSet`), a grant an
370    ///   operator writes into the policy file. Absent it no peer ever asks us to allocate, and an
371    ///   `AllocateUDPRelayEndpointRequest` that does arrive is decoded and dropped. Contrast
372    ///   127/128/138, which control acts on unilaterally the moment the version is declared — which
373    ///   is why *those* were resolved by lowering and this one is not.
374    ///
375    /// Closing it for real means porting the relay server, which was ruled out of scope for an
376    /// embedded client when the peer-relay client half landed. Until then it is a recorded,
377    /// bounded exception rather than an oversight.
378    ///
379    /// **Before raising this**, check that every version between the old value and the new one is
380    /// implemented here, not just the topmost one — capability versions are monotone, so declaring
381    /// `N` asserts everything at or below `N`. **Before lowering it**, check it against
382    /// [`Self::is_relay_capable`] first.
383    pub const CURRENT: Self = Self::V125;
384
385    /// The capability version at and above which an upstream Go peer will treat a node as
386    /// **peer-relay capable**: `121`.
387    ///
388    /// Faithful port of Go `magicsock.capVerIsRelayCapable` (`wgengine/magicsock/magicsock.go`,
389    /// pinned at `49e148c4a30b4f8098f69468fd27a7021d85ea02`), which is exactly
390    /// `version >= 121`. Go evaluates it over a peer's netmap `tailcfg.Node.Cap` and stores the
391    /// result as `endpoint.relayCapable`, which gates two things:
392    ///
393    /// - `endpoint.wantUDPRelayPathDiscoveryLocked` — a peer below the floor never has UDP relay
394    ///   path discovery started toward it, so it is never sent a `CallMeMaybeVia`.
395    /// - the inbound `CallMeMaybeVia` path in `Conn.handleDiscoMessage` — a `CallMeMaybeVia`
396    ///   *from* a peer below the floor is ignored ("is not known to be relay capable").
397    ///
398    /// So this is the floor [`Self::CURRENT`] must stay at or above for this tree's ported
399    /// peer-relay client half to be reachable at all by a real Tailscale peer; see that constant
400    /// for why the tree sits above the floor despite not implementing all of 120/121.
401    #[must_use]
402    pub const fn is_relay_capable(self) -> bool {
403        self.0 >= Self::V121.0
404    }
405
406    /// Create a new [`CapabilityVersion`] instance from a `u16`. Note that the versions 0, 1, 2,
407    /// and 35 are undefined and will result in an error.
408    pub const fn new(value: u16) -> Option<Self> {
409        match value {
410            v if v < 3 || v == 35 => None,
411            _ => Some(Self(value)),
412        }
413    }
414}
415
416impl fmt::Display for CapabilityVersion {
417    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
418        write!(f, "{}", self.0)
419    }
420}
421
422/// Convert [`CapabilityVersion`] into a native-endian [`u16`]; little-endian on `x86_64`.
423impl From<CapabilityVersion> for u16 {
424    fn from(value: CapabilityVersion) -> Self {
425        value.0
426    }
427}
428
429impl TryFrom<u16> for CapabilityVersion {
430    type Error = ();
431
432    fn try_from(value: u16) -> Result<Self, Self::Error> {
433        Self::new(value).ok_or(())
434    }
435}
436
437#[cfg(test)]
438mod tests {
439    use super::CapabilityVersion;
440
441    /// Upper bound. 126 (seamless key renewal), 127 (c2n `/debug/netmap`) and 128 (c2n
442    /// `/debug/health`) are all unimplemented, so 125 is the ceiling; see
443    /// [`CapabilityVersion::CURRENT`] for the evidence behind each. This test exists so raising the
444    /// constant without doing the port fails here rather than silently on the wire.
445    #[test]
446    fn current_is_not_declared_above_what_is_implemented() {
447        assert_eq!(CapabilityVersion::CURRENT, CapabilityVersion::V125);
448        assert!(CapabilityVersion::CURRENT < CapabilityVersion::V126);
449    }
450
451    /// Lower bound, and the reason 125 is not lowered to 119 even though 120 and 121 are only
452    /// half-implemented (peer-relay client, no relay server, no allocation request of our own).
453    ///
454    /// Go decides whether a node may be offered a peer-relay path from its declared capability
455    /// version alone — `magicsock.capVerIsRelayCapable(n.Cap())`, `>= 121`, ported as
456    /// [`CapabilityVersion::is_relay_capable`]. Below that floor no Go peer starts UDP relay path
457    /// discovery toward us and any `CallMeMaybeVia` we did receive would have been dropped by the
458    /// sender's own gate, so the ported client half in `ts_magicsock` would be dead code against
459    /// every real peer. Dropping under the floor is therefore a functional regression, not a
460    /// tightening of an honest claim, and this test is what makes that visible to whoever tries it.
461    #[test]
462    fn current_stays_at_or_above_the_relay_capable_floor() {
463        assert!(
464            CapabilityVersion::CURRENT.is_relay_capable(),
465            "declaring below {} makes upstream peers stop offering peer-relay paths, which would \
466             leave this tree's ported peer-relay client half unreachable in production",
467            CapabilityVersion::V121,
468        );
469    }
470
471    /// The floor itself is upstream's, not a local guess: Go `capVerIsRelayCapable` is
472    /// `version >= 121`, so 120 is out and 121 is in, exactly.
473    #[test]
474    fn relay_capable_floor_matches_upstream() {
475        for below in [3u16, 119, 120] {
476            let v = CapabilityVersion::new(below).expect("valid capability version");
477            assert!(!v.is_relay_capable(), "{v} is below Go's 121 relay floor");
478        }
479        for at_or_above in [121u16, 122, 125, 145, u16::MAX] {
480            let v = CapabilityVersion::new(at_or_above).expect("valid capability version");
481            assert!(
482                v.is_relay_capable(),
483                "{v} is at or above Go's 121 relay floor"
484            );
485        }
486    }
487}