A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
fix(tailnet): vendor ts_derp so DERP failures are errors, not panics
RoversX289b92f87c40
diff --git a/Cargo.lock b/Cargo.lockindex 121dc8a6..e420fc79 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -10504,8 +10504,6 @@ dependencies = [[[package]]name = "ts_derp"version = "0.6.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2acde518e1296c20cb93242184c40b7af2731ca50a6744bab69cb2c66e24551e"dependencies = ["bytes","crypto_box",diff --git a/Cargo.toml b/Cargo.tomlindex 27c5cd09..c7fd4a20 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -466,3 +466,8 @@ ts_netstack_smoltcp_core = {path="deps/tailscale-rs/ts_netstack_smoltcp_core", v# distribution and model -- which 0.6.1 drops: Remote Hosts draws a machine# of the tailnet by it.ts_control = {path="deps/tailscale-rs/ts_control", version="0.6.1"}+# Vendored so that neither a DERP region nobody can reach nor a frame too+# short for what it carries panics its client (0.6.1 unwraps the outcome of+# the dial and the frame's parse), and so that a connection gone quiet is+# noticed rather than waited on for good.+ts_derp = {path="deps/tailscale-rs/ts_derp", version="0.6.1"}diff --git a/deps/tailscale-rs/ts_derp/Cargo.toml b/deps/tailscale-rs/ts_derp/Cargo.tomlnew file mode 100644index 00000000..e5d3ba52--- /dev/null+++ b/deps/tailscale-rs/ts_derp/Cargo.toml@@ -0,0 +1,146 @@+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.+#+# ThinkTerm (build): the [[example]] sections are removed: the vendored copy carries no+# examples.++[package]+edition = "2024"+rust-version = "1.92.0"+name = "ts_derp"+version = "0.6.1"+build = false+autolib = false+autobins = false+autoexamples = false+autotests = false+autobenches = false+description = "tailscale derp client"+readme = "README.md"+keywords = [+ "tailscale",+ "packet",+ "derp",+ "network",+ "transport",+]+categories = [+ "network-programming",+ "encoding",+ "asynchronous",+]+license = "BSD-3-Clause"+repository = "https://github.com/tailscale/tailscale-rs"++[features]+insecure-for-tests = ["ts_tls_util/insecure"]++[lib]+name = "ts_derp"+path = "src/lib.rs"++[dependencies.bytes]+version = "1"++[dependencies.crypto_box]+version = "0.9"++[dependencies.futures]+version = "0.3"+default-features = false++[dependencies.hex]+version = "0.4"++[dependencies.serde]+version = "1"+features = ["derive"]++[dependencies.serde_json]+version = "1"++[dependencies.thiserror]+version = "2"+default-features = false++[dependencies.tokio]+version = "1"+features = [+ "rt-multi-thread",+ "macros",+ # ThinkTerm (derp reads): client.rs gives each read a time limit, and its tests run+ # over tokio::io::duplex; the client's tokio::io::split needed "io-util" already.+ "time",+ "io-util",+]+default-features = false++[dependencies.tokio-util]+version = "0.7"+default-features = false++[dependencies.tracing]+version = "0.1"+features = ["attributes"]+default-features = false++[dependencies.ts_hexdump]+version = "0.6.1"++[dependencies.ts_http_util]+version = "0.6.1"++[dependencies.ts_keys]+version = "0.6.1"++[dependencies.ts_packet]+version = "0.6.1"++[dependencies.ts_tls_util]+version = "0.6.1"++[dependencies.ts_transport]+version = "0.6.1"++[dependencies.url]+version = "2"+default-features = false++[dependencies.yoke]+version = "0.8"+features = [+ "alloc",+ "derive",+]+default-features = false++[dependencies.zerocopy]+version = "0.8"+features = ["derive"]++[lints.clippy]+multiple_crate_versions = "allow"+too_many_arguments = "allow"++[lints.clippy.cargo]+level = "warn"+priority = -1++[lints.rust]+closure_returning_async_block = "warn"+let-underscore = "warn"+missing_docs = "warn"++[lints.rustdoc]+bare_urls = "deny"+broken_intra_doc_links = "deny"+invalid_html_tags = "deny"+private_intra_doc_links = "deny"diff --git a/deps/tailscale-rs/ts_derp/LICENSE b/deps/tailscale-rs/ts_derp/LICENSEnew file mode 100644index 00000000..adcd4c5b--- /dev/null+++ b/deps/tailscale-rs/ts_derp/LICENSE@@ -0,0 +1,28 @@+BSD 3-Clause License++Copyright (c) 2026 Tailscale Inc & contributors.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++1. Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++2. Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++3. Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/deps/tailscale-rs/ts_derp/PATENTS b/deps/tailscale-rs/ts_derp/PATENTSnew file mode 100644index 00000000..560a2b8f--- /dev/null+++ b/deps/tailscale-rs/ts_derp/PATENTS@@ -0,0 +1,24 @@+Additional IP Rights Grant (Patents)++"This implementation" means the copyrightable works distributed by+Tailscale Inc. as part of the Tailscale project.++Tailscale Inc. hereby grants to You a perpetual, worldwide,+non-exclusive, no-charge, royalty-free, irrevocable (except as stated+in this section) patent license to make, have made, use, offer to+sell, sell, import, transfer and otherwise run, modify and propagate+the contents of this implementation of Tailscale, where such license+applies only to those patent claims, both currently owned or+controlled by Tailscale Inc. and acquired in the future, licensable+by Tailscale Inc. that are necessarily infringed by this+implementation of Tailscale. This grant does not include claims that+would be infringed only as a consequence of further modification of+this implementation. If you or your agent or exclusive licensee+institute or order or agree to the institution of patent litigation+against any entity (including a cross-claim or counterclaim in a+lawsuit) alleging that this implementation of Tailscale or any code+incorporated within this implementation of Tailscale constitutes+direct or contributory patent infringement, or inducement of patent+infringement, then any patent rights granted to you under this License+for this implementation of Tailscale shall terminate as of the date+such litigation is filed.diff --git a/deps/tailscale-rs/ts_derp/src/client.rs b/deps/tailscale-rs/ts_derp/src/client.rsnew file mode 100644index 00000000..18a24836--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/client.rs@@ -0,0 +1,423 @@+use core::fmt;+use std::time::Duration;++use crypto_box::aead::{Aead, AeadCore, AeadMutInPlace, OsRng};+use futures::{SinkExt, StreamExt};+use tokio::{+ io::{AsyncRead, AsyncWrite, ReadHalf, WriteHalf},+ sync::Mutex,+};+use tokio_util::codec::{FramedRead, FramedWrite};+use ts_http_util::Client as _;+use ts_keys::{NodeKeyPair, NodePublicKey};+use ts_packet::PacketMut;+use ts_transport::{BatchRecvIter, BatchSendIter, DynEndpoint, UnderlayTransport};+use url::Url;++use crate::{+ Error, ServerConnInfo, frame,+ frame::{ClientInfo, FrameType, PeerGone, Ping, RawFrame, ServerInfo, ServerKey},+};++type DefaultIo = ts_http_util::Upgraded;++/// Type alias for the default derp client over upgraded HTTP on a tokio executor.+pub type DefaultClient = Client<DefaultIo>;++// ThinkTerm (derp reads): added.+/// The longest a connection may go without a frame from the server before it counts as gone.+/// The server sends a keep-alive whenever it has had nothing else to send for a minute, so a+/// connection quiet for longer died without a word: the machine slept, the network changed.+/// Go's client allows as long.+const READ_TIMEOUT: Duration = if cfg!(test) {+ Duration::from_millis(300)+} else {+ Duration::from_secs(120)+};++/// Single-region DERP client.+pub struct Client<Io> {+ read_conn: Mutex<FramedRead<ReadHalf<Io>, frame::Codec>>,+ write_conn: Mutex<FramedWrite<WriteHalf<Io>, frame::Codec>>,+}++/// Establish and upgrade a http connection to the derp region.+#[tracing::instrument(skip_all, err)]+pub async fn connect<'c>(+ region: impl IntoIterator<Item = &'c ServerConnInfo>,+) -> Result<Option<DefaultIo>, Error> {+ // ThinkTerm (derp dial): a failed TLS handshake is an error for the caller; this unwrapped it.+ let Some((conn, _, addr)) = crate::dial::dial_region_tls(region)+ .await+ .map_err(std::io::Error::other)?+ else {+ return Ok(None);+ };++ let url = Url::parse(&format!("https://{addr}/derp"))?;++ let client = ts_http_util::http1::connect(conn).await?;++ let resp = client+ .send(ts_http_util::make_upgrade_req(&url, "DERP", None)?)+ .await?;++ let upgraded = ts_http_util::do_upgrade(resp)+ .await+ .map_err(tokio::io::Error::other)+ .map_err(Error::from)?;++ Ok(Some(upgraded))+}++impl<Io> Client<Io>+where+ Io: AsyncRead + AsyncWrite,+{+ /// Perform a derp handshake over the given transport and return a [`Client`].+ #[tracing::instrument(skip_all)]+ pub async fn handshake(conn: Io, node_keypair: &NodeKeyPair) -> Result<Self, Error> {+ let (read_conn, write_conn) = tokio::io::split(conn);++ let mut fw = FramedWrite::new(write_conn, frame::Codec);+ let mut fr = FramedRead::new(read_conn, frame::Codec);++ let frame = fr.next().await.ok_or_else(|| {+ std::io::Error::new(+ std::io::ErrorKind::UnexpectedEof,+ "stream ended before server key",+ )+ })??;+ let (sk, _rest) = frame+ .get()+ .as_type::<ServerKey>()+ .ok_or_else(|| std::io::Error::other("initial message was not serverkey"))?;++ sk.validate()?;++ tracing::trace!(+ server_public_key = %sk.key,+ "derp server public key"+ );++ let (client_info, encrypted) = make_clientinfo(node_keypair, &sk.key)?;+ tracing::trace!(?client_info);++ fw.send((+ RawFrame::from_body(&client_info, encrypted.len())?,+ encrypted.as_ref(),+ ))+ .await?;++ tracing::trace!("sent client info");++ let frame = fr.next().await.ok_or_else(|| {+ std::io::Error::new(+ std::io::ErrorKind::UnexpectedEof,+ "stream ended before server info",+ )+ })??;+ let (si, payload) = frame+ .get()+ .as_type::<ServerInfo>()+ .ok_or_else(|| std::io::Error::other("frame was not serverinfo"))?;++ tracing::trace!(server_info = ?si, "got server info");++ let info = decrypt_server_info(node_keypair, sk, si, payload)?;+ tracing::trace!(server_info = ?info);++ Ok(Self {+ read_conn: Mutex::new(fr),+ write_conn: Mutex::new(fw),+ })+ }++ /// Send a message to a nodekey on the derp server.+ pub async fn send_one(&self, node_key: NodePublicKey, msg: &[u8]) -> Result<(), Error> {+ self.send_frame_with_extra(&frame::SendPacket { dest: node_key }, msg)+ .await+ }++ /// Send a frame to the derp server.+ pub async fn send_frame(+ &self,+ frame: &(impl frame::Body + zerocopy::IntoBytes + zerocopy::Immutable + Send),+ ) -> Result<(), Error> {+ self.send_frame_with_extra(frame, &[]).await+ }++ /// Send a frame to the derp server with the specified additional payload.+ pub async fn send_frame_with_extra(+ &self,+ frame: &(impl frame::Body + zerocopy::IntoBytes + zerocopy::Immutable + Send),+ additional_payload: &[u8],+ ) -> Result<(), Error> {+ let raw = RawFrame::from_body(frame, additional_payload.len())?;++ {+ let mut wr = self.write_conn.lock().await;+ wr.send((raw, additional_payload)).await?;+ }++ Ok(())+ }++ /// Waits for a single data packet from a peer to arrive via this DERP server and returns it.+ /// DERP control messages (KeepAlive, Ping, etc) are handled inline and are not returned.+ pub async fn recv_one(&self) -> Result<(NodePublicKey, PacketMut), Error> {+ // DERP exchanges control messages (KeepAlives, Pings, etc) in-band with data messages+ // (SendPacket, RecvPacket, etc). The caller only cares about the payloads of data+ // messages, so we recv_one_raw() in a loop to handle any control messages while waiting+ // for data messages.++ loop {+ let frame = {+ let mut r = self.read_conn.lock().await;+ // ThinkTerm (derp reads): each frame, keep-alives included, has READ_TIMEOUT+ // to come. Waiting without a limit, a connection that died while nothing was+ // sent on it, as the home region's often does, held its runner for good.+ tokio::time::timeout(READ_TIMEOUT, r.next())+ .await+ .map_err(|_| {+ std::io::Error::new(+ std::io::ErrorKind::TimedOut,+ "nothing from the derp server in time",+ )+ })?+ .ok_or_else(|| {+ std::io::Error::new(std::io::ErrorKind::UnexpectedEof, "derp stream ended")+ })??+ };+ let frame = frame.get();++ match frame.header.typ {+ // TODO (dylan): handle other control message types+ // TODO (dylan): handle other data message types (ForwardPacket, etc)+ #[allow(deprecated)]+ FrameType::KeepAlive => {+ // TODO (dylan): do we need to do anything on KeepAlive other than reset a timer?+ // TODO (dylan): handle KeepAlive timer+ tracing::trace!("received KeepAlive frame");+ }+ FrameType::Ping => {+ let Some((&ping, _)) = frame.as_type::<Ping>() else {+ tracing::warn!("ping frame was not ping");+ continue;+ };++ tracing::trace!(payload = ?ping.payload, "ping");++ let pong: frame::Pong = ping.into();+ self.send_frame(&pong).await?;++ tracing::trace!(payload = ?pong.payload, "pong");+ }+ FrameType::PeerGone => {+ // ThinkTerm (derp frames): a frame too short for its reason byte, as servers+ // from before the reason send, is passed over; this unwrapped it, panicking.+ let Some((gone, _rest)) = frame.as_type::<PeerGone>() else {+ tracing::debug!("peer gone frame without its reason");+ continue;+ };++ tracing::debug!(+ peer = %gone.key,+ // ThinkTerm (derp frames): a reason this does not know is no fault of+ // the connection; `?` ended it over one.+ reason = ?gone.reason(),+ "peer gone from derp server"+ );+ }+ FrameType::RecvPacket => {+ // ThinkTerm (derp frames): a packet too short for its source key is dropped;+ // this unwrapped it, panicking.+ let Some((recv, payload)) = frame.as_type::<frame::RecvPacket>() else {+ tracing::debug!("packet frame too short for its source key");+ continue;+ };++ return Ok((recv.src, payload.into()));+ }+ t => {+ return Err(Error::UnexpectedRecvFrameType(t));+ }+ }+ }+ }+}++impl Client<DefaultIo> {+ /// Connect to and handshake with the derp server with the given URL over HTTP.+ pub async fn connect<'c>(+ region: impl IntoIterator<Item = &'c ServerConnInfo>,+ node_keypair: &NodeKeyPair,+ ) -> Result<Self, Error> {+ // ThinkTerm (derp dial): no server of the region answering is an error for the caller;+ // this unwrapped it, and the panic took the region's client down.+ let conn = connect(region).await?.ok_or_else(|| {+ std::io::Error::new(+ std::io::ErrorKind::HostUnreachable,+ "no server of the DERP region could be reached",+ )+ })?;++ Client::handshake(conn, node_keypair).await+ }+}++impl<Io> fmt::Debug for Client<Io> {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ fmt::Display::fmt(self, f)+ }+}++impl<Io> fmt::Display for Client<Io> {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_tuple("Client").finish()+ }+}++fn make_clientinfo(+ node_keypair: &NodeKeyPair,+ server_key: &ts_keys::DerpServerPublicKey,+) -> Result<(ClientInfo, Vec<u8>), Error> {+ let cbox = crypto_box::SalsaBox::new(+ &server_key.to_crypto_box(),+ &node_keypair.private.to_crypto_box(),+ );+ let nonce = crypto_box::SalsaBox::generate_nonce(&mut OsRng);++ let json = serde_json::to_vec(&frame::ClientInfoPayload {+ can_ack_pings: false,+ is_prober: false,+ mesh_key: "none".to_string(),+ version: 2,+ })?;+ let encrypted = cbox+ .encrypt(&nonce, &json[..])+ .map_err(|_| frame::Error::EncryptionFailed)?;++ Ok((+ ClientInfo {+ key: node_keypair.public,+ nonce: nonce.into(),+ },+ encrypted,+ ))+}++fn decrypt_server_info(+ node_keypair: &NodeKeyPair,+ sk: &ServerKey,+ server_info: &ServerInfo,+ payload: &[u8],+) -> Result<frame::ServerInfoPayload, Error> {+ let mut payload = PacketMut::from(payload);++ let mut cbox = crypto_box::SalsaBox::new(+ &sk.key.to_crypto_box(),+ &node_keypair.private.to_crypto_box(),+ );+ cbox.decrypt_in_place(&server_info.nonce.into(), &[], &mut payload)+ .map_err(|e| frame::Error::DecryptionFailed(format!("err: {e}")))?;++ let sip = serde_json::from_slice::<frame::ServerInfoPayload>(payload.as_ref())?;+ if sip.version() != frame::PROTOCOL_VERSION {+ return Err(Error::UnsupportedProtocolVersion(+ sip.version(),+ frame::PROTOCOL_VERSION,+ ));+ }++ Ok(sip)+}++impl<Io> UnderlayTransport for Client<Io>+where+ Io: AsyncRead + AsyncWrite + Send,+{+ type Error = Error;++ async fn send(&self, packet_batch: impl BatchSendIter) -> Result<(), Self::Error> {+ for (ep, pkt) in packet_batch.batch_iter() {+ let Some(key) = ep.as_derp() else {+ tracing::warn!(?ep, "derp transport got wrong endpoint info type");+ continue;+ };++ for pkt in pkt {+ self.send_one(key, pkt.as_ref()).await?;+ }+ }++ Ok(())+ }++ async fn recv(&self) -> impl BatchRecvIter<Error = Self::Error> {+ [self+ .recv_one()+ .await+ .map(|(k, pkt)| (DynEndpoint::derp(k), [pkt]))]+ }+}++// ThinkTerm (derp reads): the tests are ours.+#[cfg(test)]+mod tests {+ use tokio::io::DuplexStream;++ use super::*;++ /// A client on one end of a connection, and the server's end to send frames on.+ fn connection() -> (+ Client<DuplexStream>,+ FramedWrite<DuplexStream, frame::Codec>,+ ) {+ let (client, server) = tokio::io::duplex(64 * 1024);+ let (read, write) = tokio::io::split(client);+ let client = Client {+ read_conn: Mutex::new(FramedRead::new(read, frame::Codec)),+ write_conn: Mutex::new(FramedWrite::new(write, frame::Codec)),+ };+ (client, FramedWrite::new(server, frame::Codec))+ }++ #[tokio::test]+ async fn a_connection_gone_quiet_is_an_error() {+ let (client, _server) = connection();+ // 0.6.1 waited for good.+ let received = tokio::time::timeout(Duration::from_secs(3), client.recv_one()).await;+ assert!(+ matches!(&received, Ok(Err(Error::IoFailure(e))) if e.kind() == std::io::ErrorKind::TimedOut),+ "{received:?}"+ );+ }++ #[tokio::test]+ #[allow(deprecated)]+ async fn keep_alives_keep_a_connection_with_nothing_to_carry() {+ let (client, mut server) = connection();+ let sender = NodeKeyPair::random().public;+ let serving = tokio::spawn(async move {+ // Well past READ_TIMEOUT in all.+ for _ in 0..10 {+ tokio::time::sleep(Duration::from_millis(100)).await;+ let keep_alive = RawFrame::from_body(&frame::KeepAlive, 0).unwrap();+ server.send((keep_alive, &[][..])).await.unwrap();+ }+ let body = frame::RecvPacket { src: sender };+ let packet = RawFrame::from_body(&body, 3).unwrap();+ server.send((packet, &b"abc"[..])).await.unwrap();+ server+ });++ let received = tokio::time::timeout(Duration::from_secs(3), client.recv_one()).await;+ let Ok(Ok((src, packet))) = received else {+ panic!("{received:?}");+ };+ assert_eq!(src, sender);+ assert_eq!(packet.as_ref(), b"abc");+ drop(serving.await);+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/dial.rs b/deps/tailscale-rs/ts_derp/src/dial.rsnew file mode 100644index 00000000..94ff2f8d--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/dial.rs@@ -0,0 +1,206 @@+//! Logic for connecting to a derp server.++use core::net::{IpAddr, SocketAddr};+use std::io;++use tokio::{+ io::{AsyncRead, AsyncWrite},+ net::TcpStream,+ task::JoinSet,+};+use ts_tls_util::ServerName;++use crate::{IpUsage, ServerConnInfo, TlsValidationConfig};++/// Error that may occur while dialing a derp server.+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]+pub enum Error {+ /// IO error occurred.+ #[error("io error occurred")]+ Io,++ /// Bad parameter.+ #[error("invalid parameter")]+ InvalidParam,+}++impl From<io::Error> for Error {+ fn from(_: io::Error) -> Self {+ Error::Io+ }+}++/// Dial a TLS connection to the first server that can successfully establish a TCP+/// connection (they are tried serially in the order presented).+///+/// A returned error is specifically an error constructing the TLS connection.+///+/// Returns `Ok(None)` iff no server could be reached, either due to connectivity errors or+/// because they were not configured to be reachable (see the note in [`dial_region_tcp`]).+/// Currently, self-signed server certs are unsupported, so servers with that configuration+/// are filtered out of the server set.+pub async fn dial_region_tls<'c>(+ servers: impl IntoIterator<Item = &'c ServerConnInfo>,+) -> Result<+ Option<(+ impl AsyncRead + AsyncWrite + Unpin + Send + 'static,+ &'c ServerConnInfo,+ SocketAddr,+ )>,+ Error,+> {+ let Some((conn, server)) = dial_region_tcp(servers).await else {+ return Ok(None);+ };+ let remote_addr = conn.peer_addr()?;++ let tls_conn = match &server.tls_validation_config {+ TlsValidationConfig::CommonName { common_name } => {+ ts_tls_util::connect(+ ServerName::try_from(common_name.clone()).map_err(|e| {+ tracing::error!(error = %e, "derp common name");+ Error::InvalidParam+ })?,+ conn,+ )+ .await?+ }+ #[cfg(feature = "insecure-for-tests")]+ TlsValidationConfig::InsecureForTests => {+ tracing::warn!(%server.hostname, "using insecure TLS for tests");++ ts_tls_util::connect_insecure(+ ServerName::try_from(server.hostname.clone()).map_err(|e| {+ tracing::error!(error = %e, "derp hostname");+ Error::InvalidParam+ })?,+ conn,+ )+ .await?+ }+ TlsValidationConfig::SelfSigned { .. } => {+ // These should be filtered out in `dial_region_tcp`, so we want this to panic.+ unimplemented!("self-signed derp server certs are currently unsupported");+ }+ };++ Ok(Some((tls_conn, server, remote_addr)))+}++/// Attempt to establish a TCP connection to one of the listed servers.+///+/// The servers are attempted serially; both IPv4 and IPv6 connections are concurrently+/// attempted for each server (if respectively enabled in the [`ServerConnInfo`]).+///+/// Returns `None` if no server could be dialed, whether due to encountered errors or+/// because they were not configured to be reachable (both ipv4/ipv6 disabled or stun_only).+/// As a temporary measure, a self-signed TLS certificate configuration also causes server+/// disablement, as this is unsupported.+pub async fn dial_region_tcp<'c>(+ servers: impl IntoIterator<Item = &'c ServerConnInfo>,+) -> Option<(TcpStream, &'c ServerConnInfo)> {+ for server in servers {+ if server.stun_only {+ tracing::trace!(%server.hostname, "server is stun only, skip");+ continue;+ }++ // TODO(npry): self-signed certs+ if matches!(+ server.tls_validation_config,+ TlsValidationConfig::SelfSigned { .. }+ ) {+ tracing::warn!(+ %server.hostname,+ "self-signed derp server certs are currently unsupported, skipping server",+ );+ continue;+ }++ // InsecureForTests is allowed through -- TLS verification is skipped in dial_region_tls.++ match dial_server(server).await {+ Ok(Some(conn)) => {+ tracing::trace!(+ remote_addr = %conn.peer_addr().unwrap_or((core::net::Ipv4Addr::UNSPECIFIED, 0).into()),+ %server.hostname,+ "derp tcp dial ok",+ );+ return Some((conn, server));+ }+ Ok(None) => {+ continue;+ }+ Err(e) => {+ tracing::error!(error = %e, %server.hostname, "failed tcp dialing server");+ continue;+ }+ }+ }++ None+}++/// Attempt a TCP connection to a single server.+///+/// IPv4 and IPv6 connections are raced concurrently: the first one to establish wins and is+/// used.+///+/// Returns `None` iff the server has both IPv4 and IPv6 configured as [`IpUsage::Disable`].+pub async fn dial_server(server: &ServerConnInfo) -> Result<Option<TcpStream>, Error> {+ let mut js = JoinSet::new();++ // TODO(npry): respect ipv6 preference. The go client just adds a flat 200ms sleep to+ // the ipv4 sample in this case.++ js.spawn(dial_by_ipusage(+ server.ipv4,+ server.hostname.clone(),+ server.https_port,+ ));+ js.spawn(dial_by_ipusage(+ server.ipv6,+ server.hostname.clone(),+ server.https_port,+ ));++ let mut last_error = None;++ while let Some(task) = js.join_next().await {+ // A JoinError is either a cancellation (not the case by inspection) or a task panic.+ // Hence, this unwrap just forwards the inner panic, which is the behavior we want here.+ match task.unwrap() {+ Ok(Some(stream)) => return Ok(Some(stream)),+ Ok(None) => {+ continue;+ }+ Err(e) => {+ last_error = Some(e);+ continue;+ }+ }+ }++ if let Some(e) = last_error {+ Err(e.into())+ } else {+ Ok(None)+ }+}++#[tracing::instrument(skip_all, level = "trace")]+async fn dial_by_ipusage(+ ip: IpUsage<impl Into<IpAddr>>,+ hostname: String,+ port: u16,+) -> io::Result<Option<TcpStream>> {+ match ip {+ IpUsage::Disable => Ok(None),+ IpUsage::FixedAddr(ip) => {+ let ip = ip.into();++ TcpStream::connect((ip, port)).await.map(Some)+ }+ IpUsage::UseDns => TcpStream::connect((hostname, port)).await.map(Some),+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/error.rs b/deps/tailscale-rs/ts_derp/src/error.rsnew file mode 100644index 00000000..4601e379--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/error.rs@@ -0,0 +1,37 @@+/// Errors encountered during derp client operation.+#[derive(Debug, thiserror::Error)]+pub enum Error {+ /// Error failed to parse.+ #[error(transparent)]+ BadUrl(#[from] url::ParseError),++ /// Deserializing JSON failed.+ #[error(transparent)]+ Deserialize(#[from] serde_json::Error),++ /// There was an error parsing the derp frame.+ #[error(transparent)]+ Frame(#[from] crate::frame::Error),++ /// An underlying IO error was encountered.+ #[error(transparent)]+ IoFailure(#[from] std::io::Error),++ /// Unsupported derp protocol version.+ #[error("unsupported DERP protocol version {0}, only supported version is {1}")]+ UnsupportedProtocolVersion(usize, usize),++ /// Received an unknown frame type.+ #[error("received unexpected DERP frame type '{0}'")]+ UnexpectedRecvFrameType(crate::frame::FrameType),++ /// Error in HTTP connection.+ #[error("http error")]+ Http,+}++impl From<ts_http_util::Error> for Error {+ fn from(_: ts_http_util::Error) -> Self {+ Error::Http+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/client_info.rs b/deps/tailscale-rs/ts_derp/src/frame/body/client_info.rsnew file mode 100644index 00000000..2c24997a--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/client_info.rs@@ -0,0 +1,37 @@+use ts_keys::NodePublicKey;+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::{+ Nonce,+ frame::{Body, FrameType},+};++/// Sent from client to server as part of the initial handshake, containing the client's+/// public key and capabilities.+///+/// An encrypted JSON-formatted [`ClientInfoPayload`] follows this message immediately.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct ClientInfo {+ /// The client's public key.+ pub key: NodePublicKey,+ /// A nonce to decrypt the payload.+ pub nonce: Nonce,+}++impl Body for ClientInfo {+ const FRAME_TYPE: FrameType = FrameType::ClientInfo;+}++/// Payload associated with [`ClientInfo`].+#[derive(serde::Serialize)]+pub struct ClientInfoPayload {+ /// Whether this client can ack pings.+ pub can_ack_pings: bool,+ /// If this client is a prober.+ pub is_prober: bool,+ /// Mesh key. Only used for server-to-server conns.+ pub mesh_key: String,+ /// Protocol version the client is using.+ pub version: i32,+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/close_peer.rs b/deps/tailscale-rs/ts_derp/src/frame/body/close_peer.rsnew file mode 100644index 00000000..573178fe--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/close_peer.rs@@ -0,0 +1,16 @@+use ts_keys::NodePublicKey;+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::frame::{Body, FrameType};++/// Mesh message to closes the provided peer's connection.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct ClosePeer {+ /// The peer whose connection should be closed.+ pub key: NodePublicKey,+}++impl Body for ClosePeer {+ const FRAME_TYPE: FrameType = FrameType::ClosePeer;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/forward_packet.rs b/deps/tailscale-rs/ts_derp/src/frame/body/forward_packet.rsnew file mode 100644index 00000000..108e401b--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/forward_packet.rs@@ -0,0 +1,20 @@+use ts_keys::NodePublicKey;+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::frame::{Body, FrameType};++/// Like [`SendPacket`][crate::frame::SendPacket], but on behalf of another peer.+///+/// Data payload follows immediately.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct ForwardPacket {+ /// Sender on behalf of which we're forwarding the packet.+ pub src: NodePublicKey,+ /// The peer to which the packet should be sent.+ pub dest: NodePublicKey,+}++impl Body for ForwardPacket {+ const FRAME_TYPE: FrameType = FrameType::ForwardPacket;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/health.rs b/deps/tailscale-rs/ts_derp/src/frame/body/health.rsnew file mode 100644index 00000000..cc1d9363--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/health.rs@@ -0,0 +1,15 @@+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::frame::{Body, FrameType};++/// Indication that the client-server connection is unhealthy.+///+/// A UTF-8 string follows in the additional payload section which should be+/// interpreted as error text. An empty additional payload clears the error state.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct Health;++impl Body for Health {+ const FRAME_TYPE: FrameType = FrameType::Health;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/keep_alive.rs b/deps/tailscale-rs/ts_derp/src/frame/body/keep_alive.rsnew file mode 100644index 00000000..67925847--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/keep_alive.rs@@ -0,0 +1,14 @@+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::frame::{Body, FrameType};++/// Empty message to keep the connection alive.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+#[deprecated = "use Ping/Pong instead"]+pub struct KeepAlive;++#[allow(deprecated)]+impl Body for KeepAlive {+ const FRAME_TYPE: FrameType = FrameType::KeepAlive;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/mod.rs b/deps/tailscale-rs/ts_derp/src/frame/body/mod.rsnew file mode 100644index 00000000..57ffa119--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/mod.rs@@ -0,0 +1,42 @@+use crate::frame::FrameType;++mod client_info;+mod close_peer;+mod forward_packet;+mod health;+mod keep_alive;+mod note_preferred;+mod peer_gone;+mod peer_present;+mod ping;+mod pong;+mod recv_packet;+mod restarting;+mod send_packet;+mod server_info;+mod server_key;+mod watch_conns;++pub use client_info::{ClientInfo, ClientInfoPayload};+pub use close_peer::ClosePeer;+pub use forward_packet::ForwardPacket;+pub use health::Health;+#[allow(deprecated)]+pub use keep_alive::KeepAlive;+pub use note_preferred::NotePreferred;+pub use peer_gone::{PeerGone, PeerGoneReason};+pub use peer_present::PeerPresent;+pub use ping::Ping;+pub use pong::Pong;+pub use recv_packet::RecvPacket;+pub use restarting::Restarting;+pub use send_packet::SendPacket;+pub use server_info::{ServerInfo, ServerInfoPayload};+pub use server_key::ServerKey;+pub use watch_conns::WatchConns;++/// Represents a derp frame body.+pub trait Body {+ /// Frame type for this frame body.+ const FRAME_TYPE: FrameType;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/note_preferred.rs b/deps/tailscale-rs/ts_derp/src/frame/body/note_preferred.rsnew file mode 100644index 00000000..f40eacd8--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/note_preferred.rs@@ -0,0 +1,15 @@+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::frame::{Body, FrameType};++/// Indicate that this derp server is the client's preferred node.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct NotePreferred {+ /// Whether this is the client's home region (`0x1`) or not (`0x0`).+ pub is_home: u8,+}++impl Body for NotePreferred {+ const FRAME_TYPE: FrameType = FrameType::NotePreferred;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/peer_gone.rs b/deps/tailscale-rs/ts_derp/src/frame/body/peer_gone.rsnew file mode 100644index 00000000..b2b5d72f--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/peer_gone.rs@@ -0,0 +1,65 @@+use core::fmt;++use ts_keys::NodePublicKey;+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};++use crate::frame;++/// Indication from the server that a previous sender has disconnected.+#[derive(+ Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes, Unaligned,+)]+#[repr(C, packed)]+pub struct PeerGone {+ /// The server that disconnected.+ pub key: NodePublicKey,+ /// The reason code for the peer disconnection.+ pub raw_reason: u8,+}++impl PeerGone {+ /// Interpret the raw reason field as a [`PeerGoneReason`].+ pub fn reason(&self) -> Result<PeerGoneReason, frame::Error> {+ self.raw_reason.try_into()+ }+}++impl frame::Body for PeerGone {+ const FRAME_TYPE: frame::FrameType = frame::FrameType::PeerGone;+}++/// Code indicating why a DERP server can't find a path to a particular peer.+#[derive(Debug, Copy, Clone, KnownLayout, Immutable, IntoBytes)]+#[repr(u8)]+pub enum PeerGoneReason {+ /// The peer was connected to this DERP server, but has disconnected.+ Disconnected = 0x0,+ /// The DERP server doesn't know about this peer, meaning the peer has not connected to this+ /// DERP server for a long time, or has never connected to this DERP server. This is+ /// unexpected in normal ops.+ NotHere = 0x1,+}++impl fmt::Display for PeerGoneReason {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{self:?}")+ }+}++impl TryFrom<u8> for PeerGoneReason {+ type Error = frame::Error;++ fn try_from(v: u8) -> Result<Self, Self::Error> {+ Ok(match v {+ 0x0 => PeerGoneReason::Disconnected,+ 0x1 => PeerGoneReason::NotHere,+ _ => return Err(frame::Error::InvalidPeerGoneReason(v)),+ })+ }+}++impl From<PeerGoneReason> for u8 {+ fn from(v: PeerGoneReason) -> Self {+ v as u8+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/peer_present.rs b/deps/tailscale-rs/ts_derp/src/frame/body/peer_present.rsnew file mode 100644index 00000000..48f49fb6--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/peer_present.rs@@ -0,0 +1,20 @@+use ts_keys::NodePublicKey;+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, network_endian::U16};++use crate::frame::{Body, FrameType, Ip};++/// DERP mesh message indicating that the node with the given key has connected.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct PeerPresent {+ /// The connected peer's public key.+ pub key: NodePublicKey,+ /// The IP of the connected peer.+ pub ip: Ip,+ /// The port on which the peer connected.+ pub port: U16,+}++impl Body for PeerPresent {+ const FRAME_TYPE: FrameType = FrameType::PeerPresent;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/ping.rs b/deps/tailscale-rs/ts_derp/src/frame/body/ping.rsnew file mode 100644index 00000000..2401a066--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/ping.rs@@ -0,0 +1,27 @@+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::frame::{Body, FrameType};++/// Message from the server to verify connectivity.+///+/// Clients should respond with [`Pong`][crate::frame::Pong].+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct Ping {+ /// Data to send to the peer.+ ///+ /// Should be echoed back exactly in the corresponding [`Pong`][crate::frame::Pong].+ pub payload: [u8; 8],+}++impl Body for Ping {+ const FRAME_TYPE: FrameType = FrameType::Ping;+}++impl From<Ping> for crate::frame::Pong {+ fn from(value: Ping) -> Self {+ Self {+ payload: value.payload,+ }+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/pong.rs b/deps/tailscale-rs/ts_derp/src/frame/body/pong.rsnew file mode 100644index 00000000..1ce5e37c--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/pong.rs@@ -0,0 +1,17 @@+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::frame::{Body, FrameType};++/// Response to a server [`Ping`][crate::frame::Ping] containing the same payload.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct Pong {+ /// The payload to echo back to the server.+ ///+ /// Should be the same data contained in the originating [`Ping`][crate::frame::Ping].+ pub payload: [u8; 8],+}++impl Body for Pong {+ const FRAME_TYPE: FrameType = FrameType::Pong;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/recv_packet.rs b/deps/tailscale-rs/ts_derp/src/frame/body/recv_packet.rsnew file mode 100644index 00000000..11dc3451--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/recv_packet.rs@@ -0,0 +1,20 @@+use ts_keys::NodePublicKey;+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};++use crate::frame::{Body, FrameType};++/// An incoming packet from the derp server.+///+/// The data payload follows this message immediately.+#[derive(+ Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes, Unaligned,+)]+#[repr(C, packed)]+pub struct RecvPacket {+ /// The sender's public key.+ pub src: NodePublicKey,+}++impl Body for RecvPacket {+ const FRAME_TYPE: FrameType = FrameType::RecvPacket;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/restarting.rs b/deps/tailscale-rs/ts_derp/src/frame/body/restarting.rsnew file mode 100644index 00000000..04a3ac65--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/restarting.rs@@ -0,0 +1,17 @@+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, network_endian::U32};++use crate::frame::{Body, FrameType};++/// Sent from server to client to indicate that the server is restarting.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct Restarting {+ /// How long to wait before reconnecting (milliseconds).+ pub reconnect: U32,+ /// How long to try to reconnect overall (milliseconds).+ pub total: U32,+}++impl Body for Restarting {+ const FRAME_TYPE: FrameType = FrameType::Restarting;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/send_packet.rs b/deps/tailscale-rs/ts_derp/src/frame/body/send_packet.rsnew file mode 100644index 00000000..46c41cf2--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/send_packet.rs@@ -0,0 +1,18 @@+use ts_keys::NodePublicKey;+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::frame::{Body, FrameType};++/// Send a packet to the peer with the specified key.+///+/// The data payload follows this message immediately.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct SendPacket {+ /// The peer to send the data to.+ pub dest: NodePublicKey,+}++impl Body for SendPacket {+ const FRAME_TYPE: FrameType = FrameType::SendPacket;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/server_info.rs b/deps/tailscale-rs/ts_derp/src/frame/body/server_info.rsnew file mode 100644index 00000000..cc48079c--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/server_info.rs@@ -0,0 +1,52 @@+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};++use crate::{+ Nonce,+ frame::{Body, FrameType},+};++/// Part of the initial derp handshake, providing info about the server.+///+/// The payload follows as an encrypted JSON blob in the format specified by+/// [`ServerInfoPayload`].+#[derive(+ Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes, Unaligned,+)]+#[repr(C, packed)]+pub struct ServerInfo {+ /// Nonce to use for decrypting the additional payload.+ pub nonce: Nonce,+}++impl Body for ServerInfo {+ const FRAME_TYPE: FrameType = FrameType::ServerInfo;+}++/// Associated payload to [`ServerInfo`], containing runtime info for the server.+#[derive(Debug, Copy, Clone, Default, serde::Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct ServerInfoPayload {+ /// Version of the server.+ pub version: i32,+ /// Sustained refill rate of the server's token bucket.+ pub token_bucket_bytes_per_second: Option<i32>,+ /// The burst rate for the server's token bucket.+ pub token_bucket_bytes_burst: Option<i32>,+}++impl ServerInfoPayload {+ /// Get the server's sustained token bucket refill rate as a usize.+ pub fn token_bucket_bytes_per_second(&self) -> Option<usize> {+ self.token_bucket_bytes_per_second.map(|v| v as usize)+ }++ /// Get the server's token bucket burst rate as a usize.+ pub fn token_bucket_bytes_burst(&self) -> Option<usize> {+ self.token_bucket_bytes_burst.map(|v| v as usize)+ }++ /// Get the server's version as a usize.+ pub fn version(&self) -> usize {+ self.version as usize+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/server_key.rs b/deps/tailscale-rs/ts_derp/src/frame/body/server_key.rsnew file mode 100644index 00000000..340fda2b--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/server_key.rs@@ -0,0 +1,38 @@+use ts_keys::DerpServerPublicKey;+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};++use crate::{+ frame,+ frame::{Body, FrameType},+};++/// Sent from the server to the client as part of the initial handshake to provide the derp+/// server's public key.+#[derive(+ Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes, Unaligned,+)]+#[repr(C, packed)]+pub struct ServerKey {+ /// Magic byte sequence to validate that this is a DERP server behaving as expected.+ ///+ /// Users should call [`ServerKey::validate`] to check that these magic bytes are valid.+ pub magic: frame::Magic,++ /// The server's public key.+ pub key: DerpServerPublicKey,+}++impl ServerKey {+ /// Ensure the magic number for this serverkey is valid.+ pub fn validate(&self) -> Result<(), frame::Error> {+ if !self.magic.is_valid() {+ return Err(frame::Error::InvalidMagic);+ }++ Ok(())+ }+}++impl Body for ServerKey {+ const FRAME_TYPE: FrameType = FrameType::ServerKey;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/body/watch_conns.rs b/deps/tailscale-rs/ts_derp/src/frame/body/watch_conns.rsnew file mode 100644index 00000000..5f30eb4c--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/body/watch_conns.rs@@ -0,0 +1,12 @@+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::frame::{Body, FrameType};++/// How one derp node in a regional mesh subscribes to others in the region.+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct WatchConns;++impl Body for WatchConns {+ const FRAME_TYPE: FrameType = FrameType::WatchConns;+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/codec.rs b/deps/tailscale-rs/ts_derp/src/frame/codec.rsnew file mode 100644index 00000000..1a7cec4a--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/codec.rs@@ -0,0 +1,99 @@+use bytes::{Buf, BufMut, BytesMut};+use ts_hexdump::{AsHexExt, Case};+use zerocopy::{FromBytes, IntoBytes};++use crate::frame::{Header, RawFrame, RawHeader};++/// Implements [`tokio_util::codec::Encoder`] and [`tokio_util::codec::Decoder`] for+/// the derp protocol.+pub struct Codec;++impl<'a, 'b> tokio_util::codec::Encoder<(RawFrame<'a>, &'b [u8])> for Codec {+ type Error = std::io::Error;++ #[tracing::instrument(skip_all, fields(frame_hdr = ?frame.header, frame_body_len = frame.raw_body.len(), extra_payload_len = extra_payload.len()), err, level = "trace")]+ fn encode(+ &mut self,+ (frame, extra_payload): (RawFrame<'a>, &'b [u8]),+ dst: &mut BytesMut,+ ) -> Result<(), Self::Error> {+ let header: RawHeader = frame.header.into();++ debug_assert_eq!(header.len(), { frame.raw_body.len() + extra_payload.len() });++ tracing::trace!(raw_header = ?header);++ dst.put_slice(header.as_bytes());+ dst.put_slice(frame.raw_body);+ dst.put_slice(extra_payload);++ tracing::trace!(+ len = dst.len(),+ "dst:\n{}",+ dst.iter().hexdump_string(Case::Lower)+ );++ Ok(())+ }+}++impl<'a> tokio_util::codec::Encoder<RawFrame<'a>> for Codec {+ type Error = std::io::Error;++ #[tracing::instrument(skip_all, fields(frame_hdr = ?frame.header, frame_body_len = frame.raw_body.len()), err, level = "trace")]+ fn encode(&mut self, frame: RawFrame<'a>, dst: &mut BytesMut) -> Result<(), Self::Error> {+ <Self as tokio_util::codec::Encoder<(RawFrame<'a>, &'static [u8])>>::encode(+ self,+ (frame, &[]),+ dst,+ )+ }+}++impl tokio_util::codec::Decoder for Codec {+ type Item = yoke::Yoke<RawFrame<'static>, Vec<u8>>;+ type Error = std::io::Error;++ #[tracing::instrument(skip_all, fields(src_len = src.len(), src_cap = src.capacity()), err, level = "trace")]+ fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {+ if src.len() < Header::LEN_BYTES {+ return Ok(None);+ }++ let (header, post_header_len) = {+ let (header, rest) = RawHeader::ref_from_prefix(src).map_err(|e| {+ tracing::error!(err = %e);+ std::io::Error::other("invalid raw header")+ })?;++ let header: Header = header.try_into().map_err(std::io::Error::other)?;+ (header, rest.len())+ };++ let header_len = src.len() - post_header_len;+ let full_packet_len = header_len + header.len() as usize;++ tracing::trace!(+ header_len,+ post_header_len,+ full_packet_len,+ orig_len = src.len(),+ ?header+ );++ if full_packet_len > src.len() {+ tracing::trace!("incomplete packet, bail out");+ return Ok(None);+ }++ src.advance(header_len);+ let payload = src.split_to(header.len() as _);++ let ret = yoke::Yoke::attach_to_cart(payload.to_vec(), move |raw_body| RawFrame {+ header,+ raw_body,+ });++ Ok(Some(ret))+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/error.rs b/deps/tailscale-rs/ts_derp/src/frame/error.rsnew file mode 100644index 00000000..adc888b8--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/error.rs@@ -0,0 +1,66 @@+use core::convert::Infallible;+use std::string::ToString;++use zerocopy::{AlignmentError, CastError, ConvertError, KnownLayout, SizeError};++use crate::frame;++/// Errors that can occur when trying to parse a DERP frame from a packet.+#[derive(Debug, thiserror::Error)]+pub enum Error {+ /// Packet too short.+ #[error("cannot parse {0}-byte packet; valid frames are at least 5 bytes")]+ InvalidPacketLength(usize),+ /// Could not parse frame header.+ #[error("cannot parse frame header from packet: {0}")]+ InvalidFrameHeader(String),+ /// Unknown frame type.+ #[error("invalid frame type {0:02X}")]+ InvalidFrameType(u8),+ /// Invalid frame length for frame type.+ #[error("frame type {0} has max length of {2} bytes; header length is {1}")]+ InvalidFrameLengthForType(frame::FrameType, usize, usize),+ /// Invalid body length for frame type.+ #[error("frame type {0} has min length of {2} bytes; body length is {1}")]+ InvalidBodyLengthForType(frame::FrameType, usize, usize),+ /// Error parsing frame body.+ #[error("cannot parse {0} frame body from packet: {1}")]+ InvalidFrameBody(frame::FrameType, String),+ /// Frame unexpectedly had a payload.+ #[error("frame type {0} cannot have a payload, but {1} bytes remained in packet")]+ InvalidFrameStructure(frame::FrameType, usize),+ /// Invalid magic bytes.+ #[error("invalid magic byte sequence in ServerKey frame")]+ InvalidMagic,+ /// Unknown peer gone reason.+ #[error("invalid peer gone reason: {0}")]+ InvalidPeerGoneReason(u8),+ /// Incomplete frame.+ #[error("incomplete frame")]+ IncompleteFrame,+ /// Decryption failed.+ #[error("could not decrypt frame payload")]+ DecryptionFailed(String),+ /// Encryption failed.+ #[error("could not encrypt frame payload")]+ EncryptionFailed,+ /// Invalid public key.+ #[error("could not parse public key from string")]+ InvalidKey,+}++impl From<CastError<&[u8], frame::RawHeader>> for Error {+ fn from(value: CastError<&[u8], frame::RawHeader>) -> Self {+ Error::InvalidFrameHeader(value.to_string())+ }+}++impl<B: frame::Body + KnownLayout>+ From<ConvertError<AlignmentError<&[u8], B>, SizeError<&[u8], B>, Infallible>> for Error+{+ fn from(+ value: ConvertError<AlignmentError<&[u8], B>, SizeError<&[u8], B>, Infallible>,+ ) -> Self {+ Error::InvalidFrameBody(B::FRAME_TYPE, value.to_string())+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/frame_type.rs b/deps/tailscale-rs/ts_derp/src/frame/frame_type.rsnew file mode 100644index 00000000..526e87fb--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/frame_type.rs@@ -0,0 +1,133 @@+use std::fmt;++use crate::frame::error::Error;++/// Indicates the type of message contained in a DERP frame.+#[derive(Debug, Copy, Clone, PartialEq, Eq)]+#[repr(u8)]+pub enum FrameType {+ /// Payload contains the server public key.+ ServerKey = 0x01,++ /// The client's connection info and public key.+ ClientInfo = 0x02,+ /// The server's connection info.+ ServerInfo = 0x03,+ /// Send a packet to a specified peer.+ SendPacket = 0x04,+ /// Send a packet on behalf of another peer.+ ForwardPacket = 0x0a,+ /// A packet sent from the server on behalf of another peer.+ RecvPacket = 0x05,++ /// Empty-payload message meant to keep the connection alive.+ #[deprecated = "use Ping/Pong instead"]+ KeepAlive = 0x06,++ /// Indicate whether this server is the client's preferred derp server.+ NotePreferred = 0x07,++ /// Signals to the client that a previous sender is no longer connected.+ ///+ /// That is, if `A` sent to `B`, and `A` disconnects, the server sends this frame type+ /// to `B` so that `B` can forget the reverse path to `A`. It is also sent to `A` if+ /// `A` tries to send a `CallMeMaybe` to `B` and the server has no record of `B`+ /// (currently, this would only happen if there is a bug).+ PeerGone = 0x08,++ /// Like [`FrameType::PeerGone`], but between meshed members of a derp region.+ PeerPresent = 0x09,++ /// How one DERP node in a regional mesh subscribes to the others in the region.+ WatchConns = 0x10,++ /// Privileged frame that closes the provided peer's connection, used for cluster load+ /// balancing.+ ClosePeer = 0x11,++ /// To be echoed back by a [`FrameType::Pong`].+ Ping = 0x12,+ /// Response to a [`FrameType::Ping`].+ Pong = 0x13,++ /// Sent from the server to the client to tell the client that the connection is+ /// unhealthy somehow.+ ///+ /// Currently, the only unhealthy state is if the connection is detected as a duplicate.+ Health = 0x14,++ /// Sent from the server to client for the server to declare that it's restarting.+ Restarting = 0x15,+}++/// The entity that originates a frame.+pub enum Originator {+ Server,+ Client,+}++impl FrameType {+ /// Report the originator of this message kind.+ pub const fn originator(&self) -> Originator {+ #[allow(deprecated)]+ match self {+ FrameType::Health+ | FrameType::ServerKey+ | FrameType::ServerInfo+ | FrameType::PeerPresent+ | FrameType::Restarting+ | FrameType::RecvPacket+ | FrameType::WatchConns+ | FrameType::KeepAlive+ | FrameType::Ping => Originator::Server,+ _ => Originator::Client,+ }+ }++ /// Report whether this frame type is privileged (requires the mesh key).+ pub const fn is_privileged(&self) -> bool {+ matches!(+ self,+ FrameType::PeerPresent | FrameType::ClosePeer | FrameType::WatchConns+ )+ }+}++impl TryFrom<u8> for FrameType {+ type Error = Error;++ fn try_from(v: u8) -> Result<Self, Self::Error> {+ Ok(match v {+ 0x01 => FrameType::ServerKey,+ 0x02 => FrameType::ClientInfo,+ 0x03 => FrameType::ServerInfo,+ 0x04 => FrameType::SendPacket,+ 0x0a => FrameType::ForwardPacket,+ 0x05 => FrameType::RecvPacket,+ #[allow(deprecated)]+ 0x06 => FrameType::KeepAlive,+ 0x07 => FrameType::NotePreferred,+ 0x08 => FrameType::PeerGone,+ 0x09 => FrameType::PeerPresent,+ 0x10 => FrameType::WatchConns,+ 0x11 => FrameType::ClosePeer,+ 0x12 => FrameType::Ping,+ 0x13 => FrameType::Pong,+ 0x14 => FrameType::Health,+ 0x15 => FrameType::Restarting,+ _ => return Err(Error::InvalidFrameType(v)),+ })+ }+}++impl fmt::Display for FrameType {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{self:?}")+ }+}++impl From<FrameType> for u8 {+ fn from(v: FrameType) -> Self {+ v as u8+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/header.rs b/deps/tailscale-rs/ts_derp/src/frame/header.rsnew file mode 100644index 00000000..14899ceb--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/header.rs@@ -0,0 +1,93 @@+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, network_endian::U32};++use crate::frame;++/// The TLV header for the derp protocol as it appears on the wire.+///+/// Convert into [`Header`] for easier manipulation.+#[derive(Debug, Copy, Clone, KnownLayout, Immutable, IntoBytes, FromBytes)]+#[repr(C)]+pub struct RawHeader {+ typ: u8,+ len: U32,+}++impl RawHeader {+ /// Interpret the type field as a well-known [`frame::FrameType`].+ pub fn typ(&self) -> Result<frame::FrameType, frame::Error> {+ self.typ.try_into()+ }++ /// Report the length of this frame (excluding the 5-byte header length).+ #[allow(clippy::len_without_is_empty)]+ pub fn len(&self) -> usize {+ self.len.get() as usize+ }+}++/// Header for the derp protocol.+///+/// Convert to [`RawHeader`] for the wire format.+#[derive(Debug, Copy, Clone, PartialEq, Eq)]+pub struct Header {+ /// The frame type.+ pub typ: frame::FrameType,+ len: u32,+}++impl Header {+ /// The length of a header in bytes on the wire.+ pub const LEN_BYTES: usize = 5;++ /// Construct a new frame of the specified type and length.+ ///+ /// May fail if the `len` exceeds `frame::MAX_PACKET_SIZE`.+ pub const fn new(typ: frame::FrameType, len: u32) -> Result<Self, frame::Error> {+ if len as usize > frame::MAX_PACKET_SIZE {+ return Err(frame::Error::InvalidPacketLength(len as _));+ }++ Ok(Self { typ, len })+ }++ /// Report the length of the associated frame (excluding the 5-byte header length).+ #[allow(clippy::len_without_is_empty)]+ pub const fn len(&self) -> u32 {+ self.len+ }++ /// Set the len to `new_len`.+ pub const fn set_len(&mut self, new_len: u32) -> Result<(), frame::Error> {+ if new_len as usize > frame::MAX_PACKET_SIZE {+ return Err(frame::Error::InvalidPacketLength(new_len as _));+ }++ self.len = new_len;+ Ok(())+ }+}++impl TryFrom<&RawHeader> for Header {+ type Error = frame::Error;++ fn try_from(&RawHeader { typ, len }: &RawHeader) -> Result<Self, Self::Error> {+ let len = len.get();+ if len as usize > frame::MAX_PACKET_SIZE {+ return Err(frame::Error::InvalidPacketLength(len as _));+ }++ Ok(Self {+ typ: typ.try_into()?,+ len,+ })+ }+}++impl From<Header> for RawHeader {+ fn from(Header { typ, len }: Header) -> Self {+ Self {+ typ: typ as _,+ len: U32::new(len),+ }+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/magic.rs b/deps/tailscale-rs/ts_derp/src/frame/magic.rsnew file mode 100644index 00000000..46ef7846--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/magic.rs@@ -0,0 +1,48 @@+use std::fmt;++use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};++/// Newtype wrapper around an 8-byte array so we can implement [`fmt::Display`] and use the+/// type in error enums/messages.+#[derive(+ Debug,+ Copy,+ Clone,+ Eq,+ PartialEq,+ PartialOrd,+ Ord,+ IntoBytes,+ KnownLayout,+ Immutable,+ FromBytes,+ Unaligned,+)]+#[repr(C)]+pub struct Magic([u8; 8]);++impl Magic {+ /// DERP magic number, sent in the [`ServerKey`][crate::frame::ServerKey] frame upon+ /// initial connection. Byte representation of the string "DERP🔑".+ pub const MAGIC: Magic = Magic([0x44, 0x45, 0x52, 0x50, 0xF0, 0x9F, 0x94, 0x91]);++ /// Report whether this magic number matches the expected value.+ pub const fn is_valid(&self) -> bool {+ matches!(self, &Self::MAGIC)+ }+}++impl AsRef<[u8]> for Magic {+ fn as_ref(&self) -> &[u8] {+ &self.0+ }+}++impl fmt::Display for Magic {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ for b in self.0 {+ f.write_fmt(format_args!("{b:02X}"))?;+ }+ Ok(())+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/frame/mod.rs b/deps/tailscale-rs/ts_derp/src/frame/mod.rsnew file mode 100644index 00000000..821c7e99--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/mod.rs@@ -0,0 +1,49 @@+//! Derp framing implementation.++use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++mod body;+mod codec;+mod error;+mod frame_type;+mod header;+mod magic;+mod raw;++#[allow(deprecated)]+pub use body::KeepAlive;+pub use body::{+ Body, ClientInfo, ClientInfoPayload, ClosePeer, ForwardPacket, Health, NotePreferred, PeerGone,+ PeerGoneReason, PeerPresent, Ping, Pong, RecvPacket, Restarting, SendPacket, ServerInfo,+ ServerInfoPayload, ServerKey, WatchConns,+};+pub use codec::Codec;+pub use error::Error;+pub use frame_type::FrameType;+pub use header::{Header, RawHeader};+pub use magic::Magic;+pub use raw::RawFrame;++/// Maximum size (in bytes) of a packet sent via DERP, not including any on-wire framing overhead.+/// Equivalent to the max payload size of a [SendPacket], [ForwardPacket], or [RecvPacket] frame.+pub const MAX_PACKET_SIZE: usize = 64 << 10;++/// Maximum length (in bytes) of a [ClientInfo] or [ServerInfo] frame's payload, excluding the+/// key and nonce fields, and any on-wire framing overhead.+pub const MAX_INFO_LEN: usize = 1 << 20;++/// Minimum frequency (in seconds) at which the DERP server sends [`KeepAlive`] frames to each DERP+/// client. The server adds some jitter, so this timing is not exact, but 2x this value can be+/// considered a missed keep-alive.+pub const KEEP_ALIVE: usize = 60;++/// Current version of the DERP protocol; must be bumped whenever there's a wire-incompatible+/// change.+/// - Version 1 (zero on wire): consistent box headers, in use by employee dev nodes a bit+/// - Version 2: received packets have src addrs in [RecvPacket] frames at beginning+pub const PROTOCOL_VERSION: usize = 2;++/// IP address.+#[repr(C)]+#[derive(Debug, Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+pub struct Ip([u8; 16]);diff --git a/deps/tailscale-rs/ts_derp/src/frame/raw.rs b/deps/tailscale-rs/ts_derp/src/frame/raw.rsnew file mode 100644index 00000000..735e0404--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/frame/raw.rs@@ -0,0 +1,84 @@+use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++use crate::frame::{Body, Error, Header, RawHeader};++/// A raw DERP frame.+#[derive(Debug, Copy, Clone, PartialEq, Eq, yoke::Yokeable)]+pub struct RawFrame<'a> {+ /// This frame's header.+ pub header: Header,++ /// This frame's raw body bytes.+ ///+ /// If the frame was parsed with [`RawFrame::parse`], this field contains both the frame+ /// body and additional subsequent data.+ pub raw_body: &'a [u8],+}++impl<'a> RawFrame<'a> {+ /// Parse a frame from the specified byte slice.+ ///+ /// # Returns+ ///+ /// A [`RawFrame`] and the rest of the bytes (that were not consumed) as a tuple, if+ /// there was no error.+ ///+ /// A successfully parsed frame always has a [`RawFrame::raw_body`] with a length+ /// exactly equal to its [`Header::len`].+ pub fn parse(b: &'a [u8]) -> Result<(Self, &'a [u8]), Error> {+ let (raw_header, rest) = RawHeader::ref_from_prefix(b)?;+ let header: Header = raw_header.try_into()?;++ let (this_frame, rest) = rest+ .split_at_checked(header.len() as _)+ .ok_or(Error::IncompleteFrame)?;++ Ok((+ RawFrame {+ header,+ raw_body: this_frame,+ },+ rest,+ ))+ }++ /// Attempt to interpret the frame body as a `T`.+ ///+ /// Consults `T`'s [`Body`] implementation to check the expected frame type against the+ /// header.+ ///+ /// # Returns+ ///+ /// If the frame type matches, the body type `T` with a trailing byte slice carrying an+ /// additional payload. This additional payload contains the data payload in+ /// [`SendPacket`][crate::frame::SendPacket], for instance.+ pub fn as_type<T>(&self) -> Option<(&T, &[u8])>+ where+ T: Body + FromBytes + Immutable + KnownLayout,+ {+ if self.header.typ != T::FRAME_TYPE {+ return None;+ }++ T::ref_from_prefix(self.raw_body).ok()+ }++ /// Construct a new [`RawFrame`] from a [`Body`] and a specified additional+ /// `payload_len`.+ ///+ /// NB: this constructs a [`RawFrame`] that does _not_ contain the full payload+ /// in the `raw_body`. This is to accommodate outgoing messages which can't put the+ /// additional payload in the same buffer as the primary payload. See the+ /// [`Codec`][crate::frame::Codec] source for a usage example.+ pub fn from_body<T>(t: &'a T, payload_len: usize) -> Result<Self, Error>+ where+ T: Body + IntoBytes + Immutable,+ {+ let bytes = t.as_bytes();++ Ok(Self {+ header: Header::new(T::FRAME_TYPE, (bytes.len() + payload_len) as _)?,+ raw_body: bytes,+ })+ }+}diff --git a/deps/tailscale-rs/ts_derp/src/lib.rs b/deps/tailscale-rs/ts_derp/src/lib.rsnew file mode 100644index 00000000..00500068--- /dev/null+++ b/deps/tailscale-rs/ts_derp/src/lib.rs@@ -0,0 +1,234 @@+//! Tailscale derp protocol and client.+// ThinkTerm (build): was `#![doc = include_str!("../README.md")]`; the README is not vendored.++use core::{+ fmt,+ net::{Ipv4Addr, Ipv6Addr},+ num::NonZeroU32,+};++use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};++mod client;+pub mod dial;+mod error;+pub mod frame;++pub use client::{Client, DefaultClient};+pub use error::Error;++/// A 24-byte nonce for symmetric encryption with ChaCha20Poly1305.+#[repr(C)]+#[derive(Copy, Clone, PartialEq, KnownLayout, Immutable, IntoBytes, FromBytes)]+pub struct Nonce(pub [u8; 24]);++impl fmt::Debug for Nonce {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ for b in self.0.iter() {+ write!(f, "{b:02x}")?;+ }+ Ok(())+ }+}++impl From<crypto_box::aead::Nonce<crypto_box::SalsaBox>> for Nonce {+ fn from(value: crypto_box::aead::Nonce<crypto_box::SalsaBox>) -> Self {+ Nonce(value.into())+ }+}++impl From<Nonce> for crypto_box::aead::Nonce<crypto_box::SalsaBox> {+ fn from(value: Nonce) -> Self {+ value.0.into()+ }+}++/// Unique identifier for a derp region.+#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct RegionId(pub NonZeroU32);++impl fmt::Display for RegionId {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ self.0.get().fmt(f)+ }+}++/// Info about a region.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct RegionInfo {+ /// The name of the region.+ pub name: String,++ /// The shortcode for the region, e.g. `nyc` for New York City.+ pub code: String,++ /// Don't attempt to use this region as a home region, and don't measure latency to+ /// it. It is permitted, however, to communicate with servers in the region to contact+ /// peers that do have this region as their home.+ pub no_measure_no_home: bool,+}++/// Info about a specific derp server.+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]+pub struct ServerConnInfo {+ /// The hostname of the server.+ pub hostname: String,++ /// The IPv4 address of the server.+ pub ipv4: IpUsage<Ipv4Addr>,+ /// The IPv6 address of the server.+ pub ipv6: IpUsage<Ipv6Addr>,++ /// Configuration used to validate the server's certificate.+ pub tls_validation_config: TlsValidationConfig,++ /// The port to use to connect to the server via HTTPS.+ pub https_port: u16,++ /// The port to use to perform STUN with the server. If `None`, STUN is disabled on this server.+ pub stun_port: Option<u16>,++ /// Whether this server is only to be used for stun.+ pub stun_only: bool,++ /// Whether the server is reachable over port 80 (typically used for captive portal+ /// detection).+ pub supports_port_80: bool,+}++impl ServerConnInfo {+ /// Convenience helper to create a [`ServerConnInfo`] from an HTTPS URL.+ ///+ /// The only canonical way to obtain a [`ServerConnInfo`] is by downloading the DERP+ /// map from a trusted source. This function allows constructing one with certain+ /// heuristic assumptions on the basis of just the HTTPS URL, which by definition+ /// doesn't contain all the information about a given DERP server. Consider this a+ /// warning that a given connection may not succeed if the assumptions made here do not+ /// match the reality of what the actual DERP server supports.+ ///+ /// ## Assumptions+ ///+ /// - The URL uses the `https` scheme+ /// - The URL's host resolves to IPv4 and IPv6 addresses via DNS+ /// - The TLS common name is the URL's host+ /// - The STUN port for the server is the default (3478)+ /// - The server doesn't support port 80 connections for captive portal detection+ pub fn default_from_url(url: &url::Url) -> Option<Self> {+ if url.scheme() != "https" {+ return None;+ }++ let hostname = url.host_str()?.to_owned();+ let https_port = url.port().unwrap_or(443);++ Some(Self {+ hostname: hostname.clone(),++ ipv4: IpUsage::UseDns,+ ipv6: IpUsage::UseDns,++ tls_validation_config: TlsValidationConfig::CommonName {+ common_name: hostname,+ },++ https_port,+ stun_port: Some(3478),+ supports_port_80: false,+ stun_only: false,+ })+ }++ /// Build the URL to connect to this derp server over IPv4.+ ///+ /// This is only possible if [`Self::ipv4`][ServerConnInfo::ipv4] is not+ /// [`IpUsage::Disable`].+ pub fn https_url_ipv4(&self) -> Result<Option<url::Url>, url::ParseError> {+ match self.ipv4 {+ IpUsage::Disable => Ok(None),+ IpUsage::FixedAddr(addr) => {+ url::Url::parse(&format!("https://{addr}:{}", self.https_port)).map(Some)+ }+ IpUsage::UseDns => {+ url::Url::parse(&format!("https://{}:{}", self.hostname, self.https_port)).map(Some)+ }+ }+ }++ /// Build the URL to connect to this derp server over IPv6.+ ///+ /// This is only possible if [`Self::ipv6`][ServerConnInfo::ipv6] is not+ /// [`IpUsage::Disable`].+ pub fn https_url_ipv6(&self) -> Result<Option<url::Url>, url::ParseError> {+ match self.ipv6 {+ IpUsage::Disable => Ok(None),+ IpUsage::FixedAddr(addr) => {+ url::Url::parse(&format!("https://{addr}:{}", self.https_port)).map(Some)+ }+ IpUsage::UseDns => {+ url::Url::parse(&format!("https://{}:{}", self.hostname, self.https_port)).map(Some)+ }+ }+ }+}++/// Specifies the usage mode for an IP addressing type.+#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]+pub enum IpUsage<T> {+ /// Disable this IP addressing mode entirely.+ Disable,+ /// Use DNS lookups to resolve the address of this node using its hostname.+ UseDns,+ /// Use this fixed address to connect to this node in the specified IP stack.+ FixedAddr(T),+}++/// Configuration for TLS certificate validation.+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]+pub enum TlsValidationConfig {+ /// The certificate is self-signed and has this SHA256 signature.+ SelfSigned {+ /// The signature of the self-signed cert.+ sha256: [u8; 64],+ },+ /// The certificate has the given common name.+ CommonName {+ /// The common name the certificate should have.+ common_name: String,+ },+ #[cfg(feature = "insecure-for-tests")]+ /// Skip TLS certificate verification entirely. Only for use in tests.+ InsecureForTests,+}++impl TlsValidationConfig {+ const TLS_SELFSIGNED_PREFIX: &str = "sha256-raw:";++ /// Convert a string to a validation config.+ ///+ /// `hostname` is used as a fallback if `s` is empty or invalid.+ pub fn from_str(s: &str, hostname: &str) -> TlsValidationConfig {+ match s {+ "" => TlsValidationConfig::CommonName {+ common_name: hostname.to_owned(),+ },+ x if x.starts_with(Self::TLS_SELFSIGNED_PREFIX) => {+ let mut buf = [0u8; 64];+ let bs = x.strip_prefix(Self::TLS_SELFSIGNED_PREFIX).unwrap().trim();++ match hex::decode_to_slice(bs, &mut buf) {+ Ok(()) => TlsValidationConfig::SelfSigned { sha256: buf },+ Err(e) => {+ tracing::error!(error = %e, "invalid tls selfsigned cert, falling back to hostname");++ TlsValidationConfig::CommonName {+ common_name: hostname.to_owned(),+ }+ }+ }+ }+ x => TlsValidationConfig::CommonName {+ common_name: x.to_owned(),+ },+ }+ }+}