feat(smartnetwork): add Rust-powered network diagnostics bridge and IP intelligence lookups
This commit is contained in:
2
rust/.cargo/config.toml
Normal file
2
rust/.cargo/config.toml
Normal file
@@ -0,0 +1,2 @@
|
||||
[target.aarch64-unknown-linux-gnu]
|
||||
linker = "aarch64-linux-gnu-gcc"
|
||||
915
rust/Cargo.lock
generated
Normal file
915
rust/Cargo.lock
generated
Normal file
@@ -0,0 +1,915 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstream"
|
||||
version = "0.6.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"anstyle-parse",
|
||||
"anstyle-query",
|
||||
"anstyle-wincon",
|
||||
"colorchoice",
|
||||
"is_terminal_polyfill",
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle"
|
||||
version = "1.0.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-parse"
|
||||
version = "0.2.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
|
||||
dependencies = [
|
||||
"utf8parse",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-query"
|
||||
version = "1.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "anstyle-wincon"
|
||||
version = "3.0.11"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
||||
dependencies = [
|
||||
"anstyle",
|
||||
"once_cell_polyfill",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.10.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "clap"
|
||||
version = "4.5.58"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63be97961acde393029492ce0be7a1af7e323e6bae9511ebfac33751be5e6806"
|
||||
dependencies = [
|
||||
"clap_builder",
|
||||
"clap_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_builder"
|
||||
version = "4.5.58"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f13174bda5dfd69d7e947827e5af4b0f2f94a4a3ee92912fba07a66150f21e2"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
"clap_lex",
|
||||
"strsim",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_derive"
|
||||
version = "4.5.55"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5"
|
||||
dependencies = [
|
||||
"heck",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clap_lex"
|
||||
version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3a822ea5bc7590f9d40f1ba12c0dc3c2760f3482c6984db1573ad11031420831"
|
||||
|
||||
[[package]]
|
||||
name = "colorchoice"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b05b61dc5112cbb17e4b6cd61790d9845d13888356391624cbe7e41efeac1e75"
|
||||
|
||||
[[package]]
|
||||
name = "errno"
|
||||
version = "0.3.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||
|
||||
[[package]]
|
||||
name = "hex"
|
||||
version = "0.4.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
||||
|
||||
[[package]]
|
||||
name = "is_terminal_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||
|
||||
[[package]]
|
||||
name = "itoa"
|
||||
version = "1.0.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
|
||||
|
||||
[[package]]
|
||||
name = "lazy_static"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.181"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "459427e2af2b9c839b132acb702a1c654d95e10f8c326bfc2ad11310e458b1c5"
|
||||
|
||||
[[package]]
|
||||
name = "lock_api"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
||||
dependencies = [
|
||||
"scopeguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.4.29"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
|
||||
|
||||
[[package]]
|
||||
name = "matchers"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
|
||||
dependencies = [
|
||||
"regex-automata",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"wasi",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "no-std-net"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "43794a0ace135be66a25d3ae77d41b91615fb68ae937f904090203e81f755b65"
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell_polyfill"
|
||||
version = "1.70.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot"
|
||||
version = "0.12.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||
dependencies = [
|
||||
"lock_api",
|
||||
"parking_lot_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "parking_lot_core"
|
||||
version = "0.9.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"redox_syscall",
|
||||
"smallvec",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.16"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
|
||||
|
||||
[[package]]
|
||||
name = "pnet_base"
|
||||
version = "0.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fe4cf6fb3ab38b68d01ab2aea03ed3d1132b4868fa4e06285f29f16da01c5f4c"
|
||||
dependencies = [
|
||||
"no-std-net",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pnet_macros"
|
||||
version = "0.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "688b17499eee04a0408aca0aa5cba5fc86401d7216de8a63fdf7a4c227871804"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pnet_macros_support"
|
||||
version = "0.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eea925b72f4bd37f8eab0f221bbe4c78b63498350c983ffa9dd4bcde7e030f56"
|
||||
dependencies = [
|
||||
"pnet_base",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pnet_packet"
|
||||
version = "0.34.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9a005825396b7fe7a38a8e288dbc342d5034dac80c15212436424fef8ea90ba"
|
||||
dependencies = [
|
||||
"glob",
|
||||
"pnet_base",
|
||||
"pnet_macros",
|
||||
"pnet_macros_support",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||
dependencies = [
|
||||
"zerocopy",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.9.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
|
||||
dependencies = [
|
||||
"rand_chacha",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_chacha"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||
dependencies = [
|
||||
"ppv-lite86",
|
||||
"rand_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rand_core"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "redox_syscall"
|
||||
version = "0.5.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c"
|
||||
|
||||
[[package]]
|
||||
name = "rustnetwork"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"socket2 0.5.10",
|
||||
"surge-ping",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||
|
||||
[[package]]
|
||||
name = "serde"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
||||
dependencies = [
|
||||
"serde_core",
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_core"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
|
||||
dependencies = [
|
||||
"serde_derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_derive"
|
||||
version = "1.0.228"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "serde_json"
|
||||
version = "1.0.149"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
|
||||
dependencies = [
|
||||
"itoa",
|
||||
"memchr",
|
||||
"serde",
|
||||
"serde_core",
|
||||
"zmij",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sharded-slab"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "signal-hook-registry"
|
||||
version = "1.4.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||
dependencies = [
|
||||
"errno",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.5.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86f4aa3ad99f2088c990dfa82d367e19cb29268ed67c574d10d0a4bfe71f07e0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "strsim"
|
||||
version = "0.11.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||
|
||||
[[package]]
|
||||
name = "surge-ping"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "30498e9c9feba213c3df6ed675bdf75519ccbee493517e7225305898c86cac05"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"parking_lot",
|
||||
"pnet_packet",
|
||||
"rand",
|
||||
"socket2 0.6.2",
|
||||
"thiserror",
|
||||
"tokio",
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.114"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d4d107df263a3013ef9b1879b0df87d706ff80f65a86ea879bd9c31f9b307c2a"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror"
|
||||
version = "1.0.69"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
|
||||
dependencies = [
|
||||
"thiserror-impl",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thiserror-impl"
|
||||
version = "1.0.69"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thread_local"
|
||||
version = "1.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio"
|
||||
version = "1.49.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72a2903cd7736441aac9df9d7688bd0ce48edccaadf181c3b90be801e81d3d86"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"libc",
|
||||
"mio",
|
||||
"parking_lot",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2 0.6.2",
|
||||
"tokio-macros",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tokio-macros"
|
||||
version = "2.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing"
|
||||
version = "0.1.44"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
||||
dependencies = [
|
||||
"pin-project-lite",
|
||||
"tracing-attributes",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-attributes"
|
||||
version = "0.1.31"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-core"
|
||||
version = "0.1.36"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"valuable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-log"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-subscriber"
|
||||
version = "0.3.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e"
|
||||
dependencies = [
|
||||
"matchers",
|
||||
"nu-ansi-term",
|
||||
"once_cell",
|
||||
"regex-automata",
|
||||
"sharded-slab",
|
||||
"smallvec",
|
||||
"thread_local",
|
||||
"tracing",
|
||||
"tracing-core",
|
||||
"tracing-log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.23"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "537dd038a89878be9b64dd4bd1b260315c1bb94f4d784956b81e27a088d9a09e"
|
||||
|
||||
[[package]]
|
||||
name = "utf8parse"
|
||||
version = "0.2.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||
|
||||
[[package]]
|
||||
name = "valuable"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.2+wasi-0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||
dependencies = [
|
||||
"windows-targets 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.60.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
|
||||
dependencies = [
|
||||
"windows-targets 0.53.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.61.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm 0.52.6",
|
||||
"windows_aarch64_msvc 0.52.6",
|
||||
"windows_i686_gnu 0.52.6",
|
||||
"windows_i686_gnullvm 0.52.6",
|
||||
"windows_i686_msvc 0.52.6",
|
||||
"windows_x86_64_gnu 0.52.6",
|
||||
"windows_x86_64_gnullvm 0.52.6",
|
||||
"windows_x86_64_msvc 0.52.6",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.53.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
|
||||
dependencies = [
|
||||
"windows-link",
|
||||
"windows_aarch64_gnullvm 0.53.1",
|
||||
"windows_aarch64_msvc 0.53.1",
|
||||
"windows_i686_gnu 0.53.1",
|
||||
"windows_i686_gnullvm 0.53.1",
|
||||
"windows_i686_msvc 0.53.1",
|
||||
"windows_x86_64_gnu 0.53.1",
|
||||
"windows_x86_64_gnullvm 0.53.1",
|
||||
"windows_x86_64_msvc 0.53.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.53.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.51.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.39"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a"
|
||||
dependencies = [
|
||||
"zerocopy-derive",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy-derive"
|
||||
version = "0.8.39"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zmij"
|
||||
version = "1.0.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4de98dfa5d5b7fef4ee834d0073d560c9ca7b6c46a71d058c48db7960f8cfaf7"
|
||||
18
rust/Cargo.toml
Normal file
18
rust/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["crates/rustnetwork"]
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
|
||||
[workspace.dependencies]
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
surge-ping = "0.8"
|
||||
socket2 = { version = "0.5", features = ["all"] }
|
||||
18
rust/crates/rustnetwork/Cargo.toml
Normal file
18
rust/crates/rustnetwork/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "rustnetwork"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "rustnetwork"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
tokio.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
clap.workspace = true
|
||||
tracing.workspace = true
|
||||
tracing-subscriber.workspace = true
|
||||
surge-ping.workspace = true
|
||||
socket2.workspace = true
|
||||
232
rust/crates/rustnetwork/src/gateway.rs
Normal file
232
rust/crates/rustnetwork/src/gateway.rs
Normal file
@@ -0,0 +1,232 @@
|
||||
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GatewayAddress {
|
||||
pub family: String,
|
||||
pub address: String,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GatewayInfo {
|
||||
pub interface_name: String,
|
||||
pub addresses: Vec<GatewayAddress>,
|
||||
}
|
||||
|
||||
/// Get the default gateway interface and its addresses.
|
||||
/// Linux-only: parses /proc/net/route to find the default route,
|
||||
/// then reads interface addresses from /proc/net/if_inet6 and /proc/net/fib_trie.
|
||||
pub fn get_default_gateway() -> Result<GatewayInfo, String> {
|
||||
let iface = get_default_interface()?;
|
||||
let addresses = get_interface_addresses(&iface)?;
|
||||
Ok(GatewayInfo {
|
||||
interface_name: iface,
|
||||
addresses,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse /proc/net/route to find the default route interface
|
||||
fn get_default_interface() -> Result<String, String> {
|
||||
let content =
|
||||
std::fs::read_to_string("/proc/net/route").map_err(|e| format!("Cannot read /proc/net/route: {e}"))?;
|
||||
|
||||
for line in content.lines().skip(1) {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
if fields.len() < 8 {
|
||||
continue;
|
||||
}
|
||||
let destination = fields[1];
|
||||
let flags = u32::from_str_radix(fields[3], 16).unwrap_or(0);
|
||||
// Destination 00000000 = default route, flags & 0x2 = RTF_GATEWAY
|
||||
if destination == "00000000" && (flags & 0x2) != 0 {
|
||||
return Ok(fields[0].to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Err("No default gateway found in /proc/net/route".to_string())
|
||||
}
|
||||
|
||||
/// Get IPv4 and IPv6 addresses for a given interface
|
||||
fn get_interface_addresses(iface: &str) -> Result<Vec<GatewayAddress>, String> {
|
||||
let mut addresses = Vec::new();
|
||||
|
||||
// IPv4: parse /proc/net/fib_trie or fallback to reading /sys/class/net/<iface>/...
|
||||
if let Ok(ipv4_addrs) = get_ipv4_addresses(iface) {
|
||||
for addr in ipv4_addrs {
|
||||
addresses.push(GatewayAddress {
|
||||
family: "IPv4".to_string(),
|
||||
address: addr.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// IPv6: parse /proc/net/if_inet6
|
||||
if let Ok(ipv6_addrs) = get_ipv6_addresses(iface) {
|
||||
for addr in ipv6_addrs {
|
||||
addresses.push(GatewayAddress {
|
||||
family: "IPv6".to_string(),
|
||||
address: addr.to_string(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(addresses)
|
||||
}
|
||||
|
||||
/// Get IPv4 addresses for an interface by reading /proc/net/fib_trie
|
||||
fn get_ipv4_addresses(iface: &str) -> Result<Vec<Ipv4Addr>, String> {
|
||||
// Simpler approach: use the ip command output or parse /sys/class/net
|
||||
// Let's read from /sys/class/net/<iface>/... via getifaddrs equivalent
|
||||
// Actually, let's parse /proc/net/fib_trie
|
||||
let content = std::fs::read_to_string("/proc/net/fib_trie")
|
||||
.map_err(|e| format!("Cannot read /proc/net/fib_trie: {e}"))?;
|
||||
|
||||
// Also need to correlate with interface. Simpler: read RTNETLINK via a different approach.
|
||||
// Fallback to a cleaner approach: parse `ip -4 addr show <iface>` equivalent via /proc
|
||||
|
||||
// Use /proc/net/if_inet6 for v6 and a different approach for v4:
|
||||
// Read all interface addresses by parsing the route table and ARP cache
|
||||
// Actually, the simplest reliable approach on Linux: use nix/libc getifaddrs
|
||||
// But to avoid extra deps, let's parse /proc/net/fib_trie looking for LOCAL entries
|
||||
|
||||
let mut addresses = Vec::new();
|
||||
let mut in_local_table = false;
|
||||
let mut current_prefix: Option<String> = None;
|
||||
|
||||
for line in content.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.starts_with("Local:") {
|
||||
in_local_table = true;
|
||||
continue;
|
||||
}
|
||||
if trimmed.starts_with("Main:") {
|
||||
in_local_table = false;
|
||||
continue;
|
||||
}
|
||||
if !in_local_table {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Look for lines like " |-- 192.168.1.0" (prefix) or "/32 host LOCAL" (entry)
|
||||
if trimmed.contains("|--") {
|
||||
let parts: Vec<&str> = trimmed.split_whitespace().collect();
|
||||
if parts.len() >= 2 {
|
||||
current_prefix = Some(parts.last().unwrap().to_string());
|
||||
}
|
||||
}
|
||||
if trimmed.contains("/32 host LOCAL") {
|
||||
if let Some(ref prefix) = current_prefix {
|
||||
if let Ok(addr) = prefix.parse::<Ipv4Addr>() {
|
||||
// Now verify this belongs to our interface
|
||||
// We need interface correlation — check via /sys
|
||||
addresses.push(addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If fib_trie parsing yielded results, filter by interface
|
||||
// Read interface index mapping
|
||||
if !addresses.is_empty() {
|
||||
let filtered = filter_addresses_by_interface(iface, &addresses);
|
||||
if !filtered.is_empty() {
|
||||
return Ok(filtered);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: try reading from /sys/class/net/<iface>/
|
||||
// Parse the operstate and try to extract from ARP
|
||||
get_ipv4_from_sys(iface)
|
||||
}
|
||||
|
||||
/// Filter addresses to those belonging to a specific interface
|
||||
fn filter_addresses_by_interface(iface: &str, candidates: &[Ipv4Addr]) -> Vec<Ipv4Addr> {
|
||||
let route_content = match std::fs::read_to_string("/proc/net/route") {
|
||||
Ok(c) => c,
|
||||
Err(_) => return Vec::new(),
|
||||
};
|
||||
|
||||
let mut iface_networks: Vec<(u32, u32)> = Vec::new(); // (network, mask)
|
||||
for line in route_content.lines().skip(1) {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
if fields.len() < 8 || fields[0] != iface {
|
||||
continue;
|
||||
}
|
||||
let dest = u32::from_str_radix(fields[1], 16).unwrap_or(0);
|
||||
let mask = u32::from_str_radix(fields[7], 16).unwrap_or(0);
|
||||
if dest != 0 && mask != 0 {
|
||||
iface_networks.push((dest, mask));
|
||||
}
|
||||
}
|
||||
|
||||
candidates
|
||||
.iter()
|
||||
.filter(|addr| {
|
||||
let octets = addr.octets();
|
||||
let addr_u32 = u32::from_le_bytes(octets); // /proc/net/route uses little-endian
|
||||
iface_networks
|
||||
.iter()
|
||||
.any(|(net, mask)| (addr_u32 & mask) == (net & mask))
|
||||
})
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Fallback: get IPv4 address from /sys filesystem
|
||||
fn get_ipv4_from_sys(_iface: &str) -> Result<Vec<Ipv4Addr>, String> {
|
||||
// Fallback: return empty — TS side uses os.networkInterfaces() to enrich
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
/// Get IPv6 addresses for an interface from /proc/net/if_inet6
|
||||
fn get_ipv6_addresses(iface: &str) -> Result<Vec<Ipv6Addr>, String> {
|
||||
let content = std::fs::read_to_string("/proc/net/if_inet6")
|
||||
.map_err(|e| format!("Cannot read /proc/net/if_inet6: {e}"))?;
|
||||
|
||||
let mut addresses = Vec::new();
|
||||
|
||||
for line in content.lines() {
|
||||
let fields: Vec<&str> = line.split_whitespace().collect();
|
||||
if fields.len() < 6 {
|
||||
continue;
|
||||
}
|
||||
let dev_name = fields[5];
|
||||
if dev_name != iface {
|
||||
continue;
|
||||
}
|
||||
let hex_addr = fields[0];
|
||||
if hex_addr.len() != 32 {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Parse 32-char hex into IPv6 address
|
||||
if let Ok(addr) = parse_ipv6_hex(hex_addr) {
|
||||
addresses.push(addr);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(addresses)
|
||||
}
|
||||
|
||||
/// Parse a 32-character hex string into an Ipv6Addr
|
||||
fn parse_ipv6_hex(hex: &str) -> Result<Ipv6Addr, String> {
|
||||
if hex.len() != 32 {
|
||||
return Err("Invalid hex length".to_string());
|
||||
}
|
||||
let mut segments = [0u16; 8];
|
||||
for (i, segment) in segments.iter_mut().enumerate() {
|
||||
let start = i * 4;
|
||||
let end = start + 4;
|
||||
*segment =
|
||||
u16::from_str_radix(&hex[start..end], 16).map_err(|e| format!("Invalid hex: {e}"))?;
|
||||
}
|
||||
Ok(Ipv6Addr::new(
|
||||
segments[0],
|
||||
segments[1],
|
||||
segments[2],
|
||||
segments[3],
|
||||
segments[4],
|
||||
segments[5],
|
||||
segments[6],
|
||||
segments[7],
|
||||
))
|
||||
}
|
||||
48
rust/crates/rustnetwork/src/ipc_types.rs
Normal file
48
rust/crates/rustnetwork/src/ipc_types.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Request received from TypeScript via stdin
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct IpcRequest {
|
||||
pub id: String,
|
||||
pub method: String,
|
||||
#[serde(default)]
|
||||
pub params: serde_json::Value,
|
||||
}
|
||||
|
||||
/// Response sent to TypeScript via stdout
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct IpcResponse {
|
||||
pub id: String,
|
||||
pub success: bool,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub result: Option<serde_json::Value>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
/// Unsolicited event sent to TypeScript via stdout (no id field)
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct IpcEvent {
|
||||
pub event: String,
|
||||
pub data: serde_json::Value,
|
||||
}
|
||||
|
||||
impl IpcResponse {
|
||||
pub fn success(id: String, result: serde_json::Value) -> Self {
|
||||
Self {
|
||||
id,
|
||||
success: true,
|
||||
result: Some(result),
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn error(id: String, message: String) -> Self {
|
||||
Self {
|
||||
id,
|
||||
success: false,
|
||||
result: None,
|
||||
error: Some(message),
|
||||
}
|
||||
}
|
||||
}
|
||||
43
rust/crates/rustnetwork/src/main.rs
Normal file
43
rust/crates/rustnetwork/src/main.rs
Normal file
@@ -0,0 +1,43 @@
|
||||
mod gateway;
|
||||
mod ipc_types;
|
||||
mod management;
|
||||
mod ping;
|
||||
mod port_scan;
|
||||
mod traceroute;
|
||||
|
||||
use clap::Parser;
|
||||
use tracing_subscriber::EnvFilter;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "rustnetwork", about = "Network diagnostics binary")]
|
||||
struct Cli {
|
||||
/// Run in IPC management mode (JSON-over-stdin/stdout)
|
||||
#[arg(long)]
|
||||
management: bool,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let cli = Cli::parse();
|
||||
|
||||
if cli.management {
|
||||
// Set up tracing to stderr (stdout is reserved for IPC)
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(
|
||||
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("warn")),
|
||||
)
|
||||
.with_writer(std::io::stderr)
|
||||
.with_target(false)
|
||||
.init();
|
||||
|
||||
// Run the tokio runtime for the management loop
|
||||
let runtime = tokio::runtime::Builder::new_multi_thread()
|
||||
.enable_all()
|
||||
.build()
|
||||
.expect("Failed to create tokio runtime");
|
||||
|
||||
runtime.block_on(management::management_loop());
|
||||
} else {
|
||||
eprintln!("Use --management for IPC mode");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
233
rust/crates/rustnetwork/src/management.rs
Normal file
233
rust/crates/rustnetwork/src/management.rs
Normal file
@@ -0,0 +1,233 @@
|
||||
use crate::ipc_types::{IpcEvent, IpcRequest, IpcResponse};
|
||||
use crate::{gateway, ping, port_scan, traceroute};
|
||||
use serde_json::json;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
/// Write a JSON line to stdout (IPC channel to TypeScript)
|
||||
fn send_line(value: &impl serde::Serialize) {
|
||||
if let Ok(json) = serde_json::to_string(value) {
|
||||
println!("{json}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Main management loop: reads JSON commands from stdin, dispatches to handlers
|
||||
pub async fn management_loop() {
|
||||
// Emit ready event
|
||||
let ready_event = IpcEvent {
|
||||
event: "ready".to_string(),
|
||||
data: json!({ "version": env!("CARGO_PKG_VERSION") }),
|
||||
};
|
||||
send_line(&ready_event);
|
||||
info!("Management mode ready");
|
||||
|
||||
// Set up stdin reader
|
||||
let stdin = tokio::io::stdin();
|
||||
let reader = BufReader::new(stdin);
|
||||
let mut lines = reader.lines();
|
||||
|
||||
// Process lines
|
||||
loop {
|
||||
match lines.next_line().await {
|
||||
Ok(Some(line)) => {
|
||||
let line = line.trim().to_string();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
debug!("Received request: {}", &line);
|
||||
|
||||
// Parse the request
|
||||
let request: IpcRequest = match serde_json::from_str(&line) {
|
||||
Ok(req) => req,
|
||||
Err(e) => {
|
||||
warn!("Invalid JSON request: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// Spawn handler task
|
||||
tokio::spawn(async move {
|
||||
let response = dispatch_command(&request).await;
|
||||
send_line(&response);
|
||||
});
|
||||
}
|
||||
Ok(None) => {
|
||||
// stdin closed — parent process is gone
|
||||
info!("Stdin closed, shutting down");
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Error reading stdin: {e}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Dispatch a command to the appropriate handler
|
||||
async fn dispatch_command(req: &IpcRequest) -> IpcResponse {
|
||||
match req.method.as_str() {
|
||||
"healthPing" => IpcResponse::success(req.id.clone(), json!({ "pong": true })),
|
||||
|
||||
"ping" => handle_ping(req).await,
|
||||
"traceroute" => handle_traceroute(req).await,
|
||||
"tcpPortCheck" => handle_tcp_port_check(req).await,
|
||||
"isLocalPortFree" => handle_is_local_port_free(req).await,
|
||||
"defaultGateway" => handle_default_gateway(req).await,
|
||||
|
||||
_ => IpcResponse::error(req.id.clone(), format!("Unknown method: {}", req.method)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_ping(req: &IpcRequest) -> IpcResponse {
|
||||
let host = req.params.get("host").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let count = req.params.get("count").and_then(|v| v.as_u64()).unwrap_or(1) as u32;
|
||||
let timeout_ms = req
|
||||
.params
|
||||
.get("timeoutMs")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(5000);
|
||||
|
||||
if host.is_empty() {
|
||||
return IpcResponse::error(req.id.clone(), "Missing 'host' parameter".to_string());
|
||||
}
|
||||
|
||||
match ping::ping(host, count, timeout_ms).await {
|
||||
Ok(result) => {
|
||||
let times: Vec<serde_json::Value> = result
|
||||
.times
|
||||
.iter()
|
||||
.map(|t| {
|
||||
if t.is_nan() {
|
||||
serde_json::Value::Null
|
||||
} else {
|
||||
json!(t)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
IpcResponse::success(
|
||||
req.id.clone(),
|
||||
json!({
|
||||
"alive": result.alive,
|
||||
"times": times,
|
||||
"min": if result.min.is_nan() { serde_json::Value::Null } else { json!(result.min) },
|
||||
"max": if result.max.is_nan() { serde_json::Value::Null } else { json!(result.max) },
|
||||
"avg": if result.avg.is_nan() { serde_json::Value::Null } else { json!(result.avg) },
|
||||
"stddev": if result.stddev.is_nan() { serde_json::Value::Null } else { json!(result.stddev) },
|
||||
"packetLoss": result.packet_loss,
|
||||
}),
|
||||
)
|
||||
}
|
||||
Err(e) => IpcResponse::error(req.id.clone(), e),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_traceroute(req: &IpcRequest) -> IpcResponse {
|
||||
let host = req.params.get("host").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let max_hops = req
|
||||
.params
|
||||
.get("maxHops")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(30) as u8;
|
||||
let timeout_ms = req
|
||||
.params
|
||||
.get("timeoutMs")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(5000);
|
||||
|
||||
if host.is_empty() {
|
||||
return IpcResponse::error(req.id.clone(), "Missing 'host' parameter".to_string());
|
||||
}
|
||||
|
||||
match traceroute::traceroute(host, max_hops, timeout_ms).await {
|
||||
Ok(hops) => {
|
||||
let hop_values: Vec<serde_json::Value> = hops
|
||||
.iter()
|
||||
.map(|h| {
|
||||
json!({
|
||||
"ttl": h.ttl,
|
||||
"ip": h.ip.as_deref().unwrap_or("*"),
|
||||
"rtt": h.rtt,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
IpcResponse::success(req.id.clone(), json!({ "hops": hop_values }))
|
||||
}
|
||||
Err(e) => IpcResponse::error(req.id.clone(), e),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_tcp_port_check(req: &IpcRequest) -> IpcResponse {
|
||||
let host = req.params.get("host").and_then(|v| v.as_str()).unwrap_or("");
|
||||
let port = req.params.get("port").and_then(|v| v.as_u64()).unwrap_or(0) as u16;
|
||||
let timeout_ms = req
|
||||
.params
|
||||
.get("timeoutMs")
|
||||
.and_then(|v| v.as_u64())
|
||||
.unwrap_or(5000);
|
||||
|
||||
if host.is_empty() {
|
||||
return IpcResponse::error(req.id.clone(), "Missing 'host' parameter".to_string());
|
||||
}
|
||||
if port == 0 {
|
||||
return IpcResponse::error(req.id.clone(), "Missing or invalid 'port' parameter".to_string());
|
||||
}
|
||||
|
||||
match port_scan::tcp_port_check(host, port, timeout_ms).await {
|
||||
Ok((is_open, latency_ms)) => IpcResponse::success(
|
||||
req.id.clone(),
|
||||
json!({
|
||||
"isOpen": is_open,
|
||||
"latencyMs": latency_ms,
|
||||
}),
|
||||
),
|
||||
Err(e) => IpcResponse::error(req.id.clone(), e),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_is_local_port_free(req: &IpcRequest) -> IpcResponse {
|
||||
let port = req.params.get("port").and_then(|v| v.as_u64()).unwrap_or(0) as u16;
|
||||
|
||||
if port == 0 {
|
||||
return IpcResponse::error(
|
||||
req.id.clone(),
|
||||
"Missing or invalid 'port' parameter".to_string(),
|
||||
);
|
||||
}
|
||||
|
||||
// Run the blocking port check on the blocking thread pool
|
||||
match tokio::task::spawn_blocking(move || port_scan::is_local_port_free(port)).await {
|
||||
Ok(Ok(free)) => IpcResponse::success(req.id.clone(), json!({ "free": free })),
|
||||
Ok(Err(e)) => IpcResponse::error(req.id.clone(), e),
|
||||
Err(e) => IpcResponse::error(req.id.clone(), format!("Task join error: {e}")),
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_default_gateway(req: &IpcRequest) -> IpcResponse {
|
||||
match tokio::task::spawn_blocking(gateway::get_default_gateway).await {
|
||||
Ok(Ok(info)) => {
|
||||
let addresses: Vec<serde_json::Value> = info
|
||||
.addresses
|
||||
.iter()
|
||||
.map(|a| {
|
||||
json!({
|
||||
"family": a.family,
|
||||
"address": a.address,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
IpcResponse::success(
|
||||
req.id.clone(),
|
||||
json!({
|
||||
"interfaceName": info.interface_name,
|
||||
"addresses": addresses,
|
||||
}),
|
||||
)
|
||||
}
|
||||
Ok(Err(e)) => IpcResponse::error(req.id.clone(), e),
|
||||
Err(e) => IpcResponse::error(req.id.clone(), format!("Task join error: {e}")),
|
||||
}
|
||||
}
|
||||
101
rust/crates/rustnetwork/src/ping.rs
Normal file
101
rust/crates/rustnetwork/src/ping.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
use std::net::IpAddr;
|
||||
use std::time::{Duration, Instant};
|
||||
use surge_ping::{Client, Config, PingIdentifier, PingSequence, ICMP};
|
||||
use tokio::time::timeout;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct PingResult {
|
||||
pub alive: bool,
|
||||
pub times: Vec<f64>,
|
||||
pub min: f64,
|
||||
pub max: f64,
|
||||
pub avg: f64,
|
||||
pub stddev: f64,
|
||||
pub packet_loss: f64,
|
||||
}
|
||||
|
||||
pub async fn ping(host: &str, count: u32, timeout_ms: u64) -> Result<PingResult, String> {
|
||||
let addr: IpAddr = resolve_host(host).await?;
|
||||
let timeout_dur = Duration::from_millis(timeout_ms);
|
||||
|
||||
let config = match addr {
|
||||
IpAddr::V4(_) => Config::default(),
|
||||
IpAddr::V6(_) => Config::builder().kind(ICMP::V6).build(),
|
||||
};
|
||||
let client = Client::new(&config).map_err(|e| format!("Failed to create ping client: {e}"))?;
|
||||
let mut pinger = client.pinger(addr, PingIdentifier(rand_u16())).await;
|
||||
|
||||
let mut times: Vec<f64> = Vec::with_capacity(count as usize);
|
||||
let mut alive_count: u32 = 0;
|
||||
|
||||
for seq in 0..count {
|
||||
let payload = vec![0u8; 56];
|
||||
let start = Instant::now();
|
||||
|
||||
match timeout(timeout_dur, pinger.ping(PingSequence(seq as u16), &payload)).await {
|
||||
Ok(Ok((_packet, rtt))) => {
|
||||
let ms = rtt.as_secs_f64() * 1000.0;
|
||||
times.push(ms);
|
||||
alive_count += 1;
|
||||
}
|
||||
Ok(Err(_)) => {
|
||||
times.push(f64::NAN);
|
||||
}
|
||||
Err(_) => {
|
||||
// timeout
|
||||
let _ = start; // suppress unused warning
|
||||
times.push(f64::NAN);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let valid: Vec<f64> = times.iter().copied().filter(|t| !t.is_nan()).collect();
|
||||
let min = valid.iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let max = valid.iter().copied().fold(f64::NEG_INFINITY, f64::max);
|
||||
let avg = if valid.is_empty() {
|
||||
f64::NAN
|
||||
} else {
|
||||
valid.iter().sum::<f64>() / valid.len() as f64
|
||||
};
|
||||
let stddev = if valid.is_empty() {
|
||||
f64::NAN
|
||||
} else {
|
||||
let variance = valid.iter().map(|v| (v - avg).powi(2)).sum::<f64>() / valid.len() as f64;
|
||||
variance.sqrt()
|
||||
};
|
||||
let packet_loss = ((count - alive_count) as f64 / count as f64) * 100.0;
|
||||
|
||||
Ok(PingResult {
|
||||
alive: alive_count > 0,
|
||||
times,
|
||||
min: if min.is_infinite() { f64::NAN } else { min },
|
||||
max: if max.is_infinite() { f64::NAN } else { max },
|
||||
avg,
|
||||
stddev,
|
||||
packet_loss,
|
||||
})
|
||||
}
|
||||
|
||||
async fn resolve_host(host: &str) -> Result<IpAddr, String> {
|
||||
// Try parsing as IP first
|
||||
if let Ok(addr) = host.parse::<IpAddr>() {
|
||||
return Ok(addr);
|
||||
}
|
||||
// DNS resolution
|
||||
let addrs = tokio::net::lookup_host(format!("{host}:0"))
|
||||
.await
|
||||
.map_err(|e| format!("DNS resolution failed for {host}: {e}"))?;
|
||||
|
||||
for addr in addrs {
|
||||
return Ok(addr.ip());
|
||||
}
|
||||
Err(format!("No addresses found for {host}"))
|
||||
}
|
||||
|
||||
fn rand_u16() -> u16 {
|
||||
// Simple random using current time
|
||||
let now = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default();
|
||||
(now.subsec_nanos() % 65536) as u16
|
||||
}
|
||||
100
rust/crates/rustnetwork/src/port_scan.rs
Normal file
100
rust/crates/rustnetwork/src/port_scan.rs
Normal file
@@ -0,0 +1,100 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::time::timeout;
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
|
||||
/// Check if a remote TCP port is open
|
||||
pub async fn tcp_port_check(
|
||||
host: &str,
|
||||
port: u16,
|
||||
timeout_ms: u64,
|
||||
) -> Result<(bool, Option<f64>), String> {
|
||||
let timeout_dur = Duration::from_millis(timeout_ms);
|
||||
|
||||
// Resolve host — treat DNS failure as "not open"
|
||||
let addr_str = format!("{host}:{port}");
|
||||
let addrs: Vec<SocketAddr> = match tokio::net::lookup_host(&addr_str).await {
|
||||
Ok(iter) => iter.collect(),
|
||||
Err(_) => return Ok((false, None)),
|
||||
};
|
||||
|
||||
if addrs.is_empty() {
|
||||
return Ok((false, None));
|
||||
}
|
||||
|
||||
// Try each resolved address
|
||||
for addr in &addrs {
|
||||
let start = Instant::now();
|
||||
match timeout(timeout_dur, TcpStream::connect(addr)).await {
|
||||
Ok(Ok(_stream)) => {
|
||||
let latency = start.elapsed().as_secs_f64() * 1000.0;
|
||||
return Ok((true, Some(latency)));
|
||||
}
|
||||
Ok(Err(_)) => continue,
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
|
||||
Ok((false, None))
|
||||
}
|
||||
|
||||
/// Check if a local port is free (both IPv4 and IPv6)
|
||||
pub fn is_local_port_free(port: u16) -> Result<bool, String> {
|
||||
// Check IPv4
|
||||
let ipv4_free = check_bind_ipv4(port)?;
|
||||
if !ipv4_free {
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// Check IPv6
|
||||
let ipv6_free = check_bind_ipv6(port)?;
|
||||
Ok(ipv6_free)
|
||||
}
|
||||
|
||||
fn check_bind_ipv4(port: u16) -> Result<bool, String> {
|
||||
let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP))
|
||||
.map_err(|e| format!("Failed to create IPv4 socket: {e}"))?;
|
||||
socket
|
||||
.set_reuse_address(true)
|
||||
.map_err(|e| format!("Failed to set SO_REUSEADDR: {e}"))?;
|
||||
|
||||
let addr: SocketAddr = format!("0.0.0.0:{port}")
|
||||
.parse()
|
||||
.map_err(|e| format!("Invalid address: {e}"))?;
|
||||
|
||||
match socket.bind(&addr.into()) {
|
||||
Ok(()) => {
|
||||
// Try to listen to fully test availability
|
||||
match socket.listen(1) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_bind_ipv6(port: u16) -> Result<bool, String> {
|
||||
let socket = Socket::new(Domain::IPV6, Type::STREAM, Some(Protocol::TCP))
|
||||
.map_err(|e| format!("Failed to create IPv6 socket: {e}"))?;
|
||||
socket
|
||||
.set_reuse_address(true)
|
||||
.map_err(|e| format!("Failed to set SO_REUSEADDR: {e}"))?;
|
||||
// Set IPV6_ONLY to avoid dual-stack interference
|
||||
socket
|
||||
.set_only_v6(true)
|
||||
.map_err(|e| format!("Failed to set IPV6_V6ONLY: {e}"))?;
|
||||
|
||||
let addr: SocketAddr = format!("[::]:{port}")
|
||||
.parse()
|
||||
.map_err(|e| format!("Invalid address: {e}"))?;
|
||||
|
||||
match socket.bind(&addr.into()) {
|
||||
Ok(()) => match socket.listen(1) {
|
||||
Ok(()) => Ok(true),
|
||||
Err(_) => Ok(false),
|
||||
},
|
||||
Err(_) => Ok(false),
|
||||
}
|
||||
}
|
||||
308
rust/crates/rustnetwork/src/traceroute.rs
Normal file
308
rust/crates/rustnetwork/src/traceroute.rs
Normal file
@@ -0,0 +1,308 @@
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
use std::io;
|
||||
use std::mem::MaybeUninit;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct TracerouteHop {
|
||||
pub ttl: u8,
|
||||
pub ip: Option<String>,
|
||||
pub rtt: Option<f64>,
|
||||
}
|
||||
|
||||
pub async fn traceroute(
|
||||
host: &str,
|
||||
max_hops: u8,
|
||||
timeout_ms: u64,
|
||||
) -> Result<Vec<TracerouteHop>, String> {
|
||||
let dest: IpAddr = resolve_host(host).await?;
|
||||
let timeout_dur = Duration::from_millis(timeout_ms);
|
||||
|
||||
// Run blocking raw-socket traceroute on the blocking thread pool
|
||||
tokio::task::spawn_blocking(move || traceroute_blocking(dest, max_hops, timeout_dur))
|
||||
.await
|
||||
.map_err(|e| format!("Task join error: {e}"))?
|
||||
}
|
||||
|
||||
fn traceroute_blocking(
|
||||
dest: IpAddr,
|
||||
max_hops: u8,
|
||||
timeout: Duration,
|
||||
) -> Result<Vec<TracerouteHop>, String> {
|
||||
let mut hops = Vec::new();
|
||||
|
||||
for ttl in 1..=max_hops {
|
||||
match send_probe(dest, ttl, timeout) {
|
||||
Ok((ip, rtt)) => {
|
||||
let reached = ip.as_ref().map(|a| a == &dest.to_string()).unwrap_or(false);
|
||||
hops.push(TracerouteHop {
|
||||
ttl,
|
||||
ip,
|
||||
rtt: Some(rtt),
|
||||
});
|
||||
if reached {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(ProbeError::Timeout) => {
|
||||
hops.push(TracerouteHop {
|
||||
ttl,
|
||||
ip: None,
|
||||
rtt: None,
|
||||
});
|
||||
}
|
||||
Err(ProbeError::Other(e)) => {
|
||||
hops.push(TracerouteHop {
|
||||
ttl,
|
||||
ip: None,
|
||||
rtt: None,
|
||||
});
|
||||
// Log but continue
|
||||
eprintln!("Probe error at TTL {ttl}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(hops)
|
||||
}
|
||||
|
||||
enum ProbeError {
|
||||
Timeout,
|
||||
Other(String),
|
||||
}
|
||||
|
||||
fn send_probe(dest: IpAddr, ttl: u8, timeout: Duration) -> Result<(Option<String>, f64), ProbeError> {
|
||||
let (domain, proto) = match dest {
|
||||
IpAddr::V4(_) => (Domain::IPV4, Protocol::ICMPV4),
|
||||
IpAddr::V6(_) => (Domain::IPV6, Protocol::ICMPV6),
|
||||
};
|
||||
|
||||
let sock = Socket::new(domain, Type::RAW, Some(proto))
|
||||
.map_err(|e| ProbeError::Other(format!("Socket creation failed: {e}")))?;
|
||||
|
||||
sock.set_ttl(ttl as u32)
|
||||
.map_err(|e| ProbeError::Other(format!("Failed to set TTL: {e}")))?;
|
||||
sock.set_read_timeout(Some(timeout))
|
||||
.map_err(|e| ProbeError::Other(format!("Failed to set timeout: {e}")))?;
|
||||
|
||||
let dest_addr = match dest {
|
||||
IpAddr::V4(v4) => SocketAddr::new(IpAddr::V4(v4), 0),
|
||||
IpAddr::V6(v6) => SocketAddr::new(IpAddr::V6(v6), 0),
|
||||
};
|
||||
|
||||
// Build ICMP Echo Request packet
|
||||
let ident = (std::process::id() as u16) ^ (ttl as u16);
|
||||
let seq = ttl as u16;
|
||||
let packet = match dest {
|
||||
IpAddr::V4(_) => build_icmpv4_echo_request(ident, seq),
|
||||
IpAddr::V6(_) => build_icmpv6_echo_request(ident, seq),
|
||||
};
|
||||
|
||||
let start = Instant::now();
|
||||
|
||||
sock.send_to(&packet, &dest_addr.into())
|
||||
.map_err(|e| ProbeError::Other(format!("Send failed: {e}")))?;
|
||||
|
||||
// Wait for response using MaybeUninit buffer as required by socket2
|
||||
let mut buf_uninit = [MaybeUninit::<u8>::uninit(); 512];
|
||||
loop {
|
||||
match sock.recv_from(&mut buf_uninit) {
|
||||
Ok((n, from_addr)) => {
|
||||
let elapsed = start.elapsed().as_secs_f64() * 1000.0;
|
||||
// Safety: recv_from initialized the first n bytes
|
||||
let buf: &[u8] = unsafe {
|
||||
std::slice::from_raw_parts(buf_uninit.as_ptr() as *const u8, n)
|
||||
};
|
||||
let from_ip = match from_addr.as_socket() {
|
||||
Some(sa) => sa.ip().to_string(),
|
||||
None => "unknown".to_string(),
|
||||
};
|
||||
|
||||
// Check if this response is for our probe
|
||||
match dest {
|
||||
IpAddr::V4(_) => {
|
||||
if is_relevant_icmpv4_response(buf, ident, seq) {
|
||||
return Ok((Some(from_ip), elapsed));
|
||||
}
|
||||
}
|
||||
IpAddr::V6(_) => {
|
||||
if is_relevant_icmpv6_response(buf, ident, seq) {
|
||||
return Ok((Some(from_ip), elapsed));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check if we've exceeded timeout
|
||||
if start.elapsed() >= timeout {
|
||||
return Err(ProbeError::Timeout);
|
||||
}
|
||||
}
|
||||
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock || e.kind() == io::ErrorKind::TimedOut => {
|
||||
return Err(ProbeError::Timeout);
|
||||
}
|
||||
Err(e) => {
|
||||
return Err(ProbeError::Other(format!("Recv error: {e}")));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if an ICMPv4 response is relevant to our probe.
|
||||
/// It could be Echo Reply (type 0) or Time Exceeded (type 11).
|
||||
fn is_relevant_icmpv4_response(buf: &[u8], ident: u16, seq: u16) -> bool {
|
||||
// IPv4 header is at least 20 bytes, then ICMP follows
|
||||
if buf.len() < 20 {
|
||||
return false;
|
||||
}
|
||||
let ip_header_len = ((buf[0] & 0x0f) as usize) * 4;
|
||||
if buf.len() < ip_header_len + 8 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let icmp = &buf[ip_header_len..];
|
||||
let icmp_type = icmp[0];
|
||||
|
||||
match icmp_type {
|
||||
0 => {
|
||||
// Echo Reply: check ident and seq
|
||||
if icmp.len() < 8 {
|
||||
return false;
|
||||
}
|
||||
let reply_ident = u16::from_be_bytes([icmp[4], icmp[5]]);
|
||||
let reply_seq = u16::from_be_bytes([icmp[6], icmp[7]]);
|
||||
reply_ident == ident && reply_seq == seq
|
||||
}
|
||||
11 => {
|
||||
// Time Exceeded: the original IP packet + first 8 bytes of original ICMP are in payload
|
||||
// icmp[0]=type, [1]=code, [2-3]=checksum, [4-7]=unused, [8+]=original IP header+8 bytes
|
||||
if icmp.len() < 36 {
|
||||
// 8 (outer ICMP header) + 20 (inner IP header) + 8 (inner ICMP header)
|
||||
return false;
|
||||
}
|
||||
let inner_ip = &icmp[8..];
|
||||
let inner_ip_header_len = ((inner_ip[0] & 0x0f) as usize) * 4;
|
||||
if icmp.len() < 8 + inner_ip_header_len + 8 {
|
||||
return false;
|
||||
}
|
||||
let inner_icmp = &inner_ip[inner_ip_header_len..];
|
||||
// Check inner ICMP echo request ident and seq
|
||||
if inner_icmp[0] != 8 {
|
||||
// Not echo request
|
||||
return false;
|
||||
}
|
||||
let inner_ident = u16::from_be_bytes([inner_icmp[4], inner_icmp[5]]);
|
||||
let inner_seq = u16::from_be_bytes([inner_icmp[6], inner_icmp[7]]);
|
||||
inner_ident == ident && inner_seq == seq
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if an ICMPv6 response is relevant to our probe
|
||||
fn is_relevant_icmpv6_response(buf: &[u8], ident: u16, seq: u16) -> bool {
|
||||
// ICMPv6: no IP header in raw socket recv (kernel strips it)
|
||||
if buf.len() < 8 {
|
||||
return false;
|
||||
}
|
||||
let icmp_type = buf[0];
|
||||
|
||||
match icmp_type {
|
||||
129 => {
|
||||
// Echo Reply
|
||||
let reply_ident = u16::from_be_bytes([buf[4], buf[5]]);
|
||||
let reply_seq = u16::from_be_bytes([buf[6], buf[7]]);
|
||||
reply_ident == ident && reply_seq == seq
|
||||
}
|
||||
3 => {
|
||||
// Time Exceeded: payload contains original IPv6 header + first bytes of original ICMPv6
|
||||
if buf.len() < 56 {
|
||||
// 8 (outer ICMPv6) + 40 (inner IPv6 header) + 8 (inner ICMPv6)
|
||||
return false;
|
||||
}
|
||||
let inner_icmp = &buf[48..]; // 8 + 40
|
||||
if inner_icmp[0] != 128 {
|
||||
// Not echo request
|
||||
return false;
|
||||
}
|
||||
let inner_ident = u16::from_be_bytes([inner_icmp[4], inner_icmp[5]]);
|
||||
let inner_seq = u16::from_be_bytes([inner_icmp[6], inner_icmp[7]]);
|
||||
inner_ident == ident && inner_seq == seq
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build an ICMPv4 Echo Request packet
|
||||
fn build_icmpv4_echo_request(ident: u16, seq: u16) -> Vec<u8> {
|
||||
let mut pkt = vec![0u8; 64]; // 8 header + 56 payload
|
||||
pkt[0] = 8; // Type: Echo Request
|
||||
pkt[1] = 0; // Code
|
||||
// Checksum placeholder [2,3]
|
||||
pkt[4] = (ident >> 8) as u8;
|
||||
pkt[5] = (ident & 0xff) as u8;
|
||||
pkt[6] = (seq >> 8) as u8;
|
||||
pkt[7] = (seq & 0xff) as u8;
|
||||
|
||||
// Fill payload with pattern
|
||||
for i in 8..64 {
|
||||
pkt[i] = (i as u8) & 0xff;
|
||||
}
|
||||
|
||||
// Calculate checksum
|
||||
let cksum = icmp_checksum(&pkt);
|
||||
pkt[2] = (cksum >> 8) as u8;
|
||||
pkt[3] = (cksum & 0xff) as u8;
|
||||
|
||||
pkt
|
||||
}
|
||||
|
||||
/// Build an ICMPv6 Echo Request packet
|
||||
fn build_icmpv6_echo_request(ident: u16, seq: u16) -> Vec<u8> {
|
||||
let mut pkt = vec![0u8; 64];
|
||||
pkt[0] = 128; // Type: Echo Request
|
||||
pkt[1] = 0; // Code
|
||||
// Checksum [2,3] - kernel calculates for ICMPv6
|
||||
pkt[4] = (ident >> 8) as u8;
|
||||
pkt[5] = (ident & 0xff) as u8;
|
||||
pkt[6] = (seq >> 8) as u8;
|
||||
pkt[7] = (seq & 0xff) as u8;
|
||||
|
||||
for i in 8..64 {
|
||||
pkt[i] = (i as u8) & 0xff;
|
||||
}
|
||||
|
||||
// Note: ICMPv6 checksum is computed by the kernel when using raw sockets on Linux
|
||||
pkt
|
||||
}
|
||||
|
||||
/// Calculate ICMP checksum
|
||||
fn icmp_checksum(data: &[u8]) -> u16 {
|
||||
let mut sum: u32 = 0;
|
||||
let mut i = 0;
|
||||
while i + 1 < data.len() {
|
||||
sum += u16::from_be_bytes([data[i], data[i + 1]]) as u32;
|
||||
i += 2;
|
||||
}
|
||||
if i < data.len() {
|
||||
sum += (data[i] as u32) << 8;
|
||||
}
|
||||
while sum >> 16 != 0 {
|
||||
sum = (sum & 0xffff) + (sum >> 16);
|
||||
}
|
||||
!sum as u16
|
||||
}
|
||||
|
||||
async fn resolve_host(host: &str) -> Result<IpAddr, String> {
|
||||
if let Ok(addr) = host.parse::<IpAddr>() {
|
||||
return Ok(addr);
|
||||
}
|
||||
let addrs = tokio::net::lookup_host(format!("{host}:0"))
|
||||
.await
|
||||
.map_err(|e| format!("DNS resolution failed for {host}: {e}"))?;
|
||||
|
||||
for addr in addrs {
|
||||
return Ok(addr.ip());
|
||||
}
|
||||
Err(format!("No addresses found for {host}"))
|
||||
}
|
||||
Reference in New Issue
Block a user