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
feat(tailnet): join a tailnet from the mux server
RoversX5e8f1b9454b7
diff --git a/Cargo.lock b/Cargo.lockindex dc576c73..b7f7b241 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -29,6 +29,16 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234"+[[package]]+name = "aead"+version = "0.5.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"+dependencies = [+ "crypto-common 0.1.6",+ "generic-array 0.14.9",+]+[[package]]name = "aead"version = "0.6.1"@@ -36,7 +46,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"dependencies = ["crypto-common 0.2.2",- "inout",+ "inout 0.2.2",][[package]]@@ -45,7 +55,7 @@ version = "0.9.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32"dependencies = [- "cipher",+ "cipher 0.5.2","cpubits","cpufeatures 0.3.1","zeroize",@@ -57,9 +67,9 @@ version = "0.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f"dependencies = [- "aead",+ "aead 0.6.1","aes",- "cipher",+ "cipher 0.5.2","ctr","ctutils","ghash",@@ -207,7 +217,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c"dependencies = ["base64ct",- "blake2",+ "blake2 0.11.0","cpufeatures 0.3.1","password-hash",]@@ -521,6 +531,29 @@ dependencies = ["arrayvec",]+[[package]]+name = "aws-lc-rs"+version = "1.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "faac5829c2b74c28f830747e7818ccfb684261b5f48a1118b1e2a13d36dfab13"+dependencies = [+ "aws-lc-sys",+ "zeroize",+]++[[package]]+name = "aws-lc-sys"+version = "0.46.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1622d8446a2d4b2ce0c7eefc73dd43a99779028d5ee5c2dd8073a658ba8a2bc"+dependencies = [+ "cc",+ "cmake",+ "dunce",+ "fs_extra",+ "pkg-config",+]+[[package]]name = "az"version = "1.2.1"@@ -674,12 +707,42 @@ dependencies = ["serde_core",]+[[package]]+name = "bitrs"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad65ba2eda683a8486f72c13f0e1f5afbaa99ccd08029e6a72b1cf46ef0f0309"+dependencies = [+ "bitrs-macro",+ "zerocopy",+]++[[package]]+name = "bitrs-macro"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "896dc69748b78a3bc4b815084e15cb51efdedc22a6d0ef5a443f6bd5e92af89a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.110",+]+[[package]]name = "bitstream-io"version = "2.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6099cdc01846bc367c4e7dd630dc5966dccf36b652fae7a74e17b640411a91b2"+[[package]]+name = "blake2"+version = "0.10.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"+dependencies = [+ "digest 0.10.7",+]+[[package]]name = "blake2"version = "0.11.0"@@ -752,9 +815,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "62ce3946557b35e71d1bbe07ec385073ce9eda05043f95de134eb578fcf1a298"dependencies = ["byteorder",- "cipher",+ "cipher 0.5.2",+]++[[package]]+name = "borsh"+version = "1.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a"+dependencies = [+ "bytes",+ "cfg_aliases",]+[[package]]+name = "bounded-integer"+version = "0.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "102dbef1187b1893e6dfe05a774e79fd52265f49f214f6879c8ff49f52c8188b"+[[package]]name = "bstr"version = "1.12.1"@@ -903,7 +982,7 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"dependencies = [- "cipher",+ "cipher 0.5.2",][[package]]@@ -949,6 +1028,17 @@ dependencies = ["libc",]+[[package]]+name = "chacha20"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"+dependencies = [+ "cfg-if",+ "cipher 0.4.4",+ "cpufeatures 0.2.17",+]+[[package]]name = "chacha20"version = "0.10.2"@@ -956,12 +1046,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"dependencies = ["cfg-if",- "cipher",+ "cipher 0.5.2","cpufeatures 0.3.1","rand_core 0.10.1","zeroize",]+[[package]]+name = "chacha20poly1305"+version = "0.10.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"+dependencies = [+ "aead 0.5.2",+ "chacha20 0.9.1",+ "cipher 0.4.4",+ "poly1305 0.8.0",+ "zeroize",+]+[[package]]name = "chrono"version = "0.4.42"@@ -1004,6 +1107,17 @@ dependencies = ["half",]+[[package]]+name = "cipher"+version = "0.4.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"+dependencies = [+ "crypto-common 0.1.6",+ "inout 0.1.4",+ "zeroize",+]+[[package]]name = "cipher"version = "0.5.2"@@ -1012,7 +1126,7 @@ checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"dependencies = ["block-buffer 0.12.1","crypto-common 0.2.2",- "inout",+ "inout 0.2.2","zeroize",]@@ -1084,6 +1198,15 @@ dependencies = ["error-code",]+[[package]]+name = "cmake"+version = "0.1.58"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678"+dependencies = [+ "cc",+]+[[package]]name = "cmov"version = "0.5.4"@@ -1426,6 +1549,21 @@ dependencies = ["libc",]+[[package]]+name = "crc"+version = "3.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"+dependencies = [+ "crc-catalog",+]++[[package]]+name = "crc-catalog"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"+[[package]]name = "crc32fast"version = "1.5.0"@@ -1584,6 +1722,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"dependencies = ["generic-array 0.14.9",+ "rand_core 0.6.4","typenum",]@@ -1598,6 +1737,35 @@ dependencies = ["rand_core 0.10.1",]+[[package]]+name = "crypto_box"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "16182b4f39a82ec8a6851155cc4c0cda3065bb1db33651726a29e1951de0f009"+dependencies = [+ "aead 0.5.2",+ "crypto_secretbox",+ "curve25519-dalek 4.1.3",+ "salsa20 0.10.2",+ "subtle",+ "zeroize",+]++[[package]]+name = "crypto_secretbox"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b9d6cf87adf719ddf43a805e92c6870a531aedda35ff640442cbaf8674e141e1"+dependencies = [+ "aead 0.5.2",+ "cipher 0.4.4",+ "generic-array 0.14.9",+ "poly1305 0.8.0",+ "salsa20 0.10.2",+ "subtle",+ "zeroize",+]+[[package]]name = "csscolorparser"version = "0.6.2"@@ -1637,7 +1805,7 @@ version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21"dependencies = [- "cipher",+ "cipher 0.5.2",][[package]]@@ -1656,6 +1824,21 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"+[[package]]+name = "curve25519-dalek"+version = "4.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be"+dependencies = [+ "cfg-if",+ "cpufeatures 0.2.17",+ "curve25519-dalek-derive",+ "fiat-crypto 0.2.9",+ "rustc_version",+ "subtle",+ "zeroize",+]+[[package]]name = "curve25519-dalek"version = "5.0.0"@@ -1666,7 +1849,7 @@ dependencies = ["cpufeatures 0.3.1","curve25519-dalek-derive","digest 0.11.3",- "fiat-crypto",+ "fiat-crypto 0.3.0","rand_core 0.10.1","rustc_version","subtle",@@ -1694,6 +1877,16 @@ dependencies = ["darling_macro 0.20.11",]+[[package]]+name = "darling"+version = "0.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0"+dependencies = [+ "darling_core 0.21.3",+ "darling_macro 0.21.3",+]+[[package]]name = "darling"version = "0.23.0"@@ -1718,6 +1911,20 @@ dependencies = ["syn 2.0.110",]+[[package]]+name = "darling_core"+version = "0.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4"+dependencies = [+ "fnv",+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 2.0.110",+]+[[package]]name = "darling_core"version = "0.23.0"@@ -1742,6 +1949,17 @@ dependencies = ["syn 2.0.110",]+[[package]]+name = "darling_macro"+version = "0.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81"+dependencies = [+ "darling_core 0.21.3",+ "quote",+ "syn 2.0.110",+]+[[package]]name = "darling_macro"version = "0.23.0"@@ -1759,6 +1977,20 @@ version = "0.3.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "06d2e3287df1c007e74221c49ca10a95d557349e54b3a75dc2fb14712c751f04"+[[package]]+name = "dashmap"+version = "6.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c"+dependencies = [+ "cfg-if",+ "crossbeam-utils",+ "hashbrown 0.14.5",+ "lock_api",+ "once_cell",+ "parking_lot_core",+]+[[package]]name = "data-encoding"version = "2.9.0"@@ -1771,6 +2003,46 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376"+[[package]]+name = "defmt"+version = "0.3.100"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0963443817029b2024136fc4dd07a5107eb8f977eaf18fcd1fdeb11306b64ad"+dependencies = [+ "defmt 1.1.1",+]++[[package]]+name = "defmt"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1"+dependencies = [+ "bitflags 1.3.2",+ "defmt-macros",+]++[[package]]+name = "defmt-macros"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8"+dependencies = [+ "defmt-parser",+ "proc-macro2",+ "quote",+ "syn 2.0.110",+]++[[package]]+name = "defmt-parser"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"+dependencies = [+ "thiserror 2.0.20",+]+[[package]]name = "delegate"version = "0.13.5"@@ -1837,7 +2109,7 @@ version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "916a94e407b54f9034d71dd748234cd1e516ced6284009906ae246f177eafe5a"dependencies = [- "cipher",+ "cipher 0.5.2",][[package]]@@ -1876,6 +2148,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"dependencies = ["block-buffer 0.10.4","crypto-common 0.1.6",+ "subtle",][[package]]@@ -1974,6 +2247,12 @@ version = "1.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"+[[package]]+name = "downcast-rs"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "117240f60069e65410b3ae1bb213295bd828f707b5bec6596a1afc8793ce0cbc"+[[package]]name = "dtoa"version = "1.0.11"@@ -2014,6 +2293,12 @@ dependencies = ["serde_json",]+[[package]]+name = "dunce"+version = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"+[[package]]name = "dwrote"version = "0.11.5"@@ -2028,6 +2313,24 @@ dependencies = ["wio",]+[[package]]+name = "dyn-clone"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"++[[package]]+name = "dyn-eq"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c2d035d21af5cde1a6f5c7b444a5bf963520a9f142e5d06931178433d7d5388"++[[package]]+name = "dyn-hash"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fdab65db9274e0168143841eb8f864a0a21f8b1b8d2ba6812bbe6024346e99e"+[[package]]name = "ecdsa"version = "0.17.0"@@ -2059,7 +2362,7 @@ version = "3.0.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de"dependencies = [- "curve25519-dalek",+ "curve25519-dalek 5.0.0","ed25519","rand_core 0.10.1","serde",@@ -2087,7 +2390,7 @@ dependencies = ["digest 0.11.3","ff","group",- "hkdf",+ "hkdf 0.13.0","hybrid-array","pem-rfc7468","pkcs8",@@ -2306,7 +2609,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.61.2",+ "windows-sys 0.52.0",][[package]]@@ -2315,6 +2618,15 @@ version = "3.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dea2df4cf52843e0452895c455a1a2cfbb842a1e7329671acf418fdc53ed4c59"+[[package]]+name = "etherparse"+version = "0.19.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b119b9796ff800751a220394b8b3613f26dd30c48f254f6837e64c464872d1c7"+dependencies = [+ "arrayvec",+]+[[package]]name = "euclid"version = "0.22.11"@@ -2398,6 +2710,9 @@ name = "fastrand"version = "2.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"+dependencies = [+ "getrandom 0.2.16",+][[package]]name = "fax"@@ -2438,6 +2753,12 @@ dependencies = ["subtle",]+[[package]]+name = "fiat-crypto"+version = "0.2.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d"+[[package]]name = "fiat-crypto"version = "0.3.0"@@ -2606,6 +2927,18 @@ dependencies = ["spin",]+[[package]]+name = "flume"+version = "0.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be"+dependencies = [+ "fastrand",+ "futures-core",+ "futures-sink",+ "spin",+]+[[package]]name = "fnv"version = "1.0.7"@@ -2722,7 +3055,7 @@ dependencies = ["chrono","serde","serde_json",- "serde_with",+ "serde_with 2.3.3",][[package]]@@ -2742,6 +3075,12 @@ dependencies = ["autocfg",]+[[package]]+name = "fs_extra"+version = "1.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"+[[package]]name = "fsevent-sys"version = "4.1.0"@@ -2874,6 +3213,7 @@ checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2"dependencies = ["typenum","version_check",+ "zeroize",][[package]]@@ -2898,13 +3238,23 @@ dependencies = [][[package]]-name = "getopts"-version = "0.2.24"+name = "gethostname"+version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"dependencies = [- "unicode-width",-]+ "rustix 1.1.2",+ "windows-link 0.2.1",+]++[[package]]+name = "getopts"+version = "0.2.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"+dependencies = [+ "unicode-width",+][[package]]name = "getrandom"@@ -3352,6 +3702,17 @@ dependencies = ["foldhash 0.2.0",]+[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"+dependencies = [+ "allocator-api2",+ "equivalent",+ "foldhash 0.2.0",+]+[[package]]name = "hashlink"version = "0.9.1"@@ -3385,6 +3746,16 @@ dependencies = ["stable_deref_trait",]+[[package]]+name = "heapless"+version = "0.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "25ba4bd83f9415b58b4ed8dc5714c76e626a105be4646c02630ad730ad3b5aa4"+dependencies = [+ "hash32",+ "stable_deref_trait",+]+[[package]]name = "heck"version = "0.5.0"@@ -3421,13 +3792,31 @@ version = "0.2.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dfa686283ad6dd069f105e5ab091b04c62850d3e4cf5d67debad1933f55023df"+[[package]]+name = "hkdf"+version = "0.12.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"+dependencies = [+ "hmac 0.12.1",+]+[[package]]name = "hkdf"version = "0.13.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4aaa26c720c68b866f2c96ef5c1264b3e6f473fe5d4ce61cd44bbe913e553018"dependencies = [- "hmac",+ "hmac 0.13.0",+]++[[package]]+name = "hmac"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"+dependencies = [+ "digest 0.10.7",][[package]]@@ -3439,6 +3828,22 @@ dependencies = ["digest 0.11.3",]+[[package]]+name = "hmac-sha1"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6b05da5b9e5d4720bfb691eebb2b9d42da3570745da71eac8a1f5bb7e59aab88"+dependencies = [+ "hmac 0.12.1",+ "sha1 0.10.6",+]++[[package]]+name = "hmac-sha256"+version = "1.1.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1ad320b3b96fb2a455a0726d16efe0a5afdbd34b71dea5bc53b05ea057714d4e"+[[package]]name = "hostname"version = "0.4.1"@@ -3450,6 +3855,12 @@ dependencies = ["windows-link 0.1.3",]+[[package]]+name = "hostname-validator"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f558a64ac9af88b5ba400d99b579451af0d39c6d360980045b91aac966d705e2"+[[package]]name = "htmlize"version = "1.1.0"@@ -3465,12 +3876,11 @@ dependencies = [[[package]]name = "http"-version = "1.3.1"+version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565"+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"dependencies = ["bytes",- "fnv","itoa",]@@ -3542,9 +3952,9 @@ dependencies = [[[package]]name = "hyper"-version = "1.7.0"+version = "1.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eb3aa54a13a0dfe7fbe3a59e0c76093041720fdc77b110cc0fc260fafb4dc51e"+checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca"dependencies = ["atomic-waker","bytes",@@ -3556,7 +3966,6 @@ dependencies = ["httparse","itoa","pin-project-lite",- "pin-utils","smallvec","tokio","want",@@ -3612,7 +4021,7 @@ dependencies = ["libc","percent-encoding","pin-project-lite",- "socket2 0.6.1",+ "socket2 0.5.10","system-configuration","tokio","tower-service",@@ -3876,6 +4285,15 @@ dependencies = ["libc",]+[[package]]+name = "inout"+version = "0.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"+dependencies = [+ "generic-array 0.14.9",+]+[[package]]name = "inout"version = "0.2.2"@@ -3951,9 +4369,12 @@ dependencies = [[[package]]name = "ipnet"-version = "2.11.0"+version = "2.12.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130"+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"+dependencies = [+ "serde",+][[package]]name = "iri-string"@@ -3973,7 +4394,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"dependencies = ["hermit-abi 0.5.2","libc",- "windows-sys 0.61.2",+ "windows-sys 0.52.0",][[package]]@@ -4102,6 +4523,46 @@ dependencies = ["terminal_size",]+[[package]]+name = "kameo"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aea00bfc3709c5b95be7c9a93289d0c3ff42cf9a3b77d532387242992705bca7"+dependencies = [+ "downcast-rs 2.0.2",+ "dyn-clone",+ "futures",+ "kameo_macros",+ "serde",+ "tokio",+ "tracing",+]++[[package]]+name = "kameo_actors"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "535f5db40b46b28085ddf4ba0391818e1b388548bf454e6d27a3b5cc805961fa"+dependencies = [+ "futures",+ "glob",+ "kameo",+ "thiserror 2.0.20",+ "tokio",+]++[[package]]+name = "kameo_macros"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f7566055976eb86ee8e8fbafa0fbdad985c5d7c3f4eed04fc11bb495f71e3856"+dependencies = [+ "heck",+ "proc-macro2",+ "quote",+ "syn 2.0.110",+]+[[package]]name = "kasuari"version = "0.4.11"@@ -4617,6 +5078,12 @@ dependencies = ["libc",]+[[package]]+name = "managed"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ca88d725a0a943b096803bd34e73a4437208b6077654cc4ecb2947a5f91618d"+[[package]]name = "manatee"version = "0.7.0"@@ -4656,6 +5123,12 @@ dependencies = ["rayon",]+[[package]]+name = "md5"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"+[[package]]name = "md5"version = "0.8.1"@@ -4929,7 +5402,7 @@ dependencies = ["chrono","config","crossbeam",- "downcast-rs",+ "downcast-rs 1.2.1","fancy-regex 0.14.0","filedescriptor 0.8.3","finl_unicode 1.3.0",@@ -5092,6 +5565,55 @@ dependencies = ["jni-sys",]+[[package]]+name = "netlink-packet-core"+version = "0.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b897d7bd4f0af82e68d40d0344cf37e97f9c97ddf74a098de3e4da05e96ca395"+dependencies = [+ "paste",+]++[[package]]+name = "netlink-packet-route"+version = "0.30.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be8919612f6028ab4eacbbfe1234a9a43e3722c6e0915e7ff519066991905092"+dependencies = [+ "bitflags 2.13.1",+ "libc",+ "log",+ "netlink-packet-core",+]++[[package]]+name = "netlink-proto"+version = "0.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93af8261786086024cd5e96e0a991dd65ced07bbf7c233a487bbc96b971d5539"+dependencies = [+ "bytes",+ "futures-channel",+ "futures-util",+ "log",+ "netlink-packet-core",+ "netlink-sys",+ "thiserror 2.0.20",+]++[[package]]+name = "netlink-sys"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd6c30ed10fa69cc491d491b85cc971f6bdeb8e7367b7cde2ee6cc878d583fae"+dependencies = [+ "bytes",+ "futures-util",+ "libc",+ "log",+ "tokio",+]+[[package]]name = "new_debug_unreachable"version = "1.0.6"@@ -5111,6 +5633,18 @@ dependencies = ["memoffset",]+[[package]]+name = "nix"+version = "0.30.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "74523f3a35e05aba87a1d978330aef40f67b0304ac79c1c00b294c9830543db6"+dependencies = [+ "bitflags 2.13.1",+ "cfg-if",+ "cfg_aliases",+ "libc",+]+[[package]]name = "nix"version = "0.31.3"@@ -5435,9 +5969,9 @@ dependencies = [[[package]]name = "once_cell"-version = "1.21.3"+version = "1.21.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"[[package]]name = "once_cell_polyfill"@@ -5451,6 +5985,12 @@ version = "11.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"+[[package]]+name = "opaque-debug"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"+[[package]]name = "openssl"version = "0.10.75"@@ -5556,7 +6096,7 @@ checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f"dependencies = ["ecdsa","elliptic-curve",- "fiat-crypto",+ "fiat-crypto 0.3.0","primefield","primeorder","sha2 0.11.0",@@ -5691,7 +6231,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629"dependencies = ["digest 0.11.3",- "hmac",+ "hmac 0.13.0",][[package]]@@ -6080,6 +6620,17 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "poly1305"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf"+dependencies = [+ "cpufeatures 0.2.17",+ "opaque-debug",+ "universal-hash 0.5.1",+]+[[package]]name = "poly1305"version = "0.9.1"@@ -6087,7 +6638,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c"dependencies = ["cpufeatures 0.3.1",- "universal-hash",+ "universal-hash 0.6.1","zeroize",]@@ -6108,7 +6659,7 @@ checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd"dependencies = ["cpubits","cpufeatures 0.3.1",- "universal-hash",+ "universal-hash 0.6.1","zeroize",]@@ -6133,7 +6684,7 @@ version = "0.9.0"dependencies = ["anyhow","bitflags 1.3.2",- "downcast-rs",+ "downcast-rs 1.2.1","filedescriptor 0.8.3","futures","lazy_static",@@ -6173,6 +6724,39 @@ dependencies = ["zerocopy",]+[[package]]+name = "precis-core"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c2e7b31f132e0c6f8682cfb7bf4a5340dbe925b7986618d0826a56dfe0c8e56"+dependencies = [+ "precis-tools",+ "ucd-parse",+ "unicode-normalization",+]++[[package]]+name = "precis-profiles"+version = "0.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "31e2768890a47af73a032af9f0cedbddce3c9d06cf8de201d5b8f2436ded7674"+dependencies = [+ "lazy_static",+ "precis-core",+ "precis-tools",+ "unicode-normalization",+]++[[package]]+name = "precis-tools"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ade9e98ddb189f367494f1fa0a966a8d0d38f9a3eec4aef0f5ec035a7e0963d"+dependencies = [+ "regex",+ "ucd-parse",+]+[[package]]name = "precomputed-hash"version = "0.1.1"@@ -6321,7 +6905,7 @@ dependencies = ["async-executor","async-io","async-task",- "flume",+ "flume 0.11.1","lazy_static","thiserror 1.0.69",]@@ -6428,6 +7012,16 @@ dependencies = ["proc-macro2",]+[[package]]+name = "quoted-string-parser"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0dc75379cdb451d001f1cb667a9f74e8b355e9df84cc5193513cbe62b96fc5e9"+dependencies = [+ "pest",+ "pest_derive",+]+[[package]]name = "r-efi"version = "5.3.0"@@ -6468,7 +7062,7 @@ version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"dependencies = [- "chacha20",+ "chacha20 0.10.2","getrandom 0.4.3","rand_core 0.10.1",]@@ -6738,11 +7332,31 @@ dependencies = ["thiserror 1.0.69",]+[[package]]+name = "ref-cast"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.6",+]+[[package]]name = "regex"-version = "1.12.2"+version = "1.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "843bc0191f75f3e22651ae5f1e72939ab2f72a4bc30fa80a066bd66edefc24d4"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"dependencies = ["aho-corasick","memchr",@@ -6752,20 +7366,26 @@ dependencies = [[[package]]name = "regex-automata"-version = "0.4.13"+version = "0.4.18"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"dependencies = ["aho-corasick","memchr","regex-syntax",]+[[package]]+name = "regex-lite"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973"+[[package]]name = "regex-syntax"-version = "0.8.8"+version = "0.8.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"[[package]]name = "relative-path"@@ -6851,7 +7471,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b"dependencies = ["crypto-bigint",- "hmac",+ "hmac 0.13.0",][[package]]@@ -6934,6 +7554,24 @@ dependencies = ["unicode-ident",]+[[package]]+name = "rtnetlink"+version = "0.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc19f84f710fa2f337617f9bc0400260a94224bde7bae28fd8879f3771ca5784"+dependencies = [+ "futures-channel",+ "futures-util",+ "log",+ "netlink-packet-core",+ "netlink-packet-route",+ "netlink-proto",+ "netlink-sys",+ "nix 0.30.1",+ "thiserror 1.0.69",+ "tokio",+]+[[package]]name = "rusqlite"version = "0.32.1"@@ -6960,10 +7598,10 @@ dependencies = ["byteorder","bytes","cbc",- "cipher",+ "cipher 0.5.2","crypto-bigint","ctr",- "curve25519-dalek",+ "curve25519-dalek 5.0.0","data-encoding","delegate","der",@@ -6977,11 +7615,11 @@ dependencies = ["getrandom 0.4.3","ghash","hex-literal",- "hmac",- "inout",+ "hmac 0.13.0",+ "inout 0.2.2","keccak","log",- "md5",+ "md5 0.8.1","ml-kem","module-lattice","num-bigint 0.5.1",@@ -6998,7 +7636,7 @@ dependencies = ["ring","russh-cryptovec","russh-util",- "salsa20",+ "salsa20 0.11.0","scrypt","sec1","sha1 0.11.0",@@ -7012,7 +7650,7 @@ dependencies = ["thiserror 2.0.20","tokio","typenum",- "universal-hash",+ "universal-hash 0.6.1","zeroize",]@@ -7104,7 +7742,7 @@ dependencies = ["errno","libc","linux-raw-sys 0.11.0",- "windows-sys 0.61.2",+ "windows-sys 0.52.0",][[package]]@@ -7113,6 +7751,7 @@ version = "0.23.35"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "533f54bc6a7d4f647e46ad909549eda97bf5afc1585190ef692b4286b198bd8f"dependencies = [+ "aws-lc-rs","once_cell","rustls-pki-types","rustls-webpki",@@ -7135,6 +7774,7 @@ version = "0.103.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2ffdfa2f5286e2247234e03f680868ac2815974dc39e00ea15adc445d0aafe52"dependencies = [+ "aws-lc-rs","ring","rustls-pki-types","untrusted",@@ -7194,6 +7834,15 @@ dependencies = ["bytemuck",]+[[package]]+name = "salsa20"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213"+dependencies = [+ "cipher 0.4.4",+]+[[package]]name = "salsa20"version = "0.11.0"@@ -7201,7 +7850,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c"dependencies = ["cfg-if",- "cipher",+ "cipher 0.5.2",][[package]]@@ -7223,13 +7872,37 @@ dependencies = [][[package]]-name = "scoped-tls"-version = "1.0.1"+name = "schemars"+version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"--[[package]]-name = "scopeguard"+checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "serde",+ "serde_json",+]++[[package]]+name = "scoped-tls"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"++[[package]]+name = "scopeguard"version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"@@ -7262,7 +7935,7 @@ checksum = "d87af57419b594aa23fa95f09f0e06d80d84ba01c26148c43844cad6ff4485f0"dependencies = ["cfg-if","pbkdf2",- "salsa20",+ "salsa20 0.11.0","sha2 0.11.0",]@@ -7468,7 +8141,26 @@ dependencies = ["indexmap 1.9.3","serde","serde_json",- "serde_with_macros",+ "serde_with_macros 2.3.3",+ "time",+]++[[package]]+name = "serde_with"+version = "3.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "381b283ce7bc6b476d903296fb59d0d36633652b633b27f64db4fb46dcbfc3b9"+dependencies = [+ "base64 0.22.1",+ "chrono",+ "hex",+ "indexmap 1.9.3",+ "indexmap 2.12.0",+ "schemars 0.9.0",+ "schemars 1.2.2",+ "serde_core",+ "serde_json",+ "serde_with_macros 3.17.0","time",]@@ -7484,6 +8176,18 @@ dependencies = ["syn 2.0.110",]+[[package]]+name = "serde_with_macros"+version = "3.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a6d4e30573c8cb306ed6ab1dca8423eec9a463ea0e155f45399455e0368b27e0"+dependencies = [+ "darling 0.21.3",+ "proc-macro2",+ "quote",+ "syn 2.0.110",+]+[[package]]name = "serde_yaml"version = "0.9.34+deprecated"@@ -7756,6 +8460,12 @@ dependencies = ["version_check",]+[[package]]+name = "smallbox"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aca054fd9f8c2ebe8557a2433f307e038c0716124efd045daa0388afa5172189"+[[package]]name = "smallvec"version = "1.15.1"@@ -7808,6 +8518,30 @@ dependencies = ["futures-lite",]+[[package]]+name = "smol_str"+version = "0.3.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4aaa7368fcf4852a4c2dd92df0cace6a71f2091ca0a23391ce7f3a31833f1523"+dependencies = [+ "borsh",+ "serde_core",+]++[[package]]+name = "smoltcp"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5f73d40463bba65efc9adc6370b56df76d563cc46e2482bba58351b4afb7535e"+dependencies = [+ "bitflags 1.3.2",+ "byteorder",+ "cfg-if",+ "defmt 0.3.100",+ "heapless 0.9.3",+ "managed",+]+[[package]]name = "socket2"version = "0.5.10"@@ -7919,14 +8653,14 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d801accda99469cde6d73da741422610fdf6508a72d9a69d1b55cb241c720597"dependencies = [- "aead",+ "aead 0.6.1","aes","aes-gcm",- "chacha20",- "cipher",+ "chacha20 0.10.2",+ "cipher 0.5.2","ctutils","des",- "poly1305",+ "poly1305 0.9.1","ssh-encoding","zeroize",]@@ -7966,7 +8700,7 @@ dependencies = ["ctutils","ed25519-dalek","hex",- "hmac",+ "hmac 0.13.0","p256","p384","p521",@@ -8106,6 +8840,30 @@ dependencies = ["syn 2.0.110",]+[[package]]+name = "stun-rs"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb921f10397d5669e1af6455e9e2d367bf1f9cebcd6b1dd1dc50e19f6a9ac2ac"+dependencies = [+ "base64 0.22.1",+ "bounded-integer",+ "byteorder",+ "crc",+ "enumflags2",+ "fallible-iterator",+ "hmac-sha1",+ "hmac-sha256",+ "hostname-validator",+ "lazy_static",+ "md5 0.7.0",+ "paste",+ "precis-core",+ "precis-profiles",+ "quoted-string-parser",+ "rand 0.9.2",+]+[[package]]name = "subtle"version = "2.6.1"@@ -8287,6 +9045,23 @@ dependencies = ["termwiz 0.24.0",]+[[package]]+name = "tailscale"+version = "0.6.1"+dependencies = [+ "rand 0.10.2",+ "serde",+ "serde_json",+ "thiserror 2.0.20",+ "tokio",+ "tracing",+ "ts_control",+ "ts_keys",+ "ts_netstack_smoltcp",+ "ts_runtime",+ "url",+]+[[package]]name = "tar"version = "0.4.44"@@ -8314,7 +9089,7 @@ dependencies = ["getrandom 0.3.4","once_cell","rustix 1.1.2",- "windows-sys 0.61.2",+ "windows-sys 0.52.0",][[package]]@@ -8710,7 +9485,7 @@ dependencies = ["anyhow","bitflags 1.3.2","bytemuck",- "downcast-rs",+ "downcast-rs 1.2.1","euclid","glium","guillotiere",@@ -8799,6 +9574,27 @@ dependencies = ["thinkterm-proto",]+[[package]]+name = "thinkterm-tailnet"+version = "0.1.0"+dependencies = [+ "anyhow",+ "config",+ "http_req",+ "log",+ "nix 0.29.0",+ "serde",+ "serde_json",+ "socket2 0.5.10",+ "tailscale",+ "tempfile",+ "thinkterm-core",+ "tokio",+ "ts_control",+ "url",+ "wezterm-ssh",+]+[[package]]name = "thinkterm-tui"version = "0.1.0"@@ -9071,6 +9867,7 @@ dependencies = ["pin-project-lite","socket2 0.6.1","tokio-macros",+ "tracing","windows-sys 0.61.2",]@@ -9105,6 +9902,18 @@ dependencies = ["tokio",]+[[package]]+name = "tokio-stream"+version = "0.1.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+ "tokio-util",+]+[[package]]name = "tokio-util"version = "0.7.17"@@ -9114,7 +9923,9 @@ dependencies = ["bytes","futures-core","futures-sink",+ "futures-util","pin-project-lite",+ "slab","tokio",]@@ -9328,208 +10139,763 @@ dependencies = [][[package]]-name = "tree-sitter-bash"-version = "0.25.1"+name = "tree-sitter-bash"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e5ec769279cc91b561d3df0d8a5deb26b0ad40d183127f409494d6d8fc53062"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-c"+version = "0.24.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a9b2eb57a55fed6b00812912e730b7a275cf4fe98bfd6a5d76263d4438371728"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-c-sharp"+version = "0.23.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1aac67f1ad71de1d6d39708d34811081c26dfa495658de6c14c34200849357c"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-cpp"+version = "0.23.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df2196ea9d47b4ab4a31b9297eaa5a5d19a0b121dceb9f118f6790ad0ab94743"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-css"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5cbc5e18f29a2c6d6435891f42569525cf95435a3e01c2f1947abcde178686f"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-go"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c8560a4d2f835cc0d4d2c2e03cbd0dde2f6114b43bc491164238d333e28b16ea"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-highlight"+version = "0.26.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cd7a0c48d503cf4e0a57a2453424eaef2fce4b4269f13e3579e52f0d0c9e5cc8"+dependencies = [+ "regex",+ "streaming-iterator",+ "thiserror 2.0.20",+ "tree-sitter",+]++[[package]]+name = "tree-sitter-html"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "261b708e5d92061ede329babaaa427b819329a9d427a1d710abb0f67bbef63ee"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-java"+version = "0.23.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0aa6cbcdc8c679b214e616fd3300da67da0e492e066df01bcf5a5921a71e90d6"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-javascript"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "68204f2abc0627a90bdf06e605f5c470aa26fdcb2081ea553a04bdad756693f5"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-json"+version = "0.24.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4d727acca406c0020cffc6cf35516764f36c8e3dc4408e5ebe2cb35a947ec471"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-language"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "009994f150cc0cd50ff54917d5bc8bffe8cad10ca10d81c34da2ec421ae61782"++[[package]]+name = "tree-sitter-lua"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8daaf5f4235188a58603c39760d5fa5d4b920d36a299c934adddae757f32a10c"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-md"+version = "0.5.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2efd398be546456c814598ee56c0f51769a77241511b4a58077815d120afa882"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-python"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6bf85fd39652e740bf60f46f4cda9492c3a9ad75880575bf14960f775cb74a1c"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-rust"+version = "0.24.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-sequel"+version = "0.3.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d198ad3c319c02e43c21efa1ec796b837afcb96ffaef1a40c1978fbdcec7d17"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-toml-ng"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e9adc2c898ae49730e857d75be403da3f92bb81d8e37a2f918a08dd10de5ebb1"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-typescript"+version = "0.23.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c5f76ed8d947a75cc446d5fccd8b602ebf0cde64ccf2ffa434d873d7a575eff"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "tree-sitter-yaml"+version = "0.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53c223db85f05e34794f065454843b0668ebc15d240ada63e2b5939f43ce7c97"+dependencies = [+ "cc",+ "tree-sitter-language",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "ts_array256"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "69af267f89d47a71d60aa2ff115e7723c18f0c874e76cddbebb9aa8ebbdf35be"+dependencies = [+ "heapless 0.9.3",+ "smallvec",+ "static_assertions",+ "ts_bitset",+]++[[package]]+name = "ts_bart"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "444f95c3c416a7dc852113c7e3a62d0e0a6bee7d0edbd0ca295f60373585719d"+dependencies = [+ "cfg-if",+ "heapless 0.9.3",+ "ipnet",+ "static_assertions",+ "ts_array256",+ "ts_bitset",+]++[[package]]+name = "ts_bart_packetfilter"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65e9aff31e23e2454b6652d09716c62cc09548018c569b3fa0a37d48a159e547"+dependencies = [+ "hashbrown 0.17.1",+ "smallvec",+ "ts_array256",+ "ts_bart",+ "ts_bitset",+ "ts_dynbitset",+ "ts_packetfilter",+]++[[package]]+name = "ts_bitset"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d509538ad206ba50db4db382a9fd94a2c4494460095fb844434d518bf4cc89e1"+dependencies = [+ "cfg-if",+ "static_assertions",+]++[[package]]+name = "ts_capabilityversion"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9b2d1b1e25c202d44972b4423d372e7e1eb9ec226864d0b5c24c1be923392fe9"+dependencies = [+ "serde",+]++[[package]]+name = "ts_control"+version = "0.6.1"+dependencies = [+ "bytes",+ "chrono",+ "futures-util",+ "gethostname 1.1.0",+ "ipnet",+ "lazy_static",+ "pin-project-lite",+ "serde",+ "serde_json",+ "thiserror 2.0.20",+ "tokio",+ "tokio-util",+ "tracing",+ "ts_bitset",+ "ts_capabilityversion",+ "ts_control_noise",+ "ts_control_serde",+ "ts_derp",+ "ts_dynbitset",+ "ts_http_util",+ "ts_keys",+ "ts_packet",+ "ts_packetfilter",+ "ts_packetfilter_state",+ "ts_tls_util",+ "url",+ "zerocopy",+]++[[package]]+name = "ts_control_noise"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cad85e8057cbc8de6f8a893ea0a417b22b6698c5a39efac995773ab5f3000166"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "chacha20poly1305",+ "futures-util",+ "pin-project-lite",+ "static_assertions",+ "thiserror 2.0.20",+ "tokio",+ "tokio-util",+ "tracing",+ "ts_capabilityversion",+ "ts_hexdump",+ "ts_keys",+ "ts_noise",+ "zerocopy",+]++[[package]]+name = "ts_control_serde"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aab4f5931c2be1ef684bc1edc0f7965c5e8dd067a1d663cfec25cfea067e8ffe"+dependencies = [+ "base64 0.22.1",+ "chrono",+ "ipnet",+ "serde",+ "serde_json",+ "serde_repr",+ "serde_with 3.17.0",+ "ts_capabilityversion",+ "ts_keys",+ "ts_nodecapability",+ "ts_packetfilter_serde",+ "url",+]++[[package]]+name = "ts_dataplane"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac692c013513afe18dc7ead7a74f3e67c048f943feae4d01b1c819d7bc445c94"+dependencies = [+ "bitrs",+ "bytes",+ "etherparse",+ "tokio",+ "tracing",+ "ts_bart",+ "ts_disco_protocol",+ "ts_overlay_router",+ "ts_packet",+ "ts_packetfilter",+ "ts_time",+ "ts_transport",+ "ts_tunnel",+ "ts_underlay_router",+]++[[package]]+name = "ts_derp"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2acde518e1296c20cb93242184c40b7af2731ca50a6744bab69cb2c66e24551e"+dependencies = [+ "bytes",+ "crypto_box",+ "futures",+ "hex",+ "serde",+ "serde_json",+ "thiserror 2.0.20",+ "tokio",+ "tokio-util",+ "tracing",+ "ts_hexdump",+ "ts_http_util",+ "ts_keys",+ "ts_packet",+ "ts_tls_util",+ "ts_transport",+ "url",+ "yoke",+ "zerocopy",+]++[[package]]+name = "ts_disco_protocol"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1eb6973ae3553eed7d672a36ef352f7f7518649031dbe62a5c94bf6663711172"+dependencies = [+ "aead 0.5.2",+ "crypto_box",+ "num-derive",+ "num-traits",+ "thiserror 2.0.20",+ "ts_hexdump",+ "ts_keys",+ "zerocopy",+]++[[package]]+name = "ts_dynbitset"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ada5dc5f35273c0f3ff67d19ac46cd71e9357f86d66b8ef931b2ee294a08e42d"+dependencies = [+ "smallvec",+ "ts_bitset",+]++[[package]]+name = "ts_future_util"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f1fdc0889d407fd7545b02ae6a5c662994ba2679f1b0fc0df7325049870aa129"+dependencies = [+ "futures-core",+ "pin-project-lite",+ "tokio",+]++[[package]]+name = "ts_hexdump"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "53f43b3841b0977e25ab975326374dacf5be152bef7403297dc44f5143e3c028"+dependencies = [+ "heapless 0.9.3",+]++[[package]]+name = "ts_http_util"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ede5ab36eef24606c78379d5b82f13a3ce98738cb71c8d6056eb8140eb603938"+dependencies = [+ "bytes",+ "futures",+ "http",+ "http-body-util",+ "httparse",+ "hyper",+ "hyper-util",+ "thiserror 2.0.20",+ "tokio",+ "tokio-util",+ "tracing",+ "ts_tls_util",+ "url",+]++[[package]]+name = "ts_keys"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9e5ec769279cc91b561d3df0d8a5deb26b0ad40d183127f409494d6d8fc53062"+checksum = "8372db61fd845ed4ace9499ade955a1a5961655e26c3a45048d1467a95eb5fe8"dependencies = [- "cc",- "tree-sitter-language",+ "crypto_box",+ "serde",+ "thiserror 2.0.20",+ "x25519-dalek",+ "zerocopy",+ "zeroize",][[package]]-name = "tree-sitter-c"-version = "0.24.2"+name = "ts_netcheck"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a9b2eb57a55fed6b00812912e730b7a275cf4fe98bfd6a5d76263d4438371728"+checksum = "ea173af20572c6444019d6f8532e67e8fc31e1cac1cea94a76d7f7fce12af7ca"dependencies = [- "cc",- "tree-sitter-language",+ "bytes",+ "dashmap",+ "stun-rs",+ "thiserror 2.0.20",+ "tokio",+ "tracing",+ "ts_control",+ "ts_derp",+ "ts_http_util",+ "url",][[package]]-name = "tree-sitter-c-sharp"-version = "0.23.5"+name = "ts_netmon"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c1aac67f1ad71de1d6d39708d34811081c26dfa495658de6c14c34200849357c"+checksum = "9db3f993efce5c30bd72dda4d9b2036945aa13ef160b2626d77b2f6adaf47fea"dependencies = [- "cc",- "tree-sitter-language",+ "bitflags 2.13.1",+ "bytes",+ "cfg-if",+ "flume 0.12.0",+ "futures-util",+ "ipnet",+ "libc",+ "nom 8.0.0",+ "pin-project-lite",+ "regex",+ "rtnetlink",+ "smallvec",+ "socket2 0.6.1",+ "static_assertions",+ "tokio",+ "tokio-stream",+ "tracing",+ "ts_future_util",+ "ts_hexdump",+ "windows 0.62.2",+ "zerocopy",][[package]]-name = "tree-sitter-cpp"-version = "0.23.4"+name = "ts_netstack_smoltcp"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "df2196ea9d47b4ab4a31b9297eaa5a5d19a0b121dceb9f118f6790ad0ab94743"+checksum = "d917f3575ece5b352360ccd2f4a5507aace4b693f0c802d0285c609cea6827fd"dependencies = [- "cc",- "tree-sitter-language",+ "bytes",+ "futures-util",+ "tokio",+ "tracing",+ "ts_netstack_smoltcp_core",+ "ts_netstack_smoltcp_socket",][[package]]-name = "tree-sitter-css"-version = "0.25.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a5cbc5e18f29a2c6d6435891f42569525cf95435a3e01c2f1947abcde178686f"+name = "ts_netstack_smoltcp_core"+version = "0.6.1"dependencies = [- "cc",- "tree-sitter-language",+ "bytes",+ "flume 0.12.0",+ "heapless 0.9.3",+ "smoltcp",+ "thiserror 2.0.20",+ "tracing",][[package]]-name = "tree-sitter-go"-version = "0.25.0"+name = "ts_netstack_smoltcp_socket"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c8560a4d2f835cc0d4d2c2e03cbd0dde2f6114b43bc491164238d333e28b16ea"+checksum = "b2109743df4bfc2b46dfc628be8d6f16ef2a8f06cea48d70c13cc72cc8a945b6"dependencies = [- "cc",- "tree-sitter-language",+ "bytes",+ "tokio",+ "tracing",+ "ts_netstack_smoltcp_core",][[package]]-name = "tree-sitter-highlight"-version = "0.26.11"+name = "ts_nodecapability"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cd7a0c48d503cf4e0a57a2453424eaef2fce4b4269f13e3579e52f0d0c9e5cc8"+checksum = "e4d7605a75d89ed0fa309404d997a3302b4d1a1f7915521e2182cb7771c58d33"dependencies = [- "regex",- "streaming-iterator",- "thiserror 2.0.20",- "tree-sitter",+ "cfg-if",+ "serde",+ "serde_json",][[package]]-name = "tree-sitter-html"-version = "0.23.2"+name = "ts_noise"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "261b708e5d92061ede329babaaa427b819329a9d427a1d710abb0f67bbef63ee"+checksum = "a2d9a4a6dfa82f19d61043b800e191b64f61bf6e50e1dcfdb38e14e7f28629a0"dependencies = [- "cc",- "tree-sitter-language",+ "aead 0.5.2",+ "blake2 0.10.6",+ "chacha20poly1305",+ "hkdf 0.12.4",+ "itertools 0.14.0",+ "ts_keys",+ "x25519-dalek",+ "zerocopy",+ "zeroize",][[package]]-name = "tree-sitter-java"-version = "0.23.5"+name = "ts_overlay_router"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0aa6cbcdc8c679b214e616fd3300da67da0e492e066df01bcf5a5921a71e90d6"+checksum = "a4516ec78124b965a9475fb941685901b4b4495b261eed0ed91afdb627b27d0c"dependencies = [- "cc",- "tree-sitter-language",+ "itertools 0.14.0",+ "tracing",+ "ts_bart",+ "ts_packet",+ "ts_transport",][[package]]-name = "tree-sitter-javascript"-version = "0.25.0"+name = "ts_packet"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "68204f2abc0627a90bdf06e605f5c470aa26fdcb2081ea553a04bdad756693f5"+checksum = "3934b1778a2899f6325c165d525f51ebec6de419c2b426ea9e82297ee64a1aa4"dependencies = [- "cc",- "tree-sitter-language",+ "bytes",+ "crypto_box",+ "stable_deref_trait",+ "ts_hexdump",+ "yoke",][[package]]-name = "tree-sitter-json"-version = "0.24.8"+name = "ts_packetfilter"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4d727acca406c0020cffc6cf35516764f36c8e3dc4408e5ebe2cb35a947ec471"+checksum = "bd167c3cebccc96ab37cace59ae8366d1487bfdf92dc518ca27813c93b0de0ef"dependencies = [- "cc",- "tree-sitter-language",+ "hashbrown 0.17.1",+ "ipnet",+ "static_assertions",+ "tracing",][[package]]-name = "tree-sitter-language"-version = "0.1.7"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "009994f150cc0cd50ff54917d5bc8bffe8cad10ca10d81c34da2ec421ae61782"--[[package]]-name = "tree-sitter-lua"-version = "0.5.0"+name = "ts_packetfilter_serde"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8daaf5f4235188a58603c39760d5fa5d4b920d36a299c934adddae757f32a10c"+checksum = "dbb8e593d7080083da9444425f05e8c24bf459daa3a5968aa4f0925eff27ed37"dependencies = [- "cc",- "tree-sitter-language",+ "ipnet",+ "nom 8.0.0",+ "serde",+ "serde_json",+ "ts_nodecapability",+ "ts_peercapability",][[package]]-name = "tree-sitter-md"-version = "0.5.3"+name = "ts_packetfilter_state"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2efd398be546456c814598ee56c0f51769a77241511b4a58077815d120afa882"+checksum = "193f4a81c47fa3abd44e80e89ecee0c64b0fd8f9d6159e6b407642708fc8ed2f"dependencies = [- "cc",- "tree-sitter-language",+ "ts_packetfilter",+ "ts_packetfilter_serde",][[package]]-name = "tree-sitter-python"-version = "0.25.0"+name = "ts_peercapability"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6bf85fd39652e740bf60f46f4cda9492c3a9ad75880575bf14960f775cb74a1c"+checksum = "81c18288184982b01e93930c42d524d9d7a2682e5a54eee456cdd176559a1143"dependencies = [- "cc",- "tree-sitter-language",+ "serde",+ "url",][[package]]-name = "tree-sitter-rust"-version = "0.24.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45"+name = "ts_runtime"+version = "0.6.1"dependencies = [- "cc",- "tree-sitter-language",+ "bytes",+ "futures",+ "futures-util",+ "ipnet",+ "itertools 0.14.0",+ "kameo",+ "kameo_actors",+ "rand 0.10.2",+ "smallvec",+ "smol_str",+ "thiserror 2.0.20",+ "tokio",+ "tokio-stream",+ "tokio-util",+ "tracing",+ "ts_bart",+ "ts_bart_packetfilter",+ "ts_control",+ "ts_dataplane",+ "ts_derp",+ "ts_disco_protocol",+ "ts_hexdump",+ "ts_keys",+ "ts_netcheck",+ "ts_netmon",+ "ts_netstack_smoltcp",+ "ts_overlay_router",+ "ts_packet",+ "ts_packetfilter",+ "ts_packetfilter_state",+ "ts_transport",+ "ts_tunnel",+ "url",+ "yoke",+ "zerocopy",][[package]]-name = "tree-sitter-sequel"-version = "0.3.11"+name = "ts_time"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9d198ad3c319c02e43c21efa1ec796b837afcb96ffaef1a40c1978fbdcec7d17"-dependencies = [- "cc",- "tree-sitter-language",-]+checksum = "0a713a89eb4946b2e0b6689003696247dce83b4f4153fe676adeb1ead8e905c6"[[package]]-name = "tree-sitter-toml-ng"-version = "0.7.0"+name = "ts_tls_util"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e9adc2c898ae49730e857d75be403da3f92bb81d8e37a2f918a08dd10de5ebb1"+checksum = "ea6a22b611afe1bfd4a38e8096b1ce66527c4a773ead601a06c6d827b066a7ca"dependencies = [- "cc",- "tree-sitter-language",+ "tokio",+ "tokio-rustls",+ "tracing",+ "url",+ "webpki-roots",][[package]]-name = "tree-sitter-typescript"-version = "0.23.2"+name = "ts_transport"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6c5f76ed8d947a75cc446d5fccd8b602ebf0cde64ccf2ffa434d873d7a575eff"+checksum = "c35ed52ac9c9e4f7f4db0a6148cae467d93d9491d3b5a3916db941862b2d65f5"dependencies = [- "cc",- "tree-sitter-language",+ "dyn-eq",+ "dyn-hash",+ "smallbox",+ "ts_hexdump",+ "ts_keys",+ "ts_packet",+ "zerocopy",][[package]]-name = "tree-sitter-yaml"-version = "0.7.2"+name = "ts_tunnel"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "53c223db85f05e34794f065454843b0668ebc15d240ada63e2b5939f43ce7c97"+checksum = "90c05be0f72d756f9790e0c6199ce775d14c5bd746dcebdc3ea0efffaf894cc3"dependencies = [- "cc",- "tree-sitter-language",+ "aead 0.5.2",+ "blake2 0.10.6",+ "chacha20poly1305",+ "itertools 0.14.0",+ "rand 0.10.2",+ "tracing",+ "ts_keys",+ "ts_noise",+ "ts_packet",+ "ts_time",+ "zerocopy",][[package]]-name = "try-lock"-version = "0.2.5"+name = "ts_underlay_router"+version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"+checksum = "430a46dbd2cc8cf3203d230733026ed0653fa9987c27609256f99e4d07312d25"+dependencies = [+ "ts_packet",+ "ts_transport",+][[package]]name = "ttf-parser"@@ -9567,6 +10933,15 @@ version = "1.20.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"+[[package]]+name = "ucd-parse"+version = "0.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c06ff81122fcbf4df4c1660b15f7e3336058e7aec14437c9f85c6b31a0f279b9"+dependencies = [+ "regex-lite",+]+[[package]]name = "ucd-trie"version = "0.1.7"@@ -9823,6 +11198,16 @@ dependencies = ["weedle2",]+[[package]]+name = "universal-hash"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea"+dependencies = [+ "crypto-common 0.1.6",+ "subtle",+]+[[package]]name = "universal-hash"version = "0.6.1"@@ -10009,7 +11394,7 @@ dependencies = [name = "vtparse"version = "0.7.0"dependencies = [- "heapless",+ "heapless 0.8.0","k9","utf8parse",]@@ -10131,7 +11516,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "673a33c33048a5ade91a6b139580fa174e19fb0d23f396dca9fa15f2e1e49b35"dependencies = ["cc",- "downcast-rs",+ "downcast-rs 1.2.1","raw-window-handle","rustix 1.1.2","scoped-tls",@@ -10263,6 +11648,15 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "webpki-roots"+version = "1.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"+dependencies = [+ "rustls-pki-types",+]+[[package]]name = "weedle2"version = "5.0.0"@@ -10314,6 +11708,7 @@ dependencies = ["thinkterm-file-index","thinkterm-plugin-channel","thinkterm-proto",+ "thinkterm-tailnet","thinkterm-tui","thinkterm-update","umask",@@ -10600,7 +11995,7 @@ dependencies = ["config","dhat","dirs-next",- "downcast-rs",+ "downcast-rs 1.2.1","embed-resource","emojis","env-bootstrap",@@ -10672,6 +12067,7 @@ dependencies = ["thinkterm-snippets","thinkterm-syntax","thinkterm-tab-icons",+ "thinkterm-tailnet","thinkterm-update","thiserror 1.0.69","tiny-skia",@@ -10761,6 +12157,7 @@ dependencies = ["smol","thinkterm-import","thinkterm-import-herdr",+ "thinkterm-tailnet","umask","wezterm-blob-leases 0.1.1","wezterm-gui-subcommands",@@ -10849,7 +12246,7 @@ dependencies = ["env_logger 0.11.8","filedescriptor 0.8.3","filenamegen",- "gethostname",+ "gethostname 0.5.0","hex","k9","libc",@@ -10901,7 +12298,7 @@ dependencies = ["anyhow","bitflags 1.3.2","csscolorparser",- "downcast-rs",+ "downcast-rs 1.2.1","env_logger 0.11.8","finl_unicode 1.3.0","hex",@@ -11164,7 +12561,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.61.2",+ "windows-sys 0.48.0",][[package]]@@ -11929,6 +13326,18 @@ dependencies = ["pkg-config",]+[[package]]+name = "x25519-dalek"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e7e8131a03190127fb2263afc72b322ecadae46b6ff8c6f399ff5d02f5559af6"+dependencies = [+ "curve25519-dalek 5.0.0",+ "getrandom 0.4.3",+ "rand_core 0.10.1",+ "zeroize",+]+[[package]]name = "xattr"version = "1.6.1"@@ -12168,6 +13577,20 @@ name = "zeroize"version = "1.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"+dependencies = [+ "zeroize_derive",+]++[[package]]+name = "zeroize_derive"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.110",+][[package]]name = "zerotrie"diff --git a/Cargo.toml b/Cargo.tomlindex 956c252c..274ebd93 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -7,6 +7,7 @@ members = ["sync-color-schemes","thinkterm-syntax","thinkterm-core",+ "thinkterm-tailnet","thinkterm-file-index","thinkterm-font-core","thinkterm-font-web",@@ -46,6 +47,10 @@ resolver = "2"exclude = ["termwiz/codegen","wezterm-char-props/codegen",+ "deps/tailscale",+ "deps/ts_control",+ "deps/ts_netstack_smoltcp_core",+ "deps/ts_runtime",][profile.release]@@ -185,6 +190,7 @@ color-funcs = { path = "lua-api-crates/color-funcs" }colorgrad = "0.6"config = { path = "config" }thinkterm-core = { path = "thinkterm-core" }+thinkterm-tailnet = { path = "thinkterm-tailnet" }thinkterm-file-index = { path = "thinkterm-file-index" }thinkterm-font-core = { path = "thinkterm-font-core" }thinkterm-font-web = { path = "thinkterm-font-web" }@@ -450,3 +456,16 @@ zvariant = "4.0"cairo-sys-rs = {path="deps/cairo", version="0.18.0"}# Vendored to bound allocations by the bytes present, not by declared lengths.varbincode = {path="deps/varbincode", version="0.1.0"}+# Vendored to list every peer in the tailnet (Device::peers), which 0.6.1+# only offers as lookups by name or address, and so that a forward to an+# actor that is gone is an error rather than a panic.+tailscale = {path="deps/tailscale", version="0.6.1"}+ts_runtime = {path="deps/ts_runtime", version="0.6.1"}+# Vendored so that a connection notices a peer gone without a word, and a+# connect nobody waits for any more ends: 0.6.1 sets neither a timeout nor+# keep-alives on its TCP sockets.+ts_netstack_smoltcp_core = {path="deps/ts_netstack_smoltcp_core", version="0.6.1"}+# Vendored so that a peer keeps what it says about its device -- its system,+# distribution and model -- which 0.6.1 drops: Remote Hosts draws a machine+# of the tailnet by it.+ts_control = {path="deps/ts_control", version="0.6.1"}diff --git a/thinkterm-tailnet/Cargo.toml b/thinkterm-tailnet/Cargo.tomlnew file mode 100644index 00000000..3be7f6a0--- /dev/null+++ b/thinkterm-tailnet/Cargo.toml@@ -0,0 +1,38 @@+[package]+name = "thinkterm-tailnet"+version = "0.1.0"+edition = "2021"+publish = false++[features]+# The node itself, for the one process that holds it: the mux server.+# Without it this crate reads and changes the settings, reads the server's+# reports, and asks the server for connections -- all the app and+# `thinkterm` need, without the library in them.+node = ["dep:tailscale", "dep:tokio", "dep:ts_control"]++[dependencies]+anyhow.workspace = true+config.workspace = true+log.workspace = true+serde = { workspace = true, features = ["std"] }+serde_json.workspace = true+socket2.workspace = true+thinkterm-core.workspace = true+url.workspace = true+# Only for the dialer a process registers with it (see use_for_ssh).+wezterm-ssh.workspace = true++[target.'cfg(unix)'.dependencies]+nix = { workspace = true, features = ["signal", "user"] }++# The library runs on macOS and Linux only; elsewhere this crate builds+# without it and SUPPORTED says so.+[target.'cfg(any(target_os = "macos", target_os = "linux"))'.dependencies]+http_req.workspace = true+tailscale = { version = "0.6.1", optional = true }+tokio = { workspace = true, optional = true, features = ["rt-multi-thread", "sync", "time", "net", "io-util", "macros"] }+ts_control = { version = "0.6.1", optional = true }++[dev-dependencies]+tempfile.workspace = truediff --git a/thinkterm-tailnet/src/holder.rs b/thinkterm-tailnet/src/holder.rsnew file mode 100644index 00000000..339f73cb--- /dev/null+++ b/thinkterm-tailnet/src/holder.rs@@ -0,0 +1,561 @@+//! Holding the machine's node: what the mux server does, from the time it+//! starts following the settings ([`follow`]). The node starts when the+//! settings turn the tailnet on, restarts when they change what it runs on,+//! and stops when they turn it off; what it does goes to the report the app+//! and `thinkterm tailnet` read.++use crate::node;+use crate::settings::{self, Settings};+use crate::status::{self, read_live_report, read_report, Family, Peer, Report, Status};+use anyhow::Result;+use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};+use std::sync::mpsc;+use std::sync::{Arc, Mutex, OnceLock};+use std::time::{Duration, Instant};++/// How often the settings file is looked at for a change made by another+/// process -- the app's switch, `thinkterm tailnet up` -- and how soon a+/// process kept from the node by another one tries again.+const POLL: Duration = Duration::from_secs(3);++/// The longest wait before trying again at a node that would not start.+const RETRY_MAX: Duration = Duration::from_secs(60);++/// How long a connection asked for while this process acts on the settings+/// waits for it to finish.+const SETTLE_WAIT: Duration = Duration::from_secs(5);++type Changed = Arc<dyn Fn() + Send + Sync>;++/// Why the settings thread looks again before its next poll.+enum Wake {+ /// This process changed the settings file.+ Settings,+ /// The node's status or its list of machines changed.+ Node,+}++struct Follower {+ wake: Mutex<mpsc::Sender<Wake>>,+}++static FOLLOWER: OnceLock<Follower> = OnceLock::new();++/// The status while no node runs here: Off, or why there is none.+static IDLE: Mutex<Status> = Mutex::new(Status::Off);++/// How many looks at the settings this process asked its settings thread+/// for -- the first one, and one after each change this process makes --+/// and up to which of them it has acted on. Until it has acted on all, a+/// connection selecting the tailnet waits for the node rather+/// than go out without it: sessions taken over at a restart connect before+/// the first look. Counted, not a flag: a look begun before a change does+/// not act on it, so its end must not end the wait for it.+static ASKED: AtomicU64 = AtomicU64::new(0);+static ACTED_ON: AtomicU64 = AtomicU64::new(0);++/// Whether the settings thread has settings to act on that it has not yet.+fn settling() -> bool {+ ACTED_ON.load(Ordering::SeqCst) < ASKED.load(Ordering::SeqCst)+}++/// Ends every wait for the settings thread however it ends, a panic+/// included: nothing would act on what is asked after that.+struct SettlingEnds;++impl Drop for SettlingEnds {+ fn drop(&mut self) {+ ACTED_ON.store(u64::MAX, Ordering::SeqCst);+ }+}++/// The settings' revision this process last acted on, for its reports.+static ACTED: AtomicU64 = AtomicU64::new(0);++static NODE: Mutex<Option<Arc<node::Node>>> = Mutex::new(None);++/// The nodes in a row this process gave up and started anew (see+/// `node::Node::is_broken`) since one last got in or as far as a login: each+/// waits longer before it is given up.+static GIVEN_UP: AtomicU32 = AtomicU32::new(0);++/// The lock this process holds the machine's node by (see+/// `settings::try_hold_node`), from before its node starts until after the+/// node is gone and said to be.+static HOLD: Mutex<Option<std::fs::File>> = Mutex::new(None);++/// Set from `will_hold` until the settings thread first acted on the+/// settings: the process took over from a predecessor that holds the node+/// until it exits.+static TAKING_OVER: AtomicBool = AtomicBool::new(false);++/// How long a connection selecting the tailnet+/// waits for this process to take the node up from its predecessor.+const TAKEOVER_WAIT: Duration = Duration::from_secs(15);++/// This process takes over from a predecessor that holds the node until it+/// exits, and starts following the settings (see `follow`) after that:+/// connections to the tailnet's machines meanwhile wait for this process's+/// own node, rather than go through the predecessor's and end with it.+pub fn will_hold() {+ TAKING_OVER.store(true, Ordering::SeqCst);+}++/// Holds the machine's node in this process for as long as the settings+/// file turns the tailnet on, starting, stopping and restarting it as the+/// file changes. `changed` is called, on a background thread, whenever the+/// file, the status or the list of machines changes. Calling it again does+/// nothing.+pub fn follow(changed: impl Fn() + Send + Sync + 'static) {+ let changed: Changed = Arc::new(changed);+ let (wake, woken) = mpsc::channel();+ if FOLLOWER+ .set(Follower {+ wake: Mutex::new(wake),+ })+ .is_err()+ {+ return;+ }+ ASKED.fetch_add(1, Ordering::SeqCst);+ let spawned = std::thread::Builder::new()+ .name("tailnet-settings".into())+ .spawn(move || {+ let _ends = SettlingEnds;+ follow_loop(changed, woken)+ });+ if let Err(err) = spawned {+ ACTED_ON.store(u64::MAX, Ordering::SeqCst);+ log::error!("tailnet: starting the settings thread: {err}");+ }+}++/// This process changed the settings file: connections asked for from here+/// on wait for the settings thread to act on it, while there is one to.+pub(crate) fn settings_changed() {+ if FOLLOWER.get().is_none() {+ return;+ }+ ASKED.fetch_add(1, Ordering::SeqCst);+ send(Wake::Settings);+}++/// Whether the settings thread got it: not once it has ended.+fn send(wake: Wake) -> bool {+ FOLLOWER+ .get()+ .is_some_and(|follower| follower.wake.lock().unwrap().send(wake).is_ok())+}++/// Whether this process's node was given up (see `node::Node::is_broken`).+fn node_is_broken() -> bool {+ NODE.lock()+ .unwrap()+ .as_ref()+ .is_some_and(|node| node.is_broken())+}++/// This process's node as last seen.+fn status() -> Status {+ if let Some(node) = NODE.lock().unwrap().as_ref() {+ return node.status();+ }+ IDLE.lock().unwrap().clone()+}++/// The other machines in the tailnet, by name.+fn peers() -> Vec<Peer> {+ if let Some(node) = NODE.lock().unwrap().as_ref() {+ return node.peers();+ }+ vec![]+}++/// A connection through this process's node (see crate::dial): Some with+/// its answer while this process holds one, None for the caller to ask the+/// process that does.+pub(crate) fn dial(+ host: &str,+ port: u16,+ family: Family,+ timeout: Duration,+ cancelled: &dyn Fn() -> bool,+) -> Option<Option<Result<socket2::Socket>>> {+ // A node stopped while this went through it -- restarted for new+ // settings, or given up -- took what it had with it: the one in its+ // place is asked again. Within the one `timeout` either way.+ let started = Instant::now();+ let left = || timeout.saturating_sub(started.elapsed());+ for _ in 0..2 {+ // The caller selected this node, including while settings restart it.+ if settling() {+ if let Err(err) = wait_for_settings(left(), cancelled, settling) {+ return Some(Some(Err(err)));+ }+ }+ let node = NODE.lock().unwrap().clone();+ let Some(node) = node else {+ return dial_once_held(host, port, family, left(), cancelled);+ };+ let dialed = node.dial(host, port, family, left(), cancelled);+ if !node.is_stopped() || cancelled() {+ return Some(dialed);+ }+ }+ Some(None)+}++/// While a predecessor still holds the node (see `will_hold`), the selected+/// connection waits for this process's own node within `timeout`. None once this+/// process is not taking over, or is but holds no node after all, for the+/// caller to ask whichever process holds it.+fn dial_once_held(+ host: &str,+ port: u16,+ family: Family,+ timeout: Duration,+ cancelled: &dyn Fn() -> bool,+) -> Option<Option<Result<socket2::Socket>>> {+ if !TAKING_OVER.load(Ordering::SeqCst)+ || !settings::load_summary().is_ok_and(|settings| settings.enabled)+ {+ return None;+ }+ let started = Instant::now();+ let deadline = started + timeout.min(TAKEOVER_WAIT);+ loop {+ if let Some(node) = NODE.lock().unwrap().clone() {+ let left = timeout.saturating_sub(started.elapsed());+ return Some(node.dial(host, port, family, left, cancelled));+ }+ if !TAKING_OVER.load(Ordering::SeqCst) {+ return None;+ }+ if cancelled() || Instant::now() >= deadline {+ return Some(None);+ }+ std::thread::sleep(Duration::from_millis(100));+ }+}++/// Waits, for up to SETTLE_WAIT, for the settings thread to act on settings+/// it has not yet: a node being started is not a node turned off. The+/// connection goes on after that either way, with whatever node there is --+/// a thread that is slow or gone must not fail every connection, the+/// tailnet's or not. Err only when the session is closed meanwhile.+fn wait_for_settings(+ timeout: Duration,+ cancelled: &dyn Fn() -> bool,+ settling: impl Fn() -> bool,+) -> Result<()> {+ let deadline = Instant::now() + timeout.min(SETTLE_WAIT);+ loop {+ if cancelled() {+ anyhow::bail!("the session was closed while waiting for the tailnet settings");+ }+ if !settling() {+ return Ok(());+ }+ let remaining = deadline.saturating_duration_since(Instant::now());+ if remaining.is_zero() {+ log::warn!("tailnet: connecting before the settings thread acted on the settings");+ return Ok(());+ }+ std::thread::sleep(remaining.min(Duration::from_millis(50)));+ }+}++/// What the settings thread does after acting on the settings.+enum Next {+ /// Nothing until the settings change.+ Settled,+ /// Another process holds the node: try again at the next poll.+ Held,+ /// It went wrong: try again after a while, a longer one each time.+ Failed,+}++fn follow_loop(changed: Changed, woken: mpsc::Receiver<Wake>) {+ let path = match settings::path() {+ Ok(path) => path,+ Err(err) => {+ log::error!("tailnet: {err:#}");+ return;+ }+ };+ let mut seen = None;+ let mut look = true;+ // When to try again, and how long the wait before that was.+ let mut retry: Option<(Instant, Duration)> = None;+ let mut told = None;+ loop {+ let stamp = settings::stamp(&path);+ let file_changed = look || stamp != seen;+ if file_changed || retry.is_some_and(|(at, _)| Instant::now() >= at) {+ seen = stamp;+ // The looks asked for so far: this one reads the file as they+ // left it.+ let asked = ASKED.load(Ordering::SeqCst);+ retry = match reconcile() {+ Next::Settled => None,+ Next::Held => Some((Instant::now() + POLL, POLL)),+ Next::Failed => {+ let wait = retry.map_or(POLL, |(_, wait)| (wait * 2).min(RETRY_MAX));+ Some((Instant::now() + wait, wait))+ }+ };+ ACTED_ON.fetch_max(asked, Ordering::SeqCst);+ // Whatever came of it: holding the node now, or not to.+ TAKING_OVER.store(false, Ordering::SeqCst);+ }+ // Told when it changes, and after every change of the file even when+ // the node goes on as it was: the page shows the file, and+ // `thinkterm tailnet up` waits for a report written after its+ // change.+ let now = (status(), peers());+ if matches!(now.0, Status::Connected { .. } | Status::NeedsLogin { .. }) {+ GIVEN_UP.store(0, Ordering::SeqCst);+ }+ if file_changed || told.as_ref() != Some(&now) {+ report(&now);+ changed();+ told = Some(now);+ }+ look = match woken.recv_timeout(POLL) {+ Ok(Wake::Settings) => true,+ // A node that has to get in again may take an auth key saved+ // while it was in, which did not restart it then; one given up+ // is started anew at once, even one that got in at the last+ // moment, not at whatever look comes next.+ Ok(Wake::Node) => node_is_broken() || !matches!(status(), Status::Connected { .. }),+ Err(mpsc::RecvTimeoutError::Timeout) => false,+ Err(mpsc::RecvTimeoutError::Disconnected) => return,+ };+ }+}++/// Starts, stops or restarts this process's node to match the settings.+///+/// The slow parts -- writing new keys, building the node's runtime -- run+/// without the NODE lock, which a dial takes.+fn reconcile() -> Next {+ // Without the secrets first: most looks change nothing.+ let summary = match settings::load_summary() {+ Ok(summary) => summary,+ Err(err) => return failed(err),+ };+ ACTED.store(summary.revision, Ordering::SeqCst);+ if !summary.enabled {+ let node = NODE.lock().unwrap().take();+ let stopped = node.is_some();+ if let Some(node) = node {+ node.stop();+ }+ let was = std::mem::replace(&mut *IDLE.lock().unwrap(), Status::Off);+ let held = HOLD.lock().unwrap().is_some();+ if held && (stopped || matches!(was, Status::Failed { .. })) {+ report_if_ours(Status::Off);+ }+ // Only after the report: the process that takes the node over can+ // only start once this lock is free, so its report comes after.+ HOLD.lock().unwrap().take();+ return Next::Settled;+ }++ {+ let mut hold = HOLD.lock().unwrap();+ if hold.is_none() {+ match settings::try_hold_node() {+ Ok(Some(lock)) => *hold = Some(lock),+ Ok(None) => {+ drop(hold);+ *IDLE.lock().unwrap() = Status::HeldElsewhere;+ return Next::Held;+ }+ Err(err) => {+ drop(hold);+ return failed(err);+ }+ }+ }+ }++ let settings = match settings::load() {+ Ok(settings) => settings,+ Err(err) => return failed(err),+ };+ // The machine's identity is made on its first start and kept from then+ // on, so that it stays one node across restarts. Made only while the+ // file still turns the tailnet on -- not after a Log out landed since+ // the file was read -- and the node then starts on the file as it is.+ let settings = if settings.node_keys.is_some() {+ settings+ } else {+ match settings_with_node_keys() {+ Ok(Some(settings)) => settings,+ // Turned off meanwhile: the look the change brings acts on it.+ Ok(None) => return Next::Settled,+ Err(err) => return failed(err),+ }+ };+ let Some(node_keys) = settings.node_keys.clone() else {+ return failed(anyhow::anyhow!("the node's keys were not saved"));+ };+ // Compared in the one spelling, an address written by hand included.+ let control_url = match settings+ .control_url+ .as_deref()+ .map(crate::control_url_as_kept)+ {+ Some(Ok(url)) => url,+ Some(Err(err)) => return unusable(err),+ None => None,+ };+ let config = node::NodeConfig {+ control_url,+ hostname: settings.hostname.clone(),+ auth_key: settings.auth_key.clone(),+ node_keys,+ forward_ssh: settings.serve_ssh,+ };+ if let Err(err) = config.check() {+ return unusable(err);+ }+ let (restart, broken) = match NODE.lock().unwrap().as_ref() {+ Some(node) if node.is_broken() => (true, true),+ Some(node) => {+ let restart = node+ .config()+ .needs_restart_for(&config, &node.status(), node.was_in());+ (restart, false)+ }+ None => (true, false),+ };+ if !restart {+ return Next::Settled;+ }+ if broken {+ GIVEN_UP.fetch_add(1, Ordering::SeqCst);+ }+ // One node on these keys at a time: the old one goes first.+ let old = NODE.lock().unwrap().take();+ if let Some(old) = old {+ old.stop();+ }+ match node::Node::start(+ config,+ node::broken_after(GIVEN_UP.load(Ordering::SeqCst)),+ Box::new(|| {+ send(Wake::Node);+ }),+ ) {+ Ok(node) => {+ *NODE.lock().unwrap() = Some(Arc::new(node));+ *IDLE.lock().unwrap() = Status::Off;+ Next::Settled+ }+ Err(err) => failed(err),+ }+}++/// Settings no node can start on -- the file edited by hand -- leave a+/// running one as it was, rather than take the machine off the tailnet+/// until someone gets to it some other way. Not tried again until the file+/// changes.+fn unusable(err: anyhow::Error) -> Next {+ failed(err.context("not acting on the tailnet settings"));+ Next::Settled+}++/// Says why there is no node; one already running goes on as it was.+fn failed(err: anyhow::Error) -> Next {+ log::warn!("tailnet: {err:#}");+ if NODE.lock().unwrap().is_none() {+ *IDLE.lock().unwrap() = Status::Failed {+ error: format!("{err:#}"),+ };+ }+ Next::Failed+}++/// Writes new keys to the settings file while it still turns the tailnet+/// on, unless another process got there first, and returns the settings as+/// the file holds them now. None once the tailnet is off.+fn settings_with_node_keys() -> Result<Option<Settings>> {+ let mut made = None;+ let settings = crate::update(|settings| {+ if settings.enabled && settings.node_keys.is_none() {+ settings.node_keys = node::new_node_keys().map_err(|err| made = Some(err)).ok();+ }+ })?;+ if !settings.enabled {+ return Ok(None);+ }+ if let Some(err) = made {+ return Err(err);+ }+ Ok(Some(settings))+}++/// Writes what the node is doing for the app and `thinkterm tailnet` to+/// read: this process's node, or why it has none -- held elsewhere, failed+/// before it got the node -- unless another live process reports here.+fn report((status, peers): &(Status, Vec<Peer>)) {+ let holding = HOLD.lock().unwrap().is_some();+ if !holding && read_live_report().is_some_and(|report| report.pid != std::process::id()) {+ return;+ }+ // Nothing to say where the tailnet has never been on.+ if !holding && *status == Status::Off && read_report().is_none() {+ return;+ }+ status::write_report(&Report {+ pid: std::process::id(),+ status: status.clone(),+ peers: peers.clone(),+ revision: ACTED.load(Ordering::SeqCst),+ });+}++/// Says this process's node is gone, unless the report is already another+/// process's.+fn report_if_ours(status: Status) {+ if read_report().is_some_and(|report| report.pid != std::process::id()) {+ return;+ }+ status::write_report(&Report {+ pid: std::process::id(),+ status,+ peers: vec![],+ revision: ACTED.load(Ordering::SeqCst),+ });+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn dialing_waits_for_settings_to_finish_initializing() {+ let settling = AtomicBool::new(true);+ std::thread::scope(|scope| {+ scope.spawn(|| {+ std::thread::sleep(Duration::from_millis(75));+ settling.store(false, Ordering::SeqCst);+ });+ wait_for_settings(Duration::from_secs(1), &|| false, || {+ settling.load(Ordering::SeqCst)+ })+ .unwrap();+ assert!(!settling.load(Ordering::SeqCst));+ });+ }++ #[test]+ fn a_closed_session_stops_waiting_and_a_long_wait_goes_on() {+ assert!(wait_for_settings(Duration::from_secs(1), &|| true, || true).is_err());+ // A settings thread that is slow or gone fails no connection.+ assert!(wait_for_settings(Duration::from_millis(20), &|| false, || true).is_ok());+ assert!(wait_for_settings(Duration::ZERO, &|| false, || false).is_ok());+ }+}diff --git a/thinkterm-tailnet/src/lib.rs b/thinkterm-tailnet/src/lib.rsnew file mode 100644index 00000000..5c144603--- /dev/null+++ b/thinkterm-tailnet/src/lib.rs@@ -0,0 +1,391 @@+//! Joining a tailnet from inside ThinkTerm, without the Tailscale app: a node+//! of Tailscale's own Rust implementation, held by the machine's mux server.+//!+//! The settings file says whether the machine joins; the mux server, built+//! with the `node` feature, holds the node while it does ([`follow`]) and+//! reports what the node is doing to a file the app and `thinkterm tailnet`+//! read. SSH connections to the tailnet's machines go through the node+//! ([`use_for_ssh`]) from any ThinkTerm process on the machine: the others+//! ask the server for them on a socket, and need nothing of the library. The node+//! also takes SSH connections from the tailnet to this machine's own sshd+//! when `thinkterm tailnet up --serve-ssh` said to ([`Settings::serve_ssh`]), and+//! nothing else.++mod settings;+mod status;++#[cfg(all(feature = "node", any(target_os = "macos", target_os = "linux")))]+mod holder;+#[cfg(all(feature = "node", any(target_os = "macos", target_os = "linux")))]+mod node;+#[cfg(any(target_os = "macos", target_os = "linux"))]+mod proxy;++#[cfg(all(feature = "node", any(target_os = "macos", target_os = "linux")))]+pub use holder::{follow, will_hold};+pub use settings::{load, load_summary, Settings, Summary};+pub(crate) use status::Family;+pub use status::{read_live_report, Peer, Report, Status};++/// Nothing to hold where the library does not run.+#[cfg(all(feature = "node", not(any(target_os = "macos", target_os = "linux"))))]+pub fn follow(changed: impl Fn() + Send + Sync + 'static) {+ let _ = changed;+}++/// Nothing to hold where the library does not run.+#[cfg(all(feature = "node", not(any(target_os = "macos", target_os = "linux"))))]+pub fn will_hold() {}++use anyhow::{Context, Result};+use std::time::Duration;++/// Whether this build can join a tailnet: the library runs on macOS and+/// Linux only.+pub const SUPPORTED: bool = cfg!(any(target_os = "macos", target_os = "linux"));++/// How long a connection waits for the other machine when the caller sets+/// no limit of its own.+const DIAL_TIMEOUT: Duration = Duration::from_secs(30);++/// How long a connection selecting the tailnet waits for the mux server+/// to take up the node: just after the switch was+/// turned on, or while the server starts at login.+#[cfg(any(target_os = "macos", target_os = "linux"))]+const HOLDER_WAIT: Duration = Duration::from_secs(15);++/// Tailscale's own control server, where a node goes when none is set.+const DEFAULT_CONTROL_SERVER: &str = "https://controlplane.tailscale.com";++/// The capability version the key is asked for with: the one the library+/// speaks (ts_control's `CapabilityVersion::CURRENT`). A control server+/// sends its key the same way to every recent one.+#[cfg(any(target_os = "macos", target_os = "linux"))]+const KEY_VERSION: &str = "130";++/// Changes the settings file: reads it afresh, applies `change`, writes it+/// back and has this process act on it at once if it holds the node. Blank+/// fields are stored as absent (see [`Settings::normalize`]) and the control+/// server in one spelling (see [`control_url_as_kept`]). Settings a node is+/// to start on are not stored unless one could; leaving never needs usable+/// ones.+pub fn update(change: impl FnOnce(&mut Settings)) -> Result<Settings> {+ // Serializes this process's read-modify-write of the file; the file+ // lock does the same between processes.+ static SETTINGS: std::sync::Mutex<()> = std::sync::Mutex::new(());+ settings::check_writer()?;+ let settings = {+ let _guard = SETTINGS.lock().unwrap();+ let _locked = settings::lock_for_update()?;+ let mut settings = settings::load()?;+ let saved_url = settings.control_url.clone();+ change(&mut settings);+ settings.normalize();+ // Only an address that is new, or that a node is to start on, has+ // to be one: an address broken by hand does not keep the node on.+ if settings.enabled || settings.control_url != saved_url {+ settings.control_url = match &settings.control_url {+ Some(url) => control_url_as_kept(url)?,+ None => None,+ };+ }+ settings.revision = settings.revision.wrapping_add(1);+ settings::save(&settings)?;+ settings+ };+ #[cfg(all(feature = "node", any(target_os = "macos", target_os = "linux")))]+ holder::settings_changed();+ Ok(settings)+}++/// A control server's address as the settings keep it: None for+/// Tailscale's own (blank), else in one spelling, so that the same server+/// typed two ways is no change and restarts nothing. Only HTTPS: the+/// library asks a control server for its key over HTTPS whatever the+/// address says, so one reached by plain HTTP would never let a node in.+pub fn control_url_as_kept(text: &str) -> Result<Option<String>> {+ let text = text.trim();+ if text.is_empty() {+ return Ok(None);+ }+ let url = control_url(text)?;+ if url.scheme() != "https" {+ anyhow::bail!(+ "the control server address {text:?}: a control server is reached over HTTPS"+ );+ }+ Ok(Some(url.to_string()))+}++/// What a person types for a control server, as a URL: "https://" when no+/// scheme is given.+pub(crate) fn control_url(text: &str) -> Result<url::Url> {+ let text = text.trim();+ let with_scheme = if text.contains("://") {+ text.to_string()+ } else {+ format!("https://{text}")+ };+ with_scheme+ .parse()+ .with_context(|| format!("the control server address {text:?}"))+}++/// Whether a control server answers at `text` -- Tailscale's own when it is+/// empty -- the way it answers a node about to join: with its key, over+/// HTTPS. Takes up to 15 seconds.+pub fn check_control_server(text: &str) -> Result<()> {+ let url = match text.trim() {+ "" => control_url(DEFAULT_CONTROL_SERVER)?,+ text => control_url(text)?,+ };+ fetch_control_key(&url).with_context(|| format!("the control server at {url}"))+}++#[cfg(any(target_os = "macos", target_os = "linux"))]+fn fetch_control_key(url: &url::Url) -> Result<()> {+ use std::convert::TryFrom;+ let mut key_url = url.join("/key")?;+ // Over HTTPS whatever the address says, as the node asks.+ key_url+ .set_scheme("https")+ .map_err(|()| anyhow::anyhow!("not an address HTTPS can reach"))?;+ key_url.query_pairs_mut().append_pair("v", KEY_VERSION);+ let uri = http_req::uri::Uri::try_from(key_url.as_str())?;+ let mut body = Vec::new();+ let response = http_req::request::Request::new(&uri)+ .timeout(Duration::from_secs(15))+ .send(&mut body)?;+ if !response.status_code().is_success() {+ anyhow::bail!(+ "it answered HTTP {} {}",+ response.status_code(),+ response.reason()+ );+ }+ let keys: serde_json::Value =+ serde_json::from_slice(&body).context("it sent no key it could be told by")?;+ match keys.get("publicKey").and_then(|key| key.as_str()) {+ Some(key) if !key.is_empty() => Ok(()),+ _ => anyhow::bail!("it sent no key"),+ }+}++#[cfg(not(any(target_os = "macos", target_os = "linux")))]+fn fetch_control_key(_url: &url::Url) -> Result<()> {+ anyhow::bail!("joining a tailnet is not supported on this platform")+}++/// Registers the tailnet for SSH connections that explicitly select it.+/// For the processes that never hold the node: the app and `thinkterm`.+pub fn use_for_ssh() {+ if !SUPPORTED {+ return;+ }+ wezterm_ssh::set_dialer(Some(std::sync::Arc::new(+ |host: &str, port: u16, family, timeout, cancelled: &dyn Fn() -> bool| {+ dial(host, port, Family::from(family), timeout, cancelled)+ },+ )));+}++/// [`use_for_ssh`] for the mux server: through its own node while it holds+/// one (see `server_dial`).+#[cfg(feature = "node")]+pub fn use_for_ssh_in_server() {+ if !SUPPORTED {+ return;+ }+ wezterm_ssh::set_dialer(Some(std::sync::Arc::new(+ |host: &str, port: u16, family, timeout, cancelled: &dyn Fn() -> bool| {+ server_dial(host, port, Family::from(family), timeout, cancelled)+ },+ )));+}++/// A connection to `host:port` through the selected tailnet. Its machine+/// list alone resolves the name. None means the node cannot reach it;+/// the SSH dialer reports that as an error, without trying system DNS.+/// Blocks while connecting, and gives up soon after `cancelled` says so.+///+/// For the processes that never hold the node, the app and `thinkterm`:+/// it asks the server, and refers to nothing of the node itself, so that+/// they link none of it even when built together with the server.+pub(crate) fn dial(+ host: &str,+ port: u16,+ family: Family,+ timeout: Option<Duration>,+ cancelled: &dyn Fn() -> bool,+) -> Option<Result<socket2::Socket>> {+ #[cfg(any(target_os = "macos", target_os = "linux"))]+ {+ through_holder(+ host,+ port,+ family,+ timeout.unwrap_or(DIAL_TIMEOUT),+ cancelled,+ )+ }+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]+ {+ let _ = (host, port, family, timeout, cancelled, DIAL_TIMEOUT);+ None+ }+}++/// `dial` for the mux server: through its own node while it holds one,+/// else through the process that does.+#[cfg(feature = "node")]+pub(crate) fn server_dial(+ host: &str,+ port: u16,+ family: Family,+ timeout: Option<Duration>,+ cancelled: &dyn Fn() -> bool,+) -> Option<Result<socket2::Socket>> {+ #[cfg(any(target_os = "macos", target_os = "linux"))]+ {+ let timeout = timeout.unwrap_or(DIAL_TIMEOUT);+ if let Some(dialed) = holder::dial(host, port, family, timeout, cancelled) {+ return dialed;+ }+ through_holder(host, port, family, timeout, cancelled)+ }+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]+ {+ let _ = (host, port, family, timeout, cancelled);+ None+ }+}++/// A connection through the process holding the selected node. While+/// nobody holds it, the connection waits for a holder within its timeout.+#[cfg(any(target_os = "macos", target_os = "linux"))]+fn through_holder(+ host: &str,+ port: u16,+ family: Family,+ timeout: Duration,+ cancelled: &dyn Fn() -> bool,+) -> Option<Result<socket2::Socket>> {+ if !load_summary().is_ok_and(|settings| settings.enabled) {+ return None;+ }+ let path = settings::socket_path().ok()?;+ through_holder_at(&path, host, port, family, timeout, cancelled)+}++/// `through_holder`, with where the holder listens passed in.+#[cfg(any(target_os = "macos", target_os = "linux"))]+fn through_holder_at(+ path: &std::path::Path,+ host: &str,+ port: u16,+ family: Family,+ timeout: Duration,+ cancelled: &dyn Fn() -> bool,+) -> Option<Result<socket2::Socket>> {+ // One time for all of it: waiting for a holder, and what the holder+ // does with what is left.+ let started = std::time::Instant::now();+ let deadline = started + timeout.min(HOLDER_WAIT);+ loop {+ let left = timeout.saturating_sub(started.elapsed());+ if let proxy::Asked::Answered(dialed) =+ proxy::ask(path, host, port, family, left, cancelled)+ {+ return dialed;+ }+ if cancelled() || std::time::Instant::now() >= deadline {+ return None;+ }+ std::thread::sleep(Duration::from_millis(200));+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn control_urls_get_a_scheme_when_typed_without() {+ assert_eq!(+ control_url("headscale.example.com").unwrap().as_str(),+ "https://headscale.example.com/"+ );+ assert_eq!(+ control_url(" http://headscale.example.com:8080 ")+ .unwrap()+ .as_str(),+ "http://headscale.example.com:8080/"+ );+ assert!(control_url("https://").is_err());+ assert_eq!(control_url_as_kept(" ").unwrap(), None);+ assert_eq!(+ control_url_as_kept("headscale.example.com").unwrap(),+ Some("https://headscale.example.com/".to_string())+ );+ // The key would be asked for over HTTPS all the same.+ assert!(control_url_as_kept("http://headscale.example.com:8080").is_err());+ }++ /// Where a holder would listen, in a folder of its own: socket paths+ /// are short, and the default temp dir on macOS is not.+ #[cfg(any(target_os = "macos", target_os = "linux"))]+ fn temp_socket() -> (tempfile::TempDir, std::path::PathBuf) {+ let dir = tempfile::Builder::new()+ .prefix("tt-")+ .tempdir_in("/tmp")+ .unwrap();+ let path = dir.path().join("tailnet.sock");+ (dir, path)+ }++ #[cfg(any(target_os = "macos", target_os = "linux"))]+ #[test]+ fn a_tailnet_host_waits_for_the_server_to_take_up_the_node() {+ use std::io::{Read, Write};+ let (_dir, path) = temp_socket();+ let late = path.clone();+ let holder = std::thread::spawn(move || {+ std::thread::sleep(Duration::from_millis(300));+ let listener = std::os::unix::net::UnixListener::bind(&late).unwrap();+ let (mut stream, _) = listener.accept().unwrap();+ let mut byte = [0u8; 1];+ while stream.read(&mut byte).unwrap() == 1 && byte[0] != b'\n' {}+ stream.write_all(b"none\n").unwrap();+ });+ let started = std::time::Instant::now();+ let dialed = through_holder_at(+ &path,+ "server-a",+ 22,+ Family::Any,+ Duration::from_secs(5),+ &|| false,+ );+ // The holder's own answer, once it was there to give one.+ assert!(dialed.is_none());+ assert!(started.elapsed() >= Duration::from_millis(300));+ holder.join().unwrap();+ }++ #[cfg(any(target_os = "macos", target_os = "linux"))]+ #[test]+ fn a_closed_session_does_not_wait() {+ let (_dir, path) = temp_socket();+ let started = std::time::Instant::now();+ let dialed = through_holder_at(+ &path,+ "server-a",+ 22,+ Family::Any,+ Duration::from_secs(5),+ &|| true,+ );+ assert!(dialed.is_none());+ assert!(started.elapsed() < Duration::from_secs(1));+ }+}diff --git a/thinkterm-tailnet/src/node.rs b/thinkterm-tailnet/src/node.rsnew file mode 100644index 00000000..4be5efd8--- /dev/null+++ b/thinkterm-tailnet/src/node.rs@@ -0,0 +1,1494 @@+//! A node in the tailnet, on a Tokio runtime of its own: the library needs+//! one, and nothing else in these processes runs on Tokio.++use crate::proxy::widen;+use crate::status::{Family, Peer, Status};+use anyhow::{anyhow, bail, Context, Result};+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};+use std::path::PathBuf;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};+use tailscale::netstack::TcpStream;+use tailscale::{AuthState, Device};+use tokio::io::{AsyncRead, AsyncWrite};++/// How long a connection asked for while the node is still getting in+/// waits for its list of machines: at launch, restored tabs ask before the+/// node has reached the control server.+pub(crate) const STARTING_WAIT: Duration = Duration::from_secs(15);++/// How long a stopped node gets to wind down before what is left of it is+/// dropped.+const STOP_WAIT: Duration = Duration::from_secs(2);++/// The name of the node's threads.+const NODE_THREAD: &str = "tailnet";++/// What a node given up because part of it stopped says, while the one in+/// its place starts.+const STARTING_ANEW: &str = "the tailnet stopped working; starting it again";++/// How long a node may be stuck (see `is_stuck`) before it is given up and+/// started anew (see `Node::is_broken`): half a minute, doubled for each+/// node given up in a row before it, up to two, so that one left offline+/// for hours tries now and then.+pub(crate) fn broken_after(given_up: u32) -> Duration {+ Duration::from_secs(30) * 2u32.pow(given_up.min(2))+}++/// What a node starts with. No Debug: it holds the auth key and the node's+/// private keys.+#[derive(Clone, PartialEq, Eq)]+pub(crate) struct NodeConfig {+ pub control_url: Option<String>,+ pub hostname: Option<String>,+ pub auth_key: Option<String>,+ pub node_keys: String,+ /// Take SSH connections from the tailnet to this machine's own sshd.+ pub forward_ssh: bool,+}++impl NodeConfig {+ /// Whether a node running on these settings, at `status` and having got+ /// in before or not (`was_in`), has to make way for one on `new`. A new+ /// auth key alone restarts only a node it could get in: one not yet in,+ /// or one asked to log in again. It only matters for getting in, and+ /// the node that is in -- or only reconnecting -- carries connections a+ /// restart would end.+ pub fn needs_restart_for(&self, new: &NodeConfig, status: &Status, was_in: bool) -> bool {+ let same_node = self.control_url == new.control_url+ && self.hostname == new.hostname+ && self.node_keys == new.node_keys+ && self.forward_ssh == new.forward_ssh;+ let key_matters = !was_in || matches!(status, Status::NeedsLogin { .. });+ !same_node || (self.auth_key != new.auth_key && key_matters)+ }++ /// Whether a node can start on these settings, found out before the+ /// running one is stopped for them.+ pub fn check(&self) -> Result<()> {+ self.library_config().map(drop)+ }++ fn library_config(&self) -> Result<tailscale::Config> {+ let mut config = tailscale::Config::default();+ config.key_state =+ serde_json::from_str(&self.node_keys).context("reading the node's keys")?;+ config.client_name = Some("thinkterm".to_string());+ config.requested_hostname = Some(+ self.hostname+ .clone()+ .unwrap_or_else(|| automatic_name(&config.key_state)),+ );+ if let Some(url) = &self.control_url {+ config.control_server_url = crate::control_url(url)?;+ }+ Ok(config)+ }+}++pub(crate) struct Node {+ config: NodeConfig,+ handle: tokio::runtime::Handle,+ runtime: Mutex<Option<tokio::runtime::Runtime>>,+ shared: Arc<Shared>,+ /// Where the machine's other ThinkTerm processes reach this node (see+ /// crate::proxy); gone with it.+ socket: Option<PathBuf>,+}++pub(crate) struct Shared {+ state: Mutex<(Status, Vec<Peer>)>,+ device: Mutex<Option<Arc<Device>>>,+ /// The tailnet's own domain, as this machine's full name has it.+ domain: Mutex<Option<String>>,+ /// Set once the node is stopped: what waits on it gives up.+ stopped: AtomicBool,+ /// Set once the node is given up, to be started anew (see+ /// `Node::is_broken`).+ broken: AtomicBool,+ /// Set once the node has got in.+ was_in: AtomicBool,+ changed: Box<dyn Fn() + Send + Sync>,+}++impl Shared {+ /// Gives the node up, to be started anew in its place, and says so.+ fn give_up(&self, status: Status) {+ self.broken.store(true, Ordering::SeqCst);+ let unchanged = self.status() == status;+ self.set_status(status);+ if unchanged {+ (self.changed)();+ }+ }++ /// Gives the node up, as `give_up`, unless it got in -- or as far as a+ /// login -- since it was last looked at: looked at again under the+ /// lock its status changes under, so it cannot get in between.+ fn give_up_if_stuck(&self) -> bool {+ {+ let state = self.state.lock().unwrap();+ if !is_stuck(&state.0) {+ return false;+ }+ self.broken.store(true, Ordering::SeqCst);+ }+ (self.changed)();+ true+ }++ fn set_status(&self, status: Status) {+ {+ let mut state = self.state.lock().unwrap();+ if state.0 == status {+ return;+ }+ if matches!(status, Status::Connected { .. }) {+ self.was_in.store(true, Ordering::SeqCst);+ }+ state.0 = status;+ }+ (self.changed)();+ }++ fn set_peers(&self, peers: Vec<Peer>) {+ {+ let mut state = self.state.lock().unwrap();+ if state.1 == peers {+ return;+ }+ state.1 = peers;+ }+ (self.changed)();+ }++ fn status(&self) -> Status {+ self.state.lock().unwrap().0.clone()+ }++ fn peers(&self) -> Vec<Peer> {+ self.state.lock().unwrap().1.clone()+ }++ /// The selected tailnet's address of `family` for `host`, or None when+ /// its machine list cannot resolve it. Waits up to `wait` while joining.+ pub fn resolve(+ &self,+ host: &str,+ family: Family,+ wait: Duration,+ cancelled: &dyn Fn() -> bool,+ ) -> Option<IpAddr> {+ let given_up = || cancelled() || self.stopped.load(Ordering::SeqCst);+ resolve_with(+ host,+ family,+ wait,+ &given_up,+ || self.status(),+ || self.peers(),+ || self.domain.lock().unwrap().clone(),+ )+ }++ /// From inside the node's runtime: a stream to `to` through the+ /// tailnet.+ pub async fn tcp_connect(&self, to: SocketAddr, timeout: Duration) -> Result<TcpStream> {+ let device = self+ .device+ .lock()+ .unwrap()+ .clone()+ .context("the tailnet is not connected yet")?;+ match tokio::time::timeout(timeout, device.tcp_connect(to)).await {+ Ok(Ok(stream)) => Ok(stream),+ Ok(Err(err)) => {+ use tailscale::InternalErrorKind::InternalChannelClosed;+ // Its netstack gone, the node connects nowhere again while+ // saying it is in: nothing else would notice.+ if err == tailscale::Error::Internal(InternalChannelClosed) {+ self.give_up(Status::Failed {+ error: STARTING_ANEW.into(),+ });+ }+ Err(anyhow!(err))+ }+ Err(_) => bail!("no answer within {timeout:?}"),+ }+ }+}++/// How long a connection waits for a node that is still getting in, out of+/// the time it has.+pub(crate) fn starting_wait(timeout: Duration) -> Duration {+ timeout.min(STARTING_WAIT)+}++/// Shared::resolve, with what it asks passed in.+fn resolve_with(+ host: &str,+ family: Family,+ wait: Duration,+ cancelled: &dyn Fn() -> bool,+ status: impl Fn() -> Status,+ peers: impl Fn() -> Vec<Peer>,+ domain: impl Fn() -> Option<String>,+) -> Option<IpAddr> {+ let host = host.trim_end_matches('.');+ let literal = host.parse::<IpAddr>().ok();+ if literal.is_some_and(|ip| !family.allows(ip)) {+ return None;+ }+ let deadline = Instant::now().checked_add(wait);+ loop {+ if cancelled() {+ return None;+ }+ let named: Vec<Peer> = peers()+ .into_iter()+ .filter(|peer| peer.answers_to(host))+ .collect();+ if !named.is_empty() {+ let peer = one_named(named, domain().as_deref())?;+ return literal.or_else(|| peer.address_in(family));+ }+ // The caller selected this tailnet. Its machine list alone resolves+ // the name, once the node has joined; no system DNS is asked.+ if !matches!(status(), Status::Starting | Status::Failed { .. })+ || deadline.is_some_and(|by| Instant::now() >= by)+ {+ return None;+ }+ std::thread::sleep(Duration::from_millis(100));+ }+}++/// The machine a name stands for when several answer to it: the tailnet's+/// own before one shared into it from another tailnet. None when only+/// others share it -- which one is meant cannot be told, and their full+/// names can say.+fn one_named(mut named: Vec<Peer>, domain: Option<&str>) -> Option<Peer> {+ let own = domain.and_then(|domain| named.iter().position(|peer| peer.in_domain(domain)));+ if let Some(at) = own {+ return Some(named.swap_remove(at));+ }+ (named.len() == 1).then(|| named.swap_remove(0))+}++/// The keys of a new node, as [`NodeConfig::node_keys`] keeps them.+pub(crate) fn new_node_keys() -> Result<String> {+ Ok(serde_json::to_string(+ &tailscale::keys::PersistState::default(),+ )?)+}++/// The name a node asks the tailnet for when none is set: "thinkterm-" and+/// four hex digits of the machine's public key. Not the system's host+/// name, which often carries its owner's; and not none, which Headscale+/// names "node". It stays while the machine keeps its keys and changes+/// with them at logout, so the new node does not take the old one's name+/// while the tailnet still lists it.+pub(crate) fn automatic_name(keys: &tailscale::keys::PersistState) -> String {+ let public = keys.machine_key.import().public;+ let key = public.to_x25519_dalek().to_bytes();+ format!("thinkterm-{:02x}{:02x}", key[0], key[1])+}++/// Whether the control server at `url` sends its key within 15 seconds.+async fn control_server_answers(url: &url::Url) -> Result<()> {+ let wait = Duration::from_secs(15);+ match tokio::time::timeout(wait, ts_control::client::fetch_control_key(url)).await {+ Ok(Ok(_key)) => Ok(()),+ Ok(Err(err)) => Err(anyhow!(err)),+ Err(_) => Err(anyhow!("no answer within {wait:?}")),+ }+}++impl Node {+ /// Starts joining. Returns at once; the status says how it goes, and+ /// `changed` is called (on the node's own threads) whenever the status+ /// or the list of peers changes, or the node is given up (see+ /// `Node::is_broken`).+ pub fn start(+ config: NodeConfig,+ broken_after: Duration,+ changed: Box<dyn Fn() + Send + Sync>,+ ) -> Result<Self> {+ let library_config = config.library_config()?;+ let control = library_config.control_server_url.clone();+ let runtime = tokio::runtime::Builder::new_multi_thread()+ .worker_threads(2)+ .thread_name(NODE_THREAD)+ .enable_all()+ .build()+ .context("starting the tailnet's runtime")?;+ let shared = Arc::new(Shared {+ state: Mutex::new((Status::Starting, vec![])),+ device: Mutex::new(None),+ domain: Mutex::new(None),+ stopped: AtomicBool::new(false),+ broken: AtomicBool::new(false),+ was_in: AtomicBool::new(false),+ changed,+ });+ watched(+ runtime.handle(),+ &shared,+ run(+ Arc::clone(&shared),+ library_config,+ config.auth_key.clone(),+ config.forward_ssh,+ ),+ );+ watched(+ runtime.handle(),+ &shared,+ watchdog(Arc::clone(&shared), broken_after, move || {+ let control = control.clone();+ async move { control_server_answers(&control).await.is_ok() }+ }),+ );+ // A node the other processes cannot reach still serves this one.+ let socket = match crate::proxy::bind() {+ Ok((listener, path)) => {+ watched(+ runtime.handle(),+ &shared,+ crate::proxy::serve(Arc::clone(&shared), listener),+ );+ Some(path)+ }+ Err(err) => {+ log::warn!(+ "tailnet: sharing the node with this machine's other processes: {err:#}"+ );+ None+ }+ };+ Ok(Self {+ config,+ handle: runtime.handle().clone(),+ runtime: Mutex::new(Some(runtime)),+ shared,+ socket,+ })+ }++ pub fn config(&self) -> &NodeConfig {+ &self.config+ }++ pub fn status(&self) -> Status {+ self.shared.status()+ }++ pub fn peers(&self) -> Vec<Peer> {+ self.shared.peers()+ }++ /// Leaves the tailnet: every connection through the node ends with it,+ /// and one still waiting on it gives up. Waits a moment for the node to+ /// wind down, so that one started next on the same keys does not meet+ /// it at the control server. Not from inside a Tokio runtime.+ pub fn stop(&self) {+ self.shared.stopped.store(true, Ordering::SeqCst);+ let device = self.shared.device.lock().unwrap().take();+ if let Some(runtime) = self.runtime.lock().unwrap().take() {+ // The library's own way down first, for as long as it takes+ // within half the wait; what is left of it goes with the+ // runtime.+ if let Some(device) = device {+ runtime.block_on(device.stop(STOP_WAIT / 2));+ }+ runtime.shutdown_timeout(STOP_WAIT);+ }+ if let Some(socket) = &self.socket {+ let _ = std::fs::remove_file(socket);+ }+ }++ /// Whether the node was stopped: a dial that found nothing on it may+ /// find it on the node started in its place.+ pub fn is_stopped(&self) -> bool {+ self.shared.stopped.load(Ordering::SeqCst)+ }++ /// Whether the node was given up, to be started anew: it was stuck for+ /// its `broken_after` (see `watchdog`), or one of its loops panicked.+ /// The library tries the control server only a couple of times before it+ /// stops trying, and a part of it whose restarts ran out stays stopped:+ /// neither comes back by itself.+ pub fn is_broken(&self) -> bool {+ self.shared.broken.load(Ordering::SeqCst)+ }++ /// Whether the node has got in: one that has reconnects by itself.+ pub fn was_in(&self) -> bool {+ self.shared.was_in.load(Ordering::SeqCst)+ }++ /// A connection to `host:port` through the tailnet (see crate::dial),+ /// else None. Blocks while it connects, so it is for the threads SSH+ /// sessions connect on; gives up soon after `cancelled` says so.+ pub fn dial(+ &self,+ host: &str,+ port: u16,+ family: Family,+ timeout: Duration,+ cancelled: &dyn Fn() -> bool,+ ) -> Option<Result<socket2::Socket>> {+ let started = Instant::now();+ let ip = self+ .shared+ .resolve(host, family, starting_wait(timeout), cancelled)?;+ // What is left of the time, for the connection itself.+ let left = timeout.saturating_sub(started.elapsed());+ Some(+ self.connect(SocketAddr::new(ip, port), left, cancelled)+ .with_context(|| format!("connecting to {host}:{port} through the tailnet")),+ )+ }++ fn connect(+ &self,+ to: SocketAddr,+ timeout: Duration,+ cancelled: &dyn Fn() -> bool,+ ) -> Result<socket2::Socket> {+ // One end goes to the SSH library as its socket; the other is+ // copied to and from the tailnet's stream.+ let (ours, theirs) =+ std::os::unix::net::UnixStream::pair().context("making a socket pair")?;+ widen(&ours);+ widen(&theirs);+ ours.set_nonblocking(true)?;+ let (done, connected) = std::sync::mpsc::sync_channel::<Result<()>>(1);+ let shared = Arc::clone(&self.shared);+ self.handle.spawn(async move {+ let stream = match shared.tcp_connect(to, timeout).await {+ Ok(stream) => stream,+ Err(err) => {+ let _ = done.send(Err(err));+ return;+ }+ };+ let ours = match tokio::net::UnixStream::from_std(ours) {+ Ok(ours) => ours,+ Err(err) => {+ let _ = done.send(Err(err.into()));+ return;+ }+ };+ let _ = done.send(Ok(()));+ // Ends at once if the caller gave up meanwhile: its end is gone.+ bridge(stream, ours).await;+ });+ // A ConnectTimeout too large to add to now waits as long as it takes.+ let deadline = Instant::now().checked_add(timeout.saturating_add(Duration::from_secs(1)));+ loop {+ match connected.recv_timeout(Duration::from_millis(100)) {+ Ok(result) => {+ result?;+ break;+ }+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {+ if cancelled() {+ bail!("the session was closed while connecting");+ }+ if deadline.is_some_and(|deadline| Instant::now() >= deadline) {+ bail!("no answer within {timeout:?}");+ }+ }+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {+ bail!("the tailnet node stopped")+ }+ }+ }+ Ok(socket2::Socket::from(std::os::fd::OwnedFd::from(theirs)))+ }+}++async fn run(+ shared: Arc<Shared>,+ config: tailscale::Config,+ auth_key: Option<String>,+ forward_ssh: bool,+) {+ let mut wait = Duration::from_secs(5);+ let device = loop {+ shared.set_status(Status::Starting);+ match Device::new(&config, auth_key.clone()).await {+ Ok(device) => break Arc::new(device),+ Err(err) => shared.set_status(Status::Failed {+ error: err.to_string(),+ }),+ }+ tokio::time::sleep(wait).await;+ wait = (wait * 2).min(Duration::from_secs(60));+ };+ *shared.device.lock().unwrap() = Some(Arc::clone(&device));++ let mut listeners: Vec<(IpAddr, tokio::task::JoinHandle<()>)> = Vec::new();+ let mut asking_authorization = None;+ let mut asking_netmap = None;+ loop {+ let snapshot = authorized_snapshot(+ answer(&mut asking_authorization, || {+ let device = Arc::clone(&device);+ async move {+ // Turned away by the control server: why, rather than+ // a node that seems never to get anywhere.+ if let Some(reason) = device.registration_error().await? {+ bail!("{reason}");+ }+ device+ .current_auth_state()+ .await+ .map_err(anyhow::Error::from)+ }+ }),+ answer(&mut asking_netmap, || {+ let device = Arc::clone(&device);+ async move {+ // Both come with the first netmap; until then the node is+ // still getting in, the machines included.+ let Some(this) = device.current_self_node().await? else {+ return Ok(None);+ };+ let Some(nodes) = device.peers().await? else {+ return Ok(None);+ };+ Ok(Some((this, nodes)))+ }+ }),+ Duration::from_secs(5),+ )+ .await;+ match snapshot {+ Ok((this, nodes)) => {+ let addresses: Vec<IpAddr> = [+ IpAddr::V4(this.tailnet_address.ipv4.addr()),+ IpAddr::V6(this.tailnet_address.ipv6.addr()),+ ]+ .into_iter()+ .filter(|ip| !ip.is_unspecified())+ .collect();+ if forward_ssh {+ // At most one listener per current node address. A+ // fresh authorization may give the node new addresses.+ listeners.retain(|(on, task)| {+ let keep = addresses.contains(on) && !task.is_finished();+ if !keep {+ task.abort();+ }+ keep+ });+ for &on in &addresses {+ if !listeners.iter().any(|(address, _)| *address == on) {+ listeners.push((+ on,+ tokio::spawn(forward_ssh_to_this_machine(+ Arc::clone(&device),+ Arc::clone(&shared),+ on,+ )),+ ));+ }+ }+ }+ *shared.domain.lock().unwrap() = this.tailnet.clone();+ let mut peers: Vec<Peer> = nodes.iter().map(peer).collect();+ peers.sort_by(|a, b| a.name.cmp(&b.name).then_with(|| a.fqdn.cmp(&b.fqdn)));+ shared.set_peers(peers);+ shared.set_status(Status::Connected {+ name: this.hostname,+ address: addresses.first().copied(),+ });+ }+ Err(status) => {+ if matches!(status, Status::NeedsLogin { .. }) {+ shared.set_peers(vec![]);+ }+ shared.set_status(status);+ }+ }+ let wait = match shared.status() {+ Status::Starting => Duration::from_millis(250),+ Status::NeedsLogin { .. } | Status::Failed { .. } => Duration::from_secs(2),+ _ => Duration::from_secs(5),+ };+ tokio::time::sleep(wait).await;+ }+}++/// Check authorization on every refresh. A control reconnect can require+/// a new login even after this node has been connected. Reading the node+/// can lack a netmap. Use current-state reads so an offline control server+/// retains no abandoned requests, and bound the whole read as well.+async fn authorized_snapshot<T>(+ authorization: impl std::future::Future<Output = Result<Option<AuthState>>>,+ snapshot: impl std::future::Future<Output = Result<Option<T>>>,+ wait: Duration,+) -> std::result::Result<T, Status> {+ let failed = |err: anyhow::Error| Status::Failed {+ error: err.to_string(),+ };+ let read = async {+ match authorization+ .await+ .map_err(&failed)?+ .ok_or(Status::Starting)?+ {+ AuthState::Authorized => snapshot.await.map_err(&failed)?.ok_or(Status::Starting),+ AuthState::NotAuthorized(url) => Err(Status::NeedsLogin {+ url: url.to_string(),+ }),+ }+ };+ tokio::time::timeout(wait, read)+ .await+ .unwrap_or(Err(Status::Starting))+}++/// The answer to a question for the library, asked in a task kept in+/// `asking` until it is answered. A question stays in the library's+/// mailboxes after we stop waiting for it, and its control client handles+/// some messages by waiting on the network: one still unanswered is waited+/// for again rather than asked again, so a stuck library is not flooded.+async fn answer<T, F>(+ asking: &mut Option<tokio::task::JoinHandle<Result<T>>>,+ ask: impl FnOnce() -> F,+) -> Result<T>+where+ T: Send + 'static,+ F: std::future::Future<Output = Result<T>> + Send + 'static,+{+ let task = asking.get_or_insert_with(|| tokio::spawn(ask()));+ let answered = task.await;+ *asking = None;+ answered?+}++/// How long a node has gone without getting in, or as far as a login.+#[derive(Default)]+struct Stuck(Option<Instant>);++impl Stuck {+ /// Counts a look at the node, `stuck` or not: whether every look has+ /// found it stuck for at least `long` by `now`.+ fn for_at_least(&mut self, stuck: bool, long: Duration, now: Instant) -> bool {+ if !stuck {+ self.0 = None;+ return false;+ }+ now.saturating_duration_since(*self.0.get_or_insert(now)) >= long+ }+}++/// Gives the node up once it has been stuck (see `is_stuck`) for+/// `broken_after`, wherever it is stuck: building the library, waiting on a+/// control server the library stopped trying, on a control connection that+/// went with the network it was made on, or with part of the library+/// stopped. One that was in goes only once `control_answers`: until then+/// one started in its place could not get in either, while this one may+/// still carry connections to the machines it knew.+async fn watchdog<F>(shared: Arc<Shared>, broken_after: Duration, control_answers: impl Fn() -> F)+where+ F: std::future::Future<Output = bool>,+{+ let mut stuck = Stuck::default();+ let mut was_in = false;+ loop {+ tokio::time::sleep(broken_after / 30).await;+ let status = shared.status();+ was_in |= !is_stuck(&status);+ if !stuck.for_at_least(is_stuck(&status), broken_after, Instant::now()) {+ continue;+ }+ // Looked at again after another while, unless the node got in+ // while its control server was asked.+ if was_in && !(control_answers().await && is_stuck(&shared.status())) {+ stuck = Stuck::default();+ continue;+ }+ let status = shared.status();+ // One that got in at the last moment is watched on, not given up.+ if !shared.give_up_if_stuck() {+ stuck = Stuck::default();+ continue;+ }+ log::warn!("tailnet: stuck for {broken_after:?} ({status:?}); starting the node anew");+ return;+ }+}++/// Whether a node is stuck at `status`: anywhere short of in, or as far as+/// a login. Connections through one that is not in time out: the library+/// asks its control part for every one.+fn is_stuck(status: &Status) -> bool {+ !matches!(status, Status::Connected { .. } | Status::NeedsLogin { .. })+}++/// Runs one of the node's own loops. One that panics leaves nothing to+/// notice that it stopped, so the node is given up and started anew.+fn watched(+ runtime: &tokio::runtime::Handle,+ shared: &Arc<Shared>,+ task: impl std::future::Future<Output = ()> + Send + 'static,+) {+ let task = runtime.spawn(task);+ let shared = Arc::clone(shared);+ runtime.spawn(async move {+ if task.await.is_err_and(|err| err.is_panic()) {+ shared.give_up(Status::Failed {+ error: STARTING_ANEW.into(),+ });+ }+ });+}++fn peer(node: &tailscale::NodeInfo) -> Peer {+ let ipv4: Ipv4Addr = node.tailnet_address.ipv4.addr();+ let ipv6: Ipv6Addr = node.tailnet_address.ipv6.addr();+ Peer {+ name: node.hostname.clone(),+ fqdn: node.fqdn(false),+ ipv4: (!ipv4.is_unspecified()).then_some(ipv4),+ ipv6: (!ipv6.is_unspecified()).then_some(ipv6),+ online: match node.status {+ ts_control::NodeStatus::Online => Some(true),+ ts_control::NodeStatus::Offline(_) => Some(false),+ ts_control::NodeStatus::Unknown => None,+ },+ os: node.device.os.clone(),+ distro: node.device.distro.clone(),+ model: node.device.device_model.clone(),+ }+}++/// Port 22 on this machine's tailnet address, handed to its own sshd. That+/// is all the node lets in. sshd sees a loopback client, so its local-address+/// rules apply; this forwarding is enabled separately with --serve-ssh.+async fn forward_ssh_to_this_machine(device: Arc<Device>, shared: Arc<Shared>, on: IpAddr) {+ let listener = match device.tcp_listen(SocketAddr::new(on, 22)).await {+ Ok(listener) => listener,+ Err(err) => {+ log::error!("tailnet: listening for SSH on {on}: {err}");+ return;+ }+ };+ let sshd = [+ SocketAddr::from((Ipv4Addr::LOCALHOST, 22)),+ SocketAddr::from((Ipv6Addr::LOCALHOST, 22)),+ ];+ loop {+ match listener.accept().await {+ Ok(stream) => {+ tokio::spawn(async move {+ match tokio::net::TcpStream::connect(&sshd[..]).await {+ Ok(local) => bridge(stream, local).await,+ Err(err) => {+ log::warn!("tailnet: an SSH connection came in, but no sshd answers on this machine: {err}")+ }+ }+ });+ }+ // The netstack gone, nothing comes in again: the node is given+ // up rather than asked every second.+ Err(tailscale::netstack::Error::Internal(+ tailscale::netstack::InternalErrorKind::InternalChannelClosed,+ )) => {+ shared.give_up(Status::Failed {+ error: STARTING_ANEW.into(),+ });+ return;+ }+ Err(err) => {+ log::warn!("tailnet: accepting an SSH connection: {err}");+ tokio::time::sleep(Duration::from_secs(1)).await;+ }+ }+ }+}++/// Copies both ways until either side ends, then closes both. The tailnet's+/// streams cannot half-close, so waiting on the other direction after one+/// has ended could wait forever.+pub(crate) async fn bridge(a: impl AsyncRead + AsyncWrite, b: impl AsyncRead + AsyncWrite) {+ let (mut a_read, mut a_write) = tokio::io::split(a);+ let (mut b_read, mut b_write) = tokio::io::split(b);+ tokio::select! {+ _ = tokio::io::copy(&mut a_read, &mut b_write) => {}+ _ = tokio::io::copy(&mut b_read, &mut a_write) => {}+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn config() -> NodeConfig {+ NodeConfig {+ control_url: Some("https://headscale.example.com".into()),+ hostname: Some("server-a".into()),+ auth_key: Some("tskey-old".into()),+ node_keys: new_node_keys().unwrap(),+ forward_ssh: true,+ }+ }++ #[test]+ fn a_new_auth_key_alone_restarts_only_a_node_not_yet_in() {+ let running = config();+ let connected = Status::Connected {+ name: "server-a".into(),+ address: None,+ };+ let new_key = NodeConfig {+ auth_key: Some("tskey-new".into()),+ ..running.clone()+ };+ let login = Status::NeedsLogin {+ url: "https://login.example.com/a".into(),+ };+ assert!(!running.needs_restart_for(&running.clone(), &connected, true));+ assert!(!running.needs_restart_for(&new_key, &connected, true));+ // Only reconnecting: the key would not be asked for.+ assert!(!running.needs_restart_for(&new_key, &Status::Starting, true));+ // Not in yet, or to log in again: the key may get it in.+ assert!(running.needs_restart_for(&new_key, &Status::Starting, false));+ assert!(running.needs_restart_for(&new_key, &login, false));+ assert!(running.needs_restart_for(&new_key, &login, true));+ let renamed = NodeConfig {+ hostname: Some("server-b".into()),+ ..running.clone()+ };+ assert!(running.needs_restart_for(&renamed, &connected, true));+ }++ #[test]+ fn settings_a_node_cannot_start_on_are_caught_beforehand() {+ assert!(config().check().is_ok());+ let bad_url = NodeConfig {+ control_url: Some("https://".into()),+ ..config()+ };+ assert!(bad_url.check().is_err());+ let bad_keys = NodeConfig {+ node_keys: "{".into(),+ ..config()+ };+ assert!(bad_keys.check().is_err());+ }++ fn server_a() -> Peer {+ Peer {+ name: "server-a".into(),+ fqdn: "server-a.example.ts.net".into(),+ ipv4: Some(Ipv4Addr::new(100, 64, 0, 2)),+ ipv6: None,+ online: Some(true),+ ..Default::default()+ }+ }++ fn resolve_connected(host: &str) -> Option<IpAddr> {+ resolve_with(+ host,+ Family::Any,+ Duration::from_secs(5),+ &|| false,+ || Status::Connected {+ name: "example".into(),+ address: None,+ },+ || vec![server_a()],+ || None,+ )+ }++ #[test]+ fn the_selected_tailnet_resolves_only_its_own_machines() {+ let address = Some(IpAddr::V4(Ipv4Addr::new(100, 64, 0, 2)));+ assert_eq!(resolve_connected("server-a"), address);+ assert_eq!(resolve_connected("server-a.example.ts.net."), address);+ assert_eq!(resolve_connected("100.64.0.2"), address);+ assert_eq!(resolve_connected("server-b"), None);+ assert_eq!(resolve_connected("100.64.0.9"), None);+ assert_eq!(resolve_connected("localhost"), None);+ }++ #[test]+ fn a_node_waiting_to_try_again_is_waited_for_too() {+ let in_after = Instant::now() + Duration::from_millis(300);+ let getting_there = || Instant::now() < in_after;+ let resolved = resolve_with(+ "server-a",+ Family::Any,+ Duration::from_secs(5),+ &|| false,+ || {+ if getting_there() {+ Status::Failed {+ error: "no network yet".into(),+ }+ } else {+ Status::Connected {+ name: "devbox".into(),+ address: None,+ }+ }+ },+ || {+ if getting_there() {+ vec![]+ } else {+ vec![server_a()]+ }+ },+ || None,+ );+ assert_eq!(resolved, Some(IpAddr::V4(Ipv4Addr::new(100, 64, 0, 2))));+ }++ #[test]+ fn a_selected_node_is_waited_for_until_connected_or_cancelled() {+ let in_after = Instant::now() + Duration::from_millis(300);+ let status = || {+ if Instant::now() < in_after {+ Status::Starting+ } else {+ Status::Connected {+ name: "devbox".into(),+ address: None,+ }+ }+ };+ let peers = || {+ if Instant::now() < in_after {+ vec![]+ } else {+ vec![server_a()]+ }+ };+ let wait = Duration::from_secs(5);+ let started = Instant::now();+ let resolved = resolve_with(+ "server-a",+ Family::Any,+ wait,+ &|| false,+ status,+ peers,+ || None,+ );+ assert_eq!(resolved, Some(IpAddr::V4(Ipv4Addr::new(100, 64, 0, 2))));+ assert!(started.elapsed() >= Duration::from_millis(300));++ let starting = || Status::Starting;+ // A wait ends when the session is closed.+ let started = Instant::now();+ assert_eq!(+ resolve_with(+ "server-a",+ Family::Any,+ wait,+ &|| true,+ starting,+ Vec::new,+ || None,+ ),+ None+ );+ assert!(started.elapsed() < Duration::from_secs(1));+ }++ #[test]+ fn a_missing_machine_stops_waiting_at_the_deadline() {+ let started = Instant::now();+ assert_eq!(+ resolve_with(+ "server-a.example.com",+ Family::Any,+ Duration::ZERO,+ &|| false,+ || Status::Starting,+ Vec::new,+ || None,+ ),+ None+ );+ assert!(started.elapsed() < Duration::from_secs(1));+ }++ #[test]+ fn explicit_ipv6_is_preserved_for_a_dual_stack_peer() {+ let ipv6 = Ipv6Addr::new(0xfd7a, 0x115c, 0xa1e0, 0, 0, 0, 0, 2);+ let mut peer = server_a();+ peer.ipv6 = Some(ipv6);+ let resolved = resolve_with(+ &ipv6.to_string(),+ Family::Any,+ Duration::from_secs(1),+ &|| false,+ || Status::Connected {+ name: "devbox".into(),+ address: None,+ },+ || vec![peer.clone()],+ || None,+ );+ assert_eq!(resolved, Some(IpAddr::V6(ipv6)));+ }++ #[test]+ fn a_connection_kept_to_one_family_goes_to_that_address() {+ let ipv6 = Ipv6Addr::new(0xfd7a, 0x115c, 0xa1e0, 0, 0, 0, 0, 2);+ let mut dual_stack = server_a();+ dual_stack.ipv6 = Some(ipv6);+ let resolve = |host: &str, family: Family, peer: &Peer| {+ resolve_with(+ host,+ family,+ Duration::from_secs(1),+ &|| false,+ || Status::Connected {+ name: "devbox".into(),+ address: None,+ },+ || vec![peer.clone()],+ || None,+ )+ };+ let ipv4 = Some(IpAddr::V4(Ipv4Addr::new(100, 64, 0, 2)));+ assert_eq!(resolve("server-a", Family::Any, &dual_stack), ipv4);+ assert_eq!(resolve("server-a", Family::V4, &dual_stack), ipv4);+ assert_eq!(+ resolve("server-a", Family::V6, &dual_stack),+ Some(IpAddr::V6(ipv6))+ );+ // A machine without an address of that family is not reached by it.+ assert_eq!(resolve("server-a", Family::V6, &server_a()), None);+ // Nor is an address of the other family.+ assert_eq!(resolve("100.64.0.2", Family::V6, &dual_stack), None);+ assert_eq!(resolve(&ipv6.to_string(), Family::V4, &dual_stack), None);+ }++ #[test]+ fn a_name_shared_with_a_machine_from_another_tailnet_means_this_ones() {+ let mut shared_in = server_a();+ shared_in.fqdn = "server-a.another.ts.net".into();+ shared_in.ipv4 = Some(Ipv4Addr::new(100, 64, 0, 9));+ let resolve = |host: &str, domain: Option<&str>| {+ resolve_with(+ host,+ Family::Any,+ Duration::from_secs(1),+ &|| false,+ || Status::Connected {+ name: "devbox".into(),+ address: None,+ },+ // Sorted by full name, the other tailnet's comes first.+ || vec![shared_in.clone(), server_a()],+ || domain.map(str::to_string),+ )+ };+ let own = Some(IpAddr::V4(Ipv4Addr::new(100, 64, 0, 2)));+ let other = Some(IpAddr::V4(Ipv4Addr::new(100, 64, 0, 9)));+ assert_eq!(resolve("server-a", Some("example.ts.net")), own);+ // Not knowing which tailnet is this one's, it guesses at neither.+ assert_eq!(resolve("server-a", None), None);+ // A full name says which.+ assert_eq!(resolve("server-a.another.ts.net", None), other);+ }++ #[tokio::test]+ async fn a_connected_node_can_need_login_and_be_authorized_again() {+ let wait = Duration::from_millis(20);+ assert_eq!(+ authorized_snapshot(+ async { Ok(Some(AuthState::Authorized)) },+ async { Ok(Some("before")) },+ wait+ )+ .await,+ Ok("before")+ );+ let login = "https://login.example.com/node";+ let status = authorized_snapshot(+ async { Ok(Some(AuthState::NotAuthorized(login.parse().unwrap()))) },+ std::future::pending::<Result<Option<&str>>>(),+ wait,+ )+ .await;+ assert_eq!(status, Err(Status::NeedsLogin { url: login.into() }));+ assert_eq!(+ authorized_snapshot(+ async { Ok(Some(AuthState::Authorized)) },+ async { Ok(Some("after")) },+ wait+ )+ .await,+ Ok("after")+ );+ }++ #[tokio::test]+ async fn a_missing_netmap_cannot_block_the_next_authorization_check() {+ let wait = Duration::from_millis(20);+ let pending = authorized_snapshot(+ async { Ok(Some(AuthState::Authorized)) },+ std::future::pending::<Result<Option<()>>>(),+ wait,+ )+ .await;+ assert_eq!(pending, Err(Status::Starting));+ let login = "https://login.example.com/again";+ assert_eq!(+ authorized_snapshot(+ async { Ok(Some(AuthState::NotAuthorized(login.parse().unwrap()))) },+ std::future::pending::<Result<Option<()>>>(),+ wait,+ )+ .await,+ Err(Status::NeedsLogin { url: login.into() })+ );+ assert_eq!(+ authorized_snapshot(+ std::future::pending::<Result<Option<AuthState>>>(),+ async { Ok(Some(())) },+ wait,+ )+ .await,+ Err(Status::Starting)+ );+ }++ #[tokio::test]+ async fn an_unanswered_question_is_waited_for_not_asked_again() {+ let wait = Duration::from_millis(20);+ let asked = std::sync::atomic::AtomicUsize::new(0);+ let (tell, told) = tokio::sync::oneshot::channel();+ let mut told = Some(told);+ let mut ask = || {+ asked.fetch_add(1, Ordering::SeqCst);+ let told = told.take();+ async move {+ match told {+ Some(told) => Ok(told.await?),+ None => Ok(0),+ }+ }+ };+ let mut asking = None;+ for _ in 0..2 {+ let gave_up = tokio::time::timeout(wait, answer(&mut asking, &mut ask)).await;+ assert!(gave_up.is_err());+ }+ assert_eq!(asked.load(Ordering::SeqCst), 1);+ tell.send(7).unwrap();+ assert_eq!(answer(&mut asking, &mut ask).await.unwrap(), 7);+ assert_eq!(asked.load(Ordering::SeqCst), 1);+ // Once answered, the next one is asked anew.+ assert_eq!(answer(&mut asking, &mut ask).await.unwrap(), 0);+ assert_eq!(asked.load(Ordering::SeqCst), 2);+ }++ #[tokio::test]+ async fn registration_and_netmap_not_ready_report_starting() {+ let wait = Duration::from_secs(1);+ assert_eq!(+ authorized_snapshot(+ async { Ok(None) },+ std::future::pending::<Result<Option<()>>>(),+ wait,+ )+ .await,+ Err(Status::Starting)+ );+ assert_eq!(+ authorized_snapshot(+ async { Ok(Some(AuthState::Authorized)) },+ async { Ok(None::<()>) },+ wait,+ )+ .await,+ Err(Status::Starting)+ );+ }++ #[test]+ fn new_keys_parse_as_the_library_reads_them() {+ let keys = new_node_keys().unwrap();+ let parsed: tailscale::keys::PersistState = serde_json::from_str(&keys).unwrap();+ assert_eq!(serde_json::to_string(&parsed).unwrap(), keys);+ assert_ne!(new_node_keys().unwrap(), keys);+ }++ #[test]+ fn a_machine_with_no_name_set_asks_for_one_made_from_its_key() {+ let unnamed = NodeConfig {+ hostname: None,+ ..config()+ };+ let keys: tailscale::keys::PersistState = serde_json::from_str(&unnamed.node_keys).unwrap();+ let name = automatic_name(&keys);+ let digits = name.strip_prefix("thinkterm-").unwrap();+ assert_eq!(digits.len(), 4);+ assert!(digits+ .bytes()+ .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)));+ let asked = unnamed.library_config().unwrap().requested_hostname;+ assert_eq!(asked, Some(name));+ let named = config().library_config().unwrap();+ assert_eq!(named.requested_hostname.as_deref(), Some("server-a"));+ // Made the same way in every version: a change would rename every+ // machine that has no name set.+ let fixed = tailscale::keys::PersistState {+ machine_key: tailscale::keys::Export::from_bytes([7; 32]),+ ..Default::default()+ };+ assert_eq!(automatic_name(&fixed), "thinkterm-13be");+ }++ #[tokio::test]+ async fn bridge_carries_both_ways_and_ends_with_either_side() {+ use tokio::io::{AsyncReadExt, AsyncWriteExt};+ let (mut left, left_inner) = tokio::io::duplex(64);+ let (right_inner, mut right) = tokio::io::duplex(64);+ let bridged = tokio::spawn(bridge(left_inner, right_inner));++ left.write_all(b"ping").await.unwrap();+ let mut buf = [0u8; 4];+ right.read_exact(&mut buf).await.unwrap();+ assert_eq!(&buf, b"ping");+ right.write_all(b"pong").await.unwrap();+ left.read_exact(&mut buf).await.unwrap();+ assert_eq!(&buf, b"pong");++ drop(left);+ bridged.await.unwrap();+ let mut rest = vec![];+ right.read_to_end(&mut rest).await.unwrap();+ assert!(rest.is_empty());+ }++ /// Shared state with nothing running, and how often it said it changed.+ fn shared_counting() -> (Arc<Shared>, Arc<std::sync::atomic::AtomicUsize>) {+ let said = Arc::new(std::sync::atomic::AtomicUsize::new(0));+ let shared = Arc::new(Shared {+ state: Mutex::new((Status::Starting, vec![])),+ device: Mutex::new(None),+ domain: Mutex::new(None),+ stopped: AtomicBool::new(false),+ broken: AtomicBool::new(false),+ was_in: AtomicBool::new(false),+ changed: Box::new({+ let said = Arc::clone(&said);+ move || {+ said.fetch_add(1, Ordering::SeqCst);+ }+ }),+ });+ (shared, said)+ }++ #[test]+ fn a_node_counts_as_stuck_only_when_stuck_throughout() {+ let long = Duration::from_secs(30);+ let start = Instant::now();+ let at = |secs| start + Duration::from_secs(secs);+ let mut stuck = Stuck::default();+ assert!(!stuck.for_at_least(true, long, at(0)));+ assert!(!stuck.for_at_least(true, long, at(29)));+ // One look that finds it in starts it over.+ assert!(!stuck.for_at_least(false, long, at(30)));+ assert!(!stuck.for_at_least(true, long, at(31)));+ assert!(!stuck.for_at_least(true, long, at(60)));+ assert!(stuck.for_at_least(true, long, at(61)));+ }++ #[test]+ fn a_node_short_of_in_or_a_login_is_stuck() {+ assert!(is_stuck(&Status::Starting));+ assert!(is_stuck(&Status::Failed {+ error: "stopped".into(),+ }));+ assert!(!is_stuck(&Status::Connected {+ name: "devbox".into(),+ address: None,+ }));+ assert!(!is_stuck(&Status::NeedsLogin {+ url: "https://login.example.com/node".into(),+ }));+ }++ /// Whether `shared` is given up within `wait`.+ async fn given_up_within(shared: &Shared, wait: Duration) -> bool {+ let deadline = Instant::now() + wait;+ while Instant::now() < deadline {+ if shared.broken.load(Ordering::SeqCst) {+ return true;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ shared.broken.load(Ordering::SeqCst)+ }++ #[tokio::test]+ async fn the_watchdog_gives_up_a_node_that_never_got_in() {+ let long = Duration::from_millis(300);+ let (shared, _) = shared_counting();+ tokio::spawn(watchdog(Arc::clone(&shared), long, || async {+ unreachable!("asked about the control server")+ }));+ assert!(given_up_within(&shared, Duration::from_secs(5)).await);+ assert_eq!(shared.status(), Status::Starting);+ }++ #[tokio::test]+ async fn the_watchdog_leaves_a_node_waiting_for_a_login() {+ let long = Duration::from_millis(300);+ let (shared, _) = shared_counting();+ shared.set_status(Status::NeedsLogin {+ url: "https://login.example.com/node".into(),+ });+ tokio::spawn(watchdog(Arc::clone(&shared), long, || async { true }));+ assert!(!given_up_within(&shared, long * 3).await);+ }++ #[tokio::test]+ async fn a_node_that_was_in_is_given_up_once_its_control_server_answers() {+ let long = Duration::from_millis(300);+ let (shared, _) = shared_counting();+ shared.set_status(Status::Connected {+ name: "devbox".into(),+ address: None,+ });+ let answers = Arc::new(AtomicBool::new(false));+ tokio::spawn(watchdog(Arc::clone(&shared), long, {+ let answers = Arc::clone(&answers);+ move || {+ let answers = Arc::clone(&answers);+ async move { answers.load(Ordering::SeqCst) }+ }+ }));+ tokio::time::sleep(long / 10).await;+ // Getting back to a control server that is away: one started in its+ // place could not get in either.+ shared.set_status(Status::Starting);+ assert!(!given_up_within(&shared, long * 3).await);+ // Part of the library stopped, with the control server still away.+ shared.set_status(Status::Failed {+ error: "stopped".into(),+ });+ assert!(!given_up_within(&shared, long * 3).await);+ answers.store(true, Ordering::SeqCst);+ assert!(given_up_within(&shared, Duration::from_secs(5)).await);+ }++ #[tokio::test]+ async fn a_node_that_was_in_and_never_gets_back_is_given_up() {+ let long = Duration::from_millis(300);+ let (shared, _) = shared_counting();+ shared.set_status(Status::Connected {+ name: "devbox".into(),+ address: None,+ });+ tokio::spawn(watchdog(Arc::clone(&shared), long, || async { true }));+ tokio::time::sleep(long / 10).await;+ // On a control connection that went with the network it was made+ // on, with the control server answering anew.+ shared.set_status(Status::Starting);+ assert!(given_up_within(&shared, Duration::from_secs(5)).await);+ }++ #[tokio::test]+ async fn a_node_that_gets_in_while_its_control_server_is_asked_is_left() {+ let long = Duration::from_millis(300);+ let (shared, _) = shared_counting();+ let connected = Status::Connected {+ name: "devbox".into(),+ address: None,+ };+ shared.set_status(connected.clone());+ tokio::spawn(watchdog(Arc::clone(&shared), long, {+ let shared = Arc::clone(&shared);+ move || {+ let shared = Arc::clone(&shared);+ let connected = connected.clone();+ async move {+ shared.set_status(connected);+ true+ }+ }+ }));+ tokio::time::sleep(long / 10).await;+ shared.set_status(Status::Failed {+ error: "stopped".into(),+ });+ assert!(!given_up_within(&shared, long * 3).await);+ }++ #[test]+ fn nodes_given_up_in_a_row_wait_longer_up_to_two_minutes() {+ let waits: Vec<u64> = (0..5).map(|n| broken_after(n).as_secs()).collect();+ assert_eq!(waits, [30, 60, 120, 120, 120]);+ }++ #[test]+ fn giving_up_says_so_even_with_the_status_unchanged() {+ let (shared, said) = shared_counting();+ let failed = Status::Failed {+ error: "stopped".into(),+ };+ shared.set_status(failed.clone());+ assert_eq!(said.load(Ordering::SeqCst), 1);+ shared.give_up(failed.clone());+ assert!(shared.broken.load(Ordering::SeqCst));+ assert_eq!(shared.status(), failed);+ assert_eq!(said.load(Ordering::SeqCst), 2);+ }++ #[test]+ fn a_node_that_got_in_meanwhile_is_not_given_up() {+ let (shared, said) = shared_counting();+ shared.set_status(Status::Connected {+ name: "devbox".into(),+ address: None,+ });+ let before = said.load(Ordering::SeqCst);+ assert!(!shared.give_up_if_stuck());+ assert!(!shared.broken.load(Ordering::SeqCst));+ assert_eq!(said.load(Ordering::SeqCst), before);+ // Stuck still: given up, and said so with the status as it was.+ let (shared, said) = shared_counting();+ assert!(shared.give_up_if_stuck());+ assert!(shared.broken.load(Ordering::SeqCst));+ assert_eq!(shared.status(), Status::Starting);+ assert_eq!(said.load(Ordering::SeqCst), 1);+ }++ #[tokio::test]+ async fn a_loop_that_panics_gives_the_node_up() {+ let (shared, _) = shared_counting();+ let runtime = tokio::runtime::Handle::current();+ watched(&runtime, &shared, std::future::pending());+ tokio::task::yield_now().await;+ assert!(!shared.broken.load(Ordering::SeqCst));+ watched(&runtime, &shared, async { panic!("a loop of the node") });+ for _ in 0..100 {+ if shared.broken.load(Ordering::SeqCst) {+ break;+ }+ tokio::time::sleep(Duration::from_millis(10)).await;+ }+ assert!(shared.broken.load(Ordering::SeqCst));+ assert!(matches!(shared.status(), Status::Failed { .. }));+ }+}diff --git a/thinkterm-tailnet/src/proxy.rs b/thinkterm-tailnet/src/proxy.rsnew file mode 100644index 00000000..a823e11a--- /dev/null+++ b/thinkterm-tailnet/src/proxy.rs@@ -0,0 +1,393 @@+//! The machine's ThinkTerm processes reach the tailnet through the one+//! holding the node, the mux server: the app, `thinkterm ssh`, and the+//! server itself while another server holds it. A connection is asked for on+//! a socket beside the settings that only this user can open, with a line+//! naming the host; the answer is a line too, and after "ok" the socket+//! carries the connection itself. Asking needs nothing of the library: only+//! the holder, built with the `node` feature, answers.++use crate::status::Family;+use anyhow::{anyhow, bail, Context, Result};+use serde::{Deserialize, Serialize};+use std::io::{ErrorKind, Read, Write};+use std::os::unix::net::UnixStream;+use std::path::Path;+use std::time::{Duration, Instant};+#[cfg(feature = "node")]+use {+ crate::node::{self, Shared},+ std::net::SocketAddr,+ std::os::unix::net::UnixListener,+ std::path::PathBuf,+ std::sync::Arc,+ tokio::io::{AsyncReadExt, AsyncWriteExt},+};++/// A request or an answer longer than this is not one.+const LINE_MAX: usize = 4096;++/// How long reaching the holder's socket may take: at once while it takes+/// connections, never while a stuck holder lets its backlog fill.+const CONNECT_WAIT: Duration = Duration::from_secs(2);++/// How long past the time it was given the holder may take to answer: its+/// last look the name up can start just before that runs out.+const ANSWER_SLACK: Duration = Duration::from_secs(5);++/// The local leg of each connection gets this much buffer each way: macOS+/// gives a socket pair 8 KiB, which holds a copy over SSH far below what+/// the tailnet carries.+const SOCKET_BUFFER: usize = 512 * 1024;++#[derive(Debug, PartialEq, Serialize, Deserialize)]+struct Request {+ host: String,+ port: u16,+ /// Missing from the requests of a process older than the holder.+ #[serde(default)]+ family: Family,+ timeout_ms: u64,+}++/// Gives a local socket the room SOCKET_BUFFER says. Best effort: one+/// that keeps the system's default still works, only slower.+pub(crate) fn widen(socket: &impl std::os::fd::AsFd) {+ let socket = socket2::SockRef::from(socket);+ let _ = socket.set_send_buffer_size(SOCKET_BUFFER);+ let _ = socket.set_recv_buffer_size(SOCKET_BUFFER);+}++/// What asking the holder of the node came to.+pub(crate) enum Asked {+ /// Nobody listens at `path`: no process here holds a node.+ Nobody,+ /// A connection, why there is none, or None when `host` is none of its+ /// machines or the holder went without answering.+ Answered(Option<Result<socket2::Socket>>),+}++/// A connection to `host:port` through the node of the process listening+/// at `path`, which has `timeout` to make it.+pub(crate) fn ask(+ path: &Path,+ host: &str,+ port: u16,+ family: Family,+ timeout: Duration,+ cancelled: &dyn Fn() -> bool,+) -> Asked {+ let Some(mut stream) = connect_within(path, CONNECT_WAIT) else {+ return Asked::Nobody;+ };+ let request = Request {+ host: host.to_string(),+ port,+ family,+ timeout_ms: u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),+ };+ let Ok(mut line) = serde_json::to_vec(&request) else {+ return Asked::Answered(None);+ };+ line.push(b'\n');+ if stream.write_all(&line).is_err() {+ return Asked::Answered(None);+ }+ let answer = match read_answer(&mut stream, timeout, cancelled) {+ Ok(Some(answer)) => answer,+ // It went without answering; the selected network cannot connect.+ Ok(None) => return Asked::Answered(None),+ Err(err) => return Asked::Answered(Some(Err(err))),+ };+ Asked::Answered(match answer.as_str() {+ "none" => None,+ "ok" => {+ widen(&stream);+ Some(+ stream+ .set_read_timeout(None)+ .map(|()| socket2::Socket::from(std::os::fd::OwnedFd::from(stream)))+ .context("taking over the tailnet's connection"),+ )+ }+ answer => Some(Err(anyhow!(+ "{}",+ answer.strip_prefix("error: ").unwrap_or(answer)+ ))),+ })+}++/// A stream to the socket at `path`, if something listens there and takes+/// it within `wait`.+fn connect_within(path: &Path, wait: Duration) -> Option<UnixStream> {+ let address = socket2::SockAddr::unix(path).ok()?;+ let socket = socket2::Socket::new(socket2::Domain::UNIX, socket2::Type::STREAM, None).ok()?;+ socket.connect_timeout(&address, wait).ok()?;+ socket.set_nonblocking(false).ok()?;+ Some(UnixStream::from(std::os::fd::OwnedFd::from(socket)))+}++/// The holder's answer, read a byte at a time: what follows it is the+/// connection's own. None when the holder went without one, or kept it+/// past any wait it could have.+fn read_answer(+ stream: &mut UnixStream,+ timeout: Duration,+ cancelled: &dyn Fn() -> bool,+) -> Result<Option<String>> {+ stream.set_read_timeout(Some(Duration::from_millis(100)))?;+ // The holder waits for its node to get in and for the other machine+ // within `timeout`.+ let deadline = Instant::now().checked_add(timeout.saturating_add(ANSWER_SLACK));+ let mut line = Vec::new();+ loop {+ let mut byte = [0u8; 1];+ match stream.read(&mut byte) {+ Ok(0) => return Ok(None),+ Ok(_) if byte[0] == b'\n' => {+ return Ok(Some(String::from_utf8_lossy(&line).into_owned()))+ }+ Ok(_) if line.len() < LINE_MAX => line.push(byte[0]),+ Ok(_) => bail!("the tailnet's node gave no answer it could read"),+ Err(err)+ if matches!(+ err.kind(),+ ErrorKind::WouldBlock | ErrorKind::TimedOut | ErrorKind::Interrupted+ ) =>+ {+ if cancelled() {+ bail!("the session was closed while connecting");+ }+ // The caller turns an unanswered request into a failure.+ if deadline.is_some_and(|deadline| Instant::now() >= deadline) {+ log::warn!("tailnet: the process holding the node did not answer");+ return Ok(None);+ }+ }+ Err(_) => return Ok(None),+ }+ }+}++/// The socket for a node starting in this process. This process holds the+/// node (see settings::try_hold_node), so a socket already there is one a+/// holder that has gone left behind.+#[cfg(feature = "node")]+pub(crate) fn bind() -> Result<(UnixListener, PathBuf)> {+ use std::os::unix::fs::PermissionsExt;+ let path = crate::settings::socket_path()?;+ if let Some(parent) = path.parent() {+ crate::settings::create_private_dir(parent)?;+ }+ match std::fs::remove_file(&path) {+ Ok(()) => {}+ Err(err) if err.kind() == ErrorKind::NotFound => {}+ Err(err) => return Err(err).with_context(|| format!("removing {}", path.display())),+ }+ let listener =+ UnixListener::bind(&path).with_context(|| format!("listening on {}", path.display()))?;+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))+ .with_context(|| format!("making {} private", path.display()))?;+ listener.set_nonblocking(true)?;+ Ok((listener, path))+}++/// Answers the machine's other processes for as long as the node's runtime+/// runs.+#[cfg(feature = "node")]+pub(crate) async fn serve(shared: Arc<Shared>, listener: UnixListener) {+ let listener = match tokio::net::UnixListener::from_std(listener) {+ Ok(listener) => listener,+ Err(err) => {+ log::warn!("tailnet: sharing the node with this machine's other processes: {err}");+ return;+ }+ };+ let user = nix::unistd::Uid::current().as_raw();+ loop {+ match listener.accept().await {+ Ok((stream, _)) => {+ // This user's processes only, as the socket's mode says too.+ if stream.peer_cred().is_ok_and(|peer| peer.uid() == user) {+ tokio::spawn(answer(Arc::clone(&shared), stream));+ }+ }+ Err(err) => {+ log::warn!("tailnet: taking a connection from another process: {err}");+ tokio::time::sleep(Duration::from_secs(1)).await;+ }+ }+ }+}++#[cfg(feature = "node")]+async fn answer(shared: Arc<Shared>, mut stream: tokio::net::UnixStream) {+ let Ok(Ok(request)) =+ tokio::time::timeout(Duration::from_secs(5), read_request(&mut stream)).await+ else {+ return;+ };+ let timeout = Duration::from_millis(request.timeout_ms);+ let started = std::time::Instant::now();+ let resolved = {+ let shared = Arc::clone(&shared);+ let host = request.host.clone();+ let family = request.family;+ tokio::task::spawn_blocking(move || {+ shared.resolve(&host, family, node::starting_wait(timeout), &|| false)+ })+ .await+ };+ let ip = match resolved {+ Ok(Some(ip)) => ip,+ Ok(None) => {+ let _ = stream.write_all(b"none\n").await;+ return;+ }+ Err(_) => return,+ };+ // What is left of the time, for the connection itself.+ let left = timeout.saturating_sub(started.elapsed());+ match shared+ .tcp_connect(SocketAddr::new(ip, request.port), left)+ .await+ {+ Ok(tailnet) => {+ if stream.write_all(b"ok\n").await.is_ok() {+ widen(&stream);+ node::bridge(tailnet, stream).await;+ }+ }+ Err(err) => {+ let err = err.context(format!(+ "connecting to {}:{} through the tailnet",+ request.host, request.port+ ));+ let line = format!("error: {}\n", format!("{err:#}").replace('\n', " "));+ let _ = stream.write_all(line.as_bytes()).await;+ }+ }+}++#[cfg(feature = "node")]+async fn read_request(stream: &mut tokio::net::UnixStream) -> Result<Request> {+ let mut line = Vec::new();+ loop {+ match stream.read_u8().await? {+ b'\n' => break,+ _ if line.len() >= LINE_MAX => bail!("not a request"),+ byte => line.push(byte),+ }+ }+ Ok(serde_json::from_slice(&line)?)+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::os::unix::net::UnixListener;+ use std::path::PathBuf;++ /// A holder that answers the one request it gets with `answer`, then+ /// echoes whatever comes after. Returns the socket's path and the+ /// request it got.+ fn holder(+ answer: &'static str,+ ) -> (tempfile::TempDir, PathBuf, std::thread::JoinHandle<Request>) {+ // Socket paths are short; the default temp dir on macOS is not.+ let dir = tempfile::Builder::new()+ .prefix("tt-")+ .tempdir_in("/tmp")+ .unwrap();+ let path = dir.path().join("tailnet.sock");+ let listener = UnixListener::bind(&path).unwrap();+ let served = std::thread::spawn(move || {+ let (mut stream, _) = listener.accept().unwrap();+ let mut line = Vec::new();+ let mut byte = [0u8; 1];+ while stream.read(&mut byte).unwrap() == 1 && byte[0] != b'\n' {+ line.push(byte[0]);+ }+ stream.write_all(answer.as_bytes()).unwrap();+ let mut rest = [0u8; 4];+ if stream.read_exact(&mut rest).is_ok() {+ stream.write_all(&rest).unwrap();+ }+ serde_json::from_slice(&line).unwrap()+ });+ (dir, path, served)+ }++ /// What the holder at `path` answers for `host`, port 22.+ fn answer(path: &Path, host: &str, family: Family) -> Option<Result<socket2::Socket>> {+ match ask(path, host, 22, family, Duration::from_secs(5), &|| false) {+ Asked::Answered(answered) => answered,+ Asked::Nobody => panic!("nobody listened at {}", path.display()),+ }+ }++ #[test]+ fn a_connection_through_another_process_carries_on_after_its_ok() {+ let (_dir, path, served) = holder("ok\n");+ let socket = answer(&path, "server-a", Family::V6)+ .expect("the holder knew it")+ .unwrap();+ let mut stream = UnixStream::from(std::os::fd::OwnedFd::from(socket));+ stream.write_all(b"ping").unwrap();+ let mut echoed = [0u8; 4];+ stream.read_exact(&mut echoed).unwrap();+ assert_eq!(&echoed, b"ping");+ assert_eq!(+ served.join().unwrap(),+ Request {+ host: "server-a".into(),+ port: 22,+ family: Family::V6,+ timeout_ms: 5000+ }+ );+ }++ #[test]+ fn a_request_without_a_family_allows_any() {+ let request: Request =+ serde_json::from_str(r#"{"host":"server-a","port":22,"timeout_ms":5000}"#).unwrap();+ assert_eq!(request.family, Family::Any);+ }++ #[test]+ fn an_unknown_host_gets_no_connection_from_the_holder() {+ let (_dir, path, served) = holder("none\n");+ assert!(answer(&path, "example.com", Family::Any).is_none());+ served.join().unwrap();+ }++ #[test]+ fn the_other_process_says_why_it_could_not_connect() {+ let (_dir, path, served) = holder("error: no answer within 5s\n");+ let err = answer(&path, "server-a", Family::Any)+ .expect("the holder knew it")+ .unwrap_err();+ assert_eq!(err.to_string(), "no answer within 5s");+ served.join().unwrap();+ }++ #[test]+ fn nobody_listening_is_told_from_a_holder_that_does_not_know_the_host() {+ let dir = tempfile::Builder::new()+ .prefix("tt-")+ .tempdir_in("/tmp")+ .unwrap();+ let path = dir.path().join("tailnet.sock");+ assert!(matches!(+ ask(+ &path,+ "server-a",+ 22,+ Family::Any,+ Duration::from_secs(5),+ &|| false+ ),+ Asked::Nobody+ ));+ }+}diff --git a/thinkterm-tailnet/src/settings.rs b/thinkterm-tailnet/src/settings.rsnew file mode 100644index 00000000..149393e8--- /dev/null+++ b/thinkterm-tailnet/src/settings.rs@@ -0,0 +1,480 @@+//! `tailnet.json`: whether this machine joins, whether the tailnet may SSH+//! into it, and the secrets that make it the same node every time. It sits+//! beside the SSH host catalog and its encryption key, and the auth key and+//! the node's keys are encrypted with that key the same way host passwords+//! are.++use anyhow::{Context, Result};+use serde::{Deserialize, Serialize};+use std::fs::{File, OpenOptions};+use std::io::Write;+use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};++/// What `tailnet.json` says, with the secrets decrypted. Its Debug leaves+/// the secrets out.+#[derive(Clone, Default, PartialEq, Eq)]+pub struct Settings {+ /// Whether the machine's mux server holds a node in the tailnet.+ pub enabled: bool,+ /// Whether the node takes SSH connections from the tailnet to this+ /// machine's own sshd: what `thinkterm tailnet up` turns on, for a+ /// machine nobody sits at. The app's switch never does.+ pub serve_ssh: bool,+ /// The control server; None is Tailscale's own.+ pub control_url: Option<String>,+ /// The name to ask the tailnet for; None is one made from the machine's+ /// key (see [`crate::automatic_name`]).+ pub hostname: Option<String>,+ pub auth_key: Option<String>,+ /// The node's identity as the library serializes it. Made on the first+ /// start and kept, so that the machine stays the same node.+ pub node_keys: Option<String>,+ /// Counts the saves. A process acting on the file says which one it+ /// has seen ([`crate::Report::revision`]), so that `thinkterm tailnet+ /// up` can tell the answer to its change from one written before it.+ pub revision: u64,+}++impl Settings {+ /// Blank fields mean the default, so they are kept as absent: a field+ /// emptied in Settings or `--control-url ""` goes back to Tailscale's+ /// own server, the automatic name, or no auth key.+ pub fn normalize(&mut self) {+ for field in [+ &mut self.control_url,+ &mut self.hostname,+ &mut self.auth_key,+ ] {+ *field = field+ .take()+ .map(|text| text.trim().to_string())+ .filter(|text| !text.is_empty());+ }+ }++ pub fn summary(&self) -> Summary {+ Summary {+ enabled: self.enabled,+ serve_ssh: self.serve_ssh,+ control_url: self.control_url.clone(),+ hostname: self.hostname.clone(),+ has_auth_key: self.auth_key.is_some(),+ has_node_keys: self.node_keys.is_some(),+ revision: self.revision,+ }+ }+}++impl std::fmt::Debug for Settings {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ self.summary().fmt(f)+ }+}++/// The settings without their secrets, read without decrypting them: what+/// a page shows, and all a process needs to know whether it holds the node.+#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Summary {+ pub enabled: bool,+ pub serve_ssh: bool,+ pub control_url: Option<String>,+ pub hostname: Option<String>,+ pub has_auth_key: bool,+ pub has_node_keys: bool,+ pub revision: u64,+}++/// The file's own shape: the secrets as `secret::encrypt` left them.+#[derive(Default, Serialize, Deserialize)]+struct Stored {+ #[serde(default)]+ enabled: bool,+ #[serde(default)]+ serve_ssh: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ control_url: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ hostname: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ auth_key: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ node_keys: Option<String>,+ #[serde(default)]+ revision: u64,+}++pub(crate) fn path() -> Result<PathBuf> {+ Ok(thinkterm_core::credential_data_dir()?.join("tailnet.json"))+}++/// Where the process holding the node listens for the others (see+/// crate::proxy): beside the settings, which only this user can open.+#[cfg(unix)]+pub(crate) fn socket_path() -> Result<PathBuf> {+ Ok(path()?.with_file_name("tailnet.sock"))+}++/// Refuses root a change to the settings it would leave behind for the+/// wrong user: run with sudo, which on macOS keeps the user's HOME -- root+/// would leave the user files they cannot change or remove -- and elsewhere+/// writes root's own settings, which the user's mux server never reads.+#[cfg(unix)]+pub(crate) fn check_writer() -> Result<()> {+ if !nix::unistd::geteuid().is_root() {+ return Ok(());+ }+ if std::env::var_os("SUDO_USER").is_some() {+ anyhow::bail!(+ "not changing the tailnet settings as root: run it without sudo, as the user \+ whose mux server holds the node"+ );+ }+ check_owner(&path()?, 0)+}++#[cfg(not(unix))]+pub(crate) fn check_writer() -> Result<()> {+ Ok(())+}++/// Whether `uid` may write the settings at `path`: the nearest folder of it+/// that exists has to be its own.+#[cfg(unix)]+fn check_owner(path: &Path, uid: u32) -> Result<()> {+ use std::os::unix::fs::MetadataExt;+ let owner = path+ .ancestors()+ .skip(1)+ .find_map(|dir| std::fs::metadata(dir).ok().map(|meta| (dir, meta.uid())));+ match owner {+ Some((dir, owner)) if owner != uid => anyhow::bail!(+ "not changing the tailnet settings in {} as root: they belong to another user",+ dir.display()+ ),+ _ => Ok(()),+ }+}++/// Held while one process reads, changes and writes the settings back, so+/// that the app, the server and `thinkterm tailnet` do not undo each other's+/// changes. Released when dropped.+pub(crate) fn lock_for_update() -> Result<File> {+ let file = open_lock("tailnet-settings.lock")?;+ file.lock().context("locking the tailnet settings")?;+ Ok(file)+}++/// Held for as long as a process holds the machine's node: two processes on+/// one node's keys would take the node from each other -- a debug build's+/// mux server beside the release one's. None while another process holds+/// it. Released when dropped, or when the process ends.+#[cfg(all(feature = "node", any(target_os = "macos", target_os = "linux")))]+pub(crate) fn try_hold_node() -> Result<Option<File>> {+ let file = open_lock("tailnet-node.lock")?;+ match file.try_lock() {+ Ok(()) => Ok(Some(file)),+ Err(std::fs::TryLockError::WouldBlock) => Ok(None),+ Err(std::fs::TryLockError::Error(err)) => {+ Err(err).context("locking this machine's tailnet node")+ }+ }+}++/// Creates `dir`, and the folders it is in, open to this user alone where+/// they are new: the files in it are this user's alone, and so are their+/// names.+pub(crate) fn create_private_dir(dir: &Path) -> Result<()> {+ #[cfg(unix)]+ let created = {+ use std::os::unix::fs::DirBuilderExt;+ std::fs::DirBuilder::new()+ .recursive(true)+ .mode(0o700)+ .create(dir)+ };+ #[cfg(not(unix))]+ let created = std::fs::create_dir_all(dir);+ created.with_context(|| format!("creating {}", dir.display()))+}++fn open_lock(name: &str) -> Result<File> {+ let path = path()?.with_file_name(name);+ if let Some(parent) = path.parent() {+ create_private_dir(parent)?;+ }+ OpenOptions::new()+ .create(true)+ .truncate(false)+ .write(true)+ .open(&path)+ .with_context(|| format!("opening {}", path.display()))+}++/// What tells one version of the file from the next: a save puts a new+/// file in place, so its inode tells even where the clock is too coarse to.+#[cfg(any(+ all(feature = "node", any(target_os = "macos", target_os = "linux")),+ test+))]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct Stamp {+ modified: Option<std::time::SystemTime>,+ len: u64,+ #[cfg(unix)]+ inode: u64,+}++/// None while there is no file.+#[cfg(any(+ all(feature = "node", any(target_os = "macos", target_os = "linux")),+ test+))]+pub(crate) fn stamp(path: &Path) -> Option<Stamp> {+ let meta = std::fs::metadata(path).ok()?;+ Some(Stamp {+ modified: meta.modified().ok(),+ len: meta.len(),+ #[cfg(unix)]+ inode: std::os::unix::fs::MetadataExt::ino(&meta),+ })+}++/// The settings, or the defaults (off) when there is no file yet.+pub fn load() -> Result<Settings> {+ load_from(&path()?, thinkterm_core::secret::decrypt)+}++/// The settings without their secrets. A secret that is there counts even+/// when it no longer decrypts.+pub fn load_summary() -> Result<Summary> {+ Ok(load_from(&path()?, |_| Some(String::new()))?.summary())+}++pub(crate) fn save(settings: &Settings) -> Result<()> {+ save_to(&path()?, settings, thinkterm_core::secret::encrypt)+}++/// A secret that no longer decrypts -- the key beside it was replaced --+/// reads as absent: the machine signs in again rather than not at all.+pub(crate) fn load_from(path: &Path, decrypt: impl Fn(&str) -> Option<String>) -> Result<Settings> {+ let text = match std::fs::read_to_string(path) {+ Ok(text) => text,+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Settings::default()),+ Err(err) => return Err(err).with_context(|| format!("reading {}", path.display())),+ };+ let stored: Stored =+ serde_json::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;+ Ok(Settings {+ enabled: stored.enabled,+ serve_ssh: stored.serve_ssh,+ control_url: stored.control_url,+ hostname: stored.hostname,+ auth_key: stored.auth_key.as_deref().and_then(&decrypt),+ node_keys: stored.node_keys.as_deref().and_then(&decrypt),+ revision: stored.revision,+ })+}++pub(crate) fn save_to(+ path: &Path,+ settings: &Settings,+ encrypt: impl Fn(&str) -> Result<String>,+) -> Result<()> {+ let stored = Stored {+ enabled: settings.enabled,+ serve_ssh: settings.serve_ssh,+ control_url: settings.control_url.clone(),+ hostname: settings.hostname.clone(),+ auth_key: settings.auth_key.as_deref().map(&encrypt).transpose()?,+ node_keys: settings.node_keys.as_deref().map(&encrypt).transpose()?,+ revision: settings.revision,+ };+ let mut json = serde_json::to_string_pretty(&stored)?;+ json.push('\n');+ write_private(path, json.as_bytes(), true)+}++/// Written whole through a temporary file, readable by this user alone. The+/// temporary file is this write's own: two processes writing at once each+/// put a whole file in place, rather than one file made of both. `durable`+/// waits for the disk too, which a file that is only ever this moment's+/// news does not need.+pub(crate) fn write_private(path: &Path, bytes: &[u8], durable: bool) -> Result<()> {+ static WRITES: AtomicU64 = AtomicU64::new(0);+ let parent = path+ .parent()+ .with_context(|| format!("{} has no folder", path.display()))?;+ create_private_dir(parent)?;+ let tmp = path.with_extension(format!(+ "json.{}.{}.tmp",+ std::process::id(),+ WRITES.fetch_add(1, Ordering::Relaxed)+ ));+ let mut options = OpenOptions::new();+ options.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options.mode(0o600);+ }+ let mut file = options+ .open(&tmp)+ .with_context(|| format!("creating {}", tmp.display()))?;+ let written = file+ .write_all(bytes)+ .and_then(|()| if durable { file.sync_all() } else { Ok(()) })+ .with_context(|| format!("writing {}", tmp.display()));+ drop(file);+ let result = written.and_then(|()| {+ std::fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))+ });+ if result.is_err() {+ let _ = std::fs::remove_file(&tmp);+ }+ result+}++#[cfg(test)]+mod tests {+ use super::*;++ #[cfg(unix)]+ #[test]+ fn settings_are_changed_only_by_whoever_owns_their_folder() {+ let dir = tempfile::tempdir().unwrap();+ // Not made yet: the nearest folder that is says whose they are.+ let path = dir.path().join("ThinkTerm").join("tailnet.json");+ let me = nix::unistd::getuid().as_raw();+ assert!(check_owner(&path, me).is_ok());+ assert!(check_owner(&path, me.wrapping_add(1)).is_err());+ }++ // Stand-ins for `secret`, which would read the real key under the+ // user's data folder.+ fn seal(plain: &str) -> Result<String> {+ Ok(format!("sealed:{plain}"))+ }++ fn unseal(stored: &str) -> Option<String> {+ stored.strip_prefix("sealed:").map(str::to_string)+ }++ #[test]+ fn missing_file_reads_as_off() {+ let dir = tempfile::tempdir().unwrap();+ let settings = load_from(&dir.path().join("tailnet.json"), unseal).unwrap();+ assert_eq!(settings, Settings::default());+ assert!(!settings.enabled && !settings.serve_ssh);+ }++ #[test]+ fn secrets_are_written_sealed_and_read_back() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("tailnet.json");+ let settings = Settings {+ enabled: true,+ serve_ssh: true,+ control_url: Some("https://headscale.example.com".into()),+ hostname: Some("server-a".into()),+ auth_key: Some("tskey-example".into()),+ node_keys: Some("{\"keys\":1}".into()),+ revision: 3,+ };+ save_to(&path, &settings, seal).unwrap();++ let text = std::fs::read_to_string(&path).unwrap();+ assert!(!text.contains("\"tskey-example\""));+ assert!(text.contains("sealed:tskey-example"));+ assert_eq!(load_from(&path, unseal).unwrap(), settings);++ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ let mode = std::fs::metadata(&path).unwrap().permissions().mode();+ assert_eq!(mode & 0o777, 0o600);+ }+ }++ #[test]+ fn blank_fields_read_as_the_defaults() {+ let mut settings = Settings {+ control_url: Some(" https://headscale.example.com ".into()),+ hostname: Some(" ".into()),+ auth_key: Some(String::new()),+ node_keys: Some("k".into()),+ ..Settings::default()+ };+ settings.normalize();+ assert_eq!(+ settings.control_url.as_deref(),+ Some("https://headscale.example.com")+ );+ assert_eq!(settings.hostname, None);+ assert_eq!(settings.auth_key, None);+ assert_eq!(settings.node_keys.as_deref(), Some("k"));+ }++ #[test]+ fn writes_leave_no_temporary_files_behind() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("tailnet.json");+ write_private(&path, b"{}", true).unwrap();+ write_private(&path, b"{\"enabled\":true}", false).unwrap();+ let names: Vec<_> = std::fs::read_dir(dir.path())+ .unwrap()+ .map(|entry| entry.unwrap().file_name())+ .collect();+ assert_eq!(names, vec![std::ffi::OsString::from("tailnet.json")]);+ assert_eq!(+ std::fs::read_to_string(&path).unwrap(),+ "{\"enabled\":true}"+ );+ }++ #[test]+ fn every_save_tells_from_the_last() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("tailnet.json");+ assert_eq!(stamp(&path), None);+ write_private(&path, b"{\"enabled\":true }", false).unwrap();+ let first = stamp(&path);+ // The same length, as fast as it goes.+ write_private(&path, b"{\"enabled\":false}", false).unwrap();+ assert!(first.is_some());+ assert_ne!(stamp(&path), first);+ }++ #[test]+ fn debug_and_summary_leave_the_secrets_out() {+ let settings = Settings {+ enabled: true,+ auth_key: Some("tskey-example".into()),+ node_keys: Some("node-secret".into()),+ ..Settings::default()+ };+ let shown = format!("{settings:?}");+ assert!(!shown.contains("tskey-example"));+ assert!(!shown.contains("node-secret"));+ let summary = settings.summary();+ assert!(summary.has_auth_key && summary.has_node_keys);+ assert!(summary.enabled && !summary.serve_ssh);+ }++ #[test]+ fn a_secret_that_no_longer_decrypts_reads_as_absent() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("tailnet.json");+ // An older file's "runs_in" means nothing any more: the mux server+ // holds the node either way, and lets no SSH in until told to.+ std::fs::write(+ &path,+ r#"{"enabled":true,"runs_in":"server","auth_key":"enc:v1:stale","node_keys":"sealed:k"}"#,+ )+ .unwrap();+ let settings = load_from(&path, unseal).unwrap();+ assert_eq!(settings.auth_key, None);+ assert_eq!(settings.node_keys.as_deref(), Some("k"));+ assert!(settings.enabled && !settings.serve_ssh);+ }+}diff --git a/thinkterm-tailnet/src/status.rs b/thinkterm-tailnet/src/status.rsnew file mode 100644index 00000000..044c6c9f--- /dev/null+++ b/thinkterm-tailnet/src/status.rs@@ -0,0 +1,275 @@+//! Where the node is, as the process holding it -- the mux server -- last+//! saw. It writes that to a file in the runtime folder, which is how the app+//! and `thinkterm tailnet` learn what the node is doing without asking it.++use serde::{Deserialize, Serialize};+use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};+use std::path::PathBuf;++#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(tag = "state", rename_all = "snake_case")]+pub enum Status {+ /// No node runs in this process.+ #[default]+ Off,+ /// Reaching the control server.+ Starting,+ /// The control server wants a person to approve this machine at `url`.+ NeedsLogin { url: String },+ Connected {+ /// This machine's name in the tailnet.+ name: String,+ address: Option<IpAddr>,+ },+ /// It stopped trying, or is waiting to try again.+ Failed { error: String },+ /// This process should hold the node, but another one on this machine+ /// does; this one takes over when that one lets go.+ HeldElsewhere,+}++/// Another machine in the tailnet.+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct Peer {+ /// What a host's address can say to reach it.+ pub name: String,+ /// The name with the tailnet's domain, for when two machines share one.+ pub fqdn: String,+ pub ipv4: Option<Ipv4Addr>,+ pub ipv6: Option<Ipv6Addr>,+ /// None while the control server has not said.+ pub online: Option<bool>,+ /// What the machine says it runs, as Tailscale names it: "macOS",+ /// "iOS", "android", "linux", "windows"... Empty when it does not say,+ /// as in a report from before it was kept.+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub os: String,+ /// Its Linux distribution ("ubuntu"), when it says.+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub distro: String,+ /// The model of a phone or tablet ("iPad13,4"), when it says.+ #[serde(default, skip_serializing_if = "String::is_empty")]+ pub model: String,+}++/// Which of a machine's addresses a connection may go to, as AddressFamily+/// in the SSH config says.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum Family {+ #[default]+ Any,+ V4,+ V6,+}++impl From<wezterm_ssh::AddressFamily> for Family {+ fn from(family: wezterm_ssh::AddressFamily) -> Self {+ match family {+ wezterm_ssh::AddressFamily::Any => Family::Any,+ wezterm_ssh::AddressFamily::Inet => Family::V4,+ wezterm_ssh::AddressFamily::Inet6 => Family::V6,+ }+ }+}++impl Family {+ #[cfg(feature = "node")]+ pub fn allows(self, ip: IpAddr) -> bool {+ match self {+ Family::Any => true,+ Family::V4 => ip.is_ipv4(),+ Family::V6 => ip.is_ipv6(),+ }+ }+}++impl Peer {+ /// The address a connection to it goes to.+ pub fn address(&self) -> Option<IpAddr> {+ self.address_in(Family::Any)+ }++ /// The address a connection to it goes to, of those `family` allows.+ pub(crate) fn address_in(&self, family: Family) -> Option<IpAddr> {+ let ipv4 = self.ipv4.map(IpAddr::V4);+ let ipv6 = self.ipv6.map(IpAddr::V6);+ match family {+ Family::Any => ipv4.or(ipv6),+ Family::V4 => ipv4,+ Family::V6 => ipv6,+ }+ }++ /// Whether `host`, as a host's address or SSH config spells it, names+ /// this machine.+ pub fn answers_to(&self, host: &str) -> bool {+ let host = host.trim_end_matches('.');+ match host.parse::<IpAddr>() {+ Ok(IpAddr::V4(ip)) => self.ipv4 == Some(ip),+ Ok(IpAddr::V6(ip)) => self.ipv6 == Some(ip),+ Err(_) => self.name.eq_ignore_ascii_case(host) || self.fqdn.eq_ignore_ascii_case(host),+ }+ }++ /// Whether its full name is in `domain`, a tailnet's own: one shared in+ /// from another tailnet keeps that one's.+ pub fn in_domain(&self, domain: &str) -> bool {+ self.fqdn+ .trim_end_matches('.')+ .split_once('.')+ .is_some_and(|(_, rest)| rest.eq_ignore_ascii_case(domain.trim_end_matches('.')))+ }+}++/// The status file's contents.+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+pub struct Report {+ /// The process that wrote it, to tell a report from a server that has+ /// since gone.+ pub pid: u32,+ pub status: Status,+ pub peers: Vec<Peer>,+ /// The settings' revision ([`crate::Settings::revision`]) the process+ /// had acted on when it wrote this.+ #[serde(default)]+ pub revision: u64,+}++/// Scoped to the build profile like the mux server's socket, so a debug+/// build's report never stands in for the release server's.+pub(crate) fn report_path() -> PathBuf {+ config::RUNTIME_DIR.join(config::runtime_file_name("tailnet.json"))+}++/// The last report, if a process holding a node wrote one.+pub(crate) fn read_report() -> Option<Report> {+ let text = std::fs::read_to_string(report_path()).ok()?;+ serde_json::from_str(&text).ok()+}++/// The last report, if the process that wrote it is still running: one+/// left behind by a server that has since gone describes nothing. One about+/// a node in the tailnet also needs the node's socket to answer: the+/// server's number may have gone to another process since, after a crash+/// or a restart.+pub fn read_live_report() -> Option<Report> {+ read_report().filter(|report| {+ process_is_running(report.pid) && (!holds_node(&report.status) || node_answers())+ })+}++/// Whether only a process holding the node reports `status`.+fn holds_node(status: &Status) -> bool {+ matches!(+ status,+ Status::Starting | Status::NeedsLogin { .. } | Status::Connected { .. }+ )+}++/// Whether the process holding the node listens on its socket (see+/// crate::proxy), which it does for as long as it holds it.+fn node_answers() -> bool {+ #[cfg(unix)]+ {+ crate::settings::socket_path()+ .is_ok_and(|path| std::os::unix::net::UnixStream::connect(path).is_ok())+ }+ #[cfg(not(unix))]+ {+ true+ }+}++fn process_is_running(pid: u32) -> bool {+ #[cfg(unix)]+ {+ use nix::errno::Errno;+ use nix::sys::signal::kill;+ use nix::unistd::Pid;+ match i32::try_from(pid) {+ Ok(pid) => matches!(kill(Pid::from_raw(pid), None), Ok(()) | Err(Errno::EPERM)),+ Err(_) => false,+ }+ }+ #[cfg(not(unix))]+ {+ let _ = pid;+ true+ }+}++/// Private to this user: a login link in it would let whoever opens it+/// first decide which tailnet this machine joins. Not waited onto the disk:+/// it is rewritten as the node changes, and means nothing after a restart.+#[cfg(all(feature = "node", any(target_os = "macos", target_os = "linux")))]+pub(crate) fn write_report(report: &Report) {+ let result = serde_json::to_vec_pretty(report)+ .map_err(anyhow::Error::from)+ .and_then(|bytes| crate::settings::write_private(&report_path(), &bytes, false));+ if let Err(err) = result {+ log::warn!("tailnet: writing the status file: {err:#}");+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn peer() -> Peer {+ Peer {+ name: "server-a".into(),+ fqdn: "server-a.example.ts.net".into(),+ ipv4: Some(Ipv4Addr::new(100, 64, 0, 2)),+ ipv6: None,+ online: Some(true),+ ..Default::default()+ }+ }++ #[test]+ fn a_peer_answers_to_its_names_and_addresses() {+ let peer = peer();+ assert!(peer.answers_to("server-a"));+ assert!(peer.answers_to("SERVER-A"));+ assert!(peer.answers_to("server-a.example.ts.net."));+ assert!(peer.answers_to("100.64.0.2"));+ assert!(!peer.answers_to("100.64.0.3"));+ assert!(!peer.answers_to("server-b"));+ assert!(!peer.answers_to("server-a.example.com"));+ assert!(peer.in_domain("example.ts.net"));+ assert!(peer.in_domain("EXAMPLE.ts.net."));+ assert!(!peer.in_domain("other.ts.net"));+ assert!(!peer.in_domain("ts.net"));+ }++ #[test]+ fn report_round_trips_through_json() {+ let report = Report {+ pid: 42,+ status: Status::Connected {+ name: "devbox".into(),+ address: Some(IpAddr::V4(Ipv4Addr::new(100, 64, 0, 1))),+ },+ peers: vec![peer()],+ revision: 7,+ };+ let json = serde_json::to_string(&report).unwrap();+ assert!(json.contains("\"state\":\"connected\""));+ assert_eq!(serde_json::from_str::<Report>(&json).unwrap(), report);+ }++ #[test]+ fn a_machine_keeps_what_it_says_it_is() {+ let phone = Peer {+ os: "iOS".into(),+ model: "iPhone15,2".into(),+ ..peer()+ };+ let json = serde_json::to_string(&phone).unwrap();+ assert_eq!(serde_json::from_str::<Peer>(&json).unwrap(), phone);+ // Written before these were kept: it says nothing about itself.+ let old = r#"{"name":"server-a","fqdn":"server-a.example.ts.net","ipv4":"100.64.0.2","ipv6":null,"online":true}"#;+ assert_eq!(serde_json::from_str::<Peer>(old).unwrap(), peer());+ }+}diff --git a/wezterm-gui/Cargo.toml b/wezterm-gui/Cargo.tomlindex fe4783e0..74d414d5 100644--- a/wezterm-gui/Cargo.toml+++ b/wezterm-gui/Cargo.toml@@ -18,7 +18,9 @@ path = "src/main.rs"[features]cargo-clippy = []-default = ["vendored-fonts", "wayland"]+default = ["vendored-fonts", "wayland", "tailnet"]+# Joining a tailnet with no Tailscale app installed (thinkterm-tailnet).+tailnet = ["dep:thinkterm-tailnet"]wayland = ["window/wayland"]distro-defaults = ["config/distro-defaults"]vendor-nerd-font-symbols-font = ["wezterm-font/vendor-nerd-font-symbols"]@@ -44,6 +46,7 @@ cc.workspace = trueembed-resource.workspace = true[dependencies]+thinkterm-tailnet = { workspace = true, optional = true }thinkterm-import-herdr.workspace = truethinkterm-import.workspace = trueanyhow.workspace = truediff --git a/wezterm-mux-server/Cargo.toml b/wezterm-mux-server/Cargo.tomlindex c4c39724..d919dfc0 100644--- a/wezterm-mux-server/Cargo.toml+++ b/wezterm-mux-server/Cargo.toml@@ -15,7 +15,14 @@ path = "src/main.rs"# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html+[features]+default = ["tailnet"]+# Joining a tailnet with no Tailscale app installed (thinkterm-tailnet): the+# server is the process that holds the machine's node.+tailnet = ["dep:thinkterm-tailnet", "thinkterm-tailnet/node"]+[dependencies]+thinkterm-tailnet = { workspace = true, optional = true }thinkterm-import-herdr.workspace = truethinkterm-import.workspace = trueanyhow.workspace = truediff --git a/wezterm-mux-server/src/main.rs b/wezterm-mux-server/src/main.rsindex bc6203c7..ad550853 100644--- a/wezterm-mux-server/src/main.rs+++ b/wezterm-mux-server/src/main.rs@@ -449,6 +449,17 @@ async fn async_run(let mux = Mux::get();let config = config::configuration();let took_over = takeover.is_some();+ // Before anything connects: a takeover's sessions reconnect at once.+ // Until the predecessor lets go of the node, theirs to the tailnet's+ // machines wait for this server's own (see follow_tailnet).+ #[cfg(feature = "tailnet")]+ {+ // Through its own node, or whichever process here holds it.+ thinkterm_tailnet::use_for_ssh_in_server();+ if took_over {+ thinkterm_tailnet::will_hold();+ }+ }// async_run is entered through SimpleExecutor, so promise's schedulers// are available before agent detection starts its safety tick.@@ -506,6 +517,10 @@ async fn async_run(let web_servers = config.web_servers.clone();thread::spawn(move || {wezterm_mux_server_impl::handoff::wait_for_predecessor_exit(stream);+ // The predecessor's node went with it: two processes on one+ // node's keys would take the node from each other.+ #[cfg(feature = "tailnet")]+ follow_tailnet();// Its descriptors close one after another as it exits; the// handoff socket may answer for a while after the stream did.// A server that cannot be taken over is one whose sessions the@@ -551,6 +566,10 @@ async fn async_run(}#[cfg(not(unix))]let _ = (takeover, daemonized);+ #[cfg(feature = "tailnet")]+ if !took_over {+ follow_tailnet();+ }let _config_subscription = config::subscribe_to_config_reload(move || {promise::spawn::spawn_into_main_thread(async move {if let Err(err) = update_mux_domains_for_server(&config::configuration()) {@@ -593,6 +612,14 @@ async fn async_run(Ok(())}+/// Holds the machine's node while the tailnet is on -- the app's switch or+/// `thinkterm tailnet up` (see thinkterm_tailnet) -- taking SSH connections+/// from it to this machine's sshd when `thinkterm tailnet up` said to.+#[cfg(feature = "tailnet")]+fn follow_tailnet() {+ thinkterm_tailnet::follow(|| {});+}+/// The pid file the predecessor handed over: same lock, our pid in it.#[cfg(unix)]fn adopt_pid_file(fd: std::os::unix::io::RawFd) {diff --git a/wezterm/Cargo.toml b/wezterm/Cargo.tomlindex c9be6d12..c15ca447 100644--- a/wezterm/Cargo.toml+++ b/wezterm/Cargo.toml@@ -16,7 +16,13 @@ path = "src/bin/wezterm.rs"# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html+[features]+default = ["tailnet"]+# `thinkterm tailnet`: a tailnet joined with no Tailscale app installed.+tailnet = ["dep:thinkterm-tailnet"]+[dependencies]+thinkterm-tailnet = { workspace = true, optional = true }anyhow.workspace = truechrono.workspace = trueclap.workspace = truediff --git a/wezterm/src/main.rs b/wezterm/src/main.rsindex e1d5aef4..c6bfbf50 100644--- a/wezterm/src/main.rs+++ b/wezterm/src/main.rs@@ -19,6 +19,8 @@ use wezterm_gui_subcommands::*;mod asciicast;mod cli;mod plugin;+#[cfg(feature = "tailnet")]+mod tailnet;// let message = "; ❤ 😍🤢\n\x1b[91;mw00t\n\x1b[37;104;m bleet\x1b[0;m.";@@ -266,6 +268,13 @@ enum SubCommand {)]Plugin(plugin::PluginCommand),+ #[cfg(feature = "tailnet")]+ #[command(+ name = "tailnet",+ about = "Join a tailnet without the Tailscale app, for this machine's mux server"+ )]+ Tailnet(tailnet::TailnetCommand),+/// Write a project's file listing for search. The desktop runs this on a/// remote host over ssh; it is not meant to be run by hand.#[command(name = "list-files", hide = true)]@@ -1223,16 +1232,23 @@ fn run() -> anyhow::Result<()> {SubCommand::Replay(cmd) => cmd.run(),SubCommand::Update(cmd) => cmd.run(),SubCommand::Plugin(cmd) => cmd.run(),+ #[cfg(feature = "tailnet")]+ SubCommand::Tailnet(cmd) => cmd.run(),SubCommand::ListFiles(cmd) => cmd.run(),- SubCommand::Tui(cmd) => thinkterm_tui::run(- init_config(&opts)?,- thinkterm_tui::TuiOptions {- domains: cmd.domains,- class_name: cmd.class,- prefer_mux: cmd.prefer_mux,- tui_config_path: cmd.tui_config,- },- ),+ SubCommand::Tui(cmd) => {+ // Its SSH domains connect from this process.+ #[cfg(feature = "tailnet")]+ thinkterm_tailnet::use_for_ssh();+ thinkterm_tui::run(+ init_config(&opts)?,+ thinkterm_tui::TuiOptions {+ domains: cmd.domains,+ class_name: cmd.class,+ prefer_mux: cmd.prefer_mux,+ tui_config_path: cmd.tui_config,+ },+ )+ }SubCommand::ShellCompletion { shell } => {let rendered = render_shell_completion(shell)?;std::io::stdout()diff --git a/wezterm/src/tailnet.rs b/wezterm/src/tailnet.rsnew file mode 100644index 00000000..987fe927--- /dev/null+++ b/wezterm/src/tailnet.rs@@ -0,0 +1,409 @@+//! `thinkterm tailnet`: a tailnet joined without the Tailscale app, for a+//! machine nobody sits at. The mux server holds the node and lets SSH from+//! the tailnet through to this machine's sshd; this command only changes the+//! settings the server follows and reads back what it reports.++use anyhow::{bail, Context};+use clap::{Parser, Subcommand};+use std::time::{Duration, Instant};+use thinkterm_tailnet::{Report, Settings, Status};++#[derive(Debug, Parser, Clone)]+pub struct TailnetCommand {+ #[command(subcommand)]+ sub: Sub,+}++#[derive(Debug, Subcommand, Clone)]+enum Sub {+ /// Have this machine's mux server join the tailnet and wait until it+ /// has joined: it prints a link to+ /// approve the machine if the control server wants one+ Up {+ /// Forward incoming tailnet SSH to this machine's sshd. It sees+ /// loopback clients, so local-address trust rules apply to them+ #[arg(long)]+ serve_ssh: bool,+ /// The control server: a Headscale's address. Tailscale's own when+ /// not given before; an empty value goes back to it+ #[arg(long, value_name = "URL")]+ control_url: Option<String>,+ /// The machine's name in the tailnet; "thinkterm-" and four+ /// characters of the machine's key when not given before. An empty+ /// value goes back to that+ #[arg(long, value_name = "NAME")]+ hostname: Option<String>,+ /// Read an auth key from standard input instead of approving the+ /// machine in a browser+ #[arg(long)]+ auth_key_stdin: bool,+ },+ /// Leave the tailnet, keeping this machine's identity for the next `up`+ Down,+ /// Leave the tailnet and forget this machine's identity and auth key+ Logout,+ /// Show the settings and what the node is doing+ Status,+}++/// How long `up` waits for the server to report the node connected.+const UP_WAIT: Duration = Duration::from_secs(120);++impl TailnetCommand {+ pub fn run(&self) -> anyhow::Result<()> {+ if !thinkterm_tailnet::SUPPORTED {+ bail!("joining a tailnet is not supported on this platform");+ }+ match &self.sub {+ Sub::Up {+ serve_ssh,+ control_url,+ hostname,+ auth_key_stdin,+ } => {+ let before = thinkterm_tailnet::load_summary()?;+ // Compared as the settings keep it: the same server typed+ // another way is no change.+ let new_control = control_url.as_deref().is_some_and(|url| {+ thinkterm_tailnet::control_url_as_kept(url).ok()+ != Some(before.control_url.clone())+ });+ // A control server that does not answer is not switched to:+ // on a machine reached through the tailnet, nobody would+ // get back in to switch it back.+ if new_control {+ let url = control_url.as_deref().unwrap_or_default();+ thinkterm_tailnet::check_control_server(url).context("nothing was changed")?;+ }+ // Said before the node opens to the tailnet, not once it has.+ if *serve_ssh {+ println!(+ "Machines in the tailnet can reach this machine's sshd through the mux \+ server. sshd sees their connections come from 127.0.0.1 or ::1, so its \+ settings for local connections apply to them too (Match Address \+ 127.0.0.1,::1, from=\"127.0.0.1\" keys, fail2ban's ignoreip).\n"+ );+ }+ if before.enabled+ && (new_control+ || changes(hostname, &before.hostname)+ || before.serve_ssh != *serve_ssh)+ {+ println!(+ "The node restarts with the new settings: connections through the \+ tailnet end, this one too if it comes through it."+ );+ }+ let auth_key = if *auth_key_stdin {+ Some(read_auth_key()?)+ } else {+ None+ };+ let saved = thinkterm_tailnet::update(|settings| {+ settings.enabled = true;+ settings.serve_ssh = *serve_ssh;+ if let Some(url) = control_url {+ settings.control_url = Some(url.clone());+ }+ if let Some(name) = hostname {+ settings.hostname = Some(name.clone());+ }+ if auth_key.is_some() {+ settings.auth_key = auth_key;+ }+ })?;+ wait_until_up(saved.revision)+ }+ Sub::Down => {+ thinkterm_tailnet::update(|settings| {+ settings.enabled = false;+ settings.serve_ssh = false;+ })?;+ println!(+ "Left the tailnet. `thinkterm tailnet up` joins again as the same machine."+ );+ Ok(())+ }+ Sub::Logout => {+ thinkterm_tailnet::update(|settings| {+ settings.enabled = false;+ settings.serve_ssh = false;+ settings.auth_key = None;+ settings.node_keys = None;+ })?;+ println!(+ "Left the tailnet and forgot this machine's identity. \+ It stays listed in the tailnet until removed there."+ );+ Ok(())+ }+ Sub::Status => print_status(&thinkterm_tailnet::load()?),+ }+ }+}++/// Whether `given` -- an option of `up`, blank for the default -- is other+/// than what is saved.+fn changes(given: &Option<String>, saved: &Option<String>) -> bool {+ given.as_deref().is_some_and(|text| {+ let text = text.trim();+ (!text.is_empty()).then_some(text) != saved.as_deref()+ })+}++/// One line from standard input. Typed at a terminal it is not echoed, and+/// Ctrl-C gives up on it with the terminal as it was.+fn read_auth_key() -> anyhow::Result<String> {+ use std::io::{BufRead, IsTerminal, Read};+ let stdin = std::io::stdin();+ let line = if stdin.is_terminal() {+ eprint!("Auth key: ");+ let typed = {+ let _quiet = Quiet::new(&stdin);+ typed_line(stdin.lock().bytes())+ };+ eprintln!();+ typed?+ } else {+ let mut line = String::new();+ stdin.lock().read_line(&mut line)?;+ line+ };+ let key = line.trim();+ if key.is_empty() {+ bail!("no auth key on standard input");+ }+ Ok(key.to_string())+}++/// A line typed with the terminal's own line editing off (see `Quiet`):+/// up to Enter, with Backspace taking back a character and Ctrl-U the+/// lot. Ctrl-C and Ctrl-D give up on it.+fn typed_line(bytes: impl Iterator<Item = std::io::Result<u8>>) -> anyhow::Result<String> {+ let mut typed = Vec::new();+ for byte in bytes {+ match byte? {+ b'\r' | b'\n' => break,+ 0x03 | 0x04 => bail!("no auth key: given up"),+ 0x08 | 0x7f => {+ typed.pop();+ }+ 0x15 => typed.clear(),+ byte if byte < 0x20 => {}+ byte => typed.push(byte),+ }+ }+ String::from_utf8(typed).context("the auth key is not text")+}++/// Turns the terminal's echo off for as long as it lives, with its line+/// editing and Ctrl-C's signal: Ctrl-C would end the process with the echo+/// still off, so it comes in as a key instead (see `typed_line`).+struct Quiet {+ #[cfg(unix)]+ restore: Option<(std::os::fd::RawFd, termios::Termios)>,+}++impl Quiet {+ fn new(stdin: &std::io::Stdin) -> Self {+ #[cfg(unix)]+ {+ use std::os::fd::AsRawFd;+ let fd = stdin.as_raw_fd();+ let restore = termios::Termios::from_fd(fd).ok().and_then(|saved| {+ let mut quiet = saved;+ quiet.c_lflag &= !(termios::ECHO | termios::ICANON | termios::ISIG);+ quiet.c_cc[termios::VMIN] = 1;+ quiet.c_cc[termios::VTIME] = 0;+ termios::tcsetattr(fd, termios::TCSANOW, &quiet)+ .ok()+ .map(|()| (fd, saved))+ });+ Self { restore }+ }+ #[cfg(not(unix))]+ {+ let _ = stdin;+ Self {}+ }+ }+}++impl Drop for Quiet {+ fn drop(&mut self) {+ #[cfg(unix)]+ if let Some((fd, saved)) = self.restore.take() {+ let _ = termios::tcsetattr(fd, termios::TCSANOW, &saved);+ }+ }+}++/// A report the running server wrote once it had acted on the settings'+/// `revision` -- not one about the settings before it, however new -- from+/// a process that is still there.+fn fresh_report(revision: u64) -> Option<Report> {+ thinkterm_tailnet::read_live_report().filter(|report| report.revision >= revision)+}++fn wait_until_up(revision: u64) -> anyhow::Result<()> {+ let start = Instant::now();+ let mut last = None;+ loop {+ let report = fresh_report(revision);+ if report.is_none() && start.elapsed() > Duration::from_secs(10) {+ println!(+ "Saved. No mux server has picked it up yet: it joins when one starts \+ (`thinkterm-mux-server --daemonize`)."+ );+ return Ok(());+ }+ if let Some(report) = report {+ if last.as_ref() != Some(&report.status) {+ match &report.status {+ Status::Off | Status::Starting => println!("Connecting..."),+ Status::NeedsLogin { url } => {+ println!("To approve this machine, open:\n\n {url}\n");+ }+ Status::Connected { name, address } => {+ match address {+ Some(address) => println!("Connected as {name} ({address})."),+ None => println!("Connected as {name}."),+ }+ return Ok(());+ }+ Status::Failed { error } => println!("Not connected yet: {error}"),+ Status::HeldElsewhere => {+ println!("Another ThinkTerm process on this machine holds the node; waiting for it to let go.")+ }+ }+ last = Some(report.status);+ }+ }+ if start.elapsed() > UP_WAIT {+ bail!(+ "not connected after {}s; `thinkterm tailnet status` shows how it goes",+ UP_WAIT.as_secs()+ );+ }+ std::thread::sleep(Duration::from_millis(500));+ }+}++fn print_status(settings: &Settings) -> anyhow::Result<()> {+ if settings.enabled {+ println!("Tailnet: on");+ } else {+ println!("Tailnet: off");+ }+ if settings.serve_ssh {+ println!("SSH in: on (sshd sees loopback clients: 127.0.0.1 or ::1)");+ } else {+ println!("SSH in: off");+ }+ println!(+ "Control: {}",+ settings.control_url.as_deref().unwrap_or("Tailscale")+ );+ let report = thinkterm_tailnet::read_live_report().filter(|_| settings.enabled);+ let name = match (+ &settings.hostname,+ report.as_ref().map(|report| &report.status),+ ) {+ (Some(name), _) => name.clone(),+ (None, Some(Status::Connected { name, .. })) => format!("{name} (automatic)"),+ (None, _) => {+ "automatic: \"thinkterm-\" and four characters of the machine's key".to_string()+ }+ };+ println!("Name: {name}");+ println!(+ "Auth key: {}",+ if settings.auth_key.is_some() {+ "saved"+ } else {+ "none"+ }+ );+ let Some(report) = report else {+ if settings.enabled {+ println!("Node: not running (no mux server is)");+ }+ return Ok(());+ };+ let node = match &report.status {+ Status::Off => "off".to_string(),+ Status::Starting => "connecting".to_string(),+ Status::NeedsLogin { url } => format!("waiting for approval at {url}"),+ Status::Connected {+ name,+ address: Some(address),+ } => format!("connected as {name} ({address})"),+ Status::Connected {+ name,+ address: None,+ } => format!("connected as {name}"),+ Status::Failed { error } => format!("not connected: {error}"),+ Status::HeldElsewhere => "held by another ThinkTerm process".to_string(),+ };+ println!("Node: {node}");+ if !report.peers.is_empty() {+ println!("Machines:");+ let width = report+ .peers+ .iter()+ .map(|peer| peer.name.len())+ .max()+ .unwrap_or(0);+ for peer in &report.peers {+ let address = peer+ .address()+ .map(|address| address.to_string())+ .unwrap_or_default();+ let online = match peer.online {+ Some(true) => "online",+ Some(false) => "offline",+ None => "",+ };+ println!(" {:width$} {address:15} {online}", peer.name);+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn typed(keys: &[u8]) -> anyhow::Result<String> {+ typed_line(keys.iter().map(|byte| Ok(*byte)))+ }++ #[test]+ fn joining_only_serves_ssh_when_explicitly_requested() {+ for (args, expected) in [+ (vec!["tailnet", "up"], false),+ (vec!["tailnet", "up", "--serve-ssh"], true),+ ] {+ let command = TailnetCommand::try_parse_from(args).unwrap();+ let Sub::Up { serve_ssh, .. } = command.sub else {+ panic!("expected up")+ };+ assert_eq!(serve_ssh, expected);+ }+ }++ #[test]+ fn a_typed_key_is_edited_as_at_a_shell_prompt() {+ assert_eq!(typed(b"tskey-abc\r").unwrap(), "tskey-abc");+ assert_eq!(typed(b"tskey-abx\x7fc\n").unwrap(), "tskey-abc");+ assert_eq!(typed(b"oops\x15tskey-abc\r").unwrap(), "tskey-abc");+ // Pasted without a newline, then the input ends.+ assert_eq!(typed(b"tskey-abc").unwrap(), "tskey-abc");+ }++ #[test]+ fn ctrl_c_and_ctrl_d_give_up() {+ assert!(typed(b"tskey\x03").is_err());+ assert!(typed(b"\x04").is_err());+ }+}